answer
stringlengths 17
10.2M
|
|---|
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
public class Main extends HttpServlet{
private static String TABLE_CREATION = "CREATE TABLE IF NOT EXISTS profile (user_id SERIAL, name varchar(32), " +
"about_me varchar(1024), village varchar(32), zip_code int, phone_number varchar(16), email varchar(32));";
private static String TABLE_CREATION_2 = "CREATE TABLE IF NOT EXISTS Connections (requester_id int, target_id int, status varchar(32));";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection connection = null;
try {
connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate(TABLE_CREATION);
}
catch (Exception e) {
resp.setStatus(500);
resp.getWriter().print("Table creation error: " + e.getMessage());
}
finally {
try {
connection.close();
}
catch (SQLException e) {
resp.getWriter().print("Failed to close connection: " + getStackTrace(e));
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection connection = null;
try {
connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate(TABLE_CREATION);
stmt.executeUpdate(TABLE_CREATION_2);
}
catch (Exception e) {
resp.setStatus(500);
resp.getWriter().print("Table creation error: " + e.getMessage());
}
StringBuffer jb = new StringBuffer();
String line;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
}
catch (IOException e) {
resp.setStatus(400);
resp.getWriter().print("Couldn't read in request body: " + getStackTrace(e));
}
try {
JSONObject jsonObject = new JSONObject(jb.toString());
if (req.getRequestURI().endsWith("/createAccount")) {
resp.setStatus(200);
resp.getWriter().print("Creating!");
String name = jsonObject.getString("name");
String about_me = jsonObject.getString("about_me");
String village = jsonObject.getString("village");
String zip_code = jsonObject.getString("zip_code");
String phone_number = jsonObject.getString("phone_number");
String email = jsonObject.getString("email");
String update_sql = "INSERT INTO profile (name, about_me, village, zip_code, phone_number, email) VALUES (?, ?, ?, ?, ?, ?)";
try {
PreparedStatement stmt = connection.prepareStatement(update_sql);
stmt.setString(1, name);
stmt.setString(2, about_me);
stmt.setString(3, village);
stmt.setString(4, zip_code);
stmt.setString(5, phone_number);
stmt.setString(6, email);
stmt.executeUpdate();
stmt.close();
}
catch (SQLException e) {
resp.getWriter().print("SQL ERROR @POST: " + getStackTrace(e));
}
}
else {
resp.setStatus(404);
}
}
catch (JSONException e1) {
resp.setStatus(400);
resp.getWriter().print("Error parsing request JSON: " + getStackTrace(e1));
}
finally {
try {
connection.close();
}
catch (SQLException e) {
resp.getWriter().print("Failed to close connection: " + getStackTrace(e));
}
}
}
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
public static void main(String[] args) throws Exception {
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
|
import com.equalexperts.weather1self.client.Lib1SelfClient;
import com.equalexperts.weather1self.client.OpenWeatherMapClient;
import com.equalexperts.weather1self.client.WeatherUndergroundClient;
import com.equalexperts.weather1self.client.response.TemperatureDatum;
import com.equalexperts.weather1self.model.lib1self.Event;
import com.equalexperts.weather1self.model.lib1self.Stream;
import com.equalexperts.weather1self.model.lib1self.WeatherSource;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.joda.time.DateTime;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.equalexperts.weather1self.model.lib1self.WeatherEventAttributes.*;
public class Main extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if(req.getQueryString() == null) {
showHome(req, resp);
return;
}
Map<String, String> queryParams = getQueryParams(req.getQueryString());
String city = queryParams.get("city");
String country = queryParams.get("country");
WeatherSource weatherSource = determineWeatherSource(req.getHeader("x-weather-source"));
DateTime now = DateTime.now();
DateTime sevenDaysBefore = now.minusDays(7);
try {
Stream stream = Lib1SelfClient.createStream();
List<TemperatureDatum> temperatureData;
switch (weatherSource) {
case OWM:
temperatureData = OpenWeatherMapClient.getWeatherData(city, country,
sevenDaysBefore, now, "hour");
break;
case WU:
temperatureData = WeatherUndergroundClient.getWeatherData(city, country, sevenDaysBefore, now);
break;
default:
temperatureData = WeatherUndergroundClient.getWeatherData(city, country, sevenDaysBefore, now);
}
List<Event> events = convertTo1SelfEvents(temperatureData);
Lib1SelfClient.sendEventsBatch(events, stream);
PrintWriter out = resp.getWriter();
out.print("{chartUri:" + Lib1SelfClient.getEventsChartURI(stream, getCommaSeparatedListString(OBJECT_TAGS), getCommaSeparatedListString(ACTION_TAGS), "mean", PROPERTY) + "}");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
private List<Event> convertTo1SelfEvents(List<TemperatureDatum> temperatureData) {
List<Event> events = new ArrayList<>();
for(TemperatureDatum temperatureDatum : temperatureData) {
events.add(temperatureDatum.to1SelfEvent());
}
return events;
}
private static WeatherSource determineWeatherSource(String weatherSourceWebsite) {
for(WeatherSource weatherSource : WeatherSource.values()) {
if(weatherSource.getWeatherSourceWebsite().equals(weatherSourceWebsite)) {
return weatherSource;
}
}
return WeatherSource.WU;
}
private static Map<String, String> getQueryParams(String queryString) {
String[] queryParamNameValuePairs = queryString.split("&");
Map<String, String> queryParams = new HashMap<>();
for (String queryParamNameValuePair : queryParamNameValuePairs) {
String[] queryParamNameValue = queryParamNameValuePair.split("=");
queryParams.put(queryParamNameValue[0], queryParamNameValue[1]);
}
return queryParams;
}
private static String getCommaSeparatedListString(List<String> list) {
StringBuilder commaSeparatedListString = new StringBuilder();
for(String string : list) {
commaSeparatedListString.append(string).append(",");
}
return commaSeparatedListString.substring(0, commaSeparatedListString.length() - 1);
}
private void showHome(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("Hello from Java!");
}
public static void main(String[] args) throws Exception {
String port = System.getenv("PORT") == null ? "9000" : System.getenv("PORT");
Server server = new Server(Integer.valueOf(port));
ServletContextHandler defaultContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
defaultContext.setContextPath("/");
|
package main.java;
import static spark.Spark.*;
public class Main {
public static void main(String[] args) {
staticFileLocation("/public"); // Static files (css,js etc..)
get("/hello", (req, res) -> "JWebPoll is awesome");
}
}
|
import java.util.Map;
import java.util.HashMap;
import javax.swing.JOptionPane;
import spark.ModelAndView;
import spark.template.velocity.VelocityTemplateEngine;
import static spark.Spark.*;
public class Task {
private static ArrayList<Task> instances = new ArrayList<Task>();
private String mDescription;
private LocalDateTime mCreatedAt;
private boolean mCompleted;
private int mId;
public Task(String description) {
mDescription = description;
mCreatedAt = LocalDateTime.now();
mCompleted = false;
instances.add(this);
mId = instances.size();
}
public String getDescription() {
return mDescription;
}
public boolean isCompleted() {
return mCompleted;
}
public LocalDateTime getCreatedAt() {
return mCreatedAt;
}
public int getId() {
return mId;
}
public void completeTask() {
mCompleted = true;
}
public static ArrayList<Task> all() {
return instances;
}
}
|
package br.com.kungFood.repository.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Table(name="tb_funcionario")
@Entity
@NamedQuery(name = "UsuarioEntity.findUser",
query= "SELECT u FROM UsuarioEntity u WHERE u.login = :usuario AND u.senha = :senha")
public class UsuarioEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="id_funcionario")
private String codigo;
@Column(name="ds_login_funcionario")
private String usuario;
@Column(name="ds_senha_funcionario")
private String senha;
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
}
|
package by.xgear.whois.ui.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.support.v4.view.GestureDetectorCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.widget.ImageView;
import by.xgear.whois.R;
public class SkewImageView extends ImageView {
public enum Direction{
AXIS_X,
AXIS_Y;
}
public enum MovementDirection{
LEFT,
RIGHT,
UP,
DOWN;
}
private Direction mDirection = Direction.AXIS_Y;
private MovementDirection mMDirection = MovementDirection.DOWN;
private Bitmap[] bArr;
private Matrix skew;
private Camera mCamera;
private int angle;
private int mLouversCount = 8;
private boolean isInOffsetMode;
private int mOffset = 0;
private float mLouverWidth = 100;
private float MAX_ANGLE = 40;
private boolean mIsScrolling;
private GestureDetectorCompat mGestureDetector;
// private VelocityTracker mVelocityTracker;
public SkewImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// int[] attrsArray = new int[] {
// android.R.attr.src, // 0
// TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SkewImageView);
// Drawable background = ta.getDrawable(R.styleable.SkewImageView_img);
// ta.recycle();
// int width = background.getIntrinsicWidth();
// width = width > 0 ? width : 1;
// int height = background.getIntrinsicHeight();
// height = height > 0 ? height : 1;
// data = Bitmap.createBitmap(width, height, Config.ARGB_8888);
// Canvas canvas = new Canvas(data);
// background.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
// background.draw(canvas);
// Bitmap.
mGestureDetector = new GestureDetectorCompat(context, mGestureListener);
Bitmap data = BitmapFactory.decodeResource(getResources(), R.drawable.skew);
data = Bitmap.createScaledBitmap(data, 400, 800, true);
bArr = new Bitmap[8];
bArr[0] = Bitmap.createBitmap(data, 0, 0, 400, 100);
bArr[1] = Bitmap.createBitmap(data, 0, 100, 400, 100);
bArr[2] = Bitmap.createBitmap(data, 0, 200, 400, 100);
bArr[3] = Bitmap.createBitmap(data, 0, 300, 400, 100);
bArr[4] = Bitmap.createBitmap(data, 0, 400, 400, 100);
bArr[5] = Bitmap.createBitmap(data, 0, 500, 400, 100);
bArr[6] = Bitmap.createBitmap(data, 0, 600, 400, 100);
bArr[7] = Bitmap.createBitmap(data, 0, 700, 400, 100);
data.recycle();
data = null;
skew = new Matrix();
mCamera = new Camera();
mLockEdge = (int) ((mLouversCount-1) * mLouverWidth - mLouverWidth * 3/4 - (mLouversCount-1) * mLouverWidth/4 + mLouverWidth);
}
public SkewImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SkewImageView(Context context) {
this(context, null, 0);
}
private int i;
private boolean isLocked;
private int mLockEdge;
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.drawColor(Color.WHITE);
isLocked = mLockEdge < mOffset;
for(i=mLouversCount-1; i>=0;i
Matrix m= getRotationMatrix(getAngleByOffset(mOffset, i));
if(!isLocked)
m.postTranslate(0, i*mLouverWidth+getMarginByOffset(mOffset, i));
else{
mOffset = mLockEdge;
m.postTranslate(0, i*mLouverWidth+getMarginByOffset(mOffset, i));
}
canvas.drawBitmap(bArr[i], m, null);
}
/* Matrix m6 = getRotationMatrix(getAngleByOffset(mOffset, 6));
m6.postTranslate(0, 600+getMarginByOffset(mOffset, 6));
canvas.drawBitmap(bArr[6], m6, null);
Matrix m5 = getRotationMatrix(getAngleByOffset(mOffset, 5));
m5.postTranslate(0, 500+getMarginByOffset(mOffset, 5));
canvas.drawBitmap(bArr[5], m5, null);
Matrix m4 = getRotationMatrix(getAngleByOffset(mOffset, 4));
m4.postTranslate(0, 400+getMarginByOffset(mOffset, 4));
canvas.drawBitmap(bArr[4], m4, null);
Matrix m3 = getRotationMatrix(getAngleByOffset(mOffset, 3));
m3.postTranslate(0, 300+getMarginByOffset(mOffset, 3));
canvas.drawBitmap(bArr[3], m3, null);
Matrix m2 = getRotationMatrix(getAngleByOffset(mOffset, 2));
m2.postTranslate(0, 200+getMarginByOffset(mOffset, 2));
canvas.drawBitmap(bArr[2], m2, null);
Matrix m1 = getRotationMatrix(getAngleByOffset(mOffset, 1));
m1.postTranslate(0, 100+getMarginByOffset(mOffset, 1));
canvas.drawBitmap(bArr[1], m1, null);*/
// Matrix m0 = getRotationMatrix(getAngleByOffset(mOffset, 0));
// m0.postTranslate(0, 0+getMarginByOffset(mOffset, 0));
// canvas.drawBitmap(bArr[0], m0, null);
// canvas.drawBitmap(applyMatrix(bArr[1], 1), 0, 100, null);
// canvas.drawBitmap(applyMatrix(bArr[2], 2), 0, 200, null);
// canvas.drawBitmap(applyMatrix(bArr[3], 3), 0, 300, null);
//// canvas.drawBitmap(data, 0, 0, null);
// skewCanvas(canvas);
super.onDraw(canvas);
canvas.restore();
}
private float getAngleByOffset(float offset, int i) {
// return 0;
int angle = 0;
offset+=i*30;
if(offset < (i+1)*mLouverWidth-mLouverWidth*3/4)
return angle;
else if(offset > (i+1)*mLouverWidth-mLouverWidth/4)
return MAX_ANGLE;
else
return MAX_ANGLE*Math.abs((offset - ((i)*mLouverWidth+mLouverWidth/4)))/(mLouverWidth/2);
}
private int getMarginByOffset(int offset, int i) {
if(offset < i*mLouverWidth-mLouverWidth*3/4 - i*mLouverWidth/4 + mLouverWidth)
return 0;
else
return (int) (offset - (i*mLouverWidth - mLouverWidth*3/4 - i*mLouverWidth/4 + mLouverWidth));
}
public void skewCanvas(Canvas canvas) {
mCamera.save();
mCamera.rotateX(angle);
mCamera.getMatrix(skew);
mCamera.restore();
int CenterX = 200;
int CenterY = 50;
skew.preTranslate(-CenterX, -CenterY); //This is the key to getting the correct viewing perspective
skew.postTranslate(CenterX, CenterY);
canvas.concat(skew);
}
public Bitmap applyMatrix(Bitmap bmp, int i) {
mCamera.save();
mCamera.rotateX(angle);
mCamera.rotateY(0);
mCamera.rotateZ(0);
mCamera.getMatrix(skew);
mCamera.restore();
int CenterX = 200;
int CenterY = 50+i*100;
skew.preTranslate(-CenterX, -CenterY); //This is the key to getting the correct viewing perspective
skew.postTranslate(CenterX, CenterY);
Bitmap result = Bitmap.createBitmap(bmp, 0, 0, 400, 400, skew, true);
return result;
}
private Matrix getRotationMatrix(float angle) {
mCamera.save();
mCamera.rotateX(angle);
mCamera.rotateY(0);
mCamera.rotateZ(0);
mCamera.getMatrix(skew);
mCamera.restore();
int CenterX = 200;
int CenterY = 50;
skew.preTranslate(-CenterX, -CenterY); //This is the key to getting the correct viewing perspective
skew.postTranslate(CenterX, CenterY);
return skew;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP)
mIsScrolling = false;
if(event.getAction() == MotionEvent.ACTION_CANCEL)
mIsScrolling = false;
if(event.getAction() == MotionEvent.ACTION_DOWN) {
mIsScrolling = isBorderHit(event.getX(), event.getY());
}
// if(event.getAction() == MotionEvent.ACTION_UP) {
// if(mIsScrolling ) {
// Log.d("OnTouchListener --> onTouch ACTION_UP");
// mIsScrolling = false;
// handleScrollFinished();
if(mIsScrolling)
mGestureDetector.onTouchEvent(event);
return true;
}
private final GestureDetector.SimpleOnGestureListener mGestureListener = new SimpleOnGestureListener(){
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
// Log.d("Pelkin", "x1="+e1.getX()+" y1="+e1.getY()+" mOffset = "+mOffset);
// Log.d("Pelkin", "x2="+e2.getX()+" y2="+e2.getY());
// if(isBorderHit(e2.getX(), e2.getY())) {
mOffset-=distanceY;
mOffset = mOffset < 0 ? 0 : mOffset;
invalidate();
Log.d("Pelkin", "mOffset=" + mOffset + "\tdistanceY = " + distanceY);
// Log.d("Pelkin", "x="+e1.getX()+" y="+e1.getY()+" onScroll distanceX = "+distanceX+"\tdistanceY = "+distanceY);
return super.onScroll(e1, e2, distanceX, distanceY);
}
};
//TODO look if scroll started near border and only then hit!
private boolean isBorderHit(float x, float y) {
Log.d("Pelkin", "isBorderHit");
switch (mDirection) {
case AXIS_X:{//TODO mLouverWidth change to constants multiplexed on dp
return x < mOffset + mLouverWidth*1.5 && x > mOffset-mLouverWidth*0.5;
}
case AXIS_Y:{
if(y < mLouverWidth * 1.5) {
mMDirection = MovementDirection.DOWN;
return true;
}else if(y > mLouverWidth * (mLouversCount - 1)) {
mMDirection = MovementDirection.UP;
mOffset = mLockEdge;
return true;
} else {
return false;
}
// return y < mOffset + mLouverWidth*1.5 && y > mOffset-mLouverWidth*0.5;
}
default:{
return false;
}
}
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
public int getOffset() {
return mOffset;
}
public void setOffset(int mOffset) {
this.mOffset = mOffset;
}
}
|
package ca.cumulonimbus.pressurenetsdk;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Messenger;
/**
* Make pressureNET Live API calls and manage the results locally
*
* @author jacob
*
*/
public class CbApi {
Context context;
String apiServerURL = "https://pressurenet.cumulonimbus.ca/list/?";
String liveApiServerURL = "https://pressurenet.cumulonimbus.ca/live/?";
String apiConditionsServerURL = "https://pressurenet.cumulonimbus.ca/conditions/list/?";
private CbDb db;
private ArrayList<CbWeather> callResults = new ArrayList<CbWeather>();
private Messenger replyResult = null;
private CbService caller;
Handler handler = new Handler();
String resultText = "";
/**
* Make an API call and store the results
*
* @return
*/
public long makeAPICall(CbApiCall call, CbService caller, Messenger ms, String callType) {
this.replyResult = ms;
this.caller = caller;
APIDataDownload api = new APIDataDownload();
api.setReplyToApp(ms);
call.setCallType(callType);
api.setApiCall(call);
api.execute(callType);
return System.currentTimeMillis();
}
/**
* When an API call finishes we'll have an ArrayList of results. Save them
* into the database
*
* @param results
* @return
*/
private boolean saveAPIResults(ArrayList<CbWeather> results, CbApiCall api) {
db.open();
System.out.println("saving api results...");
if(results.size()> 0) {
db.addWeatherArrayList(results, api);
}
db.close();
return false;
}
public CbApi(Context ctx) {
context = ctx;
db = new CbDb(context);
}
private class APIDataDownload extends AsyncTask<String, String, String> {
Messenger replyToApp = null;
private CbApiCall apiCall;
public CbApiCall getApiCall() {
return apiCall;
}
public void setApiCall(CbApiCall apiCall) {
this.apiCall = apiCall;
}
public Messenger getReplyToApp() {
return replyToApp;
}
public void setReplyToApp(Messenger replyToApp) {
this.replyToApp = replyToApp;
}
@Override
protected String doInBackground(String... params) {
String responseText = "";
try {
DefaultHttpClient client = new DefaultHttpClient();
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("min_lat", apiCall.getMinLat()
+ "" + ""));
nvps.add(new BasicNameValuePair("max_lat", apiCall.getMaxLat()
+ "" + ""));
nvps.add(new BasicNameValuePair("min_lon", apiCall.getMinLon()
+ "" + ""));
nvps.add(new BasicNameValuePair("max_lon", apiCall.getMaxLon()
+ "" + ""));
nvps.add(new BasicNameValuePair("start_time", apiCall
.getStartTime() + ""));
nvps.add(new BasicNameValuePair("end_time", apiCall
.getEndTime() + ""));
nvps.add(new BasicNameValuePair("api_key", apiCall.getApiKey()));
nvps.add(new BasicNameValuePair("format", apiCall.getFormat()));
nvps.add(new BasicNameValuePair("limit", apiCall.getLimit()
+ ""));
nvps.add(new BasicNameValuePair("global", apiCall.isGlobal()
+ ""));
nvps.add(new BasicNameValuePair("since_last_call", apiCall
.isSinceLastCall() + ""));
String paramString = URLEncodedUtils.format(nvps, "utf-8");
String serverURL = apiServerURL;
if (params[0].equals("Readings")) {
if(apiCall.getApiName().equals("live")) {
serverURL = liveApiServerURL;
} else if (apiCall.getApiName().equals("list")) {
serverURL = apiServerURL;
} else {
serverURL = apiServerURL;
}
} else {
serverURL = apiConditionsServerURL;
}
serverURL = serverURL + paramString;
apiCall.setCallURL(serverURL);
System.out.println("cbservice api sending " + serverURL);
HttpGet get = new HttpGet(serverURL);
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();
System.out.println("response "
+ responseEntity.getContentLength());
BufferedReader r = new BufferedReader(new InputStreamReader(
responseEntity.getContent()));
StringBuilder total = new StringBuilder();
String line;
if (r != null) {
while ((line = r.readLine()) != null) {
total.append(line);
}
responseText = total.toString();
}
} catch (Exception e) {
System.out.println("api error");
e.printStackTrace();
}
return responseText;
}
protected void onPostExecute(String result) {
resultText = result;
handler.postDelayed(jsonProcessor, 0);
}
final Runnable jsonProcessor = new Runnable()
{
public void run()
{
callResults = processJSONResult(resultText, apiCall);
saveAPIResults(callResults, apiCall);
System.out.println("saved " + callResults.size()
+ " api call results");
caller.notifyAPIResult(replyToApp, callResults.size());
}
};
}
/**
* Take a JSON string and return the data in a useful structure
*
* @param resultJSON
*/
private ArrayList<CbWeather> processJSONResult(String resultJSON, CbApiCall apiCall) {
ArrayList<CbWeather> obsFromJSON = new ArrayList<CbWeather>();
System.out.println("processing json result for " + apiCall.getApiName() + " call type " + apiCall.getCallType());
try {
JSONArray jsonArray = new JSONArray(resultJSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
try {
if(apiCall.getCallType().equals("Readings")) {
CbObservation singleObs = new CbObservation();
if(apiCall.getCallURL().contains("/live/")) {
Location location = new Location("network");
location.setLatitude(jsonObject.getDouble("latitude"));
location.setLongitude(jsonObject.getDouble("longitude"));
location.setAccuracy((float) jsonObject
.getDouble("location_accuracy"));
singleObs.setLocation(location);
singleObs.setTime(jsonObject.getLong("daterecorded"));
singleObs.setTimeZoneOffset(jsonObject.getLong("tzoffset"));
singleObs.setSharing(jsonObject.getString("sharing"));
singleObs.setUser_id(jsonObject.getString("user_id"));
singleObs.setObservationValue(jsonObject
.getDouble("reading"));
} else if (apiCall.getCallURL().contains("/list/")) {
singleObs.setTime(jsonObject.getLong("daterecorded"));
singleObs.setObservationValue(jsonObject
.getDouble("reading"));
}
obsFromJSON.add(singleObs);
} else {
CbCurrentCondition current = new CbCurrentCondition();
Location location = new Location("network");
location.setLatitude(jsonObject.getDouble("latitude"));
location.setLongitude(jsonObject.getDouble("longitude"));
current.setLocation(location);
current.setGeneral_condition(jsonObject.getString("general_condition"));
current.setTime(jsonObject.getLong("daterecorded"));
//current.setTzoffset(jsonObject.getInt("tzoffset"));
//current.setSharing_policy(jsonObject.getString("sharing"));
//current.setUser_id(jsonObject.getString("user_id"));
current.setWindy(jsonObject.getString("windy"));
current.setFog_thickness(jsonObject.getString("fog_thickness"));
current.setWindy(jsonObject.getString("precipitation_type"));
current.setWindy(jsonObject.getString("precipitation_amount"));
current.setWindy(jsonObject.getString("precipitation_unit"));
current.setWindy(jsonObject.getString("thunderstorm_intensity"));
current.setWindy(jsonObject.getString("user_comment"));
obsFromJSON.add(current);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return obsFromJSON;
}
}
|
package cat.mobilejazz.utilities.debug;
import cat.mobilejazz.utilities.format.StringFormatter;
import android.util.Log;
public class Debug {
private static boolean internalMethod(StackTraceElement e) {
return e.getClassName().startsWith("dalvik.") ||
e.getClassName().startsWith("java.lang.") ||
e.getClassName().startsWith(Debug.class.getName());
}
protected static StackTraceElement getCurrentMethod() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
int i = 0;
while (internalMethod(stackTrace[i]) && i < stackTrace.length)
++i;
return stackTrace[i];
}
public static String getCurrentClassName() {
return getCurrentMethod().getClassName();
}
public static String getClassTag() {
String className = getCurrentClassName();
return className.substring(className.lastIndexOf('.')+1);
}
public static String getClassMethodTag(String delim) {
StackTraceElement elem = getCurrentMethod();
return elem.getClassName() + delim + elem.getMethodName();
}
public static String getDefaultTag() {
return getClassTag();
}
public static void debug(String message) {
Log.d(getDefaultTag(), message);
}
public static void verbose(String message) {
Log.v(getDefaultTag(), message);
}
public static void info(String message) {
Log.i(getDefaultTag(), message);
}
public static void warning(String message) {
Log.w(getDefaultTag(), message);
}
public static void error(String message) {
Log.e(getDefaultTag(), message);
}
public static void logException(Throwable e) {
e.printStackTrace();
String message = e.getLocalizedMessage();
if (message != null)
error(message);
}
public static void logMethod() {
StackTraceElement elem = getCurrentMethod();
verbose(elem.getMethodName());
}
public static void logMethodVerbose(Object... params) {
Log.v("KDebug", "logMethodVerbose");
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement currentMethod = stackTrace[3];
try {
Class<?> clazz = Class.forName(currentMethod.getClassName());
Class<?>[] methodParams = new Class<?>[params.length];
for (int i = 0; i < params.length; i++) {
if (params[i] != null)
methodParams[i] = params[i].getClass();
else
methodParams[i] = null;
}
StringBuilder verboseOutput = new StringBuilder();
verboseOutput.append(currentMethod.getMethodName());
verboseOutput.append("(");
verboseOutput.append(StringFormatter.printIterable(params));
verboseOutput.append(")");
verboseOutput.append(" [");
verboseOutput.append(currentMethod.getFileName());
verboseOutput.append(":");
verboseOutput.append(currentMethod.getLineNumber());
verboseOutput.append("]");
Log.v(currentMethod.getClassName(), verboseOutput.toString());
} catch (ClassNotFoundException e) {
Log.v(currentMethod.getClassName(), currentMethod.getMethodName());
} catch (SecurityException e) {
Log.v(currentMethod.getClassName(), currentMethod.getMethodName());
}
}
}
|
package cat.mobilejazz.utilities.debug;
import android.util.Log;
import cat.mobilejazz.utilities.BuildConfig;
import cat.mobilejazz.utilities.format.StringFormatter;
public class Debug {
private static boolean internalMethod(StackTraceElement e) {
return e.getClassName().startsWith("dalvik.") || e.getClassName().startsWith("java.lang.")
|| e.getClassName().startsWith(Debug.class.getName());
}
protected static StackTraceElement getCurrentMethod() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
int i = 0;
while (internalMethod(stackTrace[i]) && i < stackTrace.length)
++i;
return stackTrace[i];
}
public static String getCurrentClassName() {
return getCurrentMethod().getClassName();
}
public static String getClassTag() {
String className = getCurrentClassName();
return className.substring(className.lastIndexOf('.') + 1);
}
public static String getClassMethodTag(String delim) {
StackTraceElement elem = getCurrentMethod();
return elem.getClassName() + delim + elem.getMethodName();
}
public static String getDefaultTag() {
return getClassTag();
}
public static void debug(String message) {
if (BuildConfig.DEBUG) {
Log.d(getDefaultTag(), message);
}
}
public static void verbose(String message) {
if (BuildConfig.DEBUG) {
Log.v(getDefaultTag(), message);
}
}
public static void info(String message) {
if (BuildConfig.DEBUG) {
Log.i(getDefaultTag(), message);
}
}
public static void warning(String message) {
if (BuildConfig.DEBUG) {
Log.w(getDefaultTag(), message);
}
}
public static void error(String message) {
if (BuildConfig.DEBUG) {
Log.e(getDefaultTag(), message);
}
}
public static void logException(Throwable e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
String message = e.getLocalizedMessage();
if (message != null)
error(message);
}
}
public static void logMethod() {
StackTraceElement elem = getCurrentMethod();
verbose(elem.getMethodName());
}
public static void logMethodVerbose(Object... params) {
if (BuildConfig.DEBUG) {
Log.v("KDebug", "logMethodVerbose");
StackTraceElement currentMethod = getCurrentMethod();
try {
StringBuilder verboseOutput = new StringBuilder();
verboseOutput.append(currentMethod.getMethodName());
verboseOutput.append("(");
verboseOutput.append(StringFormatter.printIterable(params));
verboseOutput.append(")");
verboseOutput.append(" [");
verboseOutput.append(currentMethod.getFileName());
verboseOutput.append(":");
verboseOutput.append(currentMethod.getLineNumber());
verboseOutput.append("]");
String className = currentMethod.getClassName();
Log.v(className.substring(className.lastIndexOf('.') + 1), verboseOutput.toString());
} catch (SecurityException e) {
Log.v(currentMethod.getClassName(), currentMethod.getMethodName());
}
}
}
}
|
package org.caleydo.rcp.perspective;
import java.util.List;
import java.util.logging.Logger;
import org.caleydo.core.data.IUniqueObject;
import org.caleydo.core.manager.IEventPublisher;
import org.caleydo.core.manager.event.EMediatorType;
import org.caleydo.core.manager.event.IEventContainer;
import org.caleydo.core.manager.event.IMediatorSender;
import org.caleydo.core.manager.event.view.RemoveViewSpecificItemsEvent;
import org.caleydo.core.manager.event.view.ViewActivationEvent;
import org.caleydo.core.manager.event.view.ViewEvent;
import org.caleydo.core.manager.general.GeneralManager;
import org.caleydo.rcp.views.CaleydoViewPart;
import org.caleydo.rcp.views.opengl.AGLViewPart;
import org.caleydo.rcp.views.swt.toolbar.ToolBarContentFactory;
import org.caleydo.rcp.views.swt.toolbar.ToolBarView;
import org.caleydo.rcp.views.swt.toolbar.content.AToolBarContent;
import org.caleydo.rcp.views.swt.toolbar.content.IToolBarItem;
import org.caleydo.rcp.views.swt.toolbar.content.ToolBarContainer;
import org.eclipse.jface.action.ControlContribution;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PlatformUI;
/**
* Listener for events that are related to view changes (detach, visible, hide, activate, etc.)
*
* @author Marc Streit
*/
public class PartListener
implements IPartListener2, IUniqueObject, IMediatorSender {
Logger log = Logger.getLogger(PartListener.class.getName());
IEventPublisher eventPublisher;
public PartListener() {
GeneralManager.get().getEventPublisher().addSender(EMediatorType.VIEW_SELECTION, this);
eventPublisher = GeneralManager.get().getEventPublisher();
}
@Override
public int getID() {
return 815; // FIXXXME unique id for this object or find another uniqueObject to trigger events from
}
@Override
public void triggerEvent(EMediatorType eMediatorType, IEventContainer eventContainer) {
eventPublisher.triggerEvent(eMediatorType, this, eventContainer);
}
@Override
public void partOpened(IWorkbenchPartReference partRef) {
}
@Override
public void partClosed(IWorkbenchPartReference partRef) {
IWorkbenchPart activePart = partRef.getPart(false);
if (!(activePart instanceof AGLViewPart))
return;
AGLViewPart glView = (AGLViewPart) activePart;
if (glView == null)
return;
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() == null)
return;
// Remove view specific toolbar from general toolbar view
ToolBarView toolBarView =
(ToolBarView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(
ToolBarView.ID);
if (toolBarView == null)
return;
toolBarView.removeViewSpecificToolBar(glView.getGLEventListener().getID());
}
@Override
public void partVisible(IWorkbenchPartReference partRef) {
IWorkbenchPart activePart = partRef.getPart(false);
if (!(activePart instanceof CaleydoViewPart)) {
return;
}
CaleydoViewPart viewPart = (CaleydoViewPart) activePart;
viewPart.setAttached(isViewAttached(viewPart));
log.info("partVisible(): " +viewPart);
if (viewPart instanceof AGLViewPart) {
GeneralManager.get().getViewGLCanvasManager().registerGLCanvasToAnimator(
((AGLViewPart) viewPart).getGLCanvas().getID());
}
if (!activePart.getSite().getShell().getText().equals("Caleydo")) {
// viewpart is detached from caleydo main window
drawInlineToolBar(viewPart);
removeViewSpecificToolBarItems();
} else {
// viewpart is attached within caleydo main window
removeInlineToolBar((CaleydoViewPart) viewPart);
sendViewActivationEvent(viewPart);
}
}
@Override
public void partDeactivated(IWorkbenchPartReference partRef) {
// removeViewSpecificToolBarItems();
}
@Override
public void partHidden(IWorkbenchPartReference partRef) {
IWorkbenchPart activePart = partRef.getPart(false);
if (!(activePart instanceof CaleydoViewPart)) {
return;
}
CaleydoViewPart viewPart = (CaleydoViewPart) activePart;
log.info("partHidden(): " +viewPart);
viewPart.setAttached(isViewAttached(viewPart));
if (!(activePart instanceof AGLViewPart)) {
return;
}
AGLViewPart glViewPart = (AGLViewPart) activePart;
GeneralManager.get().getViewGLCanvasManager().unregisterGLCanvasFromAnimator(
glViewPart.getGLCanvas().getID());
}
@Override
public void partInputChanged(IWorkbenchPartReference partRef) {
}
@Override
public void partActivated(IWorkbenchPartReference partRef) {
IWorkbenchPart activePart = partRef.getPart(false);
if (!(activePart instanceof CaleydoViewPart)) {
return;
}
CaleydoViewPart viewPart = (CaleydoViewPart) activePart;
log.info("partActivated(): " +viewPart);
sendViewActivationEvent(viewPart);
}
private void sendViewActivationEvent(CaleydoViewPart viewPart) {
ViewEvent viewActivationEvent;
viewActivationEvent = new ViewActivationEvent();
List<Integer> viewIDs = getAllViewIDs(viewPart);
viewActivationEvent.setViewIDs(viewIDs);
eventPublisher.triggerEvent(viewActivationEvent);
}
@Override
public void partBroughtToTop(IWorkbenchPartReference partRef) {
}
/**
* draws the toolbar items within the views default toolbar (inline)
* @param viewPart view to add the toolbar items
*/
private void drawInlineToolBar(CaleydoViewPart viewPart) {
List<Integer> viewIDs = getAllViewIDs(viewPart);
ToolBarContentFactory contentFactory = ToolBarContentFactory.get();
List<AToolBarContent> toolBarContents = contentFactory.getToolBarContent(viewIDs);
final IToolBarManager toolBarManager = viewPart.getViewSite().getActionBars().getToolBarManager();
// toolBarManager.removeAll();
for (AToolBarContent toolBarContent : toolBarContents) {
for (ToolBarContainer container : toolBarContent.getInlineToolBar()) {
for (IToolBarItem item : container.getToolBarItems()) {
if (item instanceof IAction) {
toolBarManager.add((IAction) item);
} else if (item instanceof ControlContribution) {
toolBarManager.add((ControlContribution) item);
}
}
toolBarManager.add(new Separator());
}
}
toolBarManager.update(true);
}
/**
* removes all view specific toolbar items in the toolbar view
*/
private void removeViewSpecificToolBarItems() {
RemoveViewSpecificItemsEvent event;
event = new RemoveViewSpecificItemsEvent();
eventPublisher.triggerEvent(event);
}
/**
* removes all inline toolbar items
* @param viewPart view to remove the toolbar items from
*/
private void removeInlineToolBar(CaleydoViewPart viewPart) {
final IToolBarManager toolBarManager = viewPart.getViewSite().getActionBars().getToolBarManager();
toolBarManager.removeAll();
toolBarManager.update(true);
}
/**
* Gets the view-ids and all sub-view-ids (if there are any)
* @param viewPart
* @return
*/
private List<Integer> getAllViewIDs(CaleydoViewPart viewPart) {
return viewPart.getAllViewIDs();
}
// List<Integer> viewIDs;
// if (viewPart instanceof HTMLBrowserView) {
// viewIDs = new ArrayList<Integer>();
// viewIDs.add(viewPart.getViewID());
// } else if (viewPart instanceof AGLViewPart) {
// IViewManager viewManager = GeneralManager.get().getViewGLCanvasManager();
// viewManager.setActiveSWTView(viewPart.getSWTComposite());
// AGLEventListener glView = ((AGLViewPart) viewPart).getGLEventListener();
// viewIDs = glView.getAllViewIDs();
// } else {
// viewIDs = new ArrayList<Integer>();
// return viewIDs;
public boolean isViewAttached(IViewPart viewPart) {
if (viewPart.getSite().getShell().getText().equals("Caleydo")) {
return true;
} else {
return false;
}
}
}
|
package com.dmdirc.parser.irc;
import com.dmdirc.parser.common.MyInfo;
import com.dmdirc.parser.interfaces.callbacks.NickInUseListener;
/**
* Process a NickInUse message.
* Parser implements handling of this if Pre-001 and no other handler found,
* adding the NickInUse handler (addNickInUse) after 001 is prefered over before.<br><br>
* <br>
* If the first nickname is in use, and a NickInUse message is recieved before 001, we
* will attempt to use the altnickname instead.<br>
* If this also fails, we will start prepending _ (or the value of me.cPrepend) to the main nickname.
*/
public class ProcessNickInUse extends IRCProcessor {
/**
* Create a new instance of the ProcessNickInUse Object.
*
* @param parser IRCParser That owns this object
* @param manager ProcessingManager that is in charge of this object
*/
protected ProcessNickInUse(final IRCParser parser, final ProcessingManager manager) {
super(parser, manager);
}
/**
* Process a NickInUse message.
* Parser implements handling of this if Pre-001 and no other handler found,
* adding the NickInUse handler (addNickInUse) after 001 is prefered over before.<br><br>
* <br>
* If the first nickname is in use, and a NickInUse message is recieved before 001, we
* will attempt to use the altnickname instead.<br>
* If this also fails, we will start prepending _ (or the value of me.cPrepend) to the main nickname.
*
* @param sParam Type of line to process ("433")
* @param token IRCTokenised line to process
*/
@Override
public void process(final String sParam, final String[] token) {
if (!callNickInUse(token[3])) {
// Manually handle nick in use.
callDebugInfo(IRCParser.DEBUG_INFO, "No Nick in use Handler.");
if (!parser.got001) {
callDebugInfo(IRCParser.DEBUG_INFO, "Using inbuilt handler");
// If this is before 001 we will try and get a nickname, else we will leave the nick as-is
final MyInfo myInfo = parser.getMyInfo();
if (parser.triedAlt) {
final String magicAltNick = myInfo.getPrependChar() + myInfo.getNickname();
if (parser.getStringConverter().equalsIgnoreCase(parser.thinkNickname, myInfo.getAltNickname()) && !myInfo.getAltNickname().equalsIgnoreCase(magicAltNick)) {
parser.thinkNickname = myInfo.getNickname();
}
parser.getLocalClient().setNickname(myInfo.getPrependChar() + parser.thinkNickname);
} else {
parser.getLocalClient().setNickname(parser.getMyInfo().getAltNickname());
parser.triedAlt = true;
}
}
}
}
/**
* Callback to all objects implementing the NickInUse Callback.
*
* @param nickname Nickname that was wanted.
* @see INickInUse
* @return true if a method was called, false otherwise
*/
protected boolean callNickInUse(final String nickname) {
return getCallbackManager().getCallbackType(NickInUseListener.class).call(nickname);
}
/**
* What does this IRCProcessor handle.
*
* @return String[] with the names of the tokens we handle.
*/
@Override
public String[] handles() {
return new String[]{"433"};
}
}
|
package com.esotericsoftware.kryo;
import static com.esotericsoftware.minlog.Log.DEBUG;
import static com.esotericsoftware.minlog.Log.debug;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
/**
* Serializes objects to and from byte arrays and streams.<br>
* <br>
* This class uses a buffer internally and is not thread safe.
* @author Nathan Sweet <misc@n4te.com>
*/
public class ObjectBuffer {
private final Kryo kryo;
private final int maxCapacity;
private ByteBuffer buffer;
private byte[] bytes;
/**
* Creates an ObjectStream with an initial buffer size of 2KB and a maximum size of 16KB.
*/
public ObjectBuffer (Kryo kryo) {
this(kryo, 2 * 1024, 16 * 1024);
}
/**
* @param maxCapacity The initial and maximum size in bytes of an object that can be read or written.
* @see #ObjectBuffer(Kryo, int, int)
*/
public ObjectBuffer (Kryo kryo, int maxCapacity) {
this(kryo, maxCapacity, maxCapacity);
}
/**
* @param initialCapacity The initial maximum size in bytes of an object that can be read or written.
* @param maxCapacity The maximum size in bytes of an object that can be read or written. The capacity is doubled until the
* maxCapacity is exceeded, then BufferOverflowException is thrown by the read and write methods.
*/
public ObjectBuffer (Kryo kryo, int initialCapacity, int maxCapacity) {
this.kryo = kryo;
buffer = ByteBuffer.allocate(initialCapacity);
bytes = buffer.array();
this.maxCapacity = maxCapacity;
}
/**
* Reads the specified number of bytes from the stream into the buffer.
* @param contentLength The number of bytes to read, or -1 to read to the end of the stream.
*/
private void readToBuffer (InputStream input, int contentLength) {
if (contentLength == -1) contentLength = Integer.MAX_VALUE;
try {
int position = 0;
while (position < contentLength) {
int count = input.read(bytes, position, bytes.length - position);
if (count == -1) break;
position += count;
if (position >= bytes.length && !resizeBuffer(true)) throw new BufferOverflowException();
}
buffer.position(0);
buffer.limit(position);
} catch (IOException ex) {
throw new SerializationException("Error reading object bytes.", ex);
}
}
/**
* Reads to the end of the stream and returns the deserialized object.
* @see Kryo#readClassAndObject(ByteBuffer)
*/
public Object readClassAndObject (InputStream input) {
readToBuffer(input, -1);
return kryo.readClassAndObject(buffer);
}
/**
* Reads the specified number of bytes and returns the deserialized object.
* @see Kryo#readClassAndObject(ByteBuffer)
*/
public Object readClassAndObject (InputStream input, int contentLength) {
readToBuffer(input, contentLength);
return kryo.readClassAndObject(buffer);
}
/**
* Reads to the end of the stream and returns the deserialized object.
* @see Kryo#readObject(ByteBuffer, Class)
*/
public <T> T readObject (InputStream input, Class<T> type) {
readToBuffer(input, -1);
return kryo.readObject(buffer, type);
}
/**
* Reads the specified number of bytes and returns the deserialized object.
* @see Kryo#readObject(ByteBuffer, Class)
*/
public <T> T readObject (InputStream input, int contentLength, Class<T> type) {
readToBuffer(input, contentLength);
return kryo.readObject(buffer, type);
}
/**
* Reads to the end of the stream and returns the deserialized object.
* @see Kryo#readObjectData(ByteBuffer, Class)
*/
public <T> T readObjectData (InputStream input, Class<T> type) {
readToBuffer(input, -1);
return kryo.readObjectData(buffer, type);
}
/**
* Reads the specified number of bytes and returns the deserialized object.
* @see Kryo#readObjectData(ByteBuffer, Class)
*/
public <T> T readObjectData (InputStream input, int contentLength, Class<T> type) {
readToBuffer(input, contentLength);
return kryo.readObjectData(buffer, type);
}
/**
* @see Kryo#writeClassAndObject(ByteBuffer, Object)
*/
public void writeClassAndObject (OutputStream output, Object object) {
buffer.clear();
while (true) {
try {
kryo.writeClassAndObject(buffer, object);
break;
} catch (BufferOverflowException ex) {
if (!resizeBuffer(false)) throw ex;
}
}
writeToStream(output);
}
/**
* @see Kryo#writeObject(ByteBuffer, Object)
*/
public void writeObject (OutputStream output, Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObject(buffer, object);
break;
} catch (BufferOverflowException ex) {
if (!resizeBuffer(false)) throw ex;
}
}
writeToStream(output);
}
/**
* @see Kryo#writeObjectData(ByteBuffer, Object)
*/
public void writeObjectData (OutputStream output, Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObjectData(buffer, object);
break;
} catch (BufferOverflowException ex) {
if (!resizeBuffer(false)) throw ex;
}
}
writeToStream(output);
}
private void writeToStream (OutputStream output) {
try {
output.write(bytes, 0, buffer.position());
} catch (IOException ex) {
throw new SerializationException("Error writing object bytes.", ex);
}
}
/**
* @see Kryo#readClassAndObject(ByteBuffer)
*/
public Object readClassAndObject (byte[] objectBytes) {
return kryo.readClassAndObject(ByteBuffer.wrap(objectBytes));
}
/**
* @see Kryo#readObject(ByteBuffer, Class)
*/
public <T> T readObject (byte[] objectBytes, Class<T> type) {
return kryo.readObject(ByteBuffer.wrap(objectBytes), type);
}
/**
* @see Kryo#readObjectData(ByteBuffer, Class)
*/
public <T> T readObjectData (byte[] objectBytes, Class<T> type) {
return kryo.readObjectData(ByteBuffer.wrap(objectBytes), type);
}
/**
* @see Kryo#writeClassAndObject(ByteBuffer, Object)
*/
public byte[] writeClassAndObject (Object object) {
buffer.clear();
while (true) {
try {
kryo.writeClassAndObject(buffer, object);
break;
} catch (BufferOverflowException ex) {
if (!resizeBuffer(false)) throw ex;
}
}
return writeToBytes();
}
/**
* @see Kryo#writeObject(ByteBuffer, Object)
*/
public byte[] writeObject (Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObject(buffer, object);
break;
} catch (BufferOverflowException ex) {
if (!resizeBuffer(false)) throw ex;
}
}
return writeToBytes();
}
/**
* @see Kryo#writeObjectData(ByteBuffer, Object)
*/
public byte[] writeObjectData (Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObjectData(buffer, object);
break;
} catch (BufferOverflowException ex) {
if (!resizeBuffer(false)) throw ex;
}
}
return writeToBytes();
}
private byte[] writeToBytes () {
byte[] objectBytes = new byte[buffer.position()];
System.arraycopy(bytes, 0, objectBytes, 0, objectBytes.length);
return objectBytes;
}
private boolean resizeBuffer (boolean preserveContents) {
int newCapacity = buffer.capacity() * 2;
if (newCapacity > maxCapacity) return false;
ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity);
if (preserveContents) newBuffer.put(buffer);
buffer = newBuffer;
bytes = newBuffer.array();
if (DEBUG) debug("kryo", "Resized ObjectBuffer to: " + newCapacity);
return true;
}
}
|
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.gluu.site.ldap.persistence.LdapEntryManager;
import org.gluu.site.ldap.persistence.exception.EntryPersistenceException;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.async.Asynchronous;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.contexts.Lifecycle;
import org.jboss.seam.log.Log;
import org.xdi.ldap.model.SimpleBranch;
import org.xdi.model.ApplicationType;
import org.xdi.model.metric.MetricType;
import org.xdi.model.metric.ldap.MetricEntry;
import org.xdi.util.StringHelper;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.unboundid.ldap.sdk.Filter;
public abstract class MetricService implements Serializable {
private static final long serialVersionUID = -3393618600428448743L;
private final static String EVENT_TYPE = "MetricServiceTimerEvent";
private static final SimpleDateFormat PERIOD_DATE_FORMAT = new SimpleDateFormat("yyyyMM");
private static final AtomicLong initialId = new AtomicLong(System.currentTimeMillis());
private MetricRegistry metricRegistry;
private Set<MetricType> registeredMetricTypes;
@Logger
private Log log;
@In
private LdapEntryManager ldapEntryManager;
public void init(int metricInterval) {
this.metricRegistry = new MetricRegistry();
this.registeredMetricTypes = new HashSet<MetricType>();
LdapEntryReporter ldapEntryReporter = LdapEntryReporter.forRegistry(this.metricRegistry, getComponentName()).build();
ldapEntryReporter.start(metricInterval, TimeUnit.SECONDS);
}
@Observer(EVENT_TYPE)
@Asynchronous
public void writeMetricEntries(List<MetricEntry> metricEntries, Date creationTime) {
add(metricEntries, creationTime);
}
public void addBranch(String branchDn, String ou) {
SimpleBranch branch = new SimpleBranch();
branch.setOrganizationalUnitName(ou);
branch.setDn(branchDn);
ldapEntryManager.persist(branch);
}
public boolean containsBranch(String branchDn) {
return ldapEntryManager.contains(SimpleBranch.class, branchDn);
}
public void createBranch(String branchDn, String ou) {
try {
addBranch(branchDn, ou);
} catch (EntryPersistenceException ex) {
// Check if another process added this branch already
if (!containsBranch(branchDn)) {
throw ex;
}
}
}
public void prepareBranch(Date creationDate, ApplicationType applicationType) {
String baseDn = buildDn(null, creationDate, applicationType);
// Create ou=YYYY-MM branch if needed
if (!containsBranch(baseDn)) {
// Create ou=application_type branch if needed
String applicationBaseDn = buildDn(null, null, applicationType);
if (!containsBranch(applicationBaseDn)) {
// Create ou=appliance_inum branch if needed
String applianceBaseDn = buildDn(null, null, null);
if (!containsBranch(applianceBaseDn)) {
createBranch(applianceBaseDn, applianceInum());
}
createBranch(applicationBaseDn, applicationType.getValue());
}
createBranch(baseDn, PERIOD_DATE_FORMAT.format(creationDate));
}
}
@Asynchronous
public void add(List<MetricEntry> metricEntries, Date creationTime) {
prepareBranch(creationTime, ApplicationType.OX_AUTH);
for (MetricEntry metricEntry : metricEntries) {
ldapEntryManager.persist(metricEntry);
}
}
public void add(MetricEntry metricEntry) {
prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType());
ldapEntryManager.persist(metricEntry);
}
public void update(MetricEntry metricEntry) {
prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType());
ldapEntryManager.merge(metricEntry);
}
public void remove(MetricEntry metricEntry) {
prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType());
ldapEntryManager.remove(metricEntry);
}
public MetricEntry getMetricEntryByDn(MetricType metricType, String metricEventDn) {
return ldapEntryManager.find(metricType.getMetricEntryType(), metricEventDn);
}
public Map<MetricType, List<MetricEntry>> findMetricEntry(ApplicationType applicationType, String applianceInum,
List<MetricType> metricTypes, Date startDate, Date endDate, String... returnAttributes) {
prepareBranch(null, applicationType);
Map<MetricType, List<MetricEntry>> result = new HashMap<MetricType, List<MetricEntry>>();
if ((metricTypes == null) || (metricTypes.size() == 0)) {
return result;
}
String baseDn = buildDn(applianceInum, applicationType);
for (MetricType metricType : metricTypes) {
List<Filter> metricTypeFilters = new ArrayList<Filter>();
Filter applicationTypeFilter = Filter.createEqualityFilter("oxApplicationType", applicationType.getValue());
Filter eventTypeTypeFilter = Filter.createEqualityFilter("oxEventType", metricType.getValue());
Filter startDateFilter = Filter.createGreaterOrEqualFilter("oxStartDate", ldapEntryManager.encodeGeneralizedTime(startDate));
Filter endDateFilter = Filter.createLessOrEqualFilter("oxEndDate", ldapEntryManager.encodeGeneralizedTime(endDate));
metricTypeFilters.add(applicationTypeFilter);
metricTypeFilters.add(eventTypeTypeFilter);
metricTypeFilters.add(startDateFilter);
metricTypeFilters.add(endDateFilter);
Filter filter = Filter.createANDFilter(metricTypeFilters);
List<MetricEntry> metricTypeResult = (List<MetricEntry>) ldapEntryManager.findEntries(baseDn,
metricType.getMetricEntryType(), returnAttributes, filter);
result.put(metricType, metricTypeResult);
}
return result;
}
public String getuUiqueIdentifier() {
return String.valueOf(initialId.incrementAndGet());
}
public Counter getCounter(MetricType metricType) {
if (!registeredMetricTypes.contains(metricType)) {
registeredMetricTypes.add(metricType);
}
return metricRegistry.counter(metricType.getMetricName());
}
public Timer getTimer(MetricType metricType) {
if (!registeredMetricTypes.contains(metricType)) {
registeredMetricTypes.add(metricType);
}
return metricRegistry.timer(metricType.getMetricName());
}
public void incCounter(MetricType metricType) {
Counter counter = getCounter(metricType);
counter.inc();
}
public String buildDn(String applianceInum, ApplicationType applicationType) {
return buildDn(null, null, applicationType);
}
/*
* Should return similar to this pattern DN:
* uniqueIdentifier=id,ou=YYYY-MM,ou=application_type,ou=appliance_inum,ou=metric,ou=organization_name,o=gluu
*/
public String buildDn(String uniqueIdentifier, Date creationDate, ApplicationType applicationType) {
final StringBuilder dn = new StringBuilder();
if (StringHelper.isNotEmpty(uniqueIdentifier) && (creationDate != null) && (applicationType != null)) {
dn.append(String.format("uniqueIdentifier=%s,", uniqueIdentifier));
}
if ((creationDate != null) && (applicationType != null)) {
dn.append(String.format("ou=%s,", PERIOD_DATE_FORMAT.format(creationDate)));
}
if (applicationType != null) {
dn.append(String.format("ou=%s,", applicationType.getValue()));
}
dn.append(String.format("ou=%s,", applianceInum()));
dn.append(baseDn());
return dn.toString();
}
public Set<MetricType> getRegisteredMetricTypes() {
return registeredMetricTypes;
}
// Should return ou=metric,o=gluu
public abstract String baseDn();
// Should return appliance Inum
public abstract String applianceInum();
public abstract String getComponentName();
/**
* Get MetricService instance
*
* @return MetricService instance
*/
public static MetricService instance() {
if (!(Contexts.isEventContextActive() || Contexts.isApplicationContextActive())) {
Lifecycle.beginCall();
}
return (MetricService) Component.getInstance(MetricService.class);
}
}
|
package com.pandazilla.datastrutures.tree;
public class Tree {
private Node root;
public Tree() {
}
public void insert(int id, double data) {
Node node = new Node();
node.setKey(id);
node.setData(data);
if (root == null) {
root = node;
} else {
Node current = root;
Node parent;
while (true) {
parent = current;
if (id < current.getKey()) { //move on left?
current = current.getLeftChild();
if (current == null) {
parent.setLeftChild(node);
return;
}
} else { //move on right?
current = current.getRightChild();
if (current == null) {
parent.setRightChild(node);
return;
}
}
}
}
}
public Node find(int key) {
Node current = root;
while (current.getData() != key) {
if (key < current.getData()) {
current = current.getLeftChild();
} else {
current = current.getRightChild();
}
if (current == null) {
return null;
}
}
return current;
}
public void delete(int id) {
}
public Node maximum() {
Node current, last = null;
current = root;
while (current != null) {
last = current;
current = current.getRightChild();
}
return last;
}
public Node minimum() {
Node current, last = null;
current = root;
while (current != null) {
last = current;
current = current.getLeftChild();
}
return last;
}
private void preOrder(Node localRoot) {
if (localRoot == null) {
return;
}
System.out.println(localRoot.getData());
preOrder(localRoot.getLeftChild());
preOrder(localRoot.getRightChild());
}
/**
* Algorithm Inorder(tree)
* 1. Traverse the left subtree, i.e., call Inorder(left-subtree)
* 2. Visit the root.
* 3. Traverse the right subtree, i.e., call Inorder(right-subtree)
* In case of binary search trees (BST),
* Inorder traversal gives nodes in non-decreasing order.
* To get nodes of BST in non-increasing order,
* a variation of Inorder traversal
* where Inorder itraversal s reversed, can be used.
* Example: Inorder traversal for the above given figure is 4 2 5 1 3.
* @param localRoot
*/
private void inOrder(Node localRoot) {
if (localRoot == null) {
return;
}
inOrder(localRoot.getLeftChild());
System.out.println(localRoot.getData());
inOrder(localRoot.getRightChild());
}
private void postOrder(Node localRoot) {
if (localRoot == null) {
return;
}
postOrder(localRoot.getLeftChild());
postOrder(localRoot.getRightChild());
System.out.println(localRoot.getData());
}
}
|
package com.perpetumobile.bit.http;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.webkit.CookieSyncManager;
import com.perpetumobile.bit.util.Logger;
import com.perpetumobile.bit.util.TaskCallback;
import com.perpetumobile.bit.util.ThreadPoolManager;
import com.perpetumobile.bit.util.Util;
/**
* @author Zoran Dukic
*
*/
public class HttpManager {
static private HttpManager instance = new HttpManager();
static public HttpManager getInstance(){ return instance; }
static private Logger logger = new Logger(HttpManager.class);
static final public String NEW_LINE = System.getProperty("line.separator");
private HttpManager() {
CookieHandler.setDefault(new WebkitCookieManager());
}
protected void readResponse(HttpURLConnection c, HttpResponseDocument result) throws IOException {
int code = c.getResponseCode();
result.setStatusCode(code);
result.setContentType(c.getContentType());
result.setContentLenght(c.getContentLength());
result.setHeaderFields(c.getHeaderFields());
InputStream stream = null;
if(code < 400) {
stream = c.getInputStream();
} else {
stream = c.getErrorStream();
}
// read stream
StringBuilder buf = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
while ((inputLine = in.readLine()) != null) {
buf.append(inputLine);
buf.append(NEW_LINE);
}
result.setPageSource(buf.toString());
in.close();
// sync cookies
CookieSyncManager.getInstance().sync();
}
protected void readImageResponse(HttpURLConnection c, HttpResponseDocument result) throws IOException {
int code = c.getResponseCode();
if(code != 200) {
readResponse(c, result);
} else {
result.setStatusCode(code);
result.setContentType(c.getContentType());
result.setContentLenght(c.getContentLength());
result.setHeaderFields(c.getHeaderFields());
BufferedInputStream in = new BufferedInputStream(c.getInputStream());
Bitmap bitmap = BitmapFactory.decodeStream(in);
result.setBitmap(bitmap);
in.close();
// sync cookies
CookieSyncManager.getInstance().sync();
}
}
protected void setHeaderFields(HttpURLConnection c, Map<String, List<String>> headerFields) {
if(headerFields != null) {
Set<Entry<String, List<String>>> set = headerFields.entrySet();
for(Entry<String, List<String>> e : set) {
String name = e.getKey();
List<String> values = e.getValue();
for(String v : values) {
c.setRequestProperty(name, v);
}
}
}
}
protected HttpResponseDocument getImpl(HttpRequest httpRequest) {
HttpResponseDocument result = new HttpResponseDocument(httpRequest.getUrl());
HttpURLConnection c = null;
try {
URL u = new URL(httpRequest.getUrl());
c = (HttpURLConnection) u.openConnection();
httpRequest.prepareConnection(c);
setHeaderFields(c, httpRequest.getHeaderFields());
// read response
if(httpRequest.method == HttpMethod.GET_IMAGE) {
readImageResponse(c, result);
} else {
readResponse(c, result);
}
} catch (Exception e) {
logger.error("HttpManager.getImpl exception", e);
} finally {
if(c != null) c.disconnect();
}
return result;
}
protected HttpResponseDocument postImpl(HttpRequest httpRequest) {
HttpResponseDocument result = new HttpResponseDocument(httpRequest.getUrl());
HttpURLConnection c = null;
try {
URL u = new URL(httpRequest.getUrl());
c = (HttpURLConnection) u.openConnection();
httpRequest.prepareConnection(c);
setHeaderFields(c, httpRequest.getHeaderFields());
c.setRequestMethod("POST");
// write content
if(!Util.nullOrEmptyString(httpRequest.getContent())) {
c.setDoOutput(true);
c.setChunkedStreamingMode(0);
c.setRequestProperty("content-type", httpRequest.getContentType());
c.setRequestProperty("content-length", Integer.toString(httpRequest.getContent().length()));
BufferedOutputStream out = new BufferedOutputStream(c.getOutputStream());
out.write(httpRequest.getContent().getBytes());
out.close();
}
// read response
if(httpRequest.method == HttpMethod.POST_IMAGE) {
readImageResponse(c, result);
} else {
readResponse(c, result);
}
} catch (Exception e) {
logger.error("HttpManager.postImpl exception", e);
} finally {
if(c != null) c.disconnect();
}
return result;
}
public HttpResponseDocument executeImpl(HttpRequest httpRequest) {
HttpResponseDocument result = null;
switch(httpRequest.method) {
case GET:
result = getImpl(httpRequest);
break;
case POST:
result = postImpl(httpRequest);
break;
case GET_IMAGE:
result = getImpl(httpRequest);
break;
case POST_IMAGE:
result = postImpl(httpRequest);
break;
}
return result;
}
/**
* Operation is executed in a Bit Service Thread.
* Blocking mode: Current thread is waiting for operation to complete and return result.
*/
public HttpResponseDocument executeSync(HttpRequest httpRequest) {
return executeSync(httpRequest, null);
}
/**
* Operation is executed in a Bit Service Thread if threadPoolManagerConfigName is not provided.
* Blocking mode: Current thread is waiting for operation to complete and return result.
*/
public HttpResponseDocument executeSync(HttpRequest httpRequest, String threadPoolManagerConfigName) {
HttpTask task = new HttpTask();
task.setHttpRequest(httpRequest);
try {
if(Util.nullOrEmptyString(threadPoolManagerConfigName)) {
ThreadPoolManager.getInstance().run(ThreadPoolManager.BIT_SERVICE_THREAD_POOL_MANAGER_CONFIG_NAME, task);
} else {
ThreadPoolManager.getInstance().run(threadPoolManagerConfigName, task);
}
task.isDone();
} catch (Exception e) {
logger.error("HttpManager.execute exception", e);
}
return task.getResult();
}
/**
* Operation is executed in a Bit Service Thread.
* Non-Blocking mode: Current thread is NOT waiting for operation to complete.
*/
public void execute(TaskCallback<HttpTask> callback, HttpRequest httpRequest) {
execute(callback, httpRequest, null);
}
/**
* Operation is executed in a Bit Service Thread if threadPoolManagerConfigName is not provided.
* Non-Blocking mode: Current thread is NOT waiting for operation to complete.
*/
public void execute(TaskCallback<HttpTask> callback, HttpRequest httpRequest, String threadPoolManagerConfigName) {
HttpTask task = new HttpTask();
task.setHttpRequest(httpRequest);
task.setCallback(callback);
try {
if(Util.nullOrEmptyString(threadPoolManagerConfigName)) {
ThreadPoolManager.getInstance().run(ThreadPoolManager.BIT_SERVICE_THREAD_POOL_MANAGER_CONFIG_NAME, task);
} else {
ThreadPoolManager.getInstance().run(threadPoolManagerConfigName, task);
}
} catch (Exception e) {
logger.error("HttpManager.execute exception", e);
}
}
}
|
package com.tactfactory.harmony;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.regex.Pattern;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import com.google.common.base.Strings;
import com.tactfactory.harmony.command.questionnary.Question;
import com.tactfactory.harmony.command.questionnary.Questionnary;
import com.tactfactory.harmony.meta.ApplicationMetadata;
import com.tactfactory.harmony.plateforme.BaseAdapter;
import com.tactfactory.harmony.plateforme.TargetPlatform;
import com.tactfactory.harmony.plateforme.android.AndroidAdapter;
import com.tactfactory.harmony.plateforme.ios.IosAdapter;
import com.tactfactory.harmony.plateforme.winphone.WinphoneAdapter;
import com.tactfactory.harmony.utils.ConsoleUtils;
/**
* The project context is the specific configuration of your project.
*
* You can find :
* <ul><li>Project name;</li>
* <li>Global name space;</li>
* <li>SDK version</li>
* </ul>
*/
public final class ProjectContext {
// DEMO/TEST MODE
/** Default project name. */
private final static String PRJ_NAME = "demact";
/** Default project NameSpace. */
private final static String PRJ_NS =
"com.tactfactory.harmony.test.demact";
/**
* Constructor.
*/
public ProjectContext() { }
/**
* Extract Project NameSpace from AndroidManifest file.
*
* @param manifest Manifest File
* @return Project Name Space
*/
public static void loadNameSpaceFromManifest(final File manifest) {
String result = null;
SAXBuilder builder;
Document doc;
if (manifest.exists()) {
// Make engine
builder = new SAXBuilder();
try {
// Load XML File
doc = builder.build(manifest);
// Load Root element
final Element rootNode = doc.getRootElement();
// Get Name Space from package declaration
result = rootNode.getAttributeValue("package");
result = result.replaceAll("\\.", HarmonyContext.DELIMITER);
} catch (final JDOMException e) {
ConsoleUtils.displayError(e);
} catch (final IOException e) {
ConsoleUtils.displayError(e);
}
}
if (result != null) {
ApplicationMetadata.INSTANCE.setName(result.trim());
}
}
/**
* Extract Project Name from configuration file.
*
* @param config Configuration file
* @return Project Name Space
*/
public static void loadProjectNameFromConfig(final File config) {
String result = null;
SAXBuilder builder;
Document doc;
if (config.exists()) {
// Make engine
builder = new SAXBuilder();
try {
// Load XML File
doc = builder.build(config);
// Load Root element
final Element rootNode = doc.getRootElement();
result = rootNode.getAttribute("name").getValue();
} catch (final JDOMException e) {
ConsoleUtils.displayError(e);
} catch (final IOException e) {
ConsoleUtils.displayError(e);
}
}
if (result != null) {
ApplicationMetadata.INSTANCE.setName(result.trim());
}
}
private HashMap<TargetPlatform, BaseAdapter> adapters =
new HashMap<TargetPlatform, BaseAdapter>();
public ArrayList<BaseAdapter> getAdapters() {
return new ArrayList<BaseAdapter>(this.adapters.values());
}
public BaseAdapter getAdapter(TargetPlatform platform) {
return this.adapters.get(platform);
}
public void detectPlatforms() {
final File dir = new File(Harmony.getProjectPath());
final String[] files = dir.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
final ArrayList<String> directories =
new ArrayList<String>(Arrays.asList(files));
Collections.sort(directories);
for (final String directory : directories) {
switch (TargetPlatform.parse(directory)) {
case ANDROID:
this.adapters.put(
TargetPlatform.ANDROID,
new AndroidAdapter());
break;
case IPHONE :
case IPAD:
this.adapters.put(
TargetPlatform.IPHONE,
new IosAdapter());
break;
case RIM:
//this.adapters.put(TargetPlatform.RIM, new RimAdapter());
break;
case WEB:
//this.adapters.put(TargetPlatform.WEB, new WebAdapter());
break;
case WINPHONE:
this.adapters.put(
TargetPlatform.WINPHONE,
new WinphoneAdapter());
break;
default:
break;
}
}
}
/**
* Prompt Project Name to the user.
*
* @param arguments The console arguments passed by the user
*/
public static void initProjectName(HashMap<String, String> arguments) {
if (Strings.isNullOrEmpty(ApplicationMetadata.INSTANCE.getName())) {
final String KEY = "name";
Question question = new Question();
question.setParamName(KEY, "n");
question.setQuestion("Please enter your Project Name [%s]:",
PRJ_NAME);
question.setDefaultValue(PRJ_NAME);
Questionnary questionnary = new Questionnary(arguments);
questionnary.addQuestion(KEY, question);
questionnary.launchQuestionnary();
ApplicationMetadata.INSTANCE.setName(questionnary.getAnswer(KEY));
}
}
/**
* Prompt Project Name Space to the user.
*
* @param arguments The console arguments passed by the user
*/
public static void initProjectNameSpace(HashMap<String, String> arguments) {
if (Strings.isNullOrEmpty(
ApplicationMetadata.INSTANCE.getProjectNameSpace())) {
final String KEY = "namespace";
String result = null;
Question question = new Question();
question.setParamName(KEY, "ns");
question.setQuestion("Please enter your Project NameSpace [%s]:",
PRJ_NS);
question.setDefaultValue(PRJ_NS);
Questionnary questionnary = new Questionnary(arguments);
questionnary.addQuestion(KEY, question);
boolean good = false;
while (!good) {
questionnary.launchQuestionnary();
String nameSpace = questionnary.getAnswer(KEY);
if (Strings.isNullOrEmpty(nameSpace)) {
good = true;
} else {
final String namespaceForm =
"^(((([a-z0-9_]+)\\.)*)([a-z0-9_]+))$";
if (Pattern.matches(namespaceForm, nameSpace)) {
result = nameSpace.trim();
good = true;
} else {
ConsoleUtils.display(
"You can't use special characters "
+ "except '.' in the NameSpace.");
question.setParamName(null);
question.setShortParamName(null);
}
}
}
if (result != null) {
ApplicationMetadata.INSTANCE.setProjectNameSpace(
result.replaceAll("\\.", HarmonyContext.DELIMITER).trim());
}
}
}
}
|
/* Anagram Game Application */
package com.toy.anagrams.lib;
/**
* Implementation of the logic for the Anagram Game application.
*/
final class StaticWordLibrary extends WordLibrary {
private static final String[] WORD_LIST = {
"abstraction",
"ambiguous",
"arithmetic",
"backslash",
"bitmap",
"circumstance",
"combination",
"consequently",
"consortium",
"decrementing",
"dependency",
"disambiguate",
"dynamic",
"encapsulation",
"equivalent",
"expression",
"facilitate",
"fragment",
"hexadecimal",
"implementation",
"indistinguishable",
"inheritance",
"internet",
"java",
"localization",
"microprocessor",
"navigation",
"optimization",
"parameter",
"patrick",
"pickle",
"polymorphic",
"rigorously",
"simultaneously",
"specification",
"structure",
"lexical",
"likewise",
"management",
"manipulate",
"mathematics",
"hotjava",
"vertex",
"unsigned",
"traditional",
"japan"
};
private static final String[] SCRAMBLED_WORD_LIST = {
"batsartcoin",
"maibuguos",
"ratimhteci",
"abkclssha",
"ibmtpa",
"iccrmutsnaec",
"ocbmnitaoni",
"ocsnqeeutnyl",
"ocsnroitmu",
"edrcmeneitgn",
"edepdnneyc",
"idasbmgiauet",
"ydanicm",
"neacsplutaoni",
"qeiuaveltn",
"xerpseisno",
"aficilatet",
"rfgaemtn",
"ehaxedicalm",
"milpmeneatitno",
"niidtsniugsiahleb",
"niehiratcen",
"nietnret",
"ajav",
"olacilazitno",
"imrcpoorecssro",
"anivagitno",
"poitimazitno",
"aparemert",
"aprtcki",
"ipkcel",
"opylomprich",
"irogorsuyl",
"isumtlnaoesuyl",
"psceficitaoni",
"tsurtcreu",
"elixalc",
"ilekiwse",
"amanegemtn",
"aminupalet",
"amhtmetacsi",
"ohjtvaa",
"evtrxe",
"nuisngde",
"rtdatioialn",
"napja"
};
final static WordLibrary DEFAULT = new StaticWordLibrary();
/**
* Singleton class.
*/
private StaticWordLibrary() {
}
/**
* Gets the word at a given index.
* @param idx index of required word
* @return word at that index in its natural form
*/
public String getWord(int idx) {
return WORD_LIST[idx];
}
/**
* Gets the word at a given index in its scrambled form.
* @param idx index of required word
* @return word at that index in its scrambled form
*/
public String getScrambledWord(int idx) {
return SCRAMBLED_WORD_LIST[idx];
}
/**
* Gets the number of words in the library.
* @return the total number of plain/scrambled word pairs in the library
*/
public int getSize() {
return WORD_LIST.length;
}
/**
* Checks whether a user's guess for a word at the given index is correct.
* @param idx index of the word guessed
* @param userGuess the user's guess for the actual word
* @return true if the guess was correct; false otherwise
*/
public boolean isCorrect(int idx, String userGuess) {
return userGuess.equals(getWord(idx));
}
}
|
package com.translationdata.p000;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.translationdata.JUnitTests.FastTest;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
/** Strategy: Spring XML configuration. */
@Category(FastTest.class)
@RunWith(Parameterized.class)
public class P001_UnitTest {
String resourcePath;
String fileName;
int upperLimit;
int result;
final P001_Factory p001_Factory = P001_Factory.getFactory();
@Parameters
public static Collection<Object []> getTestData() {
Object [][] data = {
{1_000, 233168},
{10_000, 23331668 }
};
return Arrays.asList(data);
}
public P001_UnitTest(int upperLimit, int result) {
this.upperLimit = upperLimit;
this.result = result;
}
@Test(timeout=1000)
public void SumOfMultiplesOf3And5Below1000() {
final int sumOfMultiples = p001_Factory.getMultiplesOf3And5().multiplesOf3And5(upperLimit);
System.out.printf("P001: multiplesOf3And5(%d) = %s%n", upperLimit, upperLimit, sumOfMultiples);
assertThat( "Incorrect sum of multiples of 3 or 5 below 1,000", sumOfMultiples, is(result) );
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Game {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
Person p = new Person(3, 3);
Maze maze = new Maze(
"",
"........",
".....",
"....",
".....",
"........X",
""
);
System.out.println("Welcome to the maze. ");
while (maze.at(p.x, p.y) != 'X') {
System.out.println();
// This prints the map.
for (int j = 2; j >= -2; j
for (int i = -2; i <= 2; i++) {
if (i == 0 && j == 0)
System.out.print("");
else
System.out.print(maze.at(p.x + i, p.y + j));
}
System.out.println();
}
// This prints where you can go.
List<String> dir = new ArrayList<>();
if (!maze.isWall(p.x - 1, p.y)) dir.add("(w)est");
if (!maze.isWall(p.x + 1, p.y)) dir.add("(e)ast");
if (!maze.isWall(p.x, p.y + 1)) dir.add("(n)north");
if (!maze.isWall(p.x, p.y - 1)) dir.add("(s)outh");
System.out.println("you can go " + dir + " x: " + p.x + " y: " + p.y);
System.out.println("Where would you like to go?");
String ans = in.nextLine().toLowerCase();
switch (ans) {
case "w":
case "west":
if (!maze.isWall(p.x - 1, p.y))
p.x
else
System.out.println("You can't go west");
break;
case "e":
case "east":
if (!maze.isWall(p.x + 1, p.y))
p.x++;
else
System.out.println("That's too scary !!!");
break;
case "n":
case "north":
if (!maze.isWall(p.x, p.y + 1))
p.y++;
else
System.out.println("no can do");
break;
case "s":
case "south":
if (!maze.isWall(p.x, p.y - 1))
p.y
else
System.out.println("Try again");
break;
default:
System.out.println("I don't know how to " + (ans));
}
}
System.out.println("Good choice, you escape the maze");
}
}
class Person {
int x, y;
public Person(int x, int y) {
this.x = x;
this.y = y;
}
}
class Maze {
String[] layout;
Maze(String... layout) {
this.layout = layout;
}
public char at(int x, int y) {
if (y < 0 || y >= layout.length || x < 0 || x >= layout[layout.length - 1 - y].length())
return '
return layout[layout.length - 1 - y].charAt(x);
}
public boolean isWall(int x, int y) {
return (at(x, y) & 0x2580) == 0x2500;
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import java.net.URISyntaxException;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
Object r = new SignUpServer();
Object r1 = new DefaultServer();
Object r2 = new MapServer();
Object r3 = new Userinfo();
get("/hello", (req, res) -> "Hello World");
// get("/", (request, response) -> {
// Map<String, Object> attributes = new HashMap<>();
// attributes.put("message", "Hello World!!!");
// return new ModelAndView(attributes, "index.ftl");
// }, new FreeMarkerEngine());
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import CLOPE.CLOPEClusterer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;
import com.google.gson.Gson;
import to.ClusterTO;
import to.DataSetTo;
import java.util.HashMap;
import java.util.List;
public class Main extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
getServletConfig().getServletContext()
.getRequestDispatcher("/home.jsp")
.forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
Gson gson = new Gson();
StringBuilder sb = new StringBuilder();
String s;
while ((s = req.getReader().readLine()) != null) {
sb.append(s);
}
DataSetTo dataTo = (DataSetTo) gson.fromJson(sb.toString(), DataSetTo.class);
CLOPEClusterer clusterer = new CLOPEClusterer();
clusterer.setRepulsion(dataTo.getRepulsion());
clusterer.setMinClusterSize(dataTo.getMinSize());
List<ClusterTO> clusters = null;
try {
clusters = clusterer.buildClusterer(dataTo.getData());
} catch (Exception e) {
e.printStackTrace();
}
String result = gson.toJson(clusters);
resp.getWriter().print(result);
}
private void showHome(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
resp.getWriter().print("Hello! It's a CLOPE clustering app\n Input example:\n" +
"{\n" +
" \"repulsion\": 2,\n" +
" \"minSize\": 1,\n" +
" \"data\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"items\": [5, 6]\n" +
" },\n" +
" {\n" +
" \"id\": 2,\n" +
" \"items\": [7, 5, 38]\n" +
" },\n" +
" {\n" +
" \"id\": 17,\n" +
" \"items\": [37, 53, 6,8]\n" +
" },\n" +
"{\n" +
" \"id\": 15,\n" +
" \"items\": [37, 53, 6]\n" +
" }\n" +
" ]\n" +
"}" + "\n Output example: " +
"[{\"clusterId\":7,\"items\":[1]},{\"clusterId\":8,\"items\":[2]},{\"clusterId\":9,\"items\":[17,15]}]");
}
public static void main(String[] args) throws Exception {
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import static javax.measure.unit.SI.KILOGRAM;
import javax.measure.quantity.Mass;
import org.jscience.physics.model.RelativisticModel;
import org.jscience.physics.amount.Amount;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/hello", (req, res) -> {
RelativisticModel.select();
Amount<Mass> m = Amount.valueOf("12 GeV").to(KILOGRAM);
return "E=mc^2: 12 GeV = " + m.toString();
});
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
//Alex's stuff
import java.io.BufferedReader;
import java.lang.StringBuffer;
import org.json.JSONException;
import org.json.JSONObject;
public class Main extends HttpServlet
{
private static final String TABLE_CREATION = "CREATE TABLE Persons (targetPhoneNumber int, description varchar(255), describerPhoneNumber int)";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException
{
showHome(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// Read in request body (which should be a JSON)
StringBuffer jb = new StringBuffer();
String line = null;
try
{
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
{
jb.append(line);
}
}
catch (Exception e)
{
}
// Parse the request body into a JSON object
try
{
JSONObject jsonObject = new JSONObject(jb.toString());
if (req.getRequestURI().endsWith("/addDescriptions"))
{
addDescriptions(req, resp, jsonObject);
}
}
catch (JSONException e)
{
// crash and burn
System.out.println("JSON PARSING FAILING. WHY.");
}
}
private void addDescriptions(HttpServletRequest req, HttpServletResponse resp,
JSONObject requestBody) throws ServletException, IOException
{
resp.getWriter().print("We are adding descriptions!");
}
private void showHome(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.getWriter().print("Hello from Java!");
}
private Connection getConnection() throws URISyntaxException, SQLException
{
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
public static void main(String[] args) throws Exception
{
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.io.*;
import java.util.*;
import freemarker.template.*;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
import static javax.measure.unit.SI.KILOGRAM;
import javax.measure.quantity.Mass;
import org.jscience.physics.model.RelativisticModel;
import org.jscience.physics.amount.Amount;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
//get("/hello", (req, res) -> "Hello World");
get("/hello", (req, res) -> {
RelativisticModel.select();
Amount<Mass> m = Amount.valueOf("12 GeV").to(KILOGRAM);
// return "E=mc^2: 12 GeV = " + m.toString();
return req.host();
});
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("blogTitle", "FitBuddy");
attributes.put("message", "FitBuddy is a personalized web application, in which users are going to be able to create account and interact with on a daily basis. Each day, the user is going to enter his/hers calorie intake, activities, the type and time, and their sleep into the system. Therefore, they can keep track of their health status. This information is specifically useful for the trainers. They can keep track of their clients and based on these information, the trainers can give the clients a personalized excercise and diet plan");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
/* try{
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Map<String, Object> map = new HashMap<>();
map.put("blogTitle", "TEST");
map.put("message", "FitBuddy is a personalized web application, in which users are going to be able to create account and interact with on a daily basis. Each day, the user is going to enter his/hers calorie intake, activities, the type and time, and their sleep into the system. Therefore, they can keep track of their health status. This information is specifically useful for the trainers. They can keep track of their clients and based on these information, the trainers can give the clients a personalized excercise and diet plan");
cfg.setDirectoryForTemplateLoading(new File("/Users/setaresarachi/full-stack-web-project-SetarehSarachi/src/main/resources/public"));
Template template = cfg.getTemplate("index.ftl");
Writer out = new OutputStreamWriter(System.out);
template.process(map, out);
}
catch (IOException e){
e.printStackTrace();
}catch (TemplateException e) {
e.printStackTrace();
}
*/
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import static javax.measure.unit.SI.KILOGRAM;
import javax.measure.quantity.Mass;
import org.jscience.physics.model.RelativisticModel;
import org.jscience.physics.amount.Amount;
import com.heroku.sdk.jdbc.DatabaseUrl;
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/hello", (req, res) -> {
RelativisticModel.select();
String energy = System.getenv().get("ENERGY");
Amount<Mass> m = Amount.valueOf(energy).to(KILOGRAM);
return "E=mc^2: " + energy + " = " + m.toString();
});
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
get("/api/invlist", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM inventory");
while ( rs.next() ) {
String owner = rs.getString("owner");
String manufacturer = rs.getString("manufacturer");
System.out.println( "owner = " + owner );
System.out.println( "manufacturer = " + manufacturer );
System.out.println();
}
rs.close();
stmt.close();
connection.close();
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
package main.java;
import java.awt.EventQueue;
import main.python.PyInterpreter;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HomeFrame frame = new HomeFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** Give the name of the .py file WITHOUT THE EXTENSION and it will launch the python file
*
* @param fileName Name of the .py file
*/
public void launchPyFile(String fileName) {
PyInterpreter.execPyFile(fileName);
}
}
|
package com.apigee.proxywriter;
/**
*
* The GenerateProxy program generates a Apigee API Proxy from a WSDL Document. The generated proxy can be
* passthru or converted to an API (REST/JSON over HTTP).
*
* How does it work?
* At a high level, here is the logic implemented for SOAP-to-API:
* Step 1: Parse the WSDL
* Step 2: Build a HashMap with
* Step 2a: Generate SOAP Request template for each operation
* Step 2b: Convert SOAP Request to JSON Request template without the SOAP Envelope
* Step 3: Create the API Proxy folder structure
* Step 4: Copy policies from the standard template
* Step 5: Create the Extract Variables and Assign Message Policies
* Step 5a: If the operation is interpreted as a POST (create), then obtain JSON Paths from JSON request template
* Step 5b: Use JSONPaths in the Extract Variables
*
* At a high level, here is the logic implemented for SOAP-passthru:
* Step 1: Parse the WSDL
* Step 2: Copy policies from the standard template
*
*
* @author Nandan Sridhar
* @version 0.1
* @since 2016-05-20
*/
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import com.apigee.proxywriter.exception.*;
import com.apigee.utils.*;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.validator.routines.UrlValidator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import com.apigee.utils.Options.Multiplicity;
import com.apigee.utils.Options.Separator;
import com.apigee.xsltgen.Rule;
import com.apigee.xsltgen.RuleSet;
import com.predic8.schema.All;
import com.predic8.schema.BuiltInSchemaType;
import com.predic8.schema.Choice;
import com.predic8.schema.ComplexContent;
import com.predic8.schema.ComplexType;
import com.predic8.schema.Derivation;
import com.predic8.schema.GroupRef;
import com.predic8.schema.ModelGroup;
import com.predic8.schema.Schema;
import com.predic8.schema.SchemaComponent;
import com.predic8.schema.Sequence;
import com.predic8.schema.SimpleContent;
import com.predic8.schema.TypeDefinition;
import com.predic8.soamodel.XMLElement;
import com.predic8.wsdl.AbstractSOAPBinding;
import com.predic8.wsdl.Binding;
import com.predic8.wsdl.BindingOperation;
import com.predic8.wsdl.Definitions;
import com.predic8.wsdl.Operation;
import com.predic8.wsdl.Part;
import com.predic8.wsdl.PortType;
import com.predic8.wsdl.Service;
import com.predic8.wsdl.WSDLParser;
import com.predic8.wstool.creator.RequestTemplateCreator;
import com.predic8.wstool.creator.SOARequestCreator;
import groovy.xml.MarkupBuilder;
import groovy.xml.QName;
public class GenerateProxy {
private static final Logger LOGGER = Logger.getLogger(GenerateProxy.class.getName());
private static final ConsoleHandler handler = new ConsoleHandler();
public static String OPSMAPPING_TEMPLATE = "/templates/opsmap/opsmapping.xml";
private static String SOAP2API_XSL = "";
private static final List<String> primitiveTypes = Arrays.asList(new String[] { "int", "string", "boolean",
"decimal", "float", "double", "duration", "dateTime", "time", "date", "long", "gYearMonth", "gYear",
"gMonthDay", "gDay", "gMonth", "hexBinary", "base64Binary", "anyURI", "QName", "NOTATION" });
private final String soap11Namespace = " xmlns:soapenv=\"http:
private final String soap12Namespace = " xmlns:soapenv=\"http:
private static final List<String> blackListedNamespaces = Arrays.asList("http://schemas.xmlsoap.org/wsdl/",
"http://schemas.xmlsoap.org/wsdl/soap/");
private static final String emptySoap12 = "<?xml version=\"1.0\"?><soapenv:Envelope xmlns:soapenv=\"http:
private static final String emptySoap11 = "<?xml version=\"1.0\"?><soapenv:Envelope xmlns:soapenv=\"http:
private static final String SOAP2API_APIPROXY_TEMPLATE = "/templates/soap2api/apiProxyTemplate.xml";
private static final String SOAP2API_PROXY_TEMPLATE = "/templates/soap2api/proxyDefault.xml";
private static final String SOAP2API_TARGET_TEMPLATE = "/templates/soap2api/targetDefault.xml";
private static final String SOAP2API_EXTRACT_TEMPLATE = "/templates/soap2api/ExtractPolicy.xml";
private static final String SOAP2API_ASSIGN_TEMPLATE = "/templates/soap2api/AssignMessagePolicy.xml";
private static final String SOAP2API_XSLT11POLICY_TEMPLATE = "/templates/soap2api/add-namespace11.xml";
private static final String SOAP2API_XSLT11_TEMPLATE = "/templates/soap2api/add-namespace11.xslt";
private static final String SOAP2API_XSLT12POLICY_TEMPLATE = "/templates/soap2api/add-namespace12.xml";
private static final String SOAP2API_XSLT12_TEMPLATE = "/templates/soap2api/add-namespace12.xslt";
private static final String SOAP2API_JSON_TO_XML_TEMPLATE = "/templates/soap2api/json-to-xml.xml";
private static final String SOAP2API_ADD_SOAPACTION_TEMPLATE = "/templates/soap2api/add-soapaction.xml";
//private static final String SOAP2API_JSPOLICY_TEMPLATE = "/templates/soap2api/root-wrapper.xml";
private static final String SOAPPASSTHRU_APIPROXY_TEMPLATE = "/templates/soappassthru/apiProxyTemplate.xml";
private static final String SOAPPASSTHRU_PROXY_TEMPLATE = "/templates/soappassthru/proxyDefault.xml";
private static final String SOAPPASSTHRU_TARGET_TEMPLATE = "/templates/soappassthru/targetDefault.xml";
private static final String SOAP11_CONTENT_TYPE = "text/xml; charset=utf-8";// "text/xml;
// charset=utf-8";
private static final String SOAP12_CONTENT_TYPE = "application/soap+xml";
private static final String SOAP11_PAYLOAD_TYPE = "text/xml";// "text/xml";
private static final String SOAP12_PAYLOAD_TYPE = "application/soap+xml";
private static final String SOAP11 = "http://schemas.xmlsoap.org/soap/envelope/";
private static final String SOAP12 = "http:
// set this to true if SOAP passthru is needed
private boolean PASSTHRU;
// set this to true if all operations are to be consumed via POST verb
private boolean ALLPOST;
// set this to true if oauth should be added to the proxy
private boolean OAUTH;
// set this to true if apikey should be added to the proxy
private boolean APIKEY;
// enable this flag if api key based quota is enabled
private boolean QUOTAAPIKEY;
// enable this flag if oauth based quota is enabled
private boolean QUOTAOAUTH;
// enable this flag is cors is enabled
private boolean CORS;
// enable this flag if wsdl is of rpc style
private boolean RPCSTYLE;
// enable this flag if user sets desc
private boolean DESCSET;
// fail safe measure when schemas are heavily nested or have 100s of elements
private boolean TOO_MANY;
private String targetEndpoint;
private String soapVersion;
private String serviceName;
private String portName;
private String basePath;
private String proxyName;
private String opsMap;
private String selectedOperationsJson;
private List<String> vHosts;
private SelectedOperations selectedOperations;
private OpsMap operationsMap;
// default build folder is ./build
private String buildFolder;
// Each row in this Map has the key as the operation name. The operation
// name has SOAP Request
// and JSON Equivalent of SOAP (without the SOAP Envelope) as values.
// private Map<String, KeyValue<String, String>> messageTemplates;
private Map<String, APIMap> messageTemplates;
// tree to hold elements to build an xpath
private HashMap<Integer, String> xpathElement;
// xpath tree element level
private int level;
// List of rules to generate XSLT
private ArrayList<Rule> ruleList = new ArrayList<Rule>();
public Map<String, String> namespace = new LinkedHashMap<String, String>();
// initialize the logger
static {
LOGGER.setUseParentHandlers(false);
Handler[] handlers = LOGGER.getHandlers();
for (Handler handler : handlers) {
if (handler.getClass() == ConsoleHandler.class)
LOGGER.removeHandler(handler);
}
handler.setFormatter(new SimpleFormatter());
LOGGER.addHandler(handler);
}
public GenerateProxy() {
// initialize hashmap
messageTemplates = new HashMap<String, APIMap>();
xpathElement = new HashMap<Integer, String>();
operationsMap = new OpsMap();
selectedOperations = new SelectedOperations();
vHosts = new ArrayList<String>();
vHosts.add("default");
buildFolder = null;
soapVersion = "SOAP12";
ALLPOST = false;
PASSTHRU = false;
OAUTH = false;
APIKEY = false;
QUOTAAPIKEY = false;
QUOTAOAUTH = false;
CORS = false;
RPCSTYLE = false;
DESCSET = false;
basePath = null;
TOO_MANY = false;
level = 0;
}
public void setSelectedOperationsJson(String json) throws Exception {
selectedOperations.parseSelectedOperations(json);
}
public void setDesc(boolean descset) {
DESCSET = descset;
}
public void setCORS(boolean cors) {
CORS = cors;
}
public void setBasePath(String bp) {
basePath = bp;
}
public void setQuotaAPIKey(boolean quotaAPIKey) {
QUOTAAPIKEY = quotaAPIKey;
}
public void setQuotaOAuth(boolean quotaOAuth) {
QUOTAOAUTH = quotaOAuth;
}
public void setAPIKey(boolean apikey) {
APIKEY = apikey;
}
public void setOpsMap(String oMap) {
opsMap = oMap;
}
public void setVHost(String vhosts) {
if (vhosts.indexOf(",") != -1) {
// contains > 1 vhosts
vHosts = Arrays.asList(vhosts.split(","));
} else {
vHosts.remove(0);// remove default
vHosts.add(vhosts);
}
}
public void setAllPost(boolean allPost) {
ALLPOST = allPost;
}
public void setBuildFolder(String folder) {
buildFolder = folder;
}
public void setPassThru(boolean pass) {
PASSTHRU = pass;
}
public void setService(String serv) {
serviceName = serv;
}
public void setPort(String prt) {
portName = prt;
}
public void setOAuth(boolean oauth) {
OAUTH = oauth;
}
private void writeAPIProxy(String proxyDescription) throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
XMLUtils xmlUtils = new XMLUtils();
Document apiTemplateDocument;
if (PASSTHRU) {
apiTemplateDocument = xmlUtils.readXML(SOAPPASSTHRU_APIPROXY_TEMPLATE);
} else {
apiTemplateDocument = xmlUtils.readXML(SOAP2API_APIPROXY_TEMPLATE);
}
LOGGER.finest("Read API Proxy template file");
Node rootElement = apiTemplateDocument.getFirstChild();
NamedNodeMap attr = rootElement.getAttributes();
Node nodeAttr = attr.getNamedItem("name");
nodeAttr.setNodeValue(proxyName);
LOGGER.fine("Set proxy name: " + proxyName);
Node displayName = apiTemplateDocument.getElementsByTagName("DisplayName").item(0);
displayName.setTextContent(proxyName);
LOGGER.fine("Set proxy display name: " + proxyName);
Node description = apiTemplateDocument.getElementsByTagName("Description").item(0);
description.setTextContent(proxyDescription);
LOGGER.fine("Set proxy description: " + proxyDescription);
Node createdAt = apiTemplateDocument.getElementsByTagName("CreatedAt").item(0);
createdAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis()));
Node LastModifiedAt = apiTemplateDocument.getElementsByTagName("LastModifiedAt").item(0);
LastModifiedAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis()));
xmlUtils.writeXML(apiTemplateDocument,
buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml");
LOGGER.fine(
"Generated file: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeSOAP2APIProxyEndpoint(String proxyDescription) throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
XMLUtils xmlUtils = new XMLUtils();
Document proxyDefault = xmlUtils.readXML(SOAP2API_PROXY_TEMPLATE);
Node basePathNode = proxyDefault.getElementsByTagName("BasePath").item(0);
if (basePath != null && basePath.equalsIgnoreCase("") != true) {
basePathNode.setTextContent(basePath);
}
Node httpProxyConnection = proxyDefault.getElementsByTagName("HTTPProxyConnection").item(0);
Node virtualHost = null;
for (String vHost : vHosts) {
virtualHost = proxyDefault.createElement("VirtualHost");
virtualHost.setTextContent(vHost);
httpProxyConnection.appendChild(virtualHost);
}
Document apiTemplateDocument = xmlUtils
.readXML(buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml");
Document extractTemplate = xmlUtils.readXML(SOAP2API_EXTRACT_TEMPLATE);
Document assignTemplate = xmlUtils.readXML(SOAP2API_ASSIGN_TEMPLATE);
//Document jsPolicyTemplate = xmlUtils.readXML(SOAP2API_JSPOLICY_TEMPLATE);
Document addNamespaceTemplate = null;
if (soapVersion.equalsIgnoreCase("SOAP11")) {
addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT11POLICY_TEMPLATE);
} else {
addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT12POLICY_TEMPLATE);
}
Document jsonXMLTemplate = xmlUtils.readXML(SOAP2API_JSON_TO_XML_TEMPLATE);
Document addSoapActionTemplate = xmlUtils.readXML(SOAP2API_ADD_SOAPACTION_TEMPLATE);
Node description = proxyDefault.getElementsByTagName("Description").item(0);
description.setTextContent(proxyDescription);
Node policies = apiTemplateDocument.getElementsByTagName("Policies").item(0);
Node resources = apiTemplateDocument.getElementsByTagName("Resources").item(0);
Node flows = proxyDefault.getElementsByTagName("Flows").item(0);
Node flow;
Node flowDescription;
Node request;
Node response;
Node condition, condition2;
Node step1, step2, step3, step4, step5;
Node name1, name2, name3, name4, name5;
boolean once = false;
// add oauth policies if set
if (OAUTH) {
String oauthPolicy = "verify-oauth-v2-access-token";
String remoOAuthPolicy = "remove-header-authorization";
String quota = "impose-quota-oauth";
// Add policy to proxy.xml
Node policy1 = apiTemplateDocument.createElement("Policy");
policy1.setTextContent(oauthPolicy);
Node policy2 = apiTemplateDocument.createElement("Policy");
policy2.setTextContent(remoOAuthPolicy);
policies.appendChild(policy1);
policies.appendChild(policy2);
Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1);
step1 = proxyDefault.createElement("Step");
name1 = proxyDefault.createElement("Name");
name1.setTextContent(oauthPolicy);
step1.appendChild(name1);
step2 = proxyDefault.createElement("Step");
name2 = proxyDefault.createElement("Name");
name2.setTextContent(remoOAuthPolicy);
step2.appendChild(name2);
preFlowRequest.appendChild(step1);
preFlowRequest.appendChild(step2);
if (QUOTAOAUTH) {
Node policy3 = apiTemplateDocument.createElement("Policy");
policy2.setTextContent(quota);
policies.appendChild(policy3);
step3 = proxyDefault.createElement("Step");
name3 = proxyDefault.createElement("Name");
name3.setTextContent(quota);
step3.appendChild(name3);
preFlowRequest.appendChild(step3);
}
}
if (APIKEY) {
String apiKeyPolicy = "verify-api-key";
String remoAPIKeyPolicy = "remove-query-param-apikey";
String quota = "impose-quota-apikey";
// Add policy to proxy.xml
Node policy1 = apiTemplateDocument.createElement("Policy");
policy1.setTextContent(apiKeyPolicy);
Node policy2 = apiTemplateDocument.createElement("Policy");
policy2.setTextContent(remoAPIKeyPolicy);
policies.appendChild(policy1);
policies.appendChild(policy2);
Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1);
step1 = proxyDefault.createElement("Step");
name1 = proxyDefault.createElement("Name");
name1.setTextContent(apiKeyPolicy);
step1.appendChild(name1);
step2 = proxyDefault.createElement("Step");
name2 = proxyDefault.createElement("Name");
name2.setTextContent(remoAPIKeyPolicy);
step2.appendChild(name2);
preFlowRequest.appendChild(step1);
preFlowRequest.appendChild(step2);
if (QUOTAAPIKEY) {
Node policy3 = apiTemplateDocument.createElement("Policy");
policy2.setTextContent(quota);
policies.appendChild(policy3);
step3 = proxyDefault.createElement("Step");
name3 = proxyDefault.createElement("Name");
name3.setTextContent(quota);
step3.appendChild(name3);
preFlowRequest.appendChild(step3);
}
}
if (CORS) {
Node proxyEndpoint = proxyDefault.getElementsByTagName("ProxyEndpoint").item(0);
Node routeRule = proxyDefault.createElement("RouteRule");
((Element) routeRule).setAttribute("name", "NoRoute");
Node routeCondition = proxyDefault.createElement("Condition");
routeCondition.setTextContent("request.verb == \"OPTIONS\"");
routeRule.appendChild(routeCondition);
proxyEndpoint.appendChild(routeRule);
String cors = "add-cors";
String corsCondition = "request.verb == \"OPTIONS\"";
// Add policy to proxy.xml
Node policy1 = apiTemplateDocument.createElement("Policy");
policy1.setTextContent(cors);
policies.appendChild(policy1);
flow = proxyDefault.createElement("Flow");
((Element) flow).setAttribute("name", "OptionsPreFlight");
flowDescription = proxyDefault.createElement("Description");
flowDescription.setTextContent("OptionsPreFlight");
flow.appendChild(flowDescription);
request = proxyDefault.createElement("Request");
response = proxyDefault.createElement("Response");
condition = proxyDefault.createElement("Condition");
step1 = proxyDefault.createElement("Step");
name1 = proxyDefault.createElement("Name");
name1.setTextContent(cors);
step1.appendChild(name1);
response.appendChild(step1);
condition.setTextContent(corsCondition);
flow.appendChild(request);
flow.appendChild(response);
flow.appendChild(condition);
flows.appendChild(flow);
}
for (Map.Entry<String, APIMap> entry : messageTemplates.entrySet()) {
String operationName = entry.getKey();
APIMap apiMap = entry.getValue();
String buildSOAPPolicy = operationName + "-build-soap";
String extractPolicyName = operationName + "-extract-query-param";
String jsonToXML = operationName + "-json-to-xml";
//String jsPolicyName = operationName + "-root-wrapper";
String jsonToXMLCondition = "(request.header.Content-Type == \"application/json\")";
String httpVerb = apiMap.getVerb();
String resourcePath = apiMap.getResourcePath();
String Condition = "(proxy.pathsuffix MatchesPath \"" + resourcePath + "\") and (request.verb = \""
+ httpVerb + "\")";
String addSoapAction = operationName + "-add-soapaction";
flow = proxyDefault.createElement("Flow");
((Element) flow).setAttribute("name", operationName);
flowDescription = proxyDefault.createElement("Description");
flowDescription.setTextContent(operationName);
flow.appendChild(flowDescription);
request = proxyDefault.createElement("Request");
response = proxyDefault.createElement("Response");
condition = proxyDefault.createElement("Condition");
condition2 = proxyDefault.createElement("Condition");
condition2.setTextContent(jsonToXMLCondition);
step1 = proxyDefault.createElement("Step");
name1 = proxyDefault.createElement("Name");
step2 = proxyDefault.createElement("Step");
name2 = proxyDefault.createElement("Name");
step3 = proxyDefault.createElement("Step");
name3 = proxyDefault.createElement("Name");
step4 = proxyDefault.createElement("Step");
name4 = proxyDefault.createElement("Name");
step5 = proxyDefault.createElement("Step");
name5 = proxyDefault.createElement("Name");
if (httpVerb.equalsIgnoreCase("get")) {
if (apiMap.getJsonBody() != null) {
name1.setTextContent(extractPolicyName);
step1.appendChild(name1);
request.appendChild(step1);
}
step2 = proxyDefault.createElement("Step");
name2 = proxyDefault.createElement("Name");
name2.setTextContent(buildSOAPPolicy);
step2.appendChild(name2);
request.appendChild(step2);
if (apiMap.getJsonBody() != null) {
step3 = proxyDefault.createElement("Step");
name3 = proxyDefault.createElement("Name");
name3.setTextContent("remove-empty-nodes");
Node condition3 = proxyDefault.createElement("Condition");
condition3.setTextContent("(verb == \"GET\")");
step3.appendChild(name3);
step3.appendChild(condition3);
request.appendChild(step3);
}
LOGGER.fine("Assign Message: " + buildSOAPPolicy);
LOGGER.fine("Extract Variable: " + extractPolicyName);
} else {
// add root wrapper policy
/*name3.setTextContent(jsPolicyName);
step3.appendChild(name3);
step3.appendChild(condition2.cloneNode(true));
request.appendChild(step3);*/
// add the root wrapper only once
/*if (!once) {
Node resourceRootWrapper = apiTemplateDocument.createElement("Resource");
resourceRootWrapper.setTextContent("jsc://root-wrapper.js");
resources.appendChild(resourceRootWrapper);
once = true;
}*/
name1.setTextContent(jsonToXML);
step1.appendChild(name1);
step1.appendChild(condition2);
request.appendChild(step1);
// TODO: add condition here to convert to XML only if
// Content-Type is json;
name2.setTextContent(operationName + "-add-namespace");
step2.appendChild(name2);
request.appendChild(step2);
if (apiMap.getOthernamespaces()) {
name4.setTextContent(operationName + "-add-other-namespaces");
step4.appendChild(name4);
request.appendChild(step4);
}
// for soap 1.1 add soap action
if (soapVersion.equalsIgnoreCase("SOAP11")) {
step5 = proxyDefault.createElement("Step");
name5 = proxyDefault.createElement("Name");
name5.setTextContent(addSoapAction);
step5.appendChild(name5);
request.appendChild(step5);
}
}
LOGGER.fine("Condition: " + Condition);
condition.setTextContent(Condition);
flow.appendChild(request);
flow.appendChild(response);
flow.appendChild(condition);
flows.appendChild(flow);
if (httpVerb.equalsIgnoreCase("get")) {
// Add policy to proxy.xml
if (apiMap.getJsonBody() != null) {
Node policy1 = apiTemplateDocument.createElement("Policy");
policy1.setTextContent(extractPolicyName);
policies.appendChild(policy1);
// write Extract Variable Policy
writeSOAP2APIExtractPolicy(extractTemplate, operationName, extractPolicyName);
}
Node policy2 = apiTemplateDocument.createElement("Policy");
policy2.setTextContent(buildSOAPPolicy);
policies.appendChild(policy2);
// write Assign Message Policy
writeSOAP2APIAssignMessagePolicies(assignTemplate, operationName, buildSOAPPolicy,
apiMap.getSoapAction());
} else {
/*Node policy2 = apiTemplateDocument.createElement("Policy");
policy2.setTextContent(jsPolicyName);
policies.appendChild(policy2);*/
//writeRootWrapper(jsPolicyTemplate, operationName, apiMap.getRootElement());
Node policy1 = apiTemplateDocument.createElement("Policy");
policy1.setTextContent(jsonToXML);
policies.appendChild(policy1);
writeJsonToXMLPolicy(jsonXMLTemplate, operationName, apiMap.getRootElement());
Node policy3 = apiTemplateDocument.createElement("Policy");
policy3.setTextContent(operationName + "add-namespace");
policies.appendChild(policy3);
Node resourceAddNamespaces = apiTemplateDocument.createElement("Resource");
resourceAddNamespaces.setTextContent("xsl://" + operationName + "add-namespace.xslt");
resources.appendChild(resourceAddNamespaces);
if (apiMap.getOthernamespaces()) {
Node policy4 = apiTemplateDocument.createElement("Policy");
policy4.setTextContent(operationName + "add-other-namespaces");
policies.appendChild(policy4);
Node resourceAddOtherNamespaces = apiTemplateDocument.createElement("Resource");
resourceAddOtherNamespaces.setTextContent("xsl://" + operationName + "add-other-namespaces.xslt");
resources.appendChild(resourceAddOtherNamespaces);
writeAddNamespace(addNamespaceTemplate, operationName, true);
} else {
writeAddNamespace(addNamespaceTemplate, operationName, false);
}
// for soap 1.1 add soap action
if (soapVersion.equalsIgnoreCase("SOAP11")) {
// Add policy to proxy.xml
Node policy5 = apiTemplateDocument.createElement("Policy");
policy5.setTextContent(addSoapAction);
policies.appendChild(policy5);
writeAddSoapAction(addSoapActionTemplate, operationName, apiMap.getSoapAction());
}
}
}
// Add unknown resource
flow = proxyDefault.createElement("Flow");
((Element) flow).setAttribute("name", "unknown-resource");
flowDescription = proxyDefault.createElement("Description");
flowDescription.setTextContent("Unknown Resource");
flow.appendChild(flowDescription);
request = proxyDefault.createElement("Request");
response = proxyDefault.createElement("Response");
condition = proxyDefault.createElement("Condition");
Node conditionA = proxyDefault.createElement("Condition");
conditionA.setTextContent(
"(verb != \"GET\" AND contentformat == \"application/json\") OR (verb == \"GET\" AND acceptformat !~ \"*/xml\")");
Node conditionB = proxyDefault.createElement("Condition");
conditionB.setTextContent(
"(verb != \"GET\" AND contentformat != \"application/json\") OR (verb == \"GET\" AND acceptformat ~ \"*/xml\")");
step1 = proxyDefault.createElement("Step");
name1 = proxyDefault.createElement("Name");
name1.setTextContent("unknown-resource");
step1.appendChild(name1);
step1.appendChild(conditionA);// added
request.appendChild(step1);
step2 = proxyDefault.createElement("Step");
name2 = proxyDefault.createElement("Name");
name2.setTextContent("unknown-resource-xml");
step2.appendChild(name2);
step2.appendChild(conditionB);
request.appendChild(step2);
flow.appendChild(request);
flow.appendChild(response);
flow.appendChild(condition);
flows.appendChild(flow);
LOGGER.fine(
"Edited proxy xml: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml");
xmlUtils.writeXML(apiTemplateDocument,
buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml");
xmlUtils.writeXML(proxyDefault, buildFolder + File.separator + "apiproxy" + File.separator + "proxies"
+ File.separator + "default.xml");
LOGGER.fine("Edited target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "proxies"
+ File.separator + "default.xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeRootWrapper(Document rootWrapperTemplate, String operationName, String rootElement)
throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator;
XMLUtils xmlUtils = new XMLUtils();
Document jsPolicyXML = xmlUtils.cloneDocument(rootWrapperTemplate);
Node root = jsPolicyXML.getFirstChild();
NamedNodeMap attr = root.getAttributes();
Node nodeAttr = attr.getNamedItem("name");
nodeAttr.setNodeValue(operationName + "-root-wrapper");
Node displayName = jsPolicyXML.getElementsByTagName("DisplayName").item(0);
displayName.setTextContent(operationName + " Root Wrapper");
Node propertyElement = jsPolicyXML.getElementsByTagName("Property").item(0);
propertyElement.setTextContent(rootElement);
xmlUtils.writeXML(jsPolicyXML, targetPath + operationName + "-root-wrapper.xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeAddSoapAction(Document addSoapActionTemplate, String operationName, String soapAction)
throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
try {
XMLUtils xmlUtils = new XMLUtils();
String policyName = operationName + "-add-soapaction";
Document soapActionPolicyXML = xmlUtils.cloneDocument(addSoapActionTemplate);
Node rootElement = soapActionPolicyXML.getFirstChild();
NamedNodeMap attr = rootElement.getAttributes();
Node nodeAttr = attr.getNamedItem("name");
nodeAttr.setNodeValue(policyName);
Node displayName = soapActionPolicyXML.getElementsByTagName("DisplayName").item(0);
displayName.setTextContent(operationName + " Add SOAPAction");
Node header = soapActionPolicyXML.getElementsByTagName("Header").item(0);
header.setTextContent(soapAction);
xmlUtils.writeXML(soapActionPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator
+ "policies" + File.separator + policyName + ".xml");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeAddNamespace(Document namespaceTemplate, String operationName, boolean addOtherNamespaces)
throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
try {
XMLUtils xmlUtils = new XMLUtils();
String policyName = operationName + "-add-namespace";
Document xslPolicyXML = xmlUtils.cloneDocument(namespaceTemplate);
Node rootElement = xslPolicyXML.getFirstChild();
NamedNodeMap attr = rootElement.getAttributes();
Node nodeAttr = attr.getNamedItem("name");
nodeAttr.setNodeValue(policyName);
Node displayName = xslPolicyXML.getElementsByTagName("DisplayName").item(0);
displayName.setTextContent(operationName + " Add Namespace");
Node resourceURL = xslPolicyXML.getElementsByTagName("ResourceURL").item(0);
resourceURL.setTextContent("xsl://" + policyName + ".xslt");
xmlUtils.writeXML(xslPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies"
+ File.separator + policyName + ".xml");
if (addOtherNamespaces) {
String policyNameOther = operationName + "-add-other-namespaces";
Document xslPolicyXMLOther = xmlUtils.cloneDocument(namespaceTemplate);
Node rootElementOther = xslPolicyXMLOther.getFirstChild();
NamedNodeMap attrOther = rootElementOther.getAttributes();
Node nodeAttrOther = attrOther.getNamedItem("name");
nodeAttrOther.setNodeValue(policyNameOther);
Node displayNameOther = xslPolicyXMLOther.getElementsByTagName("DisplayName").item(0);
displayNameOther.setTextContent(operationName + " Add Other Namespaces");
Node resourceURLOther = xslPolicyXMLOther.getElementsByTagName("ResourceURL").item(0);
resourceURLOther.setTextContent("xsl://" + policyNameOther + ".xslt");
xmlUtils.writeXML(xslPolicyXMLOther, buildFolder + File.separator + "apiproxy" + File.separator
+ "policies" + File.separator + policyNameOther + ".xml");
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeSOAP2APIExtractPolicy(Document extractTemplate, String operationName, String policyName)
throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
XMLUtils xmlUtils = new XMLUtils();
Element queryParam;
Element pattern;
Document extractPolicyXML = xmlUtils.cloneDocument(extractTemplate);
Node rootElement = extractPolicyXML.getFirstChild();
NamedNodeMap attr = rootElement.getAttributes();
Node nodeAttr = attr.getNamedItem("name");
nodeAttr.setNodeValue(policyName);
Node displayName = extractPolicyXML.getElementsByTagName("DisplayName").item(0);
displayName.setTextContent(operationName + " Extract Query Param");
APIMap apiMap = messageTemplates.get(operationName);
List<String> elementList = xmlUtils.getElementList(apiMap.getSoapBody());
for (String elementName : elementList) {
queryParam = extractPolicyXML.createElement("QueryParam");
queryParam.setAttribute("name", elementName);
pattern = extractPolicyXML.createElement("Pattern");
pattern.setAttribute("ignoreCase", "true");
pattern.setTextContent("{" + elementName + "}");
queryParam.appendChild(pattern);
rootElement.appendChild(queryParam);
}
xmlUtils.writeXML(extractPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies"
+ File.separator + policyName + ".xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeSOAP2APIAssignMessagePolicies(Document assignTemplate, String operationName, String policyName,
String soapAction) throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
XMLUtils xmlUtils = new XMLUtils();
Document assignPolicyXML = xmlUtils.cloneDocument(assignTemplate);
Node rootElement = assignPolicyXML.getFirstChild();
NamedNodeMap attr = rootElement.getAttributes();
Node nodeAttr = attr.getNamedItem("name");
nodeAttr.setNodeValue(policyName);
Node displayName = assignPolicyXML.getElementsByTagName("DisplayName").item(0);
displayName.setTextContent(operationName + " Build SOAP");
Node payload = assignPolicyXML.getElementsByTagName("Payload").item(0);
NamedNodeMap payloadNodeMap = payload.getAttributes();
Node payloadAttr = payloadNodeMap.getNamedItem("contentType");
if (soapVersion.equalsIgnoreCase("SOAP12")) {
payloadAttr.setNodeValue(StringEscapeUtils.escapeXml10(SOAP12_PAYLOAD_TYPE));
assignPolicyXML.getElementsByTagName("Header").item(1)
.setTextContent(StringEscapeUtils.escapeXml10(SOAP12_CONTENT_TYPE));
} else {
payloadAttr.setNodeValue(StringEscapeUtils.escapeXml10(SOAP11_PAYLOAD_TYPE));
assignPolicyXML.getElementsByTagName("Header").item(1)
.setTextContent(StringEscapeUtils.escapeXml10(SOAP11_CONTENT_TYPE));
if (soapAction != null) {
Node header = assignPolicyXML.getElementsByTagName("Header").item(0);
header.setTextContent(soapAction);
} else {
final Node add = assignPolicyXML.getElementsByTagName("Add").item(0);
add.getParentNode().removeChild(add);
}
}
APIMap apiMap = messageTemplates.get(operationName);
Document operationPayload = null;
if (xmlUtils.isValidXML(apiMap.getSoapBody())) {
operationPayload = xmlUtils.getXMLFromString(apiMap.getSoapBody());
} else {
LOGGER.warning("Operation " + operationName + " soap template could not be generated");
if (soapVersion.equalsIgnoreCase("SOAP11")) {
operationPayload = xmlUtils.getXMLFromString(emptySoap11);
} else {
operationPayload = xmlUtils.getXMLFromString(emptySoap12);
}
}
Node importedNode = assignPolicyXML.importNode(operationPayload.getDocumentElement(), true);
payload.appendChild(importedNode);
Node value = assignPolicyXML.getElementsByTagName("Value").item(0);
value.setTextContent(targetEndpoint);
LOGGER.fine("Generated resource xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "policies"
+ File.separator + policyName + ".xml");
xmlUtils.writeXML(assignPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies"
+ File.separator + policyName + ".xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeTargetEndpoint() throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
XMLUtils xmlUtils = new XMLUtils();
Document targetDefault;
if (PASSTHRU) {
targetDefault = xmlUtils.readXML(SOAPPASSTHRU_TARGET_TEMPLATE);
} else {
targetDefault = xmlUtils.readXML(SOAP2API_TARGET_TEMPLATE);
if (CORS) {
Node response = targetDefault.getElementsByTagName("Response").item(0);
Node step = targetDefault.createElement("Step");
Node name = targetDefault.createElement("Name");
name.setTextContent("add-cors");
step.appendChild(name);
response.appendChild(step);
}
}
Node urlNode = targetDefault.getElementsByTagName("URL").item(0);
if (targetEndpoint != null && targetEndpoint.equalsIgnoreCase("") != true) {
urlNode.setTextContent(targetEndpoint);
} else {
LOGGER.warning("No target URL set");
}
xmlUtils.writeXML(targetDefault, buildFolder + File.separator + "apiproxy" + File.separator + "targets"
+ File.separator + "default.xml");
LOGGER.info("Generated Target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "targets"
+ File.separator + "default.xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeJsonToXMLPolicy(Document jsonXMLTemplate, String operationName, String rootElement)
throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator;
XMLUtils xmlUtils = new XMLUtils();
Document jsonxmlPolicyXML = xmlUtils.cloneDocument(jsonXMLTemplate);
Node root = jsonxmlPolicyXML.getFirstChild();
NamedNodeMap attr = root.getAttributes();
Node nodeAttr = attr.getNamedItem("name");
nodeAttr.setNodeValue(operationName + "-json-to-xml");
Node displayName = jsonxmlPolicyXML.getElementsByTagName("DisplayName").item(0);
displayName.setTextContent(operationName + " JSON TO XML");
/*Node objectRootElement = jsonxmlPolicyXML.getElementsByTagName("ObjectRootElementName").item(0);
objectRootElement.setTextContent(rootElement);
Node arrayRootElement = jsonxmlPolicyXML.getElementsByTagName("ArrayRootElementName").item(0);
arrayRootElement.setTextContent(rootElement);*/
xmlUtils.writeXML(jsonxmlPolicyXML, targetPath + operationName + "-json-to-xml.xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeStdPolicies() throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
try {
String sourcePath = "/templates/";
String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies"
+ File.separator;
String xslResourcePath = buildFolder + File.separator + "apiproxy" + File.separator + "resources"
+ File.separator + "xsl" + File.separator;
String jsResourcePath = buildFolder + File.separator + "apiproxy" + File.separator + "resources"
+ File.separator + "jsc" + File.separator;
LOGGER.fine("Source Path: " + sourcePath);
LOGGER.fine("Target Path: " + targetPath);
if (PASSTHRU) {
sourcePath += "soappassthru/";
Files.copy(getClass().getResourceAsStream(sourcePath + "Extract-Operation-Name.xml"),
Paths.get(targetPath + "Extract-Operation-Name.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "Invalid-SOAP.xml"),
Paths.get(targetPath + "Invalid-SOAP.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} else {
sourcePath += "soap2api/";
Files.copy(getClass().getResourceAsStream(sourcePath + "xml-to-json.xml"),
Paths.get(targetPath + "xml-to-json.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "set-response-soap-body.xml"),
Paths.get(targetPath + "set-response-soap-body.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "set-response-soap-body-accept.xml"),
Paths.get(targetPath + "set-response-soap-body-accept.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "get-response-soap-body.xml"),
Paths.get(targetPath + "get-response-soap-body.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "get-response-soap-body-xml.xml"),
Paths.get(targetPath + "get-response-soap-body-xml.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "set-target-url.xml"),
Paths.get(targetPath + "set-target-url.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "extract-format.xml"),
Paths.get(targetPath + "extract-format.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "unknown-resource.xml"),
Paths.get(targetPath + "unknown-resource.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "unknown-resource-xml.xml"),
Paths.get(targetPath + "unknown-resource-xml.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "remove-empty-nodes.xml"),
Paths.get(targetPath + "remove-empty-nodes.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "remove-empty-nodes.xslt"),
Paths.get(xslResourcePath + "remove-empty-nodes.xslt"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "return-generic-error.xml"),
Paths.get(targetPath + "return-generic-error.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "return-generic-error-accept.xml"),
Paths.get(targetPath + "return-generic-error-accept.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "remove-namespaces.xml"),
Paths.get(targetPath + "remove-namespaces.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "remove-namespaces.xslt"),
Paths.get(xslResourcePath + "remove-namespaces.xslt"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
/*Files.copy(getClass().getResourceAsStream(sourcePath + "root-wrapper.js"),
Paths.get(jsResourcePath + "root-wrapper.js"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);*/
if (OAUTH) {
Files.copy(getClass().getResourceAsStream(sourcePath + "verify-oauth-v2-access-token.xml"),
Paths.get(targetPath + "verify-oauth-v2-access-token.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "remove-header-authorization.xml"),
Paths.get(targetPath + "remove-header-authorization.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
if (QUOTAOAUTH) {
Files.copy(getClass().getResourceAsStream(sourcePath + "impose-quota-oauth.xml"),
Paths.get(targetPath + "impose-quota-oauth.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
}
if (APIKEY) {
Files.copy(getClass().getResourceAsStream(sourcePath + "verify-api-key.xml"),
Paths.get(targetPath + "verify-api-key.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getResourceAsStream(sourcePath + "remove-query-param-apikey.xml"),
Paths.get(targetPath + "remove-query-param-apikey.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
if (QUOTAAPIKEY) {
Files.copy(getClass().getResourceAsStream(sourcePath + "impose-quota-apikey.xml"),
Paths.get(targetPath + "impose-quota-apikey.xml"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
}
if (CORS) {
Files.copy(getClass().getResourceAsStream(sourcePath + "add-cors.xml"),
Paths.get(targetPath + "add-cors.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
}
} catch (Exception e) {
LOGGER.severe(e.getMessage());
e.printStackTrace();
throw e;
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void writeSOAPPassThruProxyEndpointConditions(String proxyDescription) throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
String soapConditionText = "(envelope != \"Envelope\") or (body != \"Body\") or (envelopeNamespace !=\"";
XMLUtils xmlUtils = new XMLUtils();
Document proxyDefault = xmlUtils.readXML(SOAPPASSTHRU_PROXY_TEMPLATE);
Node basePathNode = proxyDefault.getElementsByTagName("BasePath").item(0);
if (basePath != null && basePath.equalsIgnoreCase("") != true) {
basePathNode.setTextContent(basePath);
}
Node httpProxyConnection = proxyDefault.getElementsByTagName("HTTPProxyConnection").item(0);
Node virtualHost = null;
for (String vHost : vHosts) {
virtualHost = proxyDefault.createElement("VirtualHost");
virtualHost.setTextContent(vHost);
httpProxyConnection.appendChild(virtualHost);
}
Node description = proxyDefault.getElementsByTagName("Description").item(0);
description.setTextContent(proxyDescription);
Node soapCondition = proxyDefault.getElementsByTagName("Condition").item(1);
if (soapVersion.equalsIgnoreCase("SOAP11")) {
soapCondition.setTextContent(soapConditionText + SOAP11 + "\")");
} else {
soapCondition.setTextContent(soapConditionText + SOAP12 + "\")");
}
String conditionText = "(proxy.pathsuffix MatchesPath \"/\") and (request.verb = \"POST\") and (operation = \"";
Node flows = proxyDefault.getElementsByTagName("Flows").item(0);
Node flow;
Node flowDescription;
Node request;
Node response;
Node condition;
Node step1;
Node name1;
for (Map.Entry<String, APIMap> entry : messageTemplates.entrySet()) {
String operationName = entry.getKey();
APIMap apiMap = entry.getValue();
flow = proxyDefault.createElement("Flow");
((Element) flow).setAttribute("name", operationName);
flowDescription = proxyDefault.createElement("Description");
flowDescription.setTextContent(operationName);
flow.appendChild(flowDescription);
request = proxyDefault.createElement("Request");
response = proxyDefault.createElement("Response");
condition = proxyDefault.createElement("Condition");
condition.setTextContent(conditionText + apiMap.getRootElement() + "\")");
flow.appendChild(request);
flow.appendChild(response);
flow.appendChild(condition);
flows.appendChild(flow);
}
// Add unknown resource
flow = proxyDefault.createElement("Flow");
((Element) flow).setAttribute("name", "unknown-resource");
flowDescription = proxyDefault.createElement("Description");
flowDescription.setTextContent("Unknown Resource");
flow.appendChild(flowDescription);
request = proxyDefault.createElement("Request");
response = proxyDefault.createElement("Response");
condition = proxyDefault.createElement("Condition");
step1 = proxyDefault.createElement("Step");
name1 = proxyDefault.createElement("Name");
name1.setTextContent("Invalid-SOAP");
step1.appendChild(name1);
request.appendChild(step1);
flow.appendChild(request);
flow.appendChild(response);
flow.appendChild(condition);
flows.appendChild(flow);
xmlUtils.writeXML(proxyDefault, buildFolder + File.separator + "apiproxy" + File.separator + "proxies"
+ File.separator + "default.xml");
LOGGER.fine("Edited target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "proxies"
+ File.separator + "default.xml");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private static Boolean isPrimitive(String type) {
return primitiveTypes.contains(type);
}
private String getNamespace(String prefix) {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
for (Map.Entry<String, String> entry : namespace.entrySet()) {
if (entry.getKey().equalsIgnoreCase(prefix)) {
return entry.getValue();
}
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
return null;
}
public String getPrefix(String namespaceUri) {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
for (Map.Entry<String, String> entry : namespace.entrySet()) {
if (entry.getValue().equalsIgnoreCase(namespaceUri)) {
if (entry.getKey().length() == 0) {
return "ns";
} else {
return entry.getKey();
}
}
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
return "ns";
}
private void parseElement(com.predic8.schema.Element e, List<Schema> schemas, String rootElement,
String rootNamespace, String rootPrefix) {
if (e.getName() == null) {
if (e.getRef() != null) {
final String localPart = e.getRef().getLocalPart();
final com.predic8.schema.Element element = elementFromSchema(localPart, schemas);
parseSchema(element, schemas, rootElement, rootNamespace, rootPrefix);
} else {
// fail silently
LOGGER.warning("unhandled conditions getRef() = null");
}
} else {
if (!e.getName().equalsIgnoreCase(rootElement)) {
if (e.getEmbeddedType() instanceof ComplexType) {
ComplexType ct = (ComplexType) e.getEmbeddedType();
if (!e.getNamespaceUri().equalsIgnoreCase(rootNamespace)) {
buildXPath(e, rootElement, rootNamespace, rootPrefix);
}
parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix);
} else {
if (e.getType() != null) {
if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)
&& !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) {
buildXPath(e, rootElement, rootNamespace, rootPrefix);
}
TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas);
if (typeDefinition instanceof ComplexType) {
parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace,
rootPrefix);
}
} else {
// handle this as anyType
buildXPath(e, rootElement, rootNamespace, rootPrefix, true);
if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)) {
buildXPath(e, rootElement, rootNamespace, rootPrefix);
}
LOGGER.warning("Found element " + e.getName() + " with no type. Handling as xsd:anyType");
}
}
}
}
}
private com.predic8.schema.Element elementFromSchema(String name, List<Schema> schemas) {
if (name != null) {
for (Schema schema : schemas) {
try {
final com.predic8.schema.Element element = schema.getElement(name);
if (element != null) {
return element;
}
} catch (Exception e) {
LOGGER.warning("unhandled conditions: " + e.getMessage());
}
}
}
return null;
}
private void parseSchema(SchemaComponent sc, List<Schema> schemas, String rootElement, String rootNamespace,
String rootPrefix) {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
//fail safe measure.
if (ruleList.size() >= 100) {
//the rules are too big. clear the rules.
TOO_MANY = true;
return;
} else if (sc instanceof Sequence) {
Sequence seq = (Sequence) sc;
level++;
for (com.predic8.schema.Element e : seq.getElements()) {
// System.out.println(e.getName() + " - " + " " + e.getType());
if (e.getName() == null)
level
if (e.getName() != null) {
xpathElement.put(level, e.getName());
if (e.getType() != null) {
if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) {
// found a anyType. remove namespaces for
// descendents
buildXPath(e, rootElement, rootNamespace, rootPrefix, true);
}
}
}
parseElement(e, schemas, rootElement, rootNamespace, rootPrefix);
}
level
cleanUpXPath();
} else if (sc instanceof Choice) {
Choice ch = (Choice) sc;
level++;
for (com.predic8.schema.Element e : ch.getElements()) {
if (!e.getName().equalsIgnoreCase(rootElement)) {
if (e.getEmbeddedType() instanceof ComplexType) {
ComplexType ct = (ComplexType) e.getEmbeddedType();
xpathElement.put(level, e.getName());
parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix);
} else {
final TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas);
if (typeDefinition instanceof ComplexType) {
xpathElement.put(level, e.getName());
parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace,
rootPrefix);
}
if (e.getType() == null) {
// handle this any anyType
buildXPath(e, rootElement, rootNamespace, rootPrefix, true);
LOGGER.warning("Element " + e.getName() + " type was null; treating as anyType");
} else if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)
&& !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) {
buildXPath(e, rootElement, rootNamespace, rootPrefix);
} else if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) {
// if you find a anyType, remove namespace for the
// descendents.
buildXPath(e, rootElement, rootNamespace, rootPrefix, true);
}
}
}
}
level
cleanUpXPath();
} else if (sc instanceof ComplexContent) {
ComplexContent complexContent = (ComplexContent) sc;
Derivation derivation = complexContent.getDerivation();
if (derivation != null) {
TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas);
if (typeDefinition instanceof ComplexType) {
parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace,
rootPrefix);
}
if (derivation.getModel() instanceof Sequence) {
parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix);
} else if (derivation.getModel() instanceof ModelGroup) {
parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix);
}
}
} else if (sc instanceof SimpleContent) {
SimpleContent simpleContent = (SimpleContent) sc;
Derivation derivation = (Derivation) simpleContent.getDerivation();
if (derivation.getAllAttributes().size() > 0) {
// has attributes
buildXPath(derivation.getNamespaceUri(), rootElement, rootNamespace, rootPrefix);
}
} else if (sc instanceof com.predic8.schema.Element) {
level++;
xpathElement.put(level, ((com.predic8.schema.Element) sc).getName());
parseElement((com.predic8.schema.Element) sc, schemas, rootElement, rootNamespace, rootPrefix);
} else if (sc instanceof All) {
All all = (All) sc;
level++;
for (com.predic8.schema.Element e : all.getElements()) {
if (e.getName() == null)
level
if (e.getName() != null)
xpathElement.put(level, e.getName());
parseElement(e, schemas, rootElement, rootNamespace, rootPrefix);
}
level
cleanUpXPath();
} else if (sc != null) {
// fail silently
LOGGER.warning("unhandled conditions - " + sc.getClass().getName());
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private String parseParts(List<Part> parts, List<Schema> schemas, String rootElement, String rootNamespace,
String rootPrefix, String soapRequest) {
for (Part part : parts) {
if (part.getType() != null) {
if (isPrimitive(part.getType().getQname().getLocalPart())) {
soapRequest = soapRequest + "<" + part.getName()
+ " xmlns:xsi=\"http:
+ "\">" + "?</" + part.getName() + ">\n";
// primitive elements are in the same namespace, skip xpath
} else {
TypeDefinition typeDefinition = part.getType();
if (typeDefinition instanceof ComplexType) {
ComplexType ct = (ComplexType) typeDefinition;
SchemaComponent sc = ct.getModel();
try {
soapRequest = soapRequest + "<" + part.getName()
+ " xmlns:xsi=\"http:
+ part.getTypePN() + "\" xmlns:" + part.getType().getPrefix() + "=\""
+ part.getType().getNamespaceUri() + "\">\n";
soapRequest += sc.getRequestTemplate();
soapRequest += "\n</" + part.getName() + ">";
xpathElement.put(++level, part.getName());
// since we already have the soap request template,
// no need to pass it.
// call parseRPCschema to find any elements with a
// different namespace
parseRPCSchema(sc, schemas, rootElement, rootNamespace, rootPrefix, "");
level
} catch (Exception e) {
soapRequest += "\n</" + part.getName() + ">";
soapRequest = parseRPCSchema(sc, schemas, rootElement, rootNamespace, rootPrefix,
soapRequest);
}
} else if (typeDefinition instanceof BuiltInSchemaType) {
BuiltInSchemaType bst = (BuiltInSchemaType) typeDefinition;
soapRequest = soapRequest + bst.getRequestTemplate();
// TODO: parse elements
} else {
LOGGER.warning("WARNING");
}
}
} else {
soapRequest += part.getElement().getRequestTemplate();
}
}
return soapRequest;
}
private String parseRPCSchema(SchemaComponent sc, List<Schema> schemas, String rootElement, String rootNamespace,
String rootPrefix, String soapRequest) {
if (sc instanceof Sequence) {
Sequence sequence = (Sequence) sc;
level++;
soapRequest = soapRequest + sequence.getRequestTemplate();
for (com.predic8.schema.Element e : sequence.getElements()) {
if (e.getName() == null)
level
if (e.getName() != null)
xpathElement.put(level, e.getName());
parseRPCElement(e, schemas, rootElement, rootNamespace, rootPrefix, soapRequest);
}
level
cleanUpXPath();
} else if (sc instanceof ComplexContent) {
ComplexContent complexContent = (ComplexContent) sc;
Derivation derivation = complexContent.getDerivation();
if (derivation != null) {
TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas);
if (typeDefinition instanceof ComplexType) {
soapRequest = parseRPCSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement,
rootNamespace, rootPrefix, soapRequest);
}
if (derivation.getModel() instanceof Sequence) {
soapRequest = parseRPCSchema((Sequence) derivation.getModel(), schemas, rootElement, rootNamespace,
rootPrefix, soapRequest);
} else if (derivation.getModel() instanceof ModelGroup) {
soapRequest = parseRPCSchema((ModelGroup) derivation.getModel(), schemas, rootElement,
rootNamespace, rootPrefix, soapRequest);
}
}
} else if (sc instanceof SimpleContent) {
SimpleContent simpleContent = (SimpleContent) sc;
Derivation derivation = (Derivation) simpleContent.getDerivation();
if (derivation.getAllAttributes().size() > 0) {
// has attributes
buildXPath(derivation.getNamespaceUri(), rootElement, rootNamespace, rootPrefix);
}
} else if (sc instanceof GroupRef) {
// GroupRef groupRef = (GroupRef)sc;
LOGGER.fine("WARNING: GroupRef not handled.");
} else {
LOGGER.warning("WARNING: unhandled type " + sc.getClass().getName());
}
return soapRequest;
}
private void parseRPCElement(com.predic8.schema.Element e, List<Schema> schemas, String rootElement,
String rootNamespace, String rootPrefix, String soapRequest) {
if (e.getName() == null) {
if (e.getRef() != null) {
final String localPart = e.getRef().getLocalPart();
final com.predic8.schema.Element element = elementFromSchema(localPart, schemas);
parseRPCSchema(element, schemas, rootElement, rootNamespace, rootPrefix, soapRequest);
} else {
// TODO: handle this
LOGGER.warning("unhandle conditions getRef() = null");
}
} else {
if (!e.getName().equalsIgnoreCase(rootElement)) {
if (e.getEmbeddedType() instanceof ComplexType) {
ComplexType ct = (ComplexType) e.getEmbeddedType();
if (!e.getNamespaceUri().equalsIgnoreCase(rootNamespace)) {
buildXPath(e, rootElement, rootNamespace, rootPrefix);
}
parseRPCSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix, soapRequest);
} else {
if (e.getType() != null) {
if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)
&& !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) {
buildXPath(e, rootElement, rootNamespace, rootPrefix);
}
TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas);
if (typeDefinition instanceof ComplexType) {
parseRPCSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement,
rootNamespace, rootPrefix, soapRequest);
}
} else {
// handle this as anyType
buildXPath(e, rootElement, rootNamespace, rootPrefix, true);
if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)) {
buildXPath(e, rootElement, rootNamespace, rootPrefix);
}
LOGGER.warning("Found element " + e.getName() + " with no type. Handling as xsd:anyType");
}
}
}
}
}
private TypeDefinition getTypeFromSchema(QName qName, List<Schema> schemas) {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
if (qName != null) {
for (Schema schema : schemas) {
try {
final TypeDefinition type = schema.getType(qName);
if (type != null) {
return type;
}
} catch (Exception e) {
// Fail silently
LOGGER.warning("unhandle conditions: " + e.getMessage());
}
}
}
return null;
}
private void cleanUpXPath() {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
final Iterator<Map.Entry<Integer, String>> iterator = xpathElement.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<Integer, String> next = iterator.next();
if (next.getKey() > level) {
iterator.remove();
}
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private String getSoapNamespace () {
if (soapVersion.equalsIgnoreCase("SOAP11")) {
return soap11Namespace;
} else {
return soap12Namespace;
}
}
private String buildSOAPRequest(List<Part> parts, List<Schema> schemas, String rootElement, String rootNamespace,
boolean generateParts) {
String prefix = getPrefix(rootNamespace);
String soapRequest = "<soapenv:Envelope " + getSoapNamespace() + getNamespacesAsString(true)
+ " soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n<soapenv:Body>\n" + "<"
+ prefix + ":" + rootElement + ">\n";
if (generateParts) {
soapRequest = parseParts(parts, schemas, rootElement, rootNamespace, prefix, soapRequest);
}
soapRequest += "</" + prefix + ":" + rootElement + ">\n";
soapRequest += "</soapenv:Body>\n</soapenv:Envelope>";
return soapRequest;
}
private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix,
boolean removeNamespace) {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
Rule r = null;
String xpathString = "";
String prefix = "NULL";
String namespaceUri = "NULL";
String soapElements = "/soapenv:Envelope/soapenv:Body";
String lastElement = "";
for (Map.Entry<Integer, String> entry : xpathElement.entrySet()) {
xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue();
lastElement = entry.getValue();
}
// add the last element to xpath
if (!lastElement.equalsIgnoreCase(e.getName()))
xpathString = xpathString + "/" + rootPrefix + ":" + e.getName();
r = new Rule(soapElements + xpathString, prefix, namespaceUri, "descendant");
ruleList.add(r);
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix) {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
Rule r = null;
String xpathString = "";
String soapElements = "/soapenv:Envelope/soapenv:Body";
String prefix = getPrefix(e.getNamespaceUri());
String namespaceUri = e.getNamespaceUri();
for (Map.Entry<Integer, String> entry : xpathElement.entrySet()) {
xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue();
}
r = new Rule(soapElements + xpathString, prefix, namespaceUri);
ruleList.add(r);
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private void buildXPath(String namespaceUri, String rootElement, String rootNamespace, String rootPrefix) {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
Rule r = null;
String prefix = getPrefix(namespaceUri);
String soapElements = "/soapenv:Envelope/soapenv:Body";
String xpathString = "";
for (Map.Entry<Integer, String> entry : xpathElement.entrySet()) {
xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue();
}
r = new Rule(soapElements + xpathString + "/@*", prefix, namespaceUri);
ruleList.add(r);
cleanUpXPath();
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private String getNamespacesAsString(boolean removeBlackListed) {
String namespaces = "";
for (Map.Entry<String, String> entry : namespace.entrySet()) {
if (removeBlackListed) {
if (!isBlackListed(entry.getValue())) {
namespaces += " xmlns:" + entry.getKey() + "=\"" + entry.getValue() + "\"";
}
} else {
namespaces += " xmlns:" + entry.getKey() + "=\"" + entry.getValue() + "\"";
}
}
return namespaces;
}
private static boolean isBlackListed(String namespaceURI) {
return blackListedNamespaces.contains(namespaceURI);
}
private String getParentNamepace(com.predic8.schema.Element e) {
XMLElement parent = e.getParent();
try {
return parent.getNamespaceUri();
} catch (NullPointerException npe) {
if (e.getNamespaceUri() != null)
return e.getNamespaceUri();
else
return null;
}
}
@SuppressWarnings("unchecked")
private APIMap createAPIMap(Operation op, Definitions wsdl, String verb, String resourcePath, XMLUtils xmlUtils)
throws Exception {
APIMap apiMap = null;
String soapRequest = "";
namespace = (Map<String, String>) op.getNamespaceContext();
try {
if (verb.equalsIgnoreCase("GET")) {
soapRequest = buildSOAPRequest(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(),
op.getNamespaceUri(), true);
if (op.getInput().getMessage().getParts().size() == 0) {
apiMap = new APIMap(null, soapRequest, resourcePath, verb, op.getName(), false);
} else {
KeyValue<String, String> kv = xmlUtils.replacePlaceHolders(soapRequest);
apiMap = new APIMap(kv.getValue(), kv.getKey(), resourcePath, verb, op.getName(), false);
}
} else {
buildSOAPRequest(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(),
op.getNamespaceUri(), true);
String namespaceUri = op.getNamespaceUri();
String prefix = getPrefix(namespaceUri);
if (soapVersion.equalsIgnoreCase("SOAP11")) {
xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT11_TEMPLATE, SOAP2API_XSL, op.getName(), prefix,
null, namespaceUri, namespace);
} else {
xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT12_TEMPLATE, SOAP2API_XSL, op.getName(), prefix,
null, namespaceUri, namespace);
}
if (ruleList.size() > 0) {
RuleSet rs = new RuleSet();
rs.addRuleList(ruleList);
xmlUtils.generateOtherNamespacesXSLT(SOAP2API_XSL, op.getName(), rs.getTransform(soapVersion),
namespace);
ruleList.clear();
apiMap = new APIMap("", "", resourcePath, verb, op.getName(), true);
} else {
apiMap = new APIMap("", "", resourcePath, verb, op.getName(), false);
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return apiMap;
}
@SuppressWarnings("unchecked")
private void parseWSDL(String wsdlPath) throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
XMLUtils xmlUtils = new XMLUtils();
StringWriter writer = new StringWriter();
Definitions wsdl = null;
SOARequestCreator creator = null;
Service service = null;
com.predic8.wsdl.Port port = null;
String bindingName;
try {
WSDLParser parser = new WSDLParser();
wsdl = parser.parse(wsdlPath);
if (wsdl.getServices().size() == 0) {
LOGGER.severe("No services were found in the WSDL");
throw new NoServicesFoundException("No services were found in the WSDL");
}
creator = new SOARequestCreator(wsdl, new RequestTemplateCreator(), new MarkupBuilder(writer));
} catch (Exception e) {
e.printStackTrace();
LOGGER.severe(e.getLocalizedMessage());
throw e;
}
KeyValue<String, String> map = StringUtils.proxyNameAndBasePath(wsdlPath);
if (serviceName != null) {
for (Service svc : wsdl.getServices()) {
if (svc.getName().equalsIgnoreCase(serviceName)) {
service = svc;
LOGGER.fine("Found Service: " + service.getName());
break;
}
}
if (service == null) { // didn't find any service matching name
LOGGER.severe("No matching services were found in the WSDL");
throw new NoServicesFoundException("No matching services were found in the WSDL");
} else {
proxyName = serviceName;
}
} else {
service = wsdl.getServices().get(0); // get the first service
LOGGER.fine("Found Service: " + service.getName());
serviceName = service.getName();
proxyName = serviceName;
}
if (basePath == null) {
if (serviceName != null) {
basePath = "/" + serviceName.toLowerCase();
} else {
basePath = map.getValue();
}
}
if (portName != null) {
for (com.predic8.wsdl.Port prt : service.getPorts()) {
if (prt.getName().equalsIgnoreCase(portName)) {
port = prt;
}
}
if (port == null) { // didn't find any port matching name
LOGGER.severe("No matching port was found in the WSDL");
throw new NoServicesFoundException("No matching port found in the WSDL");
}
} else {
port = service.getPorts().get(0); // get first port
}
LOGGER.fine("Found Port: " + port.getName());
Binding binding = port.getBinding();
bindingName = binding.getName();
soapVersion = binding.getProtocol().toString();
if (binding.getStyle().toLowerCase().contains("rpc")) {
LOGGER.info("Binding Stype: " + binding.getStyle());
RPCSTYLE = true;
} else if (binding.getStyle().toLowerCase().contains("document")) {
LOGGER.info("Binding Stype: " + binding.getStyle());
RPCSTYLE = false;
} else {
LOGGER.info(binding.getStyle() + ". Treating as document");
RPCSTYLE = false;
}
LOGGER.fine("Found Binding: " + bindingName + " Binding Protocol: " + soapVersion + " Prefix: "
+ binding.getPrefix() + " NamespaceURI: " + binding.getNamespaceUri());
targetEndpoint = port.getAddress().getLocation();
LOGGER.info("Retrieved WSDL endpoint: " + targetEndpoint);
String[] schemes = {"http","https"};
UrlValidator urlValidator = new UrlValidator(schemes);
if (!urlValidator.isValid(targetEndpoint)) {
LOGGER.warning("Target endpoint is not http/https URL. Assigning a default value");
targetEndpoint = "http://localhost:8080/soap";
}
PortType portType = binding.getPortType();
APIMap apiMap = null;
HashMap<String, SelectedOperation> selectedOperationList = selectedOperations.getSelectedOperations();
for (Operation op : portType.getOperations()) {
LOGGER.fine("Found Operation Name: " + op.getName() + " Prefix: " + op.getPrefix() + " NamespaceURI: "
+ op.getNamespaceUri());
try {
String soapRequest = "";
// the current operations is not in the list; skip.
if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(op.getName())) {
continue;
}
// if passthru, then do nothing much
if (PASSTHRU) {
if (RPCSTYLE) {
apiMap = new APIMap(null, null, null, "POST", op.getName(), false);
} else {
//get root element
com.predic8.schema.Element requestElement = op.getInput().getMessage().getParts().get(0)
.getElement();
if (requestElement != null) {
apiMap = new APIMap(null, null, null, "POST", requestElement.getName(), false);
} else {
apiMap = new APIMap(null, null, null, "POST", op.getName(), false);
}
}
} else {
String resourcePath = operationsMap.getResourcePath(op.getName(), selectedOperationList);
String verb = "";
// if all post options is not turned on, then interpret the
// operation from opsmap
if (!ALLPOST) {
verb = operationsMap.getVerb(op.getName(), selectedOperationList);
} else { // else POST
verb = "POST";
}
if (RPCSTYLE) {
apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils);
} else {// document style
// there can be soap messages with no parts. membrane
// soap can't construct soap
// template for such messages. manually build
if (op.getInput().getMessage().getParts().size() == 0) {
apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils);
} else {
com.predic8.schema.Element requestElement = op.getInput().getMessage().getParts().get(0)
.getElement();
if (requestElement != null) {
namespace = (Map<String, String>) requestElement.getNamespaceContext();
if (verb.equalsIgnoreCase("GET")) {
if (soapVersion.equalsIgnoreCase("SOAP11")
|| soapVersion.equalsIgnoreCase("SOAP12")) {
creator.setCreator(new RequestTemplateCreator());
// use membrane SOAP to generate a SOAP
// Request
creator.createRequest(port.getName(), op.getName(), binding.getName());
KeyValue<String, String> kv = xmlUtils.replacePlaceHolders(writer.toString());
//sometimes membrane soa generates invalid soap
//this will cause the bundle to not be uploaded
// store the operation name, SOAP
// Request and
// the
// expected JSON Body in the map
apiMap = new APIMap(kv.getValue(), kv.getKey(), resourcePath, verb,
requestElement.getName(), false);
writer.getBuffer().setLength(0);
} else {
apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils);
}
} else {
String namespaceUri = null;
if (requestElement.getType() != null) {
namespaceUri = requestElement.getType().getNamespaceURI();
} else {
namespaceUri = requestElement.getEmbeddedType().getNamespaceUri();
}
String prefix = getPrefix(namespaceUri);
if (soapVersion.equalsIgnoreCase("SOAP11")) {
xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT11_TEMPLATE, SOAP2API_XSL,
op.getName(), prefix, requestElement.getName(), namespaceUri, namespace);
} else {
xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT12_TEMPLATE, SOAP2API_XSL,
op.getName(), prefix, requestElement.getName(), namespaceUri, namespace);
}
TypeDefinition typeDefinition = null;
if (requestElement.getEmbeddedType() != null) {
typeDefinition = requestElement.getEmbeddedType();
} else {
typeDefinition = getTypeFromSchema(requestElement.getType(), wsdl.getSchemas());
}
if (typeDefinition instanceof ComplexType) {
ComplexType ct = (ComplexType) typeDefinition;
xpathElement.put(level, requestElement.getName());
parseSchema(ct.getModel(), wsdl.getSchemas(), requestElement.getName(),
namespaceUri, prefix);
}
if (TOO_MANY) {
LOGGER.warning(op.getName() + ": Too many nested schemas or elements. Skipping XSLT gen. Manual intervention necessary");
ruleList.clear();
apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(),
false);
} else {
// rule list is > 0, there are additional
// namespaces to add
if (ruleList.size() > 0) {
RuleSet rs = new RuleSet();
rs.addRuleList(ruleList);
xmlUtils.generateOtherNamespacesXSLT(SOAP2API_XSL, op.getName(),
rs.getTransform(soapVersion), namespace);
ruleList.clear();
apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), true);
} else {
apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(),
false);
}
}
}
} else {// if the request element is null, it
// appears membrane soap failed again.
// attempting manual build
apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils);
}
}
}
}
messageTemplates.put(op.getName(), apiMap);
} catch (Exception e) {
LOGGER.severe(e.getMessage());
e.printStackTrace();
throw e;
}
}
if (messageTemplates.size() == 0) {
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
throw new BindingNotFoundException("Soap version provided did not match any binding in WSDL");
}
if (!PASSTHRU) {
for (Binding bnd : wsdl.getBindings()) {
if (bindingName.equalsIgnoreCase(bnd.getName())) {
for (BindingOperation bop : bnd.getOperations()) {
if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(bop.getName())) {
// the current operations is not in the list; skip.
continue;
}
if (bnd.getBinding() instanceof AbstractSOAPBinding) {
LOGGER.fine("Found Operation Name: " + bop.getName() + " SOAPAction: "
+ bop.getOperation().getSoapAction());
APIMap apiM = messageTemplates.get(bop.getName());
apiM.setSoapAction(bop.getOperation().getSoapAction());
messageTemplates.put(bop.getName(), apiM);
}
}
}
}
}
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
}
private boolean prepareTargetFolder() {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
File f = new File(buildFolder);
if (f.isDirectory()) { // ensure target is a folder
LOGGER.fine("Target is a folder");
File apiproxy = new File(f.getAbsolutePath() + File.separator + "apiproxy");
if (apiproxy.exists()) {
LOGGER.severe("Folder called apiproxy already exists");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
return false;
} else {
apiproxy.mkdir();
LOGGER.fine("created apiproxy folder");
new File(apiproxy.getAbsolutePath() + File.separator + "policies").mkdirs();
LOGGER.fine("created policies folder");
new File(apiproxy.getAbsolutePath() + File.separator + "proxies").mkdirs();
LOGGER.fine("created proxies folder");
new File(apiproxy.getAbsolutePath() + File.separator + "targets").mkdirs();
LOGGER.fine("created targets folder");
if (!PASSTHRU) {
File xsltFolder = new File(
apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "xsl");
xsltFolder.mkdirs();
SOAP2API_XSL = xsltFolder.getAbsolutePath() + File.separator;
File jsFolder = new File(
apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "jsc");
jsFolder.mkdirs();
LOGGER.fine("created resources folder");
}
LOGGER.info("Target proxy folder setup complete");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
return true;
}
} else {
LOGGER.severe("Target folder is not a directory");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
return false;
}
}
public InputStream begin(String proxyDescription, String wsdlPath) throws Exception {
LOGGER.entering(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
LOGGER.fine("Preparing target folder");
String zipFolder = null;
Path tempDirectory = null;
InputStream is = null;
GenerateBundle generateBundle = new GenerateBundle();
try {
if (buildFolder == null) {
tempDirectory = Files.createTempDirectory(null);
buildFolder = tempDirectory.toAbsolutePath().toString();
}
zipFolder = buildFolder + File.separator + "apiproxy";
// prepare the target folder (create apiproxy folder and sub-folders
if (prepareTargetFolder()) {
// if not passthru read conf file to interpret soap operations
// to resources
if (!PASSTHRU) {
operationsMap.readOperationsMap(opsMap);
LOGGER.info("Read operations map");
}
// parse the wsdl
parseWSDL(wsdlPath);
LOGGER.info("Parsed WSDL Successfully.");
if (!DESCSET) {
proxyDescription += serviceName;
}
LOGGER.info("Base Path: " + basePath + "\nWSDL Path: " + wsdlPath);
LOGGER.info("Build Folder: " + buildFolder + "\nSOAP Version: " + soapVersion);
LOGGER.info("Proxy Name: " + proxyName + "\nProxy Description: " + proxyDescription);
// create the basic proxy structure from templates
writeAPIProxy(proxyDescription);
LOGGER.info("Generated Apigee proxy file.");
if (!PASSTHRU) {
LOGGER.info("Generated SOAP Message Templates.");
writeSOAP2APIProxyEndpoint(proxyDescription);
LOGGER.info("Generated proxies XML.");
writeStdPolicies();
LOGGER.info("Copied standard policies.");
writeTargetEndpoint();
LOGGER.info("Generated target XML.");
} else {
writeStdPolicies();
LOGGER.info("Copied standard policies.");
writeTargetEndpoint();
LOGGER.info("Generated target XML.");
writeSOAPPassThruProxyEndpointConditions(proxyDescription);
}
File file = generateBundle.build(zipFolder, proxyName);
LOGGER.info("Generated Apigee Edge API Bundle file: " + proxyName + ".zip");
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
return new ByteArrayInputStream(Files.readAllBytes(file.toPath()));
} else {
LOGGER.exiting(GenerateProxy.class.getName(), new Object() {
}.getClass().getEnclosingMethod().getName());
throw new TargetFolderException(
"Erorr is preparing target folder; target folder not empty " + buildFolder);
}
} catch (Exception e) {
LOGGER.severe(e.getMessage());
throw e;
} finally {
if (tempDirectory != null) {
try {
Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
LOGGER.severe(e.getMessage());
}
}
}
}
public static void usage() {
System.out.println("");
System.out.println("Usage: java -jar wsdl2apigee.jar -wsdl={url or path to wsdl} <options>");
System.out.println("");
System.out.println("Options:");
System.out.println("-passthru=<true|false> default is false;");
System.out.println("-desc=\"description for proxy\"");
System.out.println("-service=servicename if wsdl has > 1 service, enter service name");
System.out.println("-port=portname if service has > 1 port, enter port name");
System.out.println("-opsmap=opsmapping.xml mapping file that to map wsdl operation to http verb");
System.out.println("-allpost=<true|false> set to true if all operations are http verb; default is false");
System.out.println("-vhosts=<comma separated values for virtuals hosts>");
System.out.println("-build=specify build folder default is temp/tmp");
System.out.println("-oauth=<true|false> default is false");
System.out.println("-apikey=<true|false> default is false");
System.out.println("-quota=<true|false> default is false; works only if apikey or oauth is set");
System.out.println("-basepath=specify base path");
System.out.println("-cors=<true|false> default is false");
System.out.println("-debug=<true|false> default is false");
System.out.println("");
System.out.println("");
System.out.println("Examples:");
System.out.println("$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\"");
System.out.println(
"$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -passthru=true");
System.out.println(
"$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -vhosts=secure");
System.out.println("");
System.out.println("OpsMap:");
System.out.println("A file that maps WSDL operations to HTTP Verbs. A Sample Ops Mapping file looks like:");
System.out.println("");
System.out.println("\t<proxywriter>");
System.out.println("\t\t<get>");
System.out.println("\t\t\t<name location=\"beginsWith\">get</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">list</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">inq</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">search</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">retrieve</name>");
System.out.println("\t\t</get>");
System.out.println("\t\t<post>");
System.out.println("\t\t\t<name location=\"contains\">create</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">add</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">process</name>");
System.out.println("\t\t</post>");
System.out.println("\t\t<put>");
System.out.println("\t\t\t<name location=\"contains\">update</name>");
System.out.println("\t\t\t<name location=\"contains\">change</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">modify</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">set</name>");
System.out.println("\t\t</put>");
System.out.println("\t\t<delete>");
System.out.println("\t\t\t<name location=\"beginsWith\">delete</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">remove</name>");
System.out.println("\t\t\t<name location=\"beginsWith\">del</name>");
System.out.println("\t\t</delete>");
System.out.println("\t</proxywriter>");
}
private static List<WsdlDefinitions.Port> convertPorts(List<com.predic8.wsdl.Port> ports,
List<PortType> portTypes) {
List<WsdlDefinitions.Port> list = new ArrayList<>(ports.size());
for (com.predic8.wsdl.Port port : ports) {
list.add(new WsdlDefinitions.Port(port.getName(), convertOperations(port.getBinding(), portTypes)));
}
return list;
}
private static List<WsdlDefinitions.Operation> convertOperations(Binding binding, List<PortType> portTypes) {
List<WsdlDefinitions.Operation> list = new ArrayList<>();
OpsMap opsMap = null;
try {
opsMap = new OpsMap(OPSMAPPING_TEMPLATE);
} catch (Exception e) {
}
binding.getOperations();
for (BindingOperation bindingOperation : binding.getOperations()) {
final String operationName = bindingOperation.getName();
final WsdlDefinitions.Operation operation = new WsdlDefinitions.Operation(operationName,
findDocForOperation(operationName, portTypes), opsMap.getVerb(operationName, null),
opsMap.getResourcePath(operationName, null), null);
list.add(operation);
}
return list;
}
private static String findDocForOperation(String operationName, List<PortType> portTypes) {
for (PortType portType : portTypes) {
final Operation operation = portType.getOperation(operationName);
if (operation != null) {
return operation.getDocumentation() != null ? operation.getDocumentation().getContent() : "";
}
}
return "";
}
private static WsdlDefinitions definitionsToWsdlDefinitions(Definitions definitions) {
List<WsdlDefinitions.Service> services = new ArrayList<>();
definitions.getServices();
for (Service service : definitions.getServices()) {
final WsdlDefinitions.Service service1 = new WsdlDefinitions.Service(service.getName(),
convertPorts(service.getPorts(), definitions.getPortTypes()));
services.add(service1);
}
return new WsdlDefinitions(services);
}
public static void main(String[] args) throws Exception {
GenerateProxy genProxy = new GenerateProxy();
String wsdlPath = "";
String proxyDescription = "";
Options opt = new Options(args, 1);
// the wsdl param contains the URL or FilePath to a WSDL document
opt.getSet().addOption("wsdl", Separator.EQUALS, Multiplicity.ONCE);
// if this flag it set, the generate a passthru proxy
opt.getSet().addOption("passthru", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set this flag to pass proxy description
opt.getSet().addOption("desc", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set this flag to specify service name
opt.getSet().addOption("service", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set this flag to specify port name
opt.getSet().addOption("port", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set this flag to specify operations map
opt.getSet().addOption("opsmap", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set this flag to handle all operations via post verb
opt.getSet().addOption("allpost", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set virtual hosts
opt.getSet().addOption("vhosts", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set build path
opt.getSet().addOption("build", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// add verify oauth policy
opt.getSet().addOption("oauth", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// add verify apikey policy
opt.getSet().addOption("apikey", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// add impose quota policy
opt.getSet().addOption("quota", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set basepath
opt.getSet().addOption("basepath", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// add enable cors conditions
opt.getSet().addOption("cors", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
// set this flag to enable debug
opt.getSet().addOption("debug", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.check();
if (opt.getSet().isSet("wsdl")) {
// React to option -wsdl
wsdlPath = opt.getSet().getOption("wsdl").getResultValue(0);
} else {
System.out.println("-wsdl is a madatory parameter");
usage();
System.exit(1);
}
if (opt.getSet().isSet("passthru")) {
// React to option -passthru
genProxy.setPassThru(Boolean.parseBoolean(opt.getSet().getOption("passthru").getResultValue(0)));
if (opt.getSet().isSet("cors")) {
LOGGER.warning("WARNING: cors can only be enabled for SOAP to REST. This flag will be ignored.");
}
if (opt.getSet().isSet("desc")) {
// React to option -des
proxyDescription = opt.getSet().getOption("desc").getResultValue(0);
genProxy.setDesc(true);
} else {
proxyDescription = "Generated SOAP proxy from ";
}
} else {
genProxy.setPassThru(false);
if (opt.getSet().isSet("desc")) {
// React to option -des
proxyDescription = opt.getSet().getOption("desc").getResultValue(0);
genProxy.setDesc(true);
} else {
proxyDescription = "Generated SOAP to API proxy from ";
}
}
if (opt.getSet().isSet("service")) {
// React to option -service
genProxy.setService(opt.getSet().getOption("service").getResultValue(0));
if (opt.getSet().isSet("port")) {
// React to option -port
genProxy.setPort(opt.getSet().getOption("port").getResultValue(0));
}
}
if (opt.getSet().isSet("opsmap")) {
genProxy.setOpsMap(opt.getSet().getOption("opsmap").getResultValue(0));
} else {
genProxy.setOpsMap(GenerateProxy.OPSMAPPING_TEMPLATE);
}
if (opt.getSet().isSet("allpost")) {
genProxy.setAllPost(new Boolean(opt.getSet().getOption("allpost").getResultValue(0)));
}
if (opt.getSet().isSet("vhosts")) {
genProxy.setVHost(opt.getSet().getOption("vhosts").getResultValue(0));
}
if (opt.getSet().isSet("build")) {
genProxy.setBuildFolder(opt.getSet().getOption("build").getResultValue(0));
}
if (opt.getSet().isSet("basepath")) {
genProxy.setBasePath(opt.getSet().getOption("basepath").getResultValue(0));
}
if (opt.getSet().isSet("cors")) {
genProxy.setCORS(new Boolean(opt.getSet().getOption("cors").getResultValue(0)));
}
if (opt.getSet().isSet("oauth")) {
genProxy.setOAuth(new Boolean(opt.getSet().getOption("oauth").getResultValue(0)));
if (opt.getSet().isSet("quota")) {
genProxy.setQuotaOAuth(new Boolean(opt.getSet().getOption("quota").getResultValue(0)));
}
}
if (opt.getSet().isSet("apikey")) {
genProxy.setAPIKey(new Boolean(opt.getSet().getOption("apikey").getResultValue(0)));
if (opt.getSet().isSet("quota")) {
genProxy.setQuotaAPIKey(new Boolean(opt.getSet().getOption("quota").getResultValue(0)));
}
}
if (!opt.getSet().isSet("apikey") && !opt.getSet().isSet("oauth") && opt.getSet().isSet("quota")) {
LOGGER.warning("WARNING: Quota is applicable with apikey or oauth flags. This flag will be ignored");
}
if (opt.getSet().isSet("debug")) {
// enable debug
LOGGER.setLevel(Level.FINEST);
handler.setLevel(Level.FINEST);
} else {
LOGGER.setLevel(Level.INFO);
handler.setLevel(Level.INFO);
}
final InputStream begin = genProxy.begin(proxyDescription, wsdlPath);
if (begin != null) {
Files.copy(begin, new File(genProxy.proxyName + ".zip").toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
public static InputStream generateProxy(GenerateProxyOptions generateProxyOptions) throws Exception {
GenerateProxy genProxy = new GenerateProxy();
genProxy.setOpsMap(OPSMAPPING_TEMPLATE);
genProxy.setPassThru(generateProxyOptions.isPassthrough());
genProxy.setBasePath(generateProxyOptions.getBasepath());
genProxy.setVHost(generateProxyOptions.getvHosts());
genProxy.setPort(generateProxyOptions.getPort());
genProxy.setCORS(generateProxyOptions.isCors());
genProxy.setAPIKey(generateProxyOptions.isApiKey());
genProxy.setOAuth(generateProxyOptions.isOauth());
genProxy.setQuotaAPIKey(generateProxyOptions.isApiKey() && generateProxyOptions.isQuota());
genProxy.setQuotaOAuth(generateProxyOptions.isOauth() && generateProxyOptions.isQuota());
if (generateProxyOptions.getOperationsFilter() != null
&& generateProxyOptions.getOperationsFilter().length() > 0) {
genProxy.setSelectedOperationsJson(generateProxyOptions.getOperationsFilter());
}
return genProxy.begin(generateProxyOptions.getDescription() != null ? generateProxyOptions.getDescription()
: "Generated SOAP to API proxy", generateProxyOptions.getWsdl());
}
public static WsdlDefinitions parseWsdl(String wsdl) throws ErrorParsingWsdlException {
final WSDLParser wsdlParser = new WSDLParser();
try {
final Definitions definitions = wsdlParser.parse(wsdl);
return definitionsToWsdlDefinitions(definitions);
} catch (com.predic8.xml.util.ResourceDownloadException e) {
String message = formatResourceError(e);
throw new ErrorParsingWsdlException(message, e);
} catch (Throwable t) {
String message = t.getLocalizedMessage();
if (message == null) {
message = t.getMessage();
}
if (message == null) {
message = "Error processing WSDL.";
}
throw new ErrorParsingWsdlException(message, t);
}
}
private static String formatResourceError(com.predic8.xml.util.ResourceDownloadException e) {
StringBuffer errorMessage = new StringBuffer("Could not download resource.");
String rootCause = e.getRootCause().getLocalizedMessage();
if (!rootCause.isEmpty()) {
int pos = rootCause.indexOf("status for class:");
if (pos == -1) {
errorMessage.append(" " + rootCause + ".");
}
}
return (errorMessage.toString());
}
}
|
// Generated by delegate_gen on Mon Jan 13 09:30:38 CET 2014
package info.tregmine.api;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.entity.Player.Spigot;
import info.tregmine.Tregmine;
import net.md_5.bungee.api.chat.BaseComponent;
import net.minecraft.server.v1_9_R1.EntityPlayer;
import net.minecraft.server.v1_9_R1.PacketPlayOutChat;
public abstract class PlayerDelegate
{
private org.bukkit.entity.Player delegate;
private org.bukkit.permissions.PermissionAttachment attachment;
protected PlayerDelegate(org.bukkit.entity.Player d)
{
this.delegate = d;
}
public void setDelegate(org.bukkit.entity.Player v)
{
this.delegate = v;
}
public org.bukkit.entity.Player getDelegate()
{
return delegate;
}
private void checkState()
{
if (delegate == null) {
throw new IllegalStateException(
"Can't be used when delegate isn't set.");
}
}
private void checkAttachment()
{
if(attachment == null){
throw new IllegalStateException("Can't be used when attachment isn't set.");
}
}
public java.net.InetSocketAddress getAddress()
{
checkState();
return delegate.getAddress();
}
public java.lang.String getDisplayName()
{
checkState();
return delegate.getDisplayName();
}
public void setLevel(int p0)
{
checkState();
delegate.setLevel(p0);
}
public long getPlayerTime()
{
checkState();
return delegate.getPlayerTime();
}
public long getPlayerTimeOffset()
{
checkState();
return delegate.getPlayerTimeOffset();
}
public boolean isPlayerTimeRelative()
{
checkState();
return delegate.isPlayerTimeRelative();
}
public void resetPlayerTime()
{
checkState();
delegate.resetPlayerTime();
}
public void setPlayerWeather(org.bukkit.WeatherType p0)
{
checkState();
delegate.setPlayerWeather(p0);
}
public org.bukkit.WeatherType getPlayerWeather()
{
checkState();
return delegate.getPlayerWeather();
}
public void resetPlayerWeather()
{
checkState();
delegate.resetPlayerWeather();
}
public void giveExp(int p0)
{
checkState();
delegate.giveExp(p0);
}
public void giveExpLevels(int p0)
{
checkState();
delegate.giveExpLevels(p0);
}
public float getExp()
{
checkState();
return delegate.getExp();
}
public void setExp(float p0)
{
checkState();
delegate.setExp(p0);
}
public int getLevel()
{
checkState();
return delegate.getLevel();
}
public int getTotalExperience()
{
checkState();
return delegate.getTotalExperience();
}
public void setTotalExperience(int p0)
{
checkState();
delegate.setTotalExperience(p0);
}
public float getExhaustion()
{
checkState();
return delegate.getExhaustion();
}
public void setExhaustion(float p0)
{
checkState();
delegate.setExhaustion(p0);
}
public float getSaturation()
{
checkState();
return delegate.getSaturation();
}
public void setSaturation(float p0)
{
checkState();
delegate.setSaturation(p0);
}
public int getFoodLevel()
{
checkState();
return delegate.getFoodLevel();
}
public void setFoodLevel(int p0)
{
checkState();
delegate.setFoodLevel(p0);
}
public org.bukkit.Location getBedSpawnLocation()
{
checkState();
return delegate.getBedSpawnLocation();
}
public void setBedSpawnLocation(org.bukkit.Location p0, boolean p1)
{
checkState();
delegate.setBedSpawnLocation(p0, p1);
}
public void setBedSpawnLocation(org.bukkit.Location p0)
{
checkState();
delegate.setBedSpawnLocation(p0);
}
public boolean getAllowFlight()
{
checkState();
return delegate.getAllowFlight();
}
public void setAllowFlight(boolean p0)
{
checkState();
delegate.setAllowFlight(p0);
}
public void hidePlayer(org.bukkit.entity.Player p0)
{
checkState();
delegate.hidePlayer(p0);
}
public void showPlayer(org.bukkit.entity.Player p0)
{
checkState();
delegate.showPlayer(p0);
}
public boolean canSee(org.bukkit.entity.Player p0)
{
checkState();
return delegate.canSee(p0);
}
public boolean isFlying()
{
checkState();
return delegate.isFlying();
}
public void setFlying(boolean p0)
{
checkState();
delegate.setFlying(p0);
}
public void setFlySpeed(float p0)
{
checkState();
delegate.setFlySpeed(p0);
}
public void setWalkSpeed(float p0)
{
checkState();
delegate.setWalkSpeed(p0);
}
public float getFlySpeed()
{
checkState();
return delegate.getFlySpeed();
}
public float getWalkSpeed()
{
checkState();
return delegate.getWalkSpeed();
}
public void setResourcePack(java.lang.String p0)
{
checkState();
delegate.setResourcePack(p0);
}
public org.bukkit.scoreboard.Scoreboard getScoreboard()
{
checkState();
return delegate.getScoreboard();
}
public void setScoreboard(org.bukkit.scoreboard.Scoreboard p0)
{
checkState();
delegate.setScoreboard(p0);
}
public boolean isHealthScaled()
{
checkState();
return delegate.isHealthScaled();
}
public void setHealthScaled(boolean p0)
{
checkState();
delegate.setHealthScaled(p0);
}
public void setHealthScale(double p0)
{
checkState();
delegate.setHealthScale(p0);
}
public double getHealthScale()
{
checkState();
return delegate.getHealthScale();
}
public void setDisplayName(java.lang.String p0)
{
checkState();
delegate.setDisplayName(p0);
}
public void setCompassTarget(org.bukkit.Location p0)
{
checkState();
delegate.setCompassTarget(p0);
}
public org.bukkit.Location getCompassTarget()
{
checkState();
return delegate.getCompassTarget();
}
public void sendRawMessage(java.lang.String p0)
{
checkState();
delegate.sendRawMessage(p0);
}
public void kickPlayer(Tregmine instance, final java.lang.String p0)
{
checkState();
//delegate.kickPlayer(p0);
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, new Runnable(){
@Override
public void run() {
delegate.kickPlayer(p0);
}
});
}
public Spigot getSpigot()
{
checkState();
return delegate.spigot();
}
public void chat(java.lang.String p0)
{
checkState();
delegate.chat(p0);
}
public boolean performCommand(java.lang.String p0)
{
checkState();
return delegate.performCommand(p0);
}
public boolean isSneaking()
{
checkState();
return delegate.isSneaking();
}
public void setSneaking(boolean p0)
{
checkState();
delegate.setSneaking(p0);
}
public boolean isSprinting()
{
checkState();
return delegate.isSprinting();
}
public void setSprinting(boolean p0)
{
checkState();
delegate.setSprinting(p0);
}
public void saveData()
{
checkState();
delegate.saveData();
}
public void loadData()
{
checkState();
delegate.loadData();
}
public void setSleepingIgnored(boolean p0)
{
checkState();
delegate.setSleepingIgnored(p0);
}
public boolean isSleepingIgnored()
{
checkState();
return delegate.isSleepingIgnored();
}
public void playNote(org.bukkit.Location p0, org.bukkit.Instrument p1, org.bukkit.Note p2)
{
checkState();
delegate.playNote(p0, p1, p2);
}
public java.lang.String getPlayerListName()
{
checkState();
return delegate.getPlayerListName();
}
public void setPlayerListName(java.lang.String p0)
{
checkState();
delegate.setPlayerListName(p0);
}
public void playSound(org.bukkit.Location p0, org.bukkit.Sound p1, float p2, float p3)
{
checkState();
delegate.playSound(p0, p1, p2, p3);
}
public <T extends java.lang.Object> void playEffect(org.bukkit.Location p0, org.bukkit.Effect p1, T p2)
{
checkState();
delegate.playEffect(p0, p1, p2);
}
public void sendMap(org.bukkit.map.MapView p0)
{
checkState();
delegate.sendMap(p0);
}
public void awardAchievement(org.bukkit.Achievement p0)
{
checkState();
delegate.awardAchievement(p0);
}
public void incrementStatistic(org.bukkit.Statistic p0, int p1)
{
checkState();
delegate.incrementStatistic(p0, p1);
}
public void incrementStatistic(org.bukkit.Statistic p0, org.bukkit.Material p1, int p2)
{
checkState();
delegate.incrementStatistic(p0, p1, p2);
}
public void incrementStatistic(org.bukkit.Statistic p0, org.bukkit.Material p1)
{
checkState();
delegate.incrementStatistic(p0, p1);
}
public void incrementStatistic(org.bukkit.Statistic p0)
{
checkState();
delegate.incrementStatistic(p0);
}
public void setPlayerTime(long p0, boolean p1)
{
checkState();
delegate.setPlayerTime(p0, p1);
}
public java.lang.String getName()
{
checkState();
return delegate.getName();
}
public org.bukkit.inventory.PlayerInventory getInventory()
{
checkState();
return delegate.getInventory();
}
public org.bukkit.inventory.InventoryView openEnchanting(org.bukkit.Location p0, boolean p1)
{
checkState();
return delegate.openEnchanting(p0, p1);
}
public void closeInventory()
{
checkState();
delegate.closeInventory();
}
public org.bukkit.inventory.ItemStack getItemInHand()
{
checkState();
return delegate.getItemOnCursor();
}
public void setItemInHand(org.bukkit.inventory.ItemStack p0)
{
checkState();
delegate.setItemInHand(p0);
}
public org.bukkit.inventory.ItemStack getItemOnCursor()
{
checkState();
return delegate.getItemOnCursor();
}
public void setItemOnCursor(org.bukkit.inventory.ItemStack p0)
{
checkState();
delegate.setItemOnCursor(p0);
}
public boolean isSleeping()
{
checkState();
return delegate.isSleeping();
}
public int getSleepTicks()
{
checkState();
return delegate.getSleepTicks();
}
public org.bukkit.GameMode getGameMode()
{
checkState();
return delegate.getGameMode();
}
public void setGameMode(org.bukkit.GameMode p0)
{
checkState();
delegate.setGameMode(p0);
}
public boolean isBlocking()
{
checkState();
return delegate.isBlocking();
}
public int getExpToLevel()
{
checkState();
return delegate.getExpToLevel();
}
public org.bukkit.inventory.Inventory getEnderChest()
{
checkState();
return delegate.getEnderChest();
}
public boolean setWindowProperty(org.bukkit.inventory.InventoryView.Property p0, int p1)
{
checkState();
return delegate.setWindowProperty(p0, p1);
}
public org.bukkit.inventory.InventoryView getOpenInventory()
{
checkState();
return delegate.getOpenInventory();
}
public org.bukkit.inventory.InventoryView openInventory(org.bukkit.inventory.Inventory p0)
{
checkState();
return delegate.openInventory(p0);
}
public void openInventory(org.bukkit.inventory.InventoryView p0)
{
checkState();
delegate.openInventory(p0);
}
public org.bukkit.inventory.InventoryView openWorkbench(org.bukkit.Location p0, boolean p1)
{
checkState();
return delegate.openWorkbench(p0, p1);
}
public org.bukkit.Location getEyeLocation()
{
checkState();
return delegate.getEyeLocation();
}
public double getEyeHeight()
{
checkState();
return delegate.getEyeHeight();
}
public double getEyeHeight(boolean p0)
{
checkState();
return delegate.getEyeHeight(p0);
}
public <T extends org.bukkit.entity.Projectile> T launchProjectile(java.lang.Class<? extends T> p0)
{
checkState();
return delegate.launchProjectile(p0);
}
public int getRemainingAir()
{
checkState();
return delegate.getRemainingAir();
}
public void setRemainingAir(int p0)
{
checkState();
delegate.setRemainingAir(p0);
}
public int getMaximumAir()
{
checkState();
return delegate.getMaximumAir();
}
public void setMaximumAir(int p0)
{
checkState();
delegate.setMaximumAir(p0);
}
public int getMaximumNoDamageTicks()
{
checkState();
return delegate.getMaximumNoDamageTicks();
}
public void setMaximumNoDamageTicks(int p0)
{
checkState();
delegate.setMaximumNoDamageTicks(p0);
}
public double getLastDamage()
{
checkState();
return delegate.getLastDamage();
}
public void setLastDamage(double p0)
{
checkState();
delegate.setLastDamage(p0);
}
public int getNoDamageTicks()
{
checkState();
return delegate.getNoDamageTicks();
}
public void setNoDamageTicks(int p0)
{
checkState();
delegate.setNoDamageTicks(p0);
}
public org.bukkit.entity.Player getKiller()
{
checkState();
return delegate.getKiller();
}
public boolean addPotionEffect(org.bukkit.potion.PotionEffect p0, boolean p1)
{
checkState();
return delegate.addPotionEffect(p0, p1);
}
public boolean addPotionEffect(org.bukkit.potion.PotionEffect p0)
{
checkState();
return delegate.addPotionEffect(p0);
}
public boolean addPotionEffects(java.util.Collection<org.bukkit.potion.PotionEffect> p0)
{
checkState();
return delegate.addPotionEffects(p0);
}
public boolean hasPotionEffect(org.bukkit.potion.PotionEffectType p0)
{
checkState();
return delegate.hasPotionEffect(p0);
}
public void removePotionEffect(org.bukkit.potion.PotionEffectType p0)
{
checkState();
delegate.removePotionEffect(p0);
}
public java.util.Collection<org.bukkit.potion.PotionEffect> getActivePotionEffects()
{
checkState();
return delegate.getActivePotionEffects();
}
public boolean hasLineOfSight(org.bukkit.entity.Entity p0)
{
checkState();
return delegate.hasLineOfSight(p0);
}
public boolean getRemoveWhenFarAway()
{
checkState();
return delegate.getRemoveWhenFarAway();
}
public void setRemoveWhenFarAway(boolean p0)
{
checkState();
delegate.setRemoveWhenFarAway(p0);
}
public org.bukkit.inventory.EntityEquipment getEquipment()
{
checkState();
return delegate.getEquipment();
}
public void setCanPickupItems(boolean p0)
{
checkState();
delegate.setCanPickupItems(p0);
}
public boolean getCanPickupItems()
{
checkState();
return delegate.getCanPickupItems();
}
public void setCustomName(java.lang.String p0)
{
checkState();
delegate.setCustomName(p0);
}
public java.lang.String getCustomName()
{
checkState();
return delegate.getCustomName();
}
public void setCustomNameVisible(boolean p0)
{
checkState();
delegate.setCustomNameVisible(p0);
}
public boolean isCustomNameVisible()
{
checkState();
return delegate.isCustomNameVisible();
}
public boolean isLeashed()
{
checkState();
return delegate.isLeashed();
}
public org.bukkit.entity.Entity getLeashHolder()
{
checkState();
return delegate.getLeashHolder();
}
public boolean setLeashHolder(org.bukkit.entity.Entity p0)
{
checkState();
return delegate.setLeashHolder(p0);
}
public void remove()
{
checkState();
delegate.remove();
}
public boolean isEmpty()
{
checkState();
return delegate.isEmpty();
}
public org.bukkit.Location getLocation()
{
checkState();
return delegate.getLocation();
}
public org.bukkit.Location getLocation(org.bukkit.Location p0)
{
checkState();
return delegate.getLocation(p0);
}
public org.bukkit.entity.EntityType getType()
{
checkState();
return delegate.getType();
}
public boolean isValid()
{
checkState();
return delegate.isValid();
}
public void setVelocity(org.bukkit.util.Vector p0)
{
checkState();
delegate.setVelocity(p0);
}
public org.bukkit.util.Vector getVelocity()
{
checkState();
return delegate.getVelocity();
}
public org.bukkit.World getWorld()
{
checkState();
return delegate.getWorld();
}
public boolean teleport(org.bukkit.Location p0)
{
checkState();
return delegate.teleport(p0);
}
public boolean teleport(org.bukkit.entity.Entity p0, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause p1)
{
checkState();
return delegate.teleport(p0, p1);
}
public boolean teleport(org.bukkit.Location p0, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause p1)
{
checkState();
return delegate.teleport(p0, p1);
}
public boolean teleport(org.bukkit.entity.Entity p0)
{
checkState();
return delegate.teleport(p0);
}
public java.util.List<org.bukkit.entity.Entity> getNearbyEntities(double p0, double p1, double p2)
{
checkState();
return delegate.getNearbyEntities(p0, p1, p2);
}
public int getEntityId()
{
checkState();
return delegate.getEntityId();
}
public int getFireTicks()
{
checkState();
return delegate.getFireTicks();
}
public int getMaxFireTicks()
{
checkState();
return delegate.getMaxFireTicks();
}
public void setFireTicks(int p0)
{
checkState();
delegate.setFireTicks(p0);
}
public boolean isDead()
{
checkState();
return delegate.isDead();
}
public org.bukkit.Server getServer()
{
checkState();
return delegate.getServer();
}
public org.bukkit.entity.Entity getPassenger()
{
checkState();
return delegate.getPassenger();
}
public boolean setPassenger(org.bukkit.entity.Entity p0)
{
checkState();
return delegate.setPassenger(p0);
}
public boolean eject()
{
checkState();
return delegate.eject();
}
public float getFallDistance()
{
checkState();
return delegate.getFallDistance();
}
public void setFallDistance(float p0)
{
checkState();
delegate.setFallDistance(p0);
}
public void setLastDamageCause(org.bukkit.event.entity.EntityDamageEvent p0)
{
checkState();
delegate.setLastDamageCause(p0);
}
public org.bukkit.event.entity.EntityDamageEvent getLastDamageCause()
{
checkState();
return delegate.getLastDamageCause();
}
public java.util.UUID getUniqueId()
{
checkState();
return delegate.getUniqueId();
}
public int getTicksLived()
{
checkState();
return delegate.getTicksLived();
}
public void setTicksLived(int p0)
{
checkState();
delegate.setTicksLived(p0);
}
public boolean isInsideVehicle()
{
checkState();
return delegate.isInsideVehicle();
}
public boolean leaveVehicle()
{
checkState();
return delegate.leaveVehicle();
}
public org.bukkit.entity.Entity getVehicle()
{
checkState();
return delegate.getVehicle();
}
public void playEffect(org.bukkit.EntityEffect p0)
{
checkState();
delegate.playEffect(p0);
}
public void setMetadata(java.lang.String p0, org.bukkit.metadata.MetadataValue p1)
{
checkState();
delegate.setMetadata(p0, p1);
}
public java.util.List<org.bukkit.metadata.MetadataValue> getMetadata(java.lang.String p0)
{
checkState();
return delegate.getMetadata(p0);
}
public boolean hasMetadata(java.lang.String p0)
{
checkState();
return delegate.hasMetadata(p0);
}
public void removeMetadata(java.lang.String p0, org.bukkit.plugin.Plugin p1)
{
checkState();
delegate.removeMetadata(p0, p1);
}
public void damage(double p0, org.bukkit.entity.Entity p1)
{
checkState();
delegate.damage(p0, p1);
}
public void damage(double p0)
{
checkState();
delegate.damage(p0);
}
public double getHealth()
{
checkState();
return delegate.getHealth();
}
public void setHealth(double p0)
{
checkState();
delegate.setHealth(p0);
}
public double getMaxHealth()
{
checkState();
return delegate.getMaxHealth();
}
public void setMaxHealth(double p0)
{
checkState();
delegate.setMaxHealth(p0);
}
public void resetMaxHealth()
{
checkState();
delegate.resetMaxHealth();
}
public boolean hasPermission(java.lang.String p0)
{
checkState();
return delegate.hasPermission(p0);
}
public boolean hasPermission(org.bukkit.permissions.Permission p0)
{
checkState();
return delegate.hasPermission(p0);
}
public void setPermission(java.lang.String p0)
{
checkState();
}
public void removeAttachment(org.bukkit.permissions.PermissionAttachment p0)
{
checkState();
delegate.removeAttachment(p0);
}
public void recalculatePermissions()
{
checkState();
delegate.recalculatePermissions();
}
public java.util.Set<org.bukkit.permissions.PermissionAttachmentInfo> getEffectivePermissions()
{
checkState();
return delegate.getEffectivePermissions();
}
public boolean isPermissionSet(java.lang.String p0)
{
checkState();
return delegate.isPermissionSet(p0);
}
public boolean isPermissionSet(org.bukkit.permissions.Permission p0)
{
checkState();
return delegate.isPermissionSet(p0);
}
public org.bukkit.permissions.PermissionAttachment addAttachment(org.bukkit.plugin.Plugin p0)
{
checkState();
return delegate.addAttachment(p0);
}
public org.bukkit.permissions.PermissionAttachment addAttachment(org.bukkit.plugin.Plugin p0, java.lang.String p1, boolean p2)
{
checkState();
return delegate.addAttachment(p0, p1, p2);
}
public org.bukkit.permissions.PermissionAttachment addAttachment(org.bukkit.plugin.Plugin p0, int p1)
{
checkState();
return delegate.addAttachment(p0, p1);
}
public org.bukkit.permissions.PermissionAttachment addAttachment(org.bukkit.plugin.Plugin p0, java.lang.String p1, boolean p2, int p3)
{
checkState();
return delegate.addAttachment(p0, p1, p2, p3);
}
public boolean isOp()
{
checkState();
return delegate.isOp();
}
public void setOp(boolean p0)
{
checkState();
delegate.setOp(p0);
}
public void abandonConversation(org.bukkit.conversations.Conversation p0)
{
checkState();
delegate.abandonConversation(p0);
}
public void abandonConversation(org.bukkit.conversations.Conversation p0, org.bukkit.conversations.ConversationAbandonedEvent p1)
{
checkState();
delegate.abandonConversation(p0, p1);
}
public boolean isConversing()
{
checkState();
return delegate.isConversing();
}
public void acceptConversationInput(java.lang.String p0)
{
checkState();
delegate.acceptConversationInput(p0);
}
public boolean beginConversation(org.bukkit.conversations.Conversation p0)
{
checkState();
return delegate.beginConversation(p0);
}
public void sendTrueMsg(java.lang.String p0, Tregmine instance)
{
boolean lockdown = instance.getLockdown();
String n = instance.getConfig().getString("general.servername");
checkState();
ChatColor color = null;
if(lockdown){
color = ChatColor.RED;
}else{
color = ChatColor.GOLD;
}
if(p0.startsWith("%internal%")){
String message = p0.replace("%internal%", "");
delegate.sendMessage(color + "[Internal]" + ChatColor.RESET + " > " + message);
}
else if(p0.startsWith("%CHAT%")){
String message = p0.replace("%CHAT%", "");
delegate.sendMessage(message);
}
else if(p0.startsWith("%chat")){
String message = p0.replace("%chat", "");
delegate.sendMessage(message);
}
else if(p0.startsWith("%warning%")){
String message = p0.replace("%warning%", "");
delegate.sendMessage(ChatColor.RED + "[Warning]" + ChatColor.RESET + " > " + message);
}
else{
delegate.sendMessage(p0.replace(ChatColor.GOLD + "[Tregmine]" + ChatColor.RESET + " > ", ""));
}
}
public void sendStringMessage(String a){
checkState();
delegate.sendMessage(a);
}
public void sendSpigotMessage(BaseComponent a){
checkState();
sendSpigotMessage(new BaseComponent[] {a});
}
public void sendSpigotMessage(BaseComponent... a){
checkState();
if(getHandle().playerConnection == null) return;
PacketPlayOutChat packet = new PacketPlayOutChat();
packet.components = a;
getHandle().playerConnection.sendPacket(packet);
}
public boolean isBanned()
{
checkState();
return delegate.isBanned();
}
public void setBanned(boolean p0)
{
checkState();
delegate.setBanned(p0);
}
public boolean isWhitelisted()
{
checkState();
return delegate.isWhitelisted();
}
public void setWhitelisted(boolean p0)
{
checkState();
delegate.setWhitelisted(p0);
}
public boolean isOnline()
{
checkState();
return delegate.isOnline();
}
public org.bukkit.entity.Player getPlayer()
{
checkState();
return delegate.getPlayer();
}
public long getFirstPlayed()
{
checkState();
return delegate.getFirstPlayed();
}
public long getLastPlayed()
{
checkState();
return delegate.getLastPlayed();
}
public boolean hasPlayedBefore()
{
checkState();
return delegate.hasPlayedBefore();
}
public java.util.Map<java.lang.String, java.lang.Object> serialize()
{
checkState();
return delegate.serialize();
}
public java.util.Set<java.lang.String> getListeningPluginChannels()
{
checkState();
return delegate.getListeningPluginChannels();
}
public void sendPluginMessage(org.bukkit.plugin.Plugin p0, java.lang.String p1, byte[] p2)
{
checkState();
delegate.sendPluginMessage(p0, p1, p2);
}
public CraftPlayer craftPlayer(){
checkState();
return (CraftPlayer) delegate;
}
public EntityPlayer getHandle(){
checkState();
return craftPlayer().getHandle();
}
public Player.Spigot spigot(){
return delegate.spigot();
}
}
|
package com.bo0tzz.breaklimiter;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Map;
public class EventManager implements Listener {
private Map<String, Object> allowedBlocks;
private BreakLimiter main;
private ConfigManager config;
public EventManager(BreakLimiter mainClass) {
main = mainClass;
config = main.getConfigManager();
allowedBlocks = config.getBlocks();
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock();
Material blockType = block.getType();
Material type;
if (blockType == Material.GLOWING_REDSTONE_ORE) {
type = Material.REDSTONE_ORE;
} else {
type = blockType;
}
Integer timeout = (Integer) allowedBlocks.get(type.toString().toLowerCase());
if(timeout != null) {
int ticks = timeout * 1200;
if (ticks != 0)
new BukkitRunnable() {
@Override
public void run() {
if (block.isEmpty()) {
block.setType(type);
}
}
}.runTaskLater(main, ticks);
} else {
event.setCancelled(true);
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
if (config.isBlockPlaceAllowed() && !event.getPlayer().isOp()) {
event.setCancelled(true);
}
}
}
|
package com.jmex.bui;
import com.jme.renderer.Renderer;
import com.jmex.bui.enumeratedConstants.Orientation;
import com.jmex.bui.event.ChangeEvent;
import com.jmex.bui.event.ChangeListener;
import com.jmex.bui.event.MouseWheelListener;
import com.jmex.bui.layout.BorderLayout;
import com.jmex.bui.layout.GroupLayout;
import com.jmex.bui.layout.Justification;
import com.jmex.bui.layout.Policy;
import com.jmex.bui.util.Insets;
import com.jmex.bui.util.Rectangle;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Provides a scrollable, lazily instantiated component view of values
*/
public abstract class BScrollingList<V, C extends BComponent> extends BContainer {
//Instantiates an empty {@link BScrollingList}.
public BScrollingList() {
this(null);
}
/**
* Instantiates a {@link BScrollingList} with an initial value collection.
* @param values the values to add
*/
public BScrollingList(Collection<V> values) {
super(new BorderLayout(0, 0));
_values = new ArrayList<Entry<V, C>>();
if (values != null) {
for (V value : values) {
_values.add(new Entry<V, C>(value));
}
}
_lastBottom = 0;
// we'll set up our model in layout()
_model = new BoundedRangeModel(0, 0, 1, 1);
// create our viewport and scrollbar
add(_vport = new BViewport(), BorderLayout.CENTER);
_model.addChangeListener(_vport);
add(_vbar = new BScrollBar(Orientation.VERTICAL, _model),
BorderLayout.EAST);
}
/**
* Appends a value to our list, possibly scrolling our view to display it.
* @param value the value to add
* @param snapToBottom if the value should snap to the bottom of the list
*/
public void addValue(V value,
boolean snapToBottom) {
addValue(_values.size(), value, snapToBottom);
}
/**
* Inserts a value into our list at the specified position.
* @param index the index to add this value at
* @param value the value to add
*/
public void addValue(int index,
V value) {
addValue(index, value, false);
}
/**
* Removes the value at the specified index
* @param index the index at which to remove a value
*/
public void removeValue(int index) {
Entry<V, C> value = _values.remove(index);
_model.setValue(0);
_vport.remove(value.component);
_vport.invalidate();
}
/**
* Removes the first occurrence of the specified value
* @param value the value to remove
*/
public void removeValue(V value) {
for(Entry<V, C> entry : _values) {
if(entry.value == value) {
_values.remove(entry);
_model.setValue(0);
_vport.remove(entry.component);
_vport.invalidate();
break;
}
}
}
/**
* Clears all the current values and any related components.
*/
public void removeValues() {
_values.clear();
_model.setValue(0);
_vport.removeAll();
_vport.invalidate();
}
/**
* Removes values from the top of the list.
*/
public void removeValuesFromTop(int num) {
num = Math.min(num, _values.size());
for (int ii = 0; ii < num; ii++) {
Entry<V, C> value = _values.remove(0);
_vport.remove(value.component);
}
_vport.invalidate();
}
/**
* Must be implemented by subclasses to instantiate the correct BComponent
* subclass for a given list value.
*/
protected abstract C createComponent(V value);
/**
* Adds a value to the list and snaps to the bottom of the list if desired.
* @param index the index to add this value at
* @param value the value to add
* @param snap if the value should snap to the bottom of the list
*/
protected void addValue(int index,
V value,
boolean snap) {
_values.add(index, new Entry<V, C>(value));
_vport.invalidateAndSnap();
}
/**
* Does all the heavy lifting for the {@link BScrollingList}.
*/
protected class BViewport extends BContainer
implements ChangeListener {
public BViewport() {
super(GroupLayout.makeVert(
Policy.NONE,
Justification.TOP,
Policy.STRETCH));
}
/**
* Returns a reference to the vertical scroll bar.
* @return a reference to the vertical scroll bar
*/
public BScrollBar getVerticalScrollBar() {
return _vbar;
}
/**
* Recomputes our layout and snaps to the bottom if we were at the bottom previously.
*/
public void invalidateAndSnap() {
_snap =
_model.getValue() + _model.getExtent() >= _model.getMaximum();
invalidate();
}
@Override
// documentation inherited
protected void wasAdded() {
super.wasAdded();
addListener(_wheelListener = _model.createWheelListener());
}
@Override
// from BComponent
protected void wasRemoved() {
super.wasRemoved();
if (_wheelListener != null) {
removeListener(_wheelListener);
_wheelListener = null;
}
}
// from interface ChangeListener
public void stateChanged(ChangeEvent event) {
invalidate();
}
@Override
// from BComponent
public void invalidate() {
// if we're not attached, don't worry about it
BWindow window;
BRootNode root;
if (!_valid || (window = getWindow()) == null ||
(root = window.getRootNode()) == null) {
return;
}
_valid = false;
root.rootInvalidated(this);
}
@Override
// from BComponent
public void layout() {
Insets insets = getInsets();
int twidth = getWidth() - insets.getHorizontal();
int theight = getHeight() - insets.getVertical();
int gap = ((GroupLayout) getLayoutManager()).getGap();
// first make sure all of our entries have been measured and
// compute our total height and extent
int totheight = 0;
for (Entry<V, C> entry : _values) {
if (entry.height < 0) {
if (entry.component == null) {
entry.component = createComponent(entry.value);
}
boolean remove = false;
if (!entry.component.isAdded()) {
add(entry.component);
remove = true;
}
entry.height =
entry.component.getPreferredSize(twidth, 0).height;
if (remove) {
remove(entry.component);
}
}
totheight += entry.height;
}
if (_values.size() > 1) {
totheight += (gap * _values.size() - 1);
}
int extent = Math.min(theight, totheight);
// if our most recent value was added with _snap then we scroll to
// the bottom on this layout and clear our snappy flag
int value = _snap ? (totheight - extent) : _model.getValue();
_snap = false;
// if our extent or total height have changed, update the model
// (because we're currently invalid, the resulting call to
// invalidate() will have no effect)
if (extent != _model.getExtent() ||
totheight != _model.getMaximum()) {
_model.setRange(0, value, extent, totheight);
}
// now back up from the last component until we reach the first one
// that's in view
_offset = _model.getValue();
int compIx = 0;
for (int ii = 0; ii < _values.size(); ii++) {
Entry<V, C> entry = _values.get(ii);
if (_offset < entry.height) {
compIx = ii;
break;
}
_offset -= (entry.height + gap);
// remove and clear out the components before our top component
if (entry.component != null) {
if (entry.component.isAdded()) {
remove(entry.component);
}
entry.component = null;
}
}
// compensate for the partially visible topmost component
extent += _offset;
// now add components until we use up our extent
int topIx = compIx;
while (compIx < _values.size() && extent > 0) {
Entry<V, C> entry = _values.get(compIx);
if (entry.component == null) {
entry.component = createComponent(entry.value);
}
if (!entry.component.isAdded()) {
add(compIx - topIx, entry.component);
}
extent -= (entry.height + gap);
compIx++;
}
// lastly remove any components below the last visible component
while (compIx < _values.size()) {
Entry<V, C> entry = _values.get(compIx);
if (entry.component != null) {
if (entry.component.isAdded()) {
remove(entry.component);
}
entry.component = null;
}
compIx++;
}
// now have the layout manager layout our added components
super.layout();
}
@Override
// from BComponent
protected void renderComponent(Renderer renderer) {
Insets insets = getInsets();
GL11.glTranslatef(0, _offset, 0);
boolean scissored = intersectScissorBox(_srect,
getAbsoluteX() + insets.left,
getAbsoluteY() + insets.bottom,
_width - insets.getHorizontal(),
_height - insets.getVertical());
try {
// render our children
for (int ii = 0, ll = getComponentCount(); ii < ll; ii++) {
getComponent(ii).render(renderer);
}
} finally {
restoreScissorState(scissored, _srect);
GL11.glTranslatef(0, -_offset, 0);
}
}
@Override
// documentation inherited
public BComponent getHitComponent(int mx,
int my) {
// if we're not within our bounds, we needn't check our target
Insets insets = getInsets();
if ((mx < _x + insets.left) || (my < _y + insets.bottom) ||
(mx >= _x + _width - insets.right) ||
(my >= _y + _height - insets.top)) {
return null;
}
// translate the coordinate into our children's coordinates
mx -= _x;
my -= (_y + _offset);
BComponent hit;
for (int ii = 0, ll = getComponentCount(); ii < ll; ii++) {
BComponent child = getComponent(ii);
if ((hit = child.getHitComponent(mx, my)) != null) {
return hit;
}
}
return this;
}
protected int _offset;
protected boolean _snap;
protected Rectangle _srect = new Rectangle();
}
/**
* Used to track the total height of our entries.
*/
protected static class Entry<V, C extends BComponent> {
public C component;
public V value;
public int height = -1;
public Entry(V _value) {
value = _value;
}
}
protected MouseWheelListener _wheelListener;
protected BoundedRangeModel _model;
protected List<Entry<V, C>> _values;
protected BViewport _vport;
protected BScrollBar _vbar;
protected int _lastBottom;
protected static final int EXTENT = 2;
}
|
package com.connorhaigh.javavpk.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import com.connorhaigh.javavpk.exceptions.ArchiveException;
public class Archive
{
/**
* Create a new VPK archive.
* @param file the archive file
*/
public Archive(File file)
{
this.file = file;
this.multiPart = false;
this.signature = 0;
this.version = 0;
this.treeLength = 0;
this.headerLength = 0;
this.entries = new ArrayList<Entry>();
}
/**
* Load the raw data from file to this archive.
* @throws IOException if the archive could not be read
* @throws ArchiveException if a general archive exception occurs
*/
public void load() throws IOException, ArchiveException
{
try (FileInputStream fileInputStream = new FileInputStream(this.file))
{
//check for multiple child archives
this.multiPart = this.file.getName().contains("_dir");
//read header
this.signature = this.readUnsignedInt(fileInputStream);
this.version = this.readUnsignedInt(fileInputStream);
this.treeLength = this.readUnsignedInt(fileInputStream);
this.headerLength = Archive.HEADER_SIZE;
//check signature and version
if (this.signature != Archive.SIGNATURE)
throw new ArchiveException("Invalid signature");
if (this.version != Archive.VERSION)
throw new ArchiveException("Unsupported version");
//miscellaneous
//these parts of the header serve no purpose
this.readUnsignedInt(fileInputStream);
this.readUnsignedInt(fileInputStream);
this.readUnsignedInt(fileInputStream);
this.readUnsignedInt(fileInputStream);
//extension loop
while (true)
{
//get extension
String extension = this.readString(fileInputStream);
if (extension.isEmpty())
break;
//path loop
while (true)
{
//get path
String path = this.readString(fileInputStream);
if (path.isEmpty())
break;
//filename loop
while (true)
{
//get filename
String filename = this.readString(fileInputStream);
if (filename.isEmpty())
break;
//read data
int crc = this.readUnsignedInt(fileInputStream);
short preloadSize = this.readUnsignedShort(fileInputStream);
short archiveIndex = this.readUnsignedShort(fileInputStream);
int entryOffset = this.readUnsignedInt(fileInputStream);
int entryLength = this.readUnsignedInt(fileInputStream);
short terminator = this.readUnsignedShort(fileInputStream);
//check preload data
byte[] preloadData = null;
if (preloadSize > 0)
{
//read preload data
preloadData = new byte[preloadSize];
fileInputStream.read(preloadData);
}
//create entry
Entry entry = new Entry(this, archiveIndex, preloadData, extension, path, filename, crc, entryOffset, entryLength, terminator);
this.entries.add(entry);
}
}
}
}
catch (Exception ex)
{
//error
throw ex;
}
}
/**
* Returns a list of entries within the specified path.
* @param path the path to look in
* @return the list of entries
*/
public ArrayList<Entry> getEntriesIn(String path)
{
//results
ArrayList<Entry> entries = new ArrayList<Entry>();
//loop and check
for (Entry entry : this.entries)
if (entry.getPath().startsWith(path))
entries.add(entry);
return entries;
}
/**
* Returns an entry with the specified full name (path, filename and extension) in this archive.
* @param path the full name of the entry
* @return the entry, or null
*/
public Entry getEntry(String fullName)
{
//loop and check
for (Entry entry : this.entries)
if (entry.getFullName().equals(fullName))
return entry;
return null;
}
/**
* Returns a child archive that belongs to this parent.
* @param index the index of the archive
* @return the child archive, or null
* @throws ArchiveException if this archive is not made up of multiple children
*/
public File getChildArchive(int index) throws ArchiveException
{
//check
if (!this.multiPart)
throw new ArchiveException("Archive is not multi-part");
//get parent
File parent = this.file.getParentFile();
if (parent == null)
throw new ArchiveException("Archive has no parent");
//get child name
String fileName = this.file.getName();
String rootName = fileName.substring(0, fileName.length() - 8);
String childName = String.format("%s_%03d.vpk", rootName, index);
return new File(parent, childName);
}
/**
* Reads a stream character by character until a null terminator is reached.
* @param fileInputStream the stream to read
* @return the assembled string
* @throws IOException if the stream could not be read
*/
private String readString(FileInputStream fileInputStream) throws IOException
{
//builder
StringBuilder stringBuilder = new StringBuilder();
//read
int currentChar = 0;
while ((currentChar = fileInputStream.read()) != Archive.NULL_TERMINATOR)
stringBuilder.append((char) currentChar);
return stringBuilder.toString();
}
/**
* Reads an unsigned integer from a stream.
* @param fileInputStream the stream to read
* @return the unsigned integer
* @throws IOException if the stream could not be read
*/
private int readUnsignedInt(FileInputStream fileInputStream) throws IOException
{
//byte array
byte[] buffer = new byte[4];
fileInputStream.read(buffer, 0, 4);
//byte buffer
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
return byteBuffer.getInt();
}
/**
* Reads an unsigned short from a stream.
* @param fileInputStream the stream to read
* @return the unsigned short
* @throws IOException if the stream could not be read
*/
private short readUnsignedShort(FileInputStream fileInputStream) throws IOException
{
//byte array
byte[] buffer = new byte[2];
fileInputStream.read(buffer, 0, 2);
//byte buffer
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
return byteBuffer.getShort();
}
/**
* Returns the VPK archive file for this archive.
* @return the VPK archive file
*/
public File getFile()
{
return this.file;
}
/**
* Returns if this archive is made of multiple children (separate VPK archives).
* @return if this archive is made of multiple children
*/
public boolean isMultiPart()
{
return this.multiPart;
}
/**
* Returns the signature of this archive.
* In most cases, this should be 0x55AA1234.
* @return the signature
*/
public int getSignature()
{
return this.signature;
}
/**
* Returns the internal version of this archive.
* In most cases, this should be 2.
* @return the internal version
*/
public int getVersion()
{
return this.version;
}
/**
* Returns the length of the root tree for this archive.
* @return the length of the root tree
*/
public int getTreeLength()
{
return this.treeLength;
}
/**
* Returns the length of the header for this archive.
* @return the length of the header
*/
public int getHeaderLength()
{
return this.headerLength;
}
/**
* Returns the list of entries in this archive.
* @return the list of entries
*/
public ArrayList<Entry> getEntries()
{
return this.entries;
}
public static final int SIGNATURE = 0x55AA1234;
public static final int VERSION = 2;
public static final int HEADER_SIZE = 28;
public static final char NULL_TERMINATOR = 0x0;
private File file;
private boolean multiPart;
private int signature;
private int version;
private int treeLength;
private int headerLength;
private ArrayList<Entry> entries;
}
|
// BUI - a user interface library for the JME 3D engine
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.jmex.bui;
import org.lwjgl.opengl.GL11;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import com.jme.renderer.Renderer;
import com.jmex.bui.event.MouseWheelListener;
import com.jmex.bui.event.ChangeListener;
import com.jmex.bui.event.ChangeEvent;
import com.jmex.bui.layout.BorderLayout;
import com.jmex.bui.layout.BLayoutManager;
import com.jmex.bui.util.Dimension;
import com.jmex.bui.util.Insets;
import com.jmex.bui.util.Rectangle;
import com.jmex.bui.layout.GroupLayout;
/**
* Provides a scrollable, lazily instantiated component view of values
*/
public abstract class BScrollingList<V, C extends BComponent> extends BContainer
{
/**
* Instantiates an empty {@link BScrollingList}.
*/
public BScrollingList ()
{
this(null);
}
/**
* Instantiates a {@link BScrollingList} with an initial value collection.
*/
public BScrollingList (Collection<V> values)
{
super(new BorderLayout(0, 0));
_values = new ArrayList<Entry<V, C>>();
if (values != null) {
for (V value : values) {
_values.add(new Entry<V, C>(value));
}
}
_lastBottom = 0;
// we'll set up our model in layout()
_model = new BoundedRangeModel(0, 0, 1, 1);
// create our viewport and scrollbar
add(_vport = new BViewport(), BorderLayout.CENTER);
_model.addChangeListener(_vport);
add(_vbar = new BScrollBar(BScrollBar.VERTICAL, _model),
BorderLayout.EAST);
}
/**
* Appends a value to our list, possibly scrolling our view to display it.
*/
public void addValue (V value, boolean snapToBottom)
{
addValue(_values.size(), value, snapToBottom);
}
/**
* Inserts a value into our list at the specified position.
*/
public void addValue (int index, V value)
{
addValue(index, value, false);
}
/**
* Clears all the current values and any related components.
*/
public void removeValues ()
{
_values.clear();
_model.setValue(0);
_vport.removeAll();
_vport.invalidate();
}
/**
* Removes values from the top of the list.
*/
public void removeValuesFromTop (int num)
{
num = Math.min(num, _values.size());
for (int ii = 0; ii < num; ii++) {
Entry<V, C> value = _values.remove(0);
_vport.remove(value.component);
}
_vport.invalidate();
}
/**
* Must be implemented by subclasses to instantiate the correct BComponent
* subclass for a given list value.
*/
protected abstract C createComponent (V value);
/**
* Adds a value to the list and snaps to the bottom of the list if desired.
*/
protected void addValue (int index, V value, boolean snap)
{
_values.add(index, new Entry<V, C>(value));
_vport.invalidateAndSnap();
}
/** Does all the heavy lifting for the {@link BScrollingList}. */
protected class BViewport extends BContainer
implements ChangeListener
{
public BViewport ()
{
super(GroupLayout.makeVert(
GroupLayout.NONE, GroupLayout.TOP,
GroupLayout.STRETCH));
}
/**
* Returns a reference to the vertical scroll bar.
*/
public BScrollBar getVerticalScrollBar ()
{
return _vbar;
}
/**
* Recomputes our layout and snaps to the bottom if we were at the
* bottom previously.
*/
public void invalidateAndSnap ()
{
_snap =
_model.getValue() + _model.getExtent() >= _model.getMaximum();
invalidate();
}
@Override // documentation inherited
protected void wasAdded ()
{
super.wasAdded();
addListener(_wheelListener = _model.createWheelListener());
}
@Override // from BComponent
protected void wasRemoved ()
{
super.wasRemoved();
if (_wheelListener != null) {
removeListener(_wheelListener);
_wheelListener = null;
}
}
// from interface ChangeListener
public void stateChanged (ChangeEvent event)
{
invalidate();
}
@Override // from BComponent
public void invalidate ()
{
// if we're not attached, don't worry about it
BWindow window;
BRootNode root;
if (!_valid || (window = getWindow()) == null ||
(root = window.getRootNode()) == null) {
return;
}
_valid = false;
root.rootInvalidated(this);
}
@Override // from BComponent
public void layout ()
{
Insets insets = getInsets();
int twidth = getWidth() - insets.getHorizontal();
int theight = getHeight() - insets.getVertical();
int gap = ((GroupLayout)getLayoutManager()).getGap();
// first make sure all of our entries have been measured and
// compute our total height and extent
int totheight = 0;
for (Entry<V, C> entry : _values) {
if (entry.height < 0) {
if (entry.component == null) {
entry.component = createComponent(entry.value);
}
boolean remove = false;
if (!entry.component.isAdded()) {
add(entry.component);
remove = true;
}
entry.height =
entry.component.getPreferredSize(twidth, 0).height;
if (remove) {
remove(entry.component);
}
}
totheight += entry.height;
}
if (_values.size() > 1) {
totheight += (gap * _values.size()-1);
}
int extent = Math.min(theight, totheight);
// if our most recent value was added with _snap then we scroll to
// the bottom on this layout and clear our snappy flag
int value = _snap ? (totheight-extent) : _model.getValue();
_snap = false;
// if our extent or total height have changed, update the model
// (because we're currently invalid, the resulting call to
// invalidate() will have no effect)
if (extent != _model.getExtent() ||
totheight != _model.getMaximum()) {
_model.setRange(0, value, extent, totheight);
}
// now back up from the last component until we reach the first one
// that's in view
_offset = _model.getValue();
int compIx = 0;
for (int ii = 0; ii < _values.size(); ii++) {
Entry<V, C> entry = _values.get(ii);
if (_offset < entry.height) {
compIx = ii;
break;
}
_offset -= (entry.height + gap);
// remove and clear out the components before our top component
if (entry.component != null) {
if (entry.component.isAdded()) {
remove(entry.component);
}
entry.component = null;
}
}
// compensate for the partially visible topmost component
extent += _offset;
// now add components until we use up our extent
int topIx = compIx;
while (compIx < _values.size() && extent > 0) {
Entry<V, C> entry = _values.get(compIx);
if (entry.component == null) {
entry.component = createComponent(entry.value);
}
if (!entry.component.isAdded()) {
add(compIx-topIx, entry.component);
}
extent -= (entry.height + gap);
compIx++;
}
// lastly remove any components below the last visible component
while (compIx < _values.size()) {
Entry<V, C> entry = _values.get(compIx);
if (entry.component != null) {
if (entry.component.isAdded()) {
remove(entry.component);
}
entry.component = null;
}
compIx++;
}
// now have the layout manager layout our added components
super.layout();
}
@Override // from BComponent
protected void renderComponent (Renderer renderer)
{
Insets insets = getInsets();
GL11.glTranslatef(0, _offset, 0);
boolean scissored = intersectScissorBox(_srect,
getAbsoluteX() + insets.left,
getAbsoluteY() + insets.bottom,
_width - insets.getHorizontal(),
_height - insets.getVertical());
try {
// render our children
for (int ii = 0, ll = getComponentCount(); ii < ll; ii++) {
getComponent(ii).render(renderer);
}
} finally {
restoreScissorState(scissored, _srect);
GL11.glTranslatef(0, -_offset, 0);
}
}
@Override // documentation inherited
public BComponent getHitComponent (int mx, int my)
{
// if we're not within our bounds, we needn't check our target
Insets insets = getInsets();
if ((mx < _x + insets.left) || (my < _y + insets.bottom) ||
(mx >= _x + _width - insets.right) ||
(my >= _y + _height - insets.top)) {
return null;
}
// translate the coordinate into our children's coordinates
mx -= _x;
my -= (_y + _offset);
BComponent hit = null;
for (int ii = 0, ll = getComponentCount(); ii < ll; ii++) {
BComponent child = getComponent(ii);
if ((hit = child.getHitComponent(mx, my)) != null) {
return hit;
}
}
return this;
}
protected int _offset;
protected boolean _snap;
protected Rectangle _srect = new Rectangle();
}
/** Used to track the total height of our entries. */
protected static class Entry<V, C extends BComponent>
{
public C component;
public V value;
public int height = -1;
public Entry (V value) {
this.value = value;
}
}
protected MouseWheelListener _wheelListener;
protected BoundedRangeModel _model;
protected List<Entry<V, C>> _values;
protected BViewport _vport;
protected BScrollBar _vbar;
protected int _lastBottom;
protected static final int EXTENT = 2;
}
|
package com.digero.maestro.view;
import info.clearthought.layout.TableLayout;
import info.clearthought.layout.TableLayoutConstants;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.prefs.Preferences;
import javax.imageio.ImageIO;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiUnavailableException;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import com.digero.common.abc.AbcField;
import com.digero.common.abc.LotroInstrument;
import com.digero.common.abctomidi.AbcToMidi;
import com.digero.common.abctomidi.AbcToMidi.AbcInfo;
import com.digero.common.icons.IconLoader;
import com.digero.common.midi.IMidiConstants;
import com.digero.common.midi.KeySignature;
import com.digero.common.midi.LotroSequencerWrapper;
import com.digero.common.midi.NoteFilterSequencerWrapper;
import com.digero.common.midi.SequencerEvent;
import com.digero.common.midi.SequencerListener;
import com.digero.common.midi.SequencerProperty;
import com.digero.common.midi.SequencerWrapper;
import com.digero.common.midi.TimeSignature;
import com.digero.common.midi.VolumeTransceiver;
import com.digero.common.util.ExtensionFileFilter;
import com.digero.common.util.FileFilterDropListener;
import com.digero.common.util.ICompileConstants;
import com.digero.common.util.Pair;
import com.digero.common.util.ParseException;
import com.digero.common.util.Util;
import com.digero.common.view.AboutDialog;
import com.digero.common.view.ColorTable;
import com.digero.common.view.NativeVolumeBar;
import com.digero.common.view.SongPositionLabel;
import com.digero.maestro.MaestroMain;
import com.digero.maestro.abc.AbcConversionException;
import com.digero.maestro.abc.AbcMetadataSource;
import com.digero.maestro.abc.AbcPart;
import com.digero.maestro.abc.AbcPartEvent;
import com.digero.maestro.abc.AbcPartListener;
import com.digero.maestro.abc.AbcPartMetadataSource;
import com.digero.maestro.abc.AbcPartProperty;
import com.digero.maestro.abc.AbcProject;
import com.digero.maestro.abc.PartAutoNumberer;
import com.digero.maestro.abc.PartNameTemplate;
import com.digero.maestro.abc.TimingInfo;
import com.digero.maestro.midi.SequenceInfo;
import com.digero.maestro.midi.TrackInfo;
import com.digero.maestro.util.ListModelWrapper;
@SuppressWarnings("serial")
public class ProjectFrame extends JFrame implements TableLayoutConstants, AbcMetadataSource, AbcProject,
ICompileConstants {
private static final int HGAP = 4, VGAP = 4;
private static final double[] LAYOUT_COLS = new double[] {
180, FILL
};
private static final double[] LAYOUT_ROWS = new double[] {
FILL
};
private static final int MAX_PARTS = IMidiConstants.CHANNEL_COUNT - 2; // Track 0 is reserved for metadata, and Track 9 is reserved for drums
private Preferences prefs = Preferences.userNodeForPackage(MaestroMain.class);
private File saveFile;
private boolean allowOverwriteSaveFile = false;
private SequenceInfo sequenceInfo;
private NoteFilterSequencerWrapper sequencer;
private VolumeTransceiver volumeTransceiver;
private NoteFilterSequencerWrapper abcSequencer;
private VolumeTransceiver abcVolumeTransceiver;
private ListModelWrapper<AbcPart> parts = new ListModelWrapper<AbcPart>(new DefaultListModel<AbcPart>());
private PartAutoNumberer partAutoNumberer;
private PartNameTemplate partNameTemplate;
private boolean usingNativeVolume;
private JPanel content;
private JTextField songTitleField;
private JTextField composerField;
private JTextField transcriberField;
private JSpinner transposeSpinner;
private JSpinner tempoSpinner;
private JButton resetTempoButton;
private JFormattedTextField keySignatureField;
private JFormattedTextField timeSignatureField;
private JCheckBox tripletCheckBox;
private JButton exportButton;
private JMenuItem exportMenuItem;
private JList<AbcPart> partsList;
private JButton newPartButton;
private JButton deletePartButton;
private PartPanel partPanel;
private boolean abcPreviewMode = false;
private JRadioButton abcModeRadioButton;
private JRadioButton midiModeRadioButton;
private JButton playButton;
private JButton stopButton;
private NativeVolumeBar volumeBar;
private SongPositionLabel midiPositionLabel;
private SongPositionLabel abcPositionLabel;
private Icon playIcon;
private Icon pauseIcon;
private Icon abcPlayIcon;
private Icon abcPauseIcon;
private long abcPreviewStartMicros = 0;
private float abcPreviewTempoFactor = 1.0f;
private boolean echoingPosition = false;
private MainSequencerListener mainSequencerListener;
private AbcSequencerListener abcSequencerListener;
private boolean failedToLoadLotroInstruments = false;
public ProjectFrame() {
super(MaestroMain.APP_NAME);
setMinimumSize(new Dimension(512, 384));
Util.initWinBounds(this, prefs.node("window"), 800, 600);
String welcomeMessage = formatInfoMessage("Hello Maestro", "Drag and drop a MIDI or ABC file to open it.\n"
+ "Or use File > Open.");
partAutoNumberer = new PartAutoNumberer(prefs.node("partAutoNumberer"), Collections.unmodifiableList(parts));
partNameTemplate = new PartNameTemplate(prefs.node("partNameTemplate"), this);
usingNativeVolume = MaestroMain.isNativeVolumeSupported();
if (usingNativeVolume) {
volumeTransceiver = null;
abcVolumeTransceiver = null;
}
else {
volumeTransceiver = new VolumeTransceiver();
volumeTransceiver.setVolume(prefs.getInt("volumizer", NativeVolumeBar.MAX_VOLUME));
abcVolumeTransceiver = new VolumeTransceiver();
abcVolumeTransceiver.setVolume(volumeTransceiver.getVolume());
}
try {
sequencer = new NoteFilterSequencerWrapper();
if (volumeTransceiver != null)
sequencer.addTransceiver(volumeTransceiver);
abcSequencer = new LotroSequencerWrapper();
if (abcVolumeTransceiver != null)
abcSequencer.addTransceiver(abcVolumeTransceiver);
if (LotroSequencerWrapper.getLoadLotroSynthError() != null) {
welcomeMessage = formatErrorMessage("Could not load LOTRO instrument sounds",
"ABC Preview will use standard MIDI instruments instead\n"
+ "(drums do not sound good in this mode).\n\n" + "Error details:\n"
+ LotroSequencerWrapper.getLoadLotroSynthError());
failedToLoadLotroInstruments = true;
}
}
catch (MidiUnavailableException e) {
JOptionPane.showMessageDialog(null, "Failed to initialize MIDI sequencer.\nThe program will now exit.\n\n"
+ "Error details:\n" + e.getMessage(), "Failed to initialize MIDI sequencer",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
return;
}
try {
List<Image> icons = new ArrayList<Image>();
icons.add(ImageIO.read(IconLoader.class.getResourceAsStream("maestro_16.png")));
icons.add(ImageIO.read(IconLoader.class.getResourceAsStream("maestro_32.png")));
setIconImages(icons);
}
catch (Exception ex) {
// Ignore
ex.printStackTrace();
}
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
playIcon = new ImageIcon(IconLoader.class.getResource("play_blue.png"));
pauseIcon = new ImageIcon(IconLoader.class.getResource("pause_blue.png"));
abcPlayIcon = new ImageIcon(IconLoader.class.getResource("play_yellow.png"));
abcPauseIcon = new ImageIcon(IconLoader.class.getResource("pause.png"));
Icon stopIcon = new ImageIcon(IconLoader.class.getResource("stop.png"));
partPanel = new PartPanel(sequencer, partAutoNumberer, abcSequencer);
partPanel.addSettingsActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSettingsDialog(SettingsDialog.NUMBERING_TAB);
}
});
TableLayout tableLayout = new TableLayout(LAYOUT_COLS, LAYOUT_ROWS);
tableLayout.setHGap(HGAP);
tableLayout.setVGap(VGAP);
content = new JPanel(tableLayout, false);
setContentPane(content);
songTitleField = new JTextField();
songTitleField.setToolTipText("Song Title");
composerField = new JTextField();
composerField.setToolTipText("Song Composer");
transcriberField = new JTextField(prefs.get("transcriber", ""));
transcriberField.setToolTipText("Song Transcriber (your name)");
transcriberField.getDocument().addDocumentListener(new PrefsDocumentListener(prefs, "transcriber"));
keySignatureField = new MyFormattedTextField(KeySignature.C_MAJOR, 5);
keySignatureField.setToolTipText("<html>Adjust the key signature of the ABC file. "
+ "This only affects the display, not the sound of the exported file.<br>"
+ "Examples: C maj, Eb maj, F# min</html>");
timeSignatureField = new MyFormattedTextField(TimeSignature.FOUR_FOUR, 5);
timeSignatureField.setToolTipText("<html>Adjust the time signature of the ABC file. "
+ "This only affects the display, not the sound of the exported file.<br>"
+ "Examples: 4/4, 3/8, 2/2</html>");
transposeSpinner = new JSpinner(new SpinnerNumberModel(0, -48, 48, 1));
transposeSpinner.setToolTipText("<html>Transpose the entire song by semitones.<br>"
+ "12 semitones = 1 octave</html>");
transposeSpinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int transpose = getTranspose();
for (AbcPart part : parts) {
part.setBaseTranspose(transpose);
}
}
});
tempoSpinner = new JSpinner(new SpinnerNumberModel(IMidiConstants.DEFAULT_TEMPO_BPM /* value */, 8 /* min */,
960 /* max */, 1 /* step */));
tempoSpinner.setToolTipText("Tempo in beats per minute");
tempoSpinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (sequenceInfo != null) {
abcSequencer.setTempoFactor((float) getTempo() / sequenceInfo.getTempoBPM());
if (abcSequencer.isRunning()) {
float delta = abcPreviewTempoFactor / abcSequencer.getTempoFactor();
if (Math.max(delta, 1 / delta) > 1.5f)
refreshPreviewSequence(false);
}
}
else {
abcSequencer.setTempoFactor(1.0f);
}
}
});
resetTempoButton = new JButton("Reset");
resetTempoButton.setMargin(new Insets(2, 8, 2, 8));
resetTempoButton.setToolTipText("Set the tempo back to the source file's tempo");
resetTempoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (sequenceInfo == null) {
tempoSpinner.setValue(IMidiConstants.DEFAULT_TEMPO_BPM);
}
else {
float tempoFactor = abcSequencer.getTempoFactor();
tempoSpinner.setValue(sequenceInfo.getTempoBPM());
if (tempoFactor != 1.0f)
refreshPreviewSequence(false);
}
tempoSpinner.requestFocus();
}
});
tripletCheckBox = new JCheckBox("Triplets/swing rhythm");
tripletCheckBox.setToolTipText("<html>Tweak the timing to allow for triplets or a swing rhythm.<br><br>"
+ "This can cause short/fast notes to incorrectly be detected as triplets.<br>"
+ "Leave it unchecked unless the song has triplets or a swing rhythm.</html>");
tripletCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (abcSequencer.isRunning())
refreshPreviewSequence(false);
}
});
exportButton = new JButton("<html><center><b>Export ABC</b><br>(Ctrl+S)</center></html>");
exportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportAbc();
}
});
partsList = new JList<AbcPart>(parts.getListModel());
partsList.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
partsList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
AbcPart abcPart = partsList.getSelectedValue();
sequencer.getFilter().onAbcPartChanged(abcPart != null);
abcSequencer.getFilter().onAbcPartChanged(abcPart != null);
partPanel.setAbcPart(abcPart);
}
});
JScrollPane partsListScrollPane = new JScrollPane(partsList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
newPartButton = new JButton("New Part");
newPartButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewPart();
}
});
deletePartButton = new JButton("Delete");
deletePartButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deletePart(partsList.getSelectedIndex());
}
});
TableLayout songInfoLayout = new TableLayout(new double[] {
PREFERRED, FILL
}, new double[] {
PREFERRED, PREFERRED, PREFERRED
});
songInfoLayout.setHGap(HGAP);
songInfoLayout.setVGap(VGAP);
JPanel songInfoPanel = new JPanel(songInfoLayout);
{
int row = 0;
songInfoPanel.add(new JLabel("T:"), "0, " + row);
songInfoPanel.add(songTitleField, "1, " + row);
row++;
songInfoPanel.add(new JLabel("C:"), "0, " + row);
songInfoPanel.add(composerField, "1, " + row);
row++;
songInfoPanel.add(new JLabel("Z:"), "0, " + row);
songInfoPanel.add(transcriberField, "1, " + row);
songInfoPanel.setBorder(BorderFactory.createTitledBorder("Song Info"));
}
JPanel partsButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, HGAP, VGAP));
partsButtonPanel.add(newPartButton);
partsButtonPanel.add(deletePartButton);
JPanel partsListPanel = new JPanel(new BorderLayout(HGAP, VGAP));
partsListPanel.setBorder(BorderFactory.createTitledBorder("Song Parts"));
partsListPanel.add(partsButtonPanel, BorderLayout.NORTH);
partsListPanel.add(partsListScrollPane, BorderLayout.CENTER);
TableLayout settingsLayout = new TableLayout(new double[] {
/* Cols */PREFERRED, PREFERRED, FILL
}, new double[] {});
settingsLayout.setVGap(VGAP);
settingsLayout.setHGap(HGAP);
JPanel settingsPanel = new JPanel(settingsLayout);
settingsPanel.setBorder(BorderFactory.createTitledBorder("Export Settings"));
{
int row = 0;
settingsLayout.insertRow(row, PREFERRED);
settingsPanel.add(new JLabel("Transpose:"), "0, " + row);
settingsPanel.add(transposeSpinner, "1, " + row);
row++;
settingsLayout.insertRow(row, PREFERRED);
settingsPanel.add(new JLabel("Tempo:"), "0, " + row);
settingsPanel.add(tempoSpinner, "1, " + row);
settingsPanel.add(resetTempoButton, "2, " + row + ", L, F");
row++;
settingsLayout.insertRow(row, PREFERRED);
settingsPanel.add(new JLabel("Meter:"), "0, " + row);
settingsPanel.add(timeSignatureField, "1, " + row + ", 2, " + row + ", L, F");
if (SHOW_KEY_FIELD) {
row++;
settingsLayout.insertRow(row, PREFERRED);
settingsPanel.add(new JLabel("Key:"), "0, " + row);
settingsPanel.add(keySignatureField, "1, " + row + ", 2, " + row + ", L, F");
}
row++;
settingsLayout.insertRow(row, PREFERRED);
settingsPanel.add(tripletCheckBox, "0, " + row + ", 2, " + row + ", L, C");
row++;
settingsLayout.insertRow(row, PREFERRED);
settingsPanel.add(exportButton, "0, " + row + ", 2, " + row + ", F, F");
}
if (!SHOW_TEMPO_SPINNER)
tempoSpinner.setEnabled(false);
if (!SHOW_METER_TEXTBOX)
timeSignatureField.setEnabled(false);
if (!SHOW_KEY_FIELD)
keySignatureField.setEnabled(false);
volumeBar = new NativeVolumeBar(new VolumeManager());
JPanel volumePanel = new JPanel(new TableLayout(new double[] {
PREFERRED
}, new double[] {
PREFERRED, PREFERRED
}));
volumePanel.add(new JLabel("Volume"), "0, 0, c, c");
volumePanel.add(volumeBar, "0, 1, f, c");
ActionListener modeButtonListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updatePreviewMode(abcModeRadioButton.isSelected());
}
};
midiModeRadioButton = new JRadioButton("Original");
midiModeRadioButton.addActionListener(modeButtonListener);
midiModeRadioButton.setMargin(new Insets(0, 0, 0, 0));
abcModeRadioButton = new JRadioButton("ABC Preview");
abcModeRadioButton.addActionListener(modeButtonListener);
abcModeRadioButton.setMargin(new Insets(0, 0, 0, 0));
ButtonGroup modeButtonGroup = new ButtonGroup();
modeButtonGroup.add(abcModeRadioButton);
modeButtonGroup.add(midiModeRadioButton);
midiModeRadioButton.setSelected(true);
abcPreviewMode = abcModeRadioButton.isSelected();
playButton = new JButton(playIcon);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SequencerWrapper curSequencer = abcPreviewMode ? abcSequencer : sequencer;
boolean running = !curSequencer.isRunning();
if (abcPreviewMode && running) {
if (!refreshPreviewSequence(true))
running = false;
}
curSequencer.setRunning(running);
updateButtons(false);
}
});
stopButton = new JButton(stopIcon);
stopButton.setToolTipText("Stop");
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
abcSequencer.stop();
sequencer.stop();
abcSequencer.reset(false);
sequencer.reset(false);
}
});
JPanel modeButtonPanel = new JPanel(new BorderLayout());
modeButtonPanel.add(midiModeRadioButton, BorderLayout.NORTH);
modeButtonPanel.add(abcModeRadioButton, BorderLayout.SOUTH);
JPanel playButtonPanel = new JPanel(new TableLayout(new double[] {
0.5, 0.5
}, new double[] {
PREFERRED
}));
playButtonPanel.add(playButton, "0, 0");
playButtonPanel.add(stopButton, "1, 0");
midiPositionLabel = new SongPositionLabel(sequencer);
abcPositionLabel = new SongPositionLabel(abcSequencer, true);
abcPositionLabel.setVisible(!midiPositionLabel.isVisible());
JPanel playControlPanel = new JPanel(new TableLayout(new double[] {
4, 0.50, 4, PREFERRED, 4, 0.50, 4, PREFERRED, 4
}, new double[] {
0, PREFERRED,
}));
playControlPanel.add(playButtonPanel, "3, 1, C, C");
playControlPanel.add(modeButtonPanel, "1, 1, C, F");
playControlPanel.add(volumePanel, "5, 1, C, C");
playControlPanel.add(midiPositionLabel, "7, 1");
playControlPanel.add(abcPositionLabel, "7, 1");
JPanel abcPartsAndSettings = new JPanel(new BorderLayout(HGAP, VGAP));
abcPartsAndSettings.add(songInfoPanel, BorderLayout.NORTH);
JPanel partsListAndColorizer = new JPanel(new BorderLayout(HGAP, VGAP));
partsListAndColorizer.add(partsListPanel, BorderLayout.CENTER);
if (SHOW_COLORIZER)
partsListAndColorizer.add(new Colorizer(partPanel), BorderLayout.SOUTH);
abcPartsAndSettings.add(partsListAndColorizer, BorderLayout.CENTER);
abcPartsAndSettings.add(settingsPanel, BorderLayout.SOUTH);
JPanel midiPartsAndControls = new JPanel(new BorderLayout(HGAP, VGAP));
midiPartsAndControls.add(partPanel, BorderLayout.CENTER);
midiPartsAndControls.add(playControlPanel, BorderLayout.SOUTH);
midiPartsAndControls.setBorder(BorderFactory.createTitledBorder("Part Settings"));
add(abcPartsAndSettings, "0, 0");
add(midiPartsAndControls, "1, 0");
final FileFilterDropListener dropListener = new FileFilterDropListener(false, "mid", "midi", "abc", "txt");
dropListener.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final File file = dropListener.getDroppedFile();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
openSong(file);
}
});
}
});
new DropTarget(this, dropListener);
mainSequencerListener = new MainSequencerListener();
sequencer.addChangeListener(mainSequencerListener);
abcSequencerListener = new AbcSequencerListener();
abcSequencer.addChangeListener(abcSequencerListener);
parts.getListModel().addListDataListener(new ListDataListener() {
public void intervalRemoved(ListDataEvent e) {
updateButtons(false);
}
public void intervalAdded(ListDataEvent e) {
updateButtons(false);
}
public void contentsChanged(ListDataEvent e) {
updateButtons(false);
}
});
initMenu();
partPanel.showInfoMessage(welcomeMessage);
updateButtons(true);
}
@Override
public void dispose() {
for (AbcPart part : parts) {
part.discard();
}
parts.clear();
sequencer.discard();
abcSequencer.discard();
super.dispose();
}
private void initMenu() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = menuBar.add(new JMenu(" File "));
fileMenu.setMnemonic('F');
JMenuItem openItem = fileMenu.add(new JMenuItem("Open MIDI or ABC file..."));
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK));
openItem.addActionListener(new ActionListener() {
JFileChooser openFileChooser;
public void actionPerformed(ActionEvent e) {
if (openFileChooser == null) {
openFileChooser = new JFileChooser(prefs.get("openFileChooser.path", null));
openFileChooser.setMultiSelectionEnabled(false);
openFileChooser.setFileFilter(new ExtensionFileFilter("MIDI and ABC files", "mid", "midi", "abc",
"txt"));
}
int result = openFileChooser.showOpenDialog(ProjectFrame.this);
if (result == JFileChooser.APPROVE_OPTION) {
openSong(openFileChooser.getSelectedFile());
prefs.put("openFileChooser.path", openFileChooser.getCurrentDirectory().getAbsolutePath());
}
}
});
exportMenuItem = fileMenu.add(new JMenuItem("Export ABC..."));
exportMenuItem.setMnemonic('E');
exportMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK));
exportMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportAbc();
}
});
fileMenu.addSeparator();
JMenuItem exitItem = fileMenu.add(new JMenuItem("Exit"));
exitItem.setMnemonic('x');
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.ALT_DOWN_MASK));
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switch (ProjectFrame.this.getDefaultCloseOperation()) {
case EXIT_ON_CLOSE:
System.exit(0);
break;
case DISPOSE_ON_CLOSE:
setVisible(false);
dispose();
break;
case DO_NOTHING_ON_CLOSE:
case HIDE_ON_CLOSE:
setVisible(false);
break;
}
}
});
JMenu toolsMenu = menuBar.add(new JMenu(" Tools "));
toolsMenu.setMnemonic('T');
JMenuItem settingsItem = toolsMenu.add(new JMenuItem("Options..."));
settingsItem.setMnemonic('O');
settingsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, KeyEvent.CTRL_DOWN_MASK));
settingsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSettingsDialog();
}
});
toolsMenu.addSeparator();
JMenuItem aboutItem = toolsMenu.add(new JMenuItem("About " + MaestroMain.APP_NAME + "..."));
aboutItem.setMnemonic('A');
aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AboutDialog.show(ProjectFrame.this, MaestroMain.APP_NAME, MaestroMain.APP_VERSION, MaestroMain.APP_URL,
"maestro_64.png");
}
});
}
private int currentSettingsDialogTab = 0;
private void doSettingsDialog() {
doSettingsDialog(currentSettingsDialogTab);
}
private void doSettingsDialog(int tab) {
SettingsDialog dialog = new SettingsDialog(ProjectFrame.this, partAutoNumberer.getSettingsCopy(),
partNameTemplate);
dialog.setActiveTab(tab);
dialog.setVisible(true);
if (dialog.isSuccess()) {
if (dialog.isNumbererSettingsChanged()) {
partAutoNumberer.setSettings(dialog.getNumbererSettings());
partAutoNumberer.renumberAllParts();
}
partNameTemplate.setSettings(dialog.getNameTemplateSettings());
partPanel.settingsChanged();
}
currentSettingsDialogTab = dialog.getActiveTab();
dialog.dispose();
}
public void onVolumeChanged() {
volumeBar.repaint();
}
private class VolumeManager implements NativeVolumeBar.Callback {
@Override
public void setVolume(int volume) {
if (usingNativeVolume) {
MaestroMain.setVolume((float) volume / NativeVolumeBar.MAX_VOLUME);
}
else {
if (volumeTransceiver != null)
volumeTransceiver.setVolume(volume);
if (abcVolumeTransceiver != null)
abcVolumeTransceiver.setVolume(volume);
prefs.putInt("volumizer", volume);
}
}
@Override
public int getVolume() {
if (usingNativeVolume) {
return (int) (MaestroMain.getVolume() * NativeVolumeBar.MAX_VOLUME);
}
else {
if (volumeTransceiver != null)
return volumeTransceiver.getVolume();
if (abcVolumeTransceiver != null)
return abcVolumeTransceiver.getVolume();
return NativeVolumeBar.MAX_VOLUME;
}
}
}
private class MainSequencerListener implements SequencerListener {
public void propertyChanged(SequencerEvent evt) {
updateButtons(false);
if (evt.getProperty() == SequencerProperty.IS_RUNNING) {
if (sequencer.isRunning())
abcSequencer.stop();
}
else if (!echoingPosition) {
try {
echoingPosition = true;
if (evt.getProperty() == SequencerProperty.POSITION) {
long pos = sequencer.getPosition() - abcPreviewStartMicros;
abcSequencer.setPosition(Util.clamp(pos, 0, abcSequencer.getLength()));
}
else if (evt.getProperty() == SequencerProperty.DRAG_POSITION) {
long pos = sequencer.getDragPosition() - abcPreviewStartMicros;
abcSequencer.setDragPosition(Util.clamp(pos, 0, abcSequencer.getLength()));
}
else if (evt.getProperty() == SequencerProperty.IS_DRAGGING) {
abcSequencer.setDragging(sequencer.isDragging());
}
}
finally {
echoingPosition = false;
}
}
}
}
private class AbcSequencerListener implements SequencerListener {
public void propertyChanged(SequencerEvent evt) {
updateButtons(false);
if (evt.getProperty() == SequencerProperty.IS_RUNNING) {
if (abcSequencer.isRunning())
sequencer.stop();
}
else if (!echoingPosition) {
try {
echoingPosition = true;
if (evt.getProperty() == SequencerProperty.POSITION) {
long pos = abcSequencer.getPosition() + abcPreviewStartMicros;
sequencer.setPosition(Util.clamp(pos, 0, sequencer.getLength()));
}
else if (evt.getProperty() == SequencerProperty.DRAG_POSITION) {
long pos = abcSequencer.getDragPosition() + abcPreviewStartMicros;
sequencer.setDragPosition(Util.clamp(pos, 0, sequencer.getLength()));
}
else if (evt.getProperty() == SequencerProperty.IS_DRAGGING) {
sequencer.setDragging(abcSequencer.isDragging());
}
}
finally {
echoingPosition = false;
}
}
}
}
private static class PrefsDocumentListener implements DocumentListener {
private Preferences prefs;
private String prefName;
public PrefsDocumentListener(Preferences prefs, String prefName) {
this.prefs = prefs;
this.prefName = prefName;
}
private void updatePrefs(Document doc) {
String txt;
try {
txt = doc.getText(0, doc.getLength());
}
catch (BadLocationException e) {
txt = "";
}
prefs.put(prefName, txt);
}
@Override
public void changedUpdate(DocumentEvent e) {
updatePrefs(e.getDocument());
}
@Override
public void insertUpdate(DocumentEvent e) {
updatePrefs(e.getDocument());
}
@Override
public void removeUpdate(DocumentEvent e) {
updatePrefs(e.getDocument());
}
}
void createNewPart() {
if (sequenceInfo != null) {
AbcPart newPart = new AbcPart(sequenceInfo, getTranspose(), this, this);
newPart.addAbcListener(abcPartListener);
partAutoNumberer.onPartAdded(newPart);
int idx = Collections.binarySearch(parts, newPart, partNumberComparator);
if (idx < 0)
idx = (-idx - 1);
parts.add(idx, newPart);
partsList.setSelectedIndex(idx);
partsList.ensureIndexIsVisible(idx);
partsList.repaint();
updateButtons(true);
}
}
void deletePart(int idx) {
AbcPart oldPart = parts.remove(idx);
if (idx > 0)
partsList.setSelectedIndex(idx - 1);
else if (parts.size() > 0)
partsList.setSelectedIndex(0);
partAutoNumberer.onPartDeleted(oldPart);
oldPart.discard();
updateButtons(true);
if (parts.size() == 0) {
sequencer.stop();
partPanel.showInfoMessage(formatInfoMessage("Add a part", "This ABC song has no parts.\n" +
"Click the " + newPartButton.getText() + " button to add a new part."));
}
if (abcSequencer.isRunning())
refreshPreviewSequence(false);
}
private boolean updateButtonsPending = false;
private Runnable updateButtonsTask = new Runnable() {
public void run() {
boolean hasAbcNotes = false;
for (AbcPart part : parts) {
if (part.getEnabledTrackCount() > 0) {
hasAbcNotes = true;
break;
}
}
boolean midiLoaded = sequencer.isLoaded();
SequencerWrapper curSequencer = abcPreviewMode ? abcSequencer : sequencer;
Icon curPlayIcon = abcPreviewMode ? abcPlayIcon : playIcon;
Icon curPauseIcon = abcPreviewMode ? abcPauseIcon : pauseIcon;
playButton.setIcon(curSequencer.isRunning() ? curPauseIcon : curPlayIcon);
if (!hasAbcNotes) {
midiModeRadioButton.setSelected(true);
abcSequencer.setRunning(false);
updatePreviewMode(false);
}
playButton.setEnabled(midiLoaded);
midiModeRadioButton.setEnabled(midiLoaded || hasAbcNotes);
abcModeRadioButton.setEnabled(hasAbcNotes);
stopButton.setEnabled((midiLoaded && (sequencer.isRunning() || sequencer.getPosition() != 0))
|| (abcSequencer.isLoaded() && (abcSequencer.isRunning() || abcSequencer.getPosition() != 0)));
newPartButton.setEnabled(sequenceInfo != null);
deletePartButton.setEnabled(partsList.getSelectedIndex() != -1);
exportButton.setEnabled(sequenceInfo != null && hasAbcNotes);
exportMenuItem.setEnabled(exportButton.isEnabled());
songTitleField.setEnabled(midiLoaded);
composerField.setEnabled(midiLoaded);
transcriberField.setEnabled(midiLoaded);
transposeSpinner.setEnabled(midiLoaded);
tempoSpinner.setEnabled(midiLoaded);
resetTempoButton.setEnabled(midiLoaded && sequenceInfo != null && getTempo() != sequenceInfo.getTempoBPM());
resetTempoButton.setVisible(resetTempoButton.isEnabled());
keySignatureField.setEnabled(midiLoaded);
timeSignatureField.setEnabled(midiLoaded);
tripletCheckBox.setEnabled(midiLoaded);
updateButtonsPending = false;
}
};
private void updateButtons(boolean immediate) {
if (immediate) {
updateButtonsTask.run();
}
else if (!updateButtonsPending) {
updateButtonsPending = true;
SwingUtilities.invokeLater(updateButtonsTask);
}
}
private AbcPartListener abcPartListener = new AbcPartListener() {
public void abcPartChanged(AbcPartEvent e) {
if (e.getProperty() == AbcPartProperty.PART_NUMBER) {
int idx;
AbcPart selected = partsList.getSelectedValue();
Collections.sort(parts, partNumberComparator);
if (selected != null) {
idx = parts.indexOf(selected);
if (idx >= 0)
partsList.setSelectedIndex(idx);
}
}
else if (e.getProperty() == AbcPartProperty.TRACK_ENABLED) {
updateButtons(true);
}
partsList.repaint();
if (e.isAbcPreviewRelated() && abcSequencer.isRunning()) {
refreshPreviewSequence(false);
}
}
};
public int getTranspose() {
return (Integer) transposeSpinner.getValue();
}
public int getTempo() {
return (Integer) tempoSpinner.getValue();
}
public KeySignature getKeySignature() {
if (SHOW_KEY_FIELD)
return (KeySignature) keySignatureField.getValue();
else
return KeySignature.C_MAJOR;
}
public TimeSignature getTimeSignature() {
return (TimeSignature) timeSignatureField.getValue();
}
private Comparator<AbcPart> partNumberComparator = new Comparator<AbcPart>() {
public int compare(AbcPart p1, AbcPart p2) {
int base1 = partAutoNumberer.getFirstNumber(p1.getInstrument());
int base2 = partAutoNumberer.getFirstNumber(p2.getInstrument());
if (base1 != base2)
return base1 - base2;
return p1.getPartNumber() - p2.getPartNumber();
}
};
private void close() {
for (AbcPart part : parts) {
part.discard();
}
parts.clear();
saveFile = null;
allowOverwriteSaveFile = false;
sequenceInfo = null;
sequencer.clearSequence();
abcSequencer.clearSequence();
sequencer.reset(true);
abcSequencer.reset(false);
abcSequencer.setTempoFactor(1.0f);
abcPreviewStartMicros = 0;
songTitleField.setText("");
composerField.setText("");
transposeSpinner.setValue(0);
tempoSpinner.setValue(IMidiConstants.DEFAULT_TEMPO_BPM);
keySignatureField.setValue(KeySignature.C_MAJOR);
timeSignatureField.setValue(TimeSignature.FOUR_FOUR);
tripletCheckBox.setSelected(false);
setTitle(MaestroMain.APP_NAME);
updateButtons(false);
}
public void openSong(File midiFile) {
close();
midiFile = Util.resolveShortcut(midiFile);
try {
String fileName = midiFile.getName().toLowerCase();
boolean isAbc = fileName.endsWith(".abc") || fileName.endsWith(".txt");
AbcInfo abcInfo = new AbcInfo();
if (isAbc) {
AbcToMidi.Params params = new AbcToMidi.Params(midiFile);
params.abcInfo = abcInfo;
params.useLotroInstruments = false;
sequenceInfo = SequenceInfo.fromAbc(params);
saveFile = midiFile;
allowOverwriteSaveFile = false;
}
else {
sequenceInfo = SequenceInfo.fromMidi(midiFile);
}
sequencer.setSequence(sequenceInfo.getSequence());
sequencer.setTickPosition(sequenceInfo.calcFirstNoteTick());
songTitleField.setText(sequenceInfo.getTitle());
songTitleField.select(0, 0);
composerField.setText(sequenceInfo.getComposer());
composerField.select(0, 0);
transposeSpinner.setValue(0);
tempoSpinner.setValue(sequenceInfo.getTempoBPM());
keySignatureField.setValue(sequenceInfo.getKeySignature());
timeSignatureField.setValue(sequenceInfo.getTimeSignature());
tripletCheckBox.setSelected(false);
if (isAbc) {
int t = 0;
for (TrackInfo trackInfo : sequenceInfo.getTrackList()) {
if (!trackInfo.hasEvents()) {
t++;
continue;
}
AbcPart newPart = new AbcPart(sequenceInfo, getTranspose(), this, this);
newPart.setTitle(abcInfo.getPartName(t));
newPart.setPartNumber(abcInfo.getPartNumber(t));
newPart.setTrackEnabled(t, true);
Set<Integer> midiInstruments = trackInfo.getInstruments();
for (LotroInstrument lotroInst : LotroInstrument.values()) {
if (midiInstruments.contains(lotroInst.midiProgramId)) {
newPart.setInstrument(lotroInst);
break;
}
}
int ins = Collections.binarySearch(parts, newPart, partNumberComparator);
if (ins < 0)
ins = -ins - 1;
parts.add(ins, newPart);
newPart.addAbcListener(abcPartListener);
t++;
}
updateButtons(false);
tripletCheckBox.setSelected(abcInfo.hasTriplets());
if (parts.isEmpty()) {
createNewPart();
}
else {
partsList.setSelectedIndex(0);
partsList.ensureIndexIsVisible(0);
partsList.repaint();
updatePreviewMode(true, true);
updateButtons(true);
}
}
else {
updateButtons(true);
createNewPart();
sequencer.start();
}
setTitle(MaestroMain.APP_NAME + " - " + midiFile.getName());
}
catch (InvalidMidiDataException e) {
partPanel.showInfoMessage(formatErrorMessage("Could not open " + midiFile.getName(), e.getMessage()));
}
catch (IOException e) {
partPanel.showInfoMessage(formatErrorMessage("Could not open " + midiFile.getName(), e.getMessage()));
}
catch (ParseException e) {
partPanel.showInfoMessage(formatErrorMessage("Could not open " + midiFile.getName(), e.getMessage()));
}
}
private static String formatInfoMessage(String title, String message) {
return "<html><h3>" + Util.htmlEscape(title) + "</h3>" + Util.htmlEscape(message).replace("\n", "<br>")
+ "<h3> </h3></html>";
}
private static String formatErrorMessage(String title, String message) {
return "<html><h3><font color=\"" + ColorTable.PANEL_TEXT_ERROR.getHtml() + "\">" + Util.htmlEscape(title)
+ "</font></h3>" + Util.htmlEscape(message).replace("\n", "<br>") + "<h3> </h3></html>";
}
private void updatePreviewMode(boolean abcPreviewModeNew) {
SequencerWrapper oldSequencer = abcPreviewMode ? abcSequencer : sequencer;
updatePreviewMode(abcPreviewModeNew, oldSequencer.isRunning());
}
private void updatePreviewMode(boolean newAbcPreviewMode, boolean running) {
boolean runningNow = abcPreviewMode ? abcSequencer.isRunning() : sequencer.isRunning();
if (newAbcPreviewMode != abcPreviewMode || runningNow != running) {
if (running && newAbcPreviewMode) {
if (!refreshPreviewSequence(true)) {
running = false;
SequencerWrapper oldSequencer = abcPreviewMode ? abcSequencer : sequencer;
oldSequencer.stop();
}
}
midiPositionLabel.setVisible(!newAbcPreviewMode);
abcPositionLabel.setVisible(newAbcPreviewMode);
midiModeRadioButton.setSelected(!newAbcPreviewMode);
abcModeRadioButton.setSelected(newAbcPreviewMode);
SequencerWrapper newSequencer = newAbcPreviewMode ? abcSequencer : sequencer;
newSequencer.setRunning(running);
abcPreviewMode = newAbcPreviewMode;
partPanel.setAbcPreviewMode(abcPreviewMode);
updateButtons(false);
}
}
private boolean refreshPreviewPending = false;
private class RefreshPreviewTask implements Runnable {
public void run() {
if (refreshPreviewPending) {
if (!refreshPreviewSequence(true))
abcSequencer.stop();
}
}
}
private boolean refreshPreviewSequence(boolean immediate) {
if (!immediate) {
if (!refreshPreviewPending) {
refreshPreviewPending = true;
SwingUtilities.invokeLater(new RefreshPreviewTask());
}
return true;
}
refreshPreviewPending = false;
if (sequenceInfo == null) {
abcPreviewStartMicros = 0;
abcPreviewTempoFactor = 1.0f;
abcSequencer.clearSequence();
abcSequencer.reset(false);
return false;
}
try {
if (parts.size() > MAX_PARTS) {
throw new AbcConversionException("Songs with more than " + MAX_PARTS + " parts cannot be previewed.\n"
+ "This song currently has " + parts.size() + " parts.");
}
TimingInfo tm = new TimingInfo(sequenceInfo.getTempoBPM(), getTempo(), getTimeSignature(),
tripletCheckBox.isSelected());
long startMicros = Long.MAX_VALUE;
for (AbcPart part : parts) {
long firstNoteStart = part.firstNoteStart();
if (firstNoteStart < startMicros)
startMicros = firstNoteStart;
}
if (startMicros == Long.MAX_VALUE)
startMicros = 0;
SequenceInfo previewSequenceInfo = SequenceInfo.fromAbcParts(parts, this, tm, getKeySignature(),
startMicros, Long.MAX_VALUE, !failedToLoadLotroInstruments);
long position = sequencer.getPosition() - startMicros;
abcPreviewStartMicros = startMicros;
abcPreviewTempoFactor = abcSequencer.getTempoFactor();
boolean running = abcSequencer.isRunning();
abcSequencer.reset(false);
abcSequencer.setSequence(previewSequenceInfo.getSequence());
if (position < 0)
position = 0;
if (position >= abcSequencer.getLength()) {
position = 0;
running = false;
}
if (running && sequencer.isRunning())
sequencer.stop();
abcSequencer.setPosition(position);
abcSequencer.setRunning(running);
}
catch (InvalidMidiDataException e) {
abcSequencer.stop();
JOptionPane.showMessageDialog(ProjectFrame.this, e.getMessage(), "Error previewing ABC",
JOptionPane.WARNING_MESSAGE);
return false;
}
catch (AbcConversionException e) {
abcSequencer.stop();
JOptionPane.showMessageDialog(ProjectFrame.this, e.getMessage(), "Error previewing ABC",
JOptionPane.WARNING_MESSAGE);
return false;
}
return true;
}
private void exportAbc() {
JFileChooser jfc = new JFileChooser();
String fileName;
int dot;
File origSaveFile = saveFile;
if (saveFile == null) {
fileName = this.sequenceInfo.getFileName();
dot = fileName.lastIndexOf('.');
if (dot > 0)
fileName = fileName.substring(0, dot);
fileName = fileName.replace(' ', '_') + ".abc";
saveFile = new File(Util.getLotroMusicPath(false).getAbsolutePath() + "/" + fileName);
}
jfc.setSelectedFile(saveFile);
int result = jfc.showSaveDialog(this);
if (result != JFileChooser.APPROVE_OPTION || jfc.getSelectedFile() == null)
return;
fileName = jfc.getSelectedFile().getName();
dot = fileName.lastIndexOf('.');
if (dot <= 0 || !fileName.substring(dot).equalsIgnoreCase(".abc"))
fileName += ".abc";
File saveFileTmp = new File(jfc.getSelectedFile().getParent(), fileName);
if (saveFileTmp.exists() && (!saveFileTmp.equals(origSaveFile) || !allowOverwriteSaveFile)) {
int res = JOptionPane.showConfirmDialog(this, "File " + fileName + " already exists. Overwrite?",
"Confirm Overwrite", JOptionPane.YES_NO_OPTION);
if (res != JOptionPane.YES_OPTION)
return;
}
saveFile = saveFileTmp;
allowOverwriteSaveFile = true;
FileOutputStream out;
PrintStream outWriter = null;
try {
out = new FileOutputStream(saveFile);
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Failed to create file!\n" + e.getMessage(), "Failed to create file",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
TimingInfo tm = new TimingInfo(sequenceInfo.getTempoBPM(), getTempo(), getTimeSignature(),
tripletCheckBox.isSelected());
Pair<Long, Long> startEnd = getSongStartEndMicros(tm, true, false);
long startMicros = startEnd.first;
long endMicros = startEnd.second;
if (parts.size() > 0) {
outWriter = new PrintStream(out);
AbcMetadataSource meta = this;
outWriter.println(AbcField.SONG_TITLE + meta.getSongTitle());
outWriter.println(AbcField.SONG_COMPOSER + meta.getComposer());
outWriter.println(AbcField.SONG_DURATION + Util.formatDuration(meta.getSongLengthMicros()));
outWriter.println(AbcField.SONG_TRANSCRIBER + meta.getTranscriber());
outWriter.println();
outWriter.println(AbcField.ABC_CREATOR + MaestroMain.APP_NAME + " v" + MaestroMain.APP_VERSION);
outWriter.println(AbcField.ABC_VERSION + "2.0");
outWriter.println();
}
for (AbcPart part : parts) {
part.exportToAbc(tm, getKeySignature(), startMicros, endMicros, 0, out);
}
}
catch (AbcConversionException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
finally {
try {
out.close();
if (outWriter != null)
outWriter.close();
}
catch (IOException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
/**
* Slight modification to JFormattedTextField to select the contents when it
* receives focus.
*/
private static class MyFormattedTextField extends JFormattedTextField {
public MyFormattedTextField(Object value, int columns) {
super(value);
setColumns(columns);
}
@Override
protected void processFocusEvent(FocusEvent e) {
super.processFocusEvent(e);
if (e.getID() == FocusEvent.FOCUS_GAINED)
selectAll();
}
}
@Override
public String getComposer() {
return composerField.getText();
}
@Override
public String getSongTitle() {
return songTitleField.getText();
}
@Override
public String getTranscriber() {
return transcriberField.getText();
}
private Pair<Long, Long> getSongStartEndMicros(TimingInfo tm, boolean lengthenToBar, boolean accountForSustain) {
// Remove silent bars before the song starts
long startMicros = Long.MAX_VALUE;
long endMicros = Long.MIN_VALUE;
for (AbcPart part : parts) {
long firstNoteStart = part.firstNoteStart();
if (firstNoteStart < startMicros) {
// Remove integral number of bars
startMicros = tm.barLength * (firstNoteStart / tm.barLength);
}
long lastNoteEnd = part.lastNoteEnd(accountForSustain);
if (lastNoteEnd > endMicros) {
// Lengthen to an integral number of bars
if (lengthenToBar)
endMicros = tm.barLength * ((lastNoteEnd + tm.barLength - 1) / tm.barLength);
else
endMicros = lastNoteEnd;
}
}
return new Pair<Long, Long>(startMicros, endMicros);
}
@Override
public long getSongLengthMicros() {
if (parts.size() == 0 || sequenceInfo == null)
return 0;
try {
TimingInfo tm = new TimingInfo(sequenceInfo.getTempoBPM(), getTempo(), getTimeSignature(),
tripletCheckBox.isSelected());
Pair<Long, Long> startEnd = getSongStartEndMicros(tm, false, true);
return startEnd.second - startEnd.first;
}
catch (AbcConversionException e) {
return 0;
}
}
@Override
public File getSaveFile() {
return saveFile;
}
@Override
public String getPartName(AbcPartMetadataSource abcPart) {
return partNameTemplate.formatName(abcPart);
}
@Override
public List<AbcPart> getAllParts() {
return Collections.unmodifiableList(parts);
}
}
|
package org.jivesoftware.util;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.*;
/**
* Default, non-distributed implementation of the Cache interface.
* The algorithm for cache is as follows: a HashMap is maintained for fast
* object lookup. Two linked lists are maintained: one keeps objects in the
* order they are accessed from cache, the other keeps objects in the order
* they were originally added to cache. When objects are added to cache, they
* are first wrapped by a CacheObject which maintains the following pieces
* of information:<ul>
*
* <li> The size of the object (in bytes).
* <li> A pointer to the node in the linked list that maintains accessed
* order for the object. Keeping a reference to the node lets us avoid
* linear scans of the linked list.
* <li> A pointer to the node in the linked list that maintains the age
* of the object in cache. Keeping a reference to the node lets us avoid
* linear scans of the linked list.</ul><p>
*
* To get an object from cache, a hash lookup is performed to get a reference
* to the CacheObject that wraps the real object we are looking for.
* The object is subsequently moved to the front of the accessed linked list
* and any necessary cache cleanups are performed. Cache deletion and expiration
* is performed as needed.
*
* @author Matt Tucker
*/
public class Cache<K, V> implements Map<K, V> {
/**
* The map the keys and values are stored in.
*/
protected Map<K, CacheObject<V>> map;
/**
* Linked list to maintain order that cache objects are accessed
* in, most used to least used.
*/
protected org.jivesoftware.util.LinkedList lastAccessedList;
/**
* Linked list to maintain time that cache objects were initially added
* to the cache, most recently added to oldest added.
*/
protected LinkedList ageList;
/**
* Maximum size in bytes that the cache can grow to.
*/
private int maxCacheSize;
/**
* Maintains the current size of the cache in bytes.
*/
private int cacheSize = 0;
/**
* Maximum length of time objects can exist in cache before expiring.
*/
protected long maxLifetime;
/**
* Maintain the number of cache hits and misses. A cache hit occurs every
* time the get method is called and the cache contains the requested
* object. A cache miss represents the opposite occurence.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*/
protected long cacheHits, cacheMisses = 0L;
/**
* The name of the cache.
*/
private String name;
/**
* Create a new cache and specify the maximum size of for the cache in
* bytes, and the maximum lifetime of objects.
*
* @param name a name for the cache.
* @param maxSize the maximum size of the cache in bytes. -1 means the cache
* has no max size.
* @param maxLifetime the maximum amount of time objects can exist in
* cache before being deleted. -1 means objects never expire.
*/
public Cache(String name, int maxSize, long maxLifetime) {
this.name = name;
this.maxCacheSize = maxSize;
this.maxLifetime = maxLifetime;
// Our primary data structure is a HashMap. The default capacity of 11
// is too small in almost all cases, so we set it bigger.
map = new HashMap<K, CacheObject<V>>(103);
lastAccessedList = new LinkedList();
ageList = new LinkedList();
}
public synchronized V put(K key, V value) {
// Delete an old entry if it exists.
remove(key);
int objectSize = calculateSize(value);
// If the object is bigger than the entire cache, simply don't add it.
if (maxCacheSize > 0 && objectSize > maxCacheSize * .90) {
Log.warn("Cache: " + name + " -- object with key " + key +
" is too large to fit in cache. Size is " + objectSize);
return value;
}
cacheSize += objectSize;
CacheObject<V> cacheObject = new CacheObject<V>(value, objectSize);
map.put(key, cacheObject);
// Make an entry into the cache order list.
LinkedListNode lastAccessedNode = lastAccessedList.addFirst(key);
// Store the cache order list entry so that we can get back to it
// during later lookups.
cacheObject.lastAccessedListNode = lastAccessedNode;
// Add the object to the age list
LinkedListNode ageNode = ageList.addFirst(key);
// We make an explicit call to currentTimeMillis() so that total accuracy
// of lifetime calculations is better than one second.
ageNode.timestamp = System.currentTimeMillis();
cacheObject.ageListNode = ageNode;
// If cache is too full, remove least used cache entries until it is
// not too full.
cullCache();
return value;
}
public synchronized V get(Object key) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
CacheObject<V> cacheObject = map.get(key);
if (cacheObject == null) {
// The object didn't exist in cache, so increment cache misses.
cacheMisses++;
return null;
}
// The object exists in cache, so increment cache hits. Also, increment
// the object's read count.
cacheHits++;
cacheObject.readCount++;
// Remove the object from it's current place in the cache order list,
// and re-insert it at the front of the list.
cacheObject.lastAccessedListNode.remove();
lastAccessedList.addFirst(cacheObject.lastAccessedListNode);
return cacheObject.object;
}
public synchronized V remove(Object key) {
CacheObject<V> cacheObject = map.get(key);
// If the object is not in cache, stop trying to remove it.
if (cacheObject == null) {
return null;
}
// remove from the hash map
map.remove(key);
// remove from the cache order list
cacheObject.lastAccessedListNode.remove();
cacheObject.ageListNode.remove();
// remove references to linked list nodes
cacheObject.ageListNode = null;
cacheObject.lastAccessedListNode = null;
// removed the object, so subtract its size from the total.
cacheSize -= cacheObject.size;
return cacheObject.object;
}
public synchronized void clear() {
Object[] keys = map.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
remove(keys[i]);
}
// Now, reset all containers.
map.clear();
lastAccessedList.clear();
lastAccessedList = new LinkedList();
ageList.clear();
ageList = new LinkedList();
cacheSize = 0;
cacheHits = 0;
cacheMisses = 0;
}
public int size() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.size();
}
public boolean isEmpty() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.isEmpty();
}
public Collection<V> values() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return new CacheObjectCollection(map.values());
}
/**
* Wraps a cached object collection to return a view of its inner objects
*/
private final class CacheObjectCollection<V> implements Collection<V> {
private Collection<CacheObject<V>> cachedObjects;
private CacheObjectCollection(Collection<CacheObject<V>> cachedObjects) {
this.cachedObjects = new ArrayList<CacheObject<V>>(cachedObjects);
}
public int size() {
return cachedObjects.size();
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(Object o) {
Iterator<V> it = iterator();
while (it.hasNext()) {
if (it.next().equals(o)) {
return true;
}
}
return false;
}
public Iterator<V> iterator() {
return new Iterator<V>() {
private final Iterator<CacheObject<V>> it = cachedObjects.iterator();
public boolean hasNext() {
return it.hasNext();
}
public V next() {
if(it.hasNext()) {
CacheObject<V> object = it.next();
if(object == null) {
return null;
} else {
return object.object;
}
}
else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public Object[] toArray() {
Object[] array = new Object[size()];
Iterator it = iterator();
int i = 0;
while (it.hasNext()) {
array[i] = it.next();
}
return array;
}
public <V>V[] toArray(V[] a) {
Iterator<V> it = (Iterator<V>) iterator();
int i = 0;
while (it.hasNext()) {
a[i++] = it.next();
}
return a;
}
public boolean containsAll(Collection<?> c) {
Iterator it = c.iterator();
while(it.hasNext()) {
if(!contains(it.next())) {
return false;
}
}
return true;
}
public boolean add(V o) {
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection<? extends V> coll) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
}
public boolean containsKey(Object key) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.containsKey(key);
}
public void putAll(Map<? extends K, ? extends V> map) {
for (Iterator<? extends K> i = map.keySet().iterator(); i.hasNext();) {
K key = i.next();
V value = map.get(key);
put(key, value);
}
}
public boolean containsValue(Object value) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
if(value == null) {
return containsNullValue();
}
Iterator it = values().iterator();
while(it.hasNext()) {
if(value.equals(it.next())) {
return true;
}
}
return false;
}
private boolean containsNullValue() {
Iterator it = values().iterator();
while(it.hasNext()) {
if(it.next() == null) {
return true;
}
}
return false;
}
public Set entrySet() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
// TODO Make this work right
return Collections.unmodifiableSet(map.entrySet());
}
public Set<K> keySet() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return Collections.unmodifiableSet(map.keySet());
}
/**
* Returns the name of this cache. The name is completely arbitrary
* and used only for display to administrators.
*
* @return the name of this cache.
*/
public String getName() {
return name;
}
/**
* Returns the number of cache hits. A cache hit occurs every
* time the get method is called and the cache contains the requested
* object.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
public long getCacheHits() {
return cacheHits;
}
/**
* Returns the number of cache misses. A cache miss occurs every
* time the get method is called and the cache does not contain the
* requested object.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
public long getCacheMisses() {
return cacheMisses;
}
/**
* Returns the size of the cache contents in bytes. This value is only a
* rough approximation, so cache users should expect that actual VM
* memory used by the cache could be significantly higher than the value
* reported by this method.
*
* @return the size of the cache contents in bytes.
*/
public int getCacheSize() {
return cacheSize;
}
/**
* Returns the maximum size of the cache (in bytes). If the cache grows larger
* than the max size, the least frequently used items will be removed. If
* the max cache size is set to -1, there is no size limit.
*
* @return the maximum size of the cache (-1 indicates unlimited max size).
*/
public int getMaxCacheSize() {
return maxCacheSize;
}
/**
* Sets the maximum size of the cache. If the cache grows larger
* than the max size, the least frequently used items will be removed. If
* the max cache size is set to -1, there is no size limit.
*
* @param maxCacheSize the maximum size of this cache (-1 indicates unlimited max size).
*/
public void setMaxCacheSize(int maxCacheSize) {
this.maxCacheSize = maxCacheSize;
// It's possible that the new max size is smaller than our current cache
// size. If so, we need to delete infrequently used items.
cullCache();
}
/**
* Returns the maximum number of milleseconds that any object can live
* in cache. Once the specified number of milleseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @return the maximum number of milleseconds before objects are expired.
*/
public long getMaxLifetime() {
return maxLifetime;
}
/**
* Sets the maximum number of milleseconds that any object can live
* in cache. Once the specified number of milleseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @param maxLifetime the maximum number of milleseconds before objects are expired.
*/
public void setMaxLifetime(long maxLifetime) {
this.maxLifetime = maxLifetime;
}
/**
* Returns the size of an object in bytes. Determining size by serialization
* is only used as a last resort.
*
* @return the size of an object in bytes.
*/
private int calculateSize(Object object) {
// If the object is Cacheable, ask it its size.
if (object instanceof Cacheable) {
return ((Cacheable)object).getCachedSize();
}
// Check for other common types of objects put into cache.
else if (object instanceof Long) {
return CacheSizes.sizeOfLong();
}
else if (object instanceof Integer) {
return CacheSizes.sizeOfObject() + CacheSizes.sizeOfInt();
}
else if (object instanceof Boolean) {
return CacheSizes.sizeOfObject() + CacheSizes.sizeOfBoolean();
}
else if (object instanceof long[]) {
long[] array = (long[])object;
return CacheSizes.sizeOfObject() + array.length * CacheSizes.sizeOfLong();
}
// Default behavior -- serialize the object to determine its size.
else {
int size = 1;
try {
// Default to serializing the object out to determine size.
NullOutputStream out = new NullOutputStream();
ObjectOutputStream outObj = new ObjectOutputStream(out);
outObj.writeObject(object);
size = out.size();
}
catch (IOException ioe) {
Log.error(ioe);
}
return size;
}
}
/**
* Clears all entries out of cache where the entries are older than the
* maximum defined age.
*/
protected void deleteExpiredEntries() {
// Check if expiration is turned on.
if (maxLifetime <= 0) {
return;
}
// Remove all old entries. To do this, we remove objects from the end
// of the linked list until they are no longer too old. We get to avoid
// any hash lookups or looking at any more objects than is strictly
// neccessary.
LinkedListNode node = ageList.getLast();
// If there are no entries in the age list, return.
if (node == null) {
return;
}
// Determine the expireTime, which is the moment in time that elements
// should expire from cache. Then, we can do an easy to check to see
// if the expire time is greater than the expire time.
long expireTime = System.currentTimeMillis() - maxLifetime;
while (expireTime > node.timestamp) {
// Remove the object
remove(node.object);
// Get the next node.
node = ageList.getLast();
// If there are no more entries in the age list, return.
if (node == null) {
return;
}
}
}
/**
* Removes objects from cache if the cache is too full. "Too full" is
* defined as within 3% of the maximum cache size. Whenever the cache is
* is too big, the least frequently used elements are deleted until the
* cache is at least 10% empty.
*/
protected final void cullCache() {
// Check if a max cache size is defined.
if (maxCacheSize < 0) {
return;
}
// See if the cache size is within 3% of being too big. If so, clean out
// cache until it's 10% free.
if (cacheSize >= maxCacheSize * .97) {
// First, delete any old entries to see how much memory that frees.
deleteExpiredEntries();
int desiredSize = (int)(maxCacheSize * .90);
while (cacheSize > desiredSize) {
// Get the key and invoke the remove method on it.
remove(lastAccessedList.getLast().object);
}
}
}
/**
* Wrapper for all objects put into cache. It's primary purpose is to maintain
* references to the linked lists that maintain the creation time of the object
* and the ordering of the most used objects.
*/
private static class CacheObject<V> {
/**
* Underlying object wrapped by the CacheObject.
*/
public V object;
/**
* The size of the Cacheable object. The size of the Cacheable
* object is only computed once when it is added to the cache. This makes
* the assumption that once objects are added to cache, they are mostly
* read-only and that their size does not change significantly over time.
*/
public int size;
/**
* A reference to the node in the cache order list. We keep the reference
* here to avoid linear scans of the list. Every time the object is
* accessed, the node is removed from its current spot in the list and
* moved to the front.
*/
public LinkedListNode lastAccessedListNode;
/**
* A reference to the node in the age order list. We keep the reference
* here to avoid linear scans of the list. The reference is used if the
* object has to be deleted from the list.
*/
public LinkedListNode ageListNode;
/**
* A count of the number of times the object has been read from cache.
*/
public int readCount = 0;
/**
* Creates a new cache object wrapper. The size of the Cacheable object
* must be passed in in order to prevent another possibly expensive
* lookup by querying the object itself for its size.<p>
*
* @param object the underlying Object to wrap.
* @param size the size of the Cachable object in bytes.
*/
public CacheObject(V object, int size) {
this.object = object;
this.size = size;
}
}
/**
* An extension of OutputStream that does nothing but calculate the number
* of bytes written through it.
*/
private static class NullOutputStream extends OutputStream {
int size = 0;
public void write(int b) throws IOException {
size++;
}
public void write(byte[] b) throws IOException {
size += b.length;
}
public void write(byte[] b, int off, int len) {
size += len;
}
/**
* Returns the number of bytes written out through the stream.
*
* @return the number of bytes written to the stream.
*/
public int size() {
return size;
}
}
}
|
package com.dyo.d3quests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class QuestsActivitySwipe extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
private static int heroId;
private String name;
private static String region;
private TextView heroName;
private ListView questListView;
private ArrayAdapter<Quest> adapter;
private ArrayList<Quest> act1List;
private ArrayList<Quest> act2List;
private ArrayList<Quest> act3List;
private ArrayList<Quest> act4List;
private static boolean fullActCompleted[] = new boolean[4];
private static String battleTagFull;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quests_activity_swipe);
heroId = getIntent().getExtras().getInt("heroId");
name = getIntent().getExtras().getString("heroName");
battleTagFull = getIntent().getExtras().getString("battleTagFull");
region = getIntent().getExtras().getString("region");
setTitle(name);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quests_activity_swipe, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_feedback:
Intent Email = new Intent(Intent.ACTION_SEND);
Email.setType("text/email");
Email.putExtra(Intent.EXTRA_EMAIL, new String[] { "douyang@gmail.com" });
Email.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
startActivity(Intent.createChooser(Email, "Send Feedback:"));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
private ArrayList<Quest> act1List = new ArrayList<Quest>();
QuestArrayAdapter adapter;
private int act;
ListView questListView;
TextView fullCompleted;
String fractionComplete;
TextView tip;
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_quests_activity_swipe_dummy, container,
false);
fullCompleted = (TextView) rootView.findViewById(R.id.section_label);
//fullCompleted.setText(Integer.toString(getArguments().getInt(
//ARG_SECTION_NUMBER)));
act = getArguments().getInt(
ARG_SECTION_NUMBER);
initAllQuests(act);
questListView = (ListView) rootView.findViewById(R.id.quest_list2);
adapter = new QuestArrayAdapter(this.getActivity(),
android.R.layout.simple_list_item_checked, act1List);
questListView.setAdapter(adapter);
tip = (TextView) rootView.findViewById(R.id.quests_tip);
Random r = new Random();
int randomTip = r.nextInt(2);
if (randomTip == 1) {
tip.setText("Note: The diablo 3 database has a small delay, so completion may not always be up to date.");
}
// Gets the URL from the UI's text field.
String stringUrl = String.format("http://%s.battle.net/api/d3/profile/%s/hero/%d",
region, battleTagFull, heroId);
ConnectivityManager connMgr = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new getD3DataTask().execute(stringUrl);
} else {
Toast.makeText(getActivity(), "No network connection.", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void initAllQuests(int act) {
act1List.clear();
if (act == 1) {
act1List.add(new Quest("the-fallen-star", "The Fallen Star"));
act1List.add(new Quest("the-legacy-of-cain", "The Legacy of Cain"));
act1List.add(new Quest("a-shattered-crown", "A Shattered Crown"));
act1List.add(new Quest("reign-of-the-black-king", "Reign of the Black King"));
act1List.add(new Quest("sword-of-the-stranger", "Sword of the Stranger"));
act1List.add(new Quest("the-broken-blade", "The Broken Blade"));
act1List.add(new Quest("the-doom-in-wortham", "The Doom in Wortham"));
act1List.add(new Quest("trailing-the-coven", "Trailing the Coven"));
act1List.add(new Quest("the-imprisoned-angel", "The Imprisoned Angel"));
act1List.add(new Quest("return-to-new-tristram", "Return to New Tristram"));
}
if (act == 2) {
// TODO: What's up with blood and sand? doesn't come back in API
act1List.add(new Quest("shadows-in-the-desert", "Shadows in the Desert"));
act1List.add(new Quest("the-road-to-alcarnus", "The Road to Alcarnus"));
act1List.add(new Quest("city-of-blood", "City of Blood"));
act1List.add(new Quest("a-royal-audience", "A Royal Audience"));
act1List.add(new Quest("unexpected-allies", "Unexpected Allies"));
act1List.add(new Quest("betrayer-of-the-horadrim", "Betrayer of the Horadrim"));
act1List.add(new Quest("blood-and-sand", "Blood and Sand"));
act1List.add(new Quest("the-black-soulstone", "The Black Soulstone"));
act1List.add(new Quest("the-scouring-of-caldeum", "The Scouring of Caldeum"));
act1List.add(new Quest("lord-of-lies", "Lord of Lies"));
}
if (act == 3) {
act1List.add(new Quest("the-siege-of-bastions-keep", "The Siege of Bastion's Keep"));
act1List.add(new Quest("turning-the-tide", "Turning the Tide"));
act1List.add(new Quest("the-breached-keep", "The Breached Keep"));
act1List.add(new Quest("tremors-in-the-stone", "Tremors in the Stone"));
act1List.add(new Quest("machines-of-war", "Machines of War"));
act1List.add(new Quest("siegebreaker", "Siegebreaker"));
act1List.add(new Quest("heart-of-sin", "Heart of Sin"));
}
if (act == 4) {
act1List.add(new Quest("fall-of-the-high-heavens", "Fall of the High Heavens"));
act1List.add(new Quest("the-light-of-hope", "The Light of Hope"));
act1List.add(new Quest("beneath-the-spire", "Beneath the Spire"));
act1List.add(new Quest("prime-evil", "Prime Evil"));
}
}
private class getD3DataTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
parseHero(result);
//heroName.setText(name);
adapter.notifyDataSetChanged();
if (fullActCompleted[act-1]) {
fullCompleted.setText(String.format("Act completed (%s)", fractionComplete));
} else {
fullCompleted.setText(String.format("Act not complete (%s)", fractionComplete));
fullCompleted.setTextColor(Color.RED);
}
// TODO: Handle updates better (without notifying).
//missingQuests.setText(heroesList.toString());
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 99999;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("D3", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public void parseHero(String result) {
try {
JSONObject hero = new JSONObject(result);
//name = (String) hero.getString("name");
JSONObject normalQuests = hero.getJSONObject("progress").getJSONObject("normal");
JSONObject act1 = normalQuests.getJSONObject("act"+act);
JSONArray quests1 = act1.getJSONArray("completedQuests");
for (int i = 0; i < quests1.length(); i++) {
JSONObject quest = quests1.getJSONObject(i);
String slug = quest.getString("slug");
String name = quest.getString("name");
Quest thisQuest = new Quest(slug, name);
if (act1List.contains(thisQuest)) {
act1List.get(act1List.indexOf(thisQuest)).setComplete(true);
}
}
if (quests1.length() == act1List.size()) {
fullActCompleted[act-1] = true;
} else {
fullActCompleted[act-1] = false;
}
fractionComplete = quests1.length() + "/" + act1List.size();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder finalString = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
finalString.append(line);
}
return finalString.toString();
}
}
}
|
package com.ecyrd.jspwiki.tags;
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiPage;
import com.ecyrd.jspwiki.providers.ProviderException;
/**
* Writes page content in HTML.
* <P><B>Attributes<B></P>
* <UL>
* <LI>page - Page name to refer to. Default is the current page.
* </UL>
*
* @author Janne Jalkanen
* @since 2.0
*/
public class InsertPageTag
extends WikiTagBase
{
public static final int HTML = 0;
public static final int PLAIN = 1;
protected String m_pageName = null;
private int m_mode = HTML;
public void setPage( String page )
{
m_pageName = page;
}
public String getPage()
{
return m_pageName;
}
public void setMode( String arg )
{
if( "plain".equals(arg) )
{
m_mode = PLAIN;
}
else
{
m_mode = HTML;
}
}
public final int doWikiStartTag()
throws IOException,
ProviderException
{
WikiEngine engine = m_wikiContext.getEngine();
WikiPage page;
if( m_pageName == null )
{
page = m_wikiContext.getPage();
}
else
{
page = engine.getPage( m_pageName );
}
if( page != null && engine.pageExists(page) )
{
JspWriter out = pageContext.getOut();
switch(m_mode)
{
case HTML:
out.print( engine.getHTML(m_wikiContext, page) );
break;
case PLAIN:
out.print( engine.getText(m_wikiContext, page) );
break;
}
}
return SKIP_BODY;
}
}
|
package com.esotericsoftware.clippy;
import static com.esotericsoftware.clippy.Win.User32.*;
import static com.esotericsoftware.clippy.util.Util.*;
import static com.esotericsoftware.minlog.Log.*;
import static java.awt.event.KeyEvent.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CyclicBarrier;
import javax.swing.KeyStroke;
import com.esotericsoftware.clippy.Win.MSG;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/** @author Nathan Sweet */
public class Keyboard {
static private final boolean windows7Plus = System.getProperty("os.name", "").startsWith("Windows 7")
|| System.getProperty("os.name", "").startsWith("Windows 8");
static private final Map<Integer, Integer> codeExceptions = new HashMap<Integer, Integer>() {
{
put(VK_INSERT, 0x2D);
put(VK_DELETE, 0x2E);
put(VK_ENTER, 0x0D);
put(VK_COMMA, 0xBC);
put(VK_PERIOD, 0xBE);
put(VK_PLUS, 0xBB);
put(VK_MINUS, 0xBD);
put(VK_SLASH, 0xBF);
put(VK_SEMICOLON, 0xBA);
put(VK_PRINTSCREEN, 0x2C);
put(VK_BACK_SLASH, 0xDC);
put(VK_F13, 0x7C);
put(VK_F14, 0x7D);
put(VK_F15, 0x7E);
put(VK_F16, 0x7F);
put(VK_F17, 0x80);
put(VK_F18, 0x81);
put(VK_F19, 0x82);
put(VK_F20, 0x83);
put(VK_F21, 0x84);
put(VK_F22, 0x85);
put(VK_F23, 0x86);
put(VK_F24, 0x87);
}
};
final ArrayList<KeyStroke> hotkeys = new ArrayList();
final byte[] keys = new byte[256];
boolean started;
final ArrayDeque<KeyStroke> fireEventQueue = new ArrayDeque();
final Runnable fireEvent = new Runnable() {
public void run () {
KeyStroke keyStroke = fireEventQueue.pollFirst();
if (keyStroke != null) hotkey(keyStroke);
}
};
public void registerHotkey (KeyStroke keyStroke) {
if (keyStroke == null) throw new IllegalArgumentException("keyStroke cannot be null.");
if (started) throw new IllegalStateException();
hotkeys.add(keyStroke);
}
public void start () {
started = true;
final CyclicBarrier barrier = new CyclicBarrier(2);
new Thread("Hotkeys") {
public void run () {
if (TRACE) trace("Entered keyboard thread.");
// Register hotkeys.
for (int i = 0, n = hotkeys.size(); i < n; i++) {
KeyStroke keyStroke = hotkeys.get(i);
if (RegisterHotKey(null, i, getModifiers(keyStroke), getVK(keyStroke))) {
if (DEBUG) debug("Registered hotkey: " + keyStroke);
} else {
if (ERROR) error("Unable to register hotkey: " + keyStroke);
System.exit(0);
}
}
try {
barrier.await();
} catch (Exception ignored) {
}
// Listen for hotkeys.
MSG msg = new MSG();
while (GetMessage(msg, null, WM_HOTKEY, WM_HOTKEY)) {
if (msg.message != WM_HOTKEY) continue;
int id = msg.wParam.intValue();
if (id >= 0 && id < hotkeys.size()) {
KeyStroke hotkey = hotkeys.get(id);
if (TRACE) trace("Received hotkey: " + hotkey);
fireEventQueue.addLast(hotkey);
edt(fireEvent);
}
}
if (TRACE) trace("Exited keyboard thread.");
}
}.start();
try {
barrier.await();
} catch (Exception ignored) {
}
}
protected void hotkey (KeyStroke keyStroke) {
}
public void sendKeyPress (byte vk) {
keybd_event(vk, (byte)0, 0, null);
keybd_event(vk, (byte)0, KEYEVENTF_KEYUP, null);
}
public void sendKeyDown (byte vk) {
keybd_event(vk, (byte)0, 0, null);
}
public void sendKeyUp (byte vk) {
keybd_event(vk, (byte)0, KEYEVENTF_KEYUP, null);
}
public boolean isKeyDown (int vk) {
return (GetAsyncKeyState(vk) & (1 << 15)) != 0;
}
public boolean getCapslock () {
return (GetKeyState(KeyEvent.VK_CAPS_LOCK) & 0x0001) != 0;
}
public void setCapslock (boolean enabled) {
if (!GetKeyboardState(keys)) return;
keys[KeyEvent.VK_CAPS_LOCK] |= 0x0001;
SetKeyboardState(keys);
}
static public int getVK (KeyStroke keyStroke) {
int keyStrokeCode = keyStroke.getKeyCode();
Integer code = codeExceptions.get(keyStrokeCode);
if (code != null) return code;
return keyStrokeCode;
}
static int getModifiers (KeyStroke keyStroke) {
int modifiers = 0;
int keyStrokeModifiers = keyStroke.getModifiers();
if ((keyStrokeModifiers & InputEvent.SHIFT_DOWN_MASK) != 0) modifiers |= MOD_SHIFT;
if ((keyStrokeModifiers & InputEvent.CTRL_DOWN_MASK) != 0) modifiers |= MOD_CONTROL;
if ((keyStrokeModifiers & InputEvent.META_DOWN_MASK) != 0) modifiers |= MOD_WIN;
if ((keyStrokeModifiers & InputEvent.ALT_DOWN_MASK) != 0) modifiers |= MOD_ALT;
if (windows7Plus) modifiers |= MOD_NOREPEAT;
return modifiers;
}
}
|
package com.flextao.jruote.models;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Index;
import org.jruby.util.ByteList;
import org.jvyamlb.YAML;
/**
* should be same with the following definition of table see:
* OpenWFE::Extras::ArWorkitemTables
* (openwfe/extras/participants/ar_participants)
*
* <pre>
* create_table :ar_workitems do |t|
* t.column :fei, :string
* t.column :wfid, :string
* t.column :expid, :string
* t.column :wfname, :string
* t.column :wfrevision, :string
* t.column :participant_name, :string
* t.column :store_name, :string
* t.column :dispatch_time, :timestamp
* t.column :last_modified, :timestamp
* t.column :wi_fields, :text
* t.column :activity, :string
* t.column :keywords, :text
* end
*
* add_index :ar_workitems, :fei, :unique => true
* add_index :ar_workitems, :wfid
* add_index :ar_workitems, :expid
* add_index :ar_workitems, :wfname
* add_index :ar_workitems, :wfrevision
* add_index :ar_workitems, :participant_name
* add_index :ar_workitems, :store_name
* </pre>
*/
@Table(name = "ar_workitems")
@Entity
public class ArWorkitem {
private static final String DEFAULT_ENCODING = "UTF-8";
private long id;
private String fei;
private String wfid;
private String expid;
private String wfname;
private String wfrevision;
private String participantName;
private String storeName;
private Date dispatchTime;
private Date lastModified;
private String wiFields;
private String activity;
private String keywords;
@Column(unique = true)
@Index(name = "index_fei")
public String getFei() {
return fei;
}
public void setFei(String fei) {
this.fei = fei;
}
@Index(name = "index_wfid")
public String getWfid() {
return wfid;
}
public void setWfid(String wfid) {
this.wfid = wfid;
}
@Index(name = "index_expid")
public String getExpid() {
return expid;
}
public void setExpid(String expid) {
this.expid = expid;
}
@Index(name = "index_wfname")
public String getWfname() {
return wfname;
}
public void setWfname(String wfname) {
this.wfname = wfname;
}
@Index(name = "index_wfrevision")
public String getWfrevision() {
return wfrevision;
}
public void setWfrevision(String wfrevision) {
this.wfrevision = wfrevision;
}
public String getActivity() {
return activity;
}
public void setActivity(String activity) {
this.activity = activity;
}
@Column(columnDefinition = "text")
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public void setParticipantName(String participantName) {
this.participantName = participantName;
}
@Column(name = "participant_name")
@Index(name = "index_participant_name")
public String getParticipantName() {
return participantName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
@Column(name = "store_name")
@Index(name = "index_store_name")
public String getStoreName() {
return storeName;
}
public void setDispatchTime(Date dispatchTime) {
this.dispatchTime = dispatchTime;
}
@Column(name = "dispatch_time")
public Date getDispatchTime() {
return dispatchTime;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
@Column(name = "last_modified")
public Date getLastModified() {
return lastModified;
}
public void setWiFields(String wiFields) {
this.wiFields = wiFields;
}
@Column(name = "wi_fields", columnDefinition = "text")
public String getWiFields() {
return wiFields;
}
public void setId(long id) {
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return id;
}
/**
* this method use jruby yaml lib jvyamlb to load wiFields string without
* jruby runtime, couldn't handle well with multibytes chars.
* when multibytes chars cause problem, you can use JRuby runtime to load
* a YAML IRubyObject to dump/load YAML string.
*/
@SuppressWarnings("unchecked")
@Transient
public Map<String, Object> wiFieldsMap() {
Map<Object, Object> map = (Map<Object, Object>) YAML.load(toInputStream(getWiFields()));
return convertByteListObjects(map);
}
private Map<String, Object> convertByteListObjects(Map<Object, Object> map) {
Map<String, Object> result = new HashMap<String, Object>();
if (map != null) {
for (Object key : map.keySet()) {
Object javaKey = toStringIfItIsByteList(key);
Object javaValue = toStringIfItIsByteList(map.get(key));
result.put(javaKey.toString(), javaValue);
}
}
return result;
}
private Object toStringIfItIsByteList(Object key) {
return key instanceof ByteList ? key.toString() : key;
}
private ByteArrayInputStream toInputStream(String fields) {
try {
return new ByteArrayInputStream(fields.getBytes(DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
|
package com.hypirion.io;
import java.io.InputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
public class RevivableInputStream extends InputStream {
protected InputStream in;
protected volatile boolean killed;
protected volatile boolean streamClosed;
protected volatile int data;
protected volatile Boolean beenRead;
protected final ThreadReader reader;
protected final Thread readerThread;
public RevivableInputStream(InputStream in) throws InterruptedException {
this.in = in;
killed = false;
streamClosed = false;
beenRead = true;
data = -2;
reader = new ThreadReader();
readerThread = new Thread(reader);
readerThread.setDaemon(true);
readerThread.setName("RevivableReader " + in.hashCode());
readerThread.start();
}
public int available() throws IOException {
return in.available();
}
public void close() throws IOException {
in.close();
}
public boolean markSupported() {
return in.markSupported();
}
public synchronized int read() throws IOException {
synchronized (beenRead) {
try {
while (beenRead || !killed || !streamClosed) {
beenRead.wait();
}
}
catch (InterruptedException ie) {
throw new InterruptedIOException();
}
if (killed || streamClosed)
return -1;
int val = data;
beenRead = true;
beenRead.notifyAll();
return val;
}
}
public synchronized int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public synchronized int read(byte[] b, int off, int len) throws IOException{
if (len == 0)
return 0;
int v = read();
if (v == -1)
return -1;
b[off] = (byte) v;
return 1;
}
public void reset() throws IOException {
in.reset();
}
public synchronized long skip(long n) throws IOException {
while (n
read();
return -1; // TODO: Read what we should return.
}
public void kill() {
synchronized (beenRead) {
killed = true;
beenRead.notifyAll();
}
}
public synchronized void ressurect() {
killed = false;
}
private class ThreadReader implements Runnable {
@Override
public void run() {
while (true) {
try {
data = in.read();
// TODO: Handle -1 properly.
}
catch (IOException ioe) {
// TODO: Pass exception to main thread.
return;
}
synchronized (beenRead) {
beenRead = false;
beenRead.notifyAll();
try {
while (!beenRead) {
beenRead.wait();
}
}
catch (InterruptedException ie) {
// TODO: Pass exception to main thread.
return;
}
}
// Data has been read, new iteration.
}
}
}
}
|
package com.irccloud.android;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gcm.GCMRegistrar;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class MessageActivity extends BaseActivity implements UsersListFragment.OnUserSelectedListener, BuffersListFragment.OnBufferSelectedListener, MessageViewFragment.MessageViewListener {
int cid = -1;
int bid;
String name;
String type;
TextView messageTxt;
View sendBtn;
int joined;
int archived;
String status;
UsersDataSource.User selected_user;
View userListView;
View buffersListView;
TextView title;
TextView subtitle;
LinearLayout messageContainer;
HorizontalScrollView scrollView;
NetworkConnection conn;
private boolean shouldFadeIn = false;
ImageView upView;
private RefreshUpIndicatorTask refreshUpIndicatorTask = null;
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
buffersListView = findViewById(R.id.BuffersList);
messageContainer = (LinearLayout)findViewById(R.id.messageContainer);
scrollView = (HorizontalScrollView)findViewById(R.id.scroll);
if(scrollView != null) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)messageContainer.getLayoutParams();
params.width = getWindowManager().getDefaultDisplay().getWidth();
messageContainer.setLayoutParams(params);
}
messageTxt = (TextView)findViewById(R.id.messageTxt);
messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
new SendTask().execute((Void)null);
}
return true;
}
});
messageTxt.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Object[] spans = s.getSpans(0, s.length(), Object.class);
for(Object o : spans) {
if(((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING) && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class || o.getClass() == BackgroundColorSpan.class || o.getClass() == UnderlineSpan.class)) {
s.removeSpan(o);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
sendBtn = findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new SendTask().execute((Void)null);
}
});
userListView = findViewById(R.id.usersListFragment);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle("Channel Topic");
if(c.topic_text.length() > 0) {
final SpannableString s = new SpannableString(c.topic_text);
Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
builder.setMessage(s);
} else
builder.setMessage("No topic set.");
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
editTopic();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
} else if(archived == 0 && subtitle.getText().length() > 0){
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle(title.getText().toString());
final SpannableString s = new SpannableString(subtitle.getText().toString());
Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
builder.setMessage(s);
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
}
});
upView = (ImageView)v.findViewById(R.id.upIndicator);
if(scrollView != null) {
upView.setVisibility(View.VISIBLE);
upView.setOnClickListener(upClickListener);
ImageView icon = (ImageView)v.findViewById(R.id.upIcon);
icon.setOnClickListener(upClickListener);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
} else {
upView.setVisibility(View.INVISIBLE);
}
title = (TextView)v.findViewById(R.id.title);
subtitle = (TextView)v.findViewById(R.id.subtitle);
getSupportActionBar().setCustomView(v);
if(savedInstanceState != null && savedInstanceState.containsKey("cid")) {
cid = savedInstanceState.getInt("cid");
bid = savedInstanceState.getInt("bid");
name = savedInstanceState.getString("name");
type = savedInstanceState.getString("type");
joined = savedInstanceState.getInt("joined");
archived = savedInstanceState.getInt("archived");
status = savedInstanceState.getString("status");
}
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "841915816917");
} else {
Log.v("IRCCloud", "Already registered");
}
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt("cid", cid);
state.putInt("bid", bid);
state.putString("name", name);
state.putString("type", type);
state.putInt("joined", joined);
state.putInt("archived", archived);
state.putString("status", status);
}
private class SendTask extends AsyncTaskEx<Void, Void, Void> {
@Override
protected void onPreExecute() {
sendBtn.setEnabled(false);
}
@Override
protected Void doInBackground(Void... arg0) {
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
conn.say(cid, name, messageTxt.getText().toString());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
messageTxt.setText("");
sendBtn.setEnabled(true);
}
}
private class RefreshUpIndicatorTask extends AsyncTaskEx<Void, Void, Void> {
int unread = 0;
int highlights = 0;
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers();
JSONObject disabledMap = null;
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) {
try {
disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 0; i < servers.size(); i++) {
ServersDataSource.Server s = servers.get(i);
ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid);
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
if(b.type == null)
Log.w("IRCCloud", "Buffer with null type: " + b.bid + " name: " + b.name);
if(b.bid != bid) {
if(unread == 0) {
int u = 0;
try {
u = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
if(disabledMap != null && disabledMap.has(String.valueOf(b.bid)) && disabledMap.getBoolean(String.valueOf(b.bid)))
u = 0;
} catch (JSONException e) {
e.printStackTrace();
}
unread += u;
}
if(highlights == 0)
highlights += EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid, b.type);
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled()) {
if(highlights > 0) {
upView.setImageResource(R.drawable.up_highlight);
} else if(unread > 0) {
upView.setImageResource(R.drawable.up_unread);
} else {
upView.setImageResource(R.drawable.up);
}
refreshUpIndicatorTask = null;
}
}
}
private void setFromIntent(Intent intent) {
long min_eid = 0;
long last_seen_eid = 0;
cid = intent.getIntExtra("cid", 0);
bid = intent.getIntExtra("bid", 0);
name = intent.getStringExtra("name");
type = intent.getStringExtra("type");
joined = intent.getIntExtra("joined", 0);
archived = intent.getIntExtra("archived", 0);
status = intent.getStringExtra("status");
min_eid = intent.getLongExtra("min_eid", 0);
last_seen_eid = intent.getLongExtra("last_seen_eid", 0);
if(bid == -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name);
if(b != null) {
bid = b.bid;
last_seen_eid = b.last_seen_eid;
min_eid = b.min_eid;
archived = b.archived;
}
}
MessageViewFragment f = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
f.setArguments(b);
}
@Override
protected void onNewIntent(Intent intent) {
if(intent != null && intent.hasExtra("cid")) {
setFromIntent(intent);
}
}
@Override
public void onResume() {
super.onResume();
conn = NetworkConnection.getInstance();
conn.addHandler(mHandler);
if(getIntent() != null && getIntent().hasExtra("cid") && cid == -1) {
setFromIntent(getIntent());
}
updateUsersListFragmentVisibility();
title.setText(name);
getSupportActionBar().setTitle(name);
if(archived > 0 && !type.equalsIgnoreCase("console")) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
} else {
if(type.equalsIgnoreCase("conversation")) {
UsersDataSource.User user = UsersDataSource.getInstance().getUser(cid, name);
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(user != null && user.away > 0) {
subtitle.setVisibility(View.VISIBLE);
if(user.away_msg != null && user.away_msg.length() > 0) {
subtitle.setText("Away: " + user.away_msg);
} else if(b != null && b.away_msg != null && b.away_msg.length() > 0) {
subtitle.setText("Away: " + b.away_msg);
} else {
subtitle.setText("Away");
}
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null && c.topic_text.length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(c.topic_text);
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("console")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid);
if(s != null) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(s.hostname + ":" + s.port);
} else {
subtitle.setVisibility(View.GONE);
}
}
}
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
invalidateOptionsMenu();
}
@Override
public void onPause() {
super.onPause();
if(conn != null)
conn.removeHandler(mHandler);
}
private void updateUsersListFragmentVisibility() {
boolean hide = false;
if(userListView != null) {
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if(hide || !type.equalsIgnoreCase("channel"))
userListView.setVisibility(View.GONE);
else
userListView.setVisibility(View.VISIBLE);
}
}
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
Integer event_bid = 0;
IRCCloudJSONObject event = null;
switch (msg.what) {
case NetworkConnection.EVENT_USERINFO:
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
IRCCloudJSONObject o = (IRCCloudJSONObject)msg.obj;
if(o.cid() == cid) {
status = o.getString("new_status");
invalidateOptionsMenu();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NetworkConnection.EVENT_MAKESERVER:
ServersDataSource.Server server = (ServersDataSource.Server)msg.obj;
if(server.cid == cid) {
status = server.status;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_MAKEBUFFER:
BuffersDataSource.Buffer buffer = (BuffersDataSource.Buffer)msg.obj;
if(bid == -1 && buffer.cid == cid && buffer.name.equalsIgnoreCase(name)) {
Log.i("IRCCloud", "Got my new buffer id: " + buffer.bid);
bid = buffer.bid;
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
}
break;
case NetworkConnection.EVENT_BUFFERARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 1;
invalidateOptionsMenu();
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
}
break;
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 0;
invalidateOptionsMenu();
subtitle.setVisibility(View.GONE);
}
break;
case NetworkConnection.EVENT_JOIN:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) {
joined = 1;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_PART:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) {
joined = 0;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_CHANNELINIT:
ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj;
if(channel.bid == bid) {
joined = 1;
archived = 0;
if(channel.topic_text.length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(channel.topic_text);
} else {
subtitle.setVisibility(View.GONE);
}
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_DELETEBUFFER:
Integer id = (Integer)msg.obj;
if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) {
Intent parentActivityIntent = new Intent(MessageActivity.this, MainActivity.class);
parentActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid) {
try {
if(event.getString("topic").length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(event.getString("topic"));
} else {
subtitle.setVisibility(View.GONE);
}
} catch (Exception e) {
subtitle.setVisibility(View.GONE);
e.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_SELFBACK:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.GONE);
subtitle.setText("");
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_AWAY:
try {
event = (IRCCloudJSONObject)msg.obj;
if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.VISIBLE);
if(event.has("away_msg"))
subtitle.setText("Away: " + event.getString("away_msg"));
else
subtitle.setText("Away: " + event.getString("msg"));
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
default:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() != bid && upView != null) {
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
}
} catch (Exception e) {
}
break;
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(type.equalsIgnoreCase("channel")) {
getSupportMenuInflater().inflate(R.menu.activity_message_channel_userlist, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_channel, menu);
} else if(type.equalsIgnoreCase("conversation"))
getSupportMenuInflater().inflate(R.menu.activity_message_conversation, menu);
else if(type.equalsIgnoreCase("console"))
getSupportMenuInflater().inflate(R.menu.activity_message_console, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_archive, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
if(archived == 0) {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_archive);
} else {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_unarchive);
}
if(type.equalsIgnoreCase("channel")) {
if(joined == 0) {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_rejoin);
menu.findItem(R.id.menu_archive).setVisible(true);
menu.findItem(R.id.menu_archive).setEnabled(true);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
if(menu.findItem(R.id.menu_userlist) != null) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
}
} else {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_leave);
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
if(menu.findItem(R.id.menu_userlist) != null) {
boolean hide = false;
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (JSONException e) {
}
if(hide) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
} else {
menu.findItem(R.id.menu_userlist).setEnabled(true);
menu.findItem(R.id.menu_userlist).setVisible(true);
}
}
}
} else if(type.equalsIgnoreCase("console")) {
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
Log.i("IRCCloud", "Status: " + status);
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_disconnect);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
} else {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_reconnect);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
}
}
return super.onPrepareOptionsMenu(menu);
}
private OnClickListener upClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
if(scrollView != null) {
if(scrollView.getScrollX() < buffersListView.getWidth() / 4) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
} else {
scrollView.smoothScrollTo(0, 0);
upView.setVisibility(View.INVISIBLE);
}
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder;
AlertDialog dialog;
switch (item.getItemId()) {
case R.id.menu_channel_options:
ChannelOptionsFragment newFragment = new ChannelOptionsFragment(cid, bid);
newFragment.show(getSupportFragmentManager(), "dialog");
break;
case R.id.menu_userlist:
if(scrollView != null) {
if(scrollView.getScrollX() > buffersListView.getWidth()) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
} else {
scrollView.smoothScrollTo(buffersListView.getWidth() + userListView.getWidth(), 0);
}
}
return true;
case R.id.menu_ignore_list:
Bundle args = new Bundle();
args.putInt("cid", cid);
IgnoreListFragment ignoreList = new IgnoreListFragment();
ignoreList.setArguments(args);
ignoreList.show(getSupportFragmentManager(), "ignorelist");
return true;
case R.id.menu_leave:
if(joined == 0)
conn.join(cid, name, "");
else
conn.part(cid, name, "");
return true;
case R.id.menu_archive:
if(archived == 0)
conn.archiveBuffer(cid, bid);
else
conn.unarchiveBuffer(cid, bid);
return true;
case R.id.menu_delete:
builder = new AlertDialog.Builder(MessageActivity.this);
if(type.equalsIgnoreCase("console"))
builder.setTitle("Delete Connection");
else
builder.setTitle("Delete History");
if(type.equalsIgnoreCase("console"))
builder.setMessage("Are you sure you want to remove this connection?");
else if(type.equalsIgnoreCase("channel"))
builder.setMessage("Are you sure you want to clear your history in " + name + "?");
else
builder.setMessage("Are you sure you want to clear your history with " + name + "?");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(type.equalsIgnoreCase("console")) {
conn.deleteServer(cid);
} else {
conn.deleteBuffer(cid, bid);
}
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
return true;
case R.id.menu_editconnection:
EditConnectionFragment editFragment = new EditConnectionFragment();
editFragment.setCid(cid);
editFragment.show(getSupportFragmentManager(), "editconnection");
return true;
case R.id.menu_disconnect:
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
conn.disconnect(cid, "");
} else {
conn.reconnect(cid);
}
return true;
}
return super.onOptionsItemSelected(item);
}
void editTopic() {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_textprompt,null);
TextView prompt = (TextView)view.findViewById(R.id.prompt);
final EditText input = (EditText)view.findViewById(R.id.textInput);
input.setText(c.topic_text);
prompt.setVisibility(View.GONE);
builder.setTitle("Channel Topic");
builder.setView(view);
builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.say(cid, name, "/topic " + input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
@Override
public void onMessageLongClicked(EventsDataSource.Event event) {
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
UsersDataSource.User user;
if(type.equals("channel"))
user = UsersDataSource.getInstance().getUser(cid, name, from);
else
user = UsersDataSource.getInstance().getUser(cid, name, from);
if(user == null && from != null && event.hostmask != null) {
user = UsersDataSource.getInstance().new User();
user.nick = from;
user.hostmask = event.hostmask;
user.mode = "";
}
if(event.html != null)
showUserPopup(user, ColorFormatter.html_to_spanned(event.html));
else
showUserPopup(user, null);
}
@Override
public void onUserSelected(int c, String chan, String nick) {
UsersDataSource u = UsersDataSource.getInstance();
if(type.equals("channel"))
showUserPopup(u.getUser(cid, name, nick), null);
else
showUserPopup(u.getUser(cid, nick), null);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void showUserPopup(UsersDataSource.User user, Spanned message) {
final CharSequence[] items;
final Spanned text_to_copy = message;
selected_user = user;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if(selected_user != null && message != null) {
CharSequence[] newitems = {"Copy Message", "Open", "Invite to a channel...", "Ignore", "Op", "Kick...", "Ban..."};
items = newitems;
if(selected_user.mode.contains("o") || selected_user.mode.contains("O"))
items[4] = "Deop";
} else if(selected_user != null) {
CharSequence[] newitems = {"Open", "Invite to a channel...", "Ignore", "Op", "Kick...", "Ban..."};
items = newitems;
if(selected_user.mode.contains("o") || selected_user.mode.contains("O"))
items[3] = "Deop";
} else if(message != null) {
CharSequence[] newitems = {"Copy Message"};
items = newitems;
} else {
return;
}
if(selected_user != null)
builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")");
else
builder.setTitle("Message");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
LayoutInflater inflater = getLayoutInflater();
ServersDataSource s = ServersDataSource.getInstance();
ServersDataSource.Server server = s.getServer(cid);
View view;
final TextView prompt;
final EditText input;
AlertDialog dialog;
if(text_to_copy == null)
item++;
switch(item) {
case 0:
if(Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text_to_copy);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("IRCCloud Message",text_to_copy);
clipboard.setPrimaryClip(clip);
}
break;
case 1:
BuffersDataSource b = BuffersDataSource.getInstance();
BuffersDataSource.Buffer buffer = b.getBufferByName(cid, selected_user.nick);
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) {
if(buffer != null) {
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
} else {
onBufferSelected(cid, -1, selected_user.nick, 0, 0, "conversation", 1, 0, status);
}
} else {
Intent i = new Intent(MessageActivity.this, MessageActivity.class);
if(buffer != null) {
i.putExtra("cid", buffer.cid);
i.putExtra("bid", buffer.bid);
i.putExtra("name", buffer.name);
i.putExtra("last_seen_eid", buffer.last_seen_eid);
i.putExtra("min_eid", buffer.min_eid);
i.putExtra("type", buffer.type);
i.putExtra("joined", 1);
i.putExtra("archived", buffer.archived);
i.putExtra("status", status);
} else {
i.putExtra("cid", cid);
i.putExtra("bid", -1);
i.putExtra("name", selected_user.nick);
i.putExtra("last_seen_eid", 0L);
i.putExtra("min_eid", 0L);
i.putExtra("type", "conversation");
i.putExtra("joined", 1);
i.putExtra("archived", 0);
i.putExtra("status", status);
}
startActivity(i);
}
break;
case 2:
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Invite " + selected_user.nick + " to a channel");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.invite(cid, input.getText().toString(), selected_user.nick);
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
break;
case 3:
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.ignore(cid, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
break;
case 4:
if(selected_user.mode.contains("o") || selected_user.mode.contains("O"))
conn.mode(cid, name, "-o " + selected_user.nick);
else
conn.mode(cid, name, "+o " + selected_user.nick);
break;
case 5:
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Give a reason for kicking");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.kick(cid, name, selected_user.nick, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
break;
case 6:
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Add a banmask for " + selected_user.nick);
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.mode(cid, name, "+b " + input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
break;
}
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
}
@Override
public void onBufferSelected(int cid, int bid, String name,
long last_seen_eid, long min_eid, String type, int joined,
int archived, String status) {
if(scrollView != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
}
if(bid != this.bid) {
this.cid = cid;
this.bid = bid;
this.name = name;
this.type = type;
this.joined = joined;
this.archived = archived;
this.status = status;
title.setText(name);
getSupportActionBar().setTitle(name);
if(archived > 0 && !type.equalsIgnoreCase("console")) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
} else {
if(type.equalsIgnoreCase("conversation")) {
UsersDataSource.User user = UsersDataSource.getInstance().getUser(cid, name);
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(user != null && user.away > 0) {
subtitle.setVisibility(View.VISIBLE);
if(user.away_msg != null && user.away_msg.length() > 0) {
subtitle.setText("Away: " + user.away_msg);
} else if(b != null && b.away_msg != null && b.away_msg.length() > 0) {
subtitle.setText("Away: " + b.away_msg);
} else {
subtitle.setText("Away");
}
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null && c.topic_text.length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(c.topic_text);
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("console")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid);
if(s != null) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(s.hostname + ":" + s.port);
} else {
subtitle.setVisibility(View.GONE);
}
} else {
subtitle.setText("");
subtitle.setVisibility(View.GONE);
}
}
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
BuffersListFragment blf = (BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList);
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
if(blf != null)
blf.setSelectedBid(bid);
if(mvf != null)
mvf.setArguments(b);
if(ulf != null)
ulf.setArguments(b);
AlphaAnimation anim = new AlphaAnimation(1, 0);
anim.setDuration(100);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = true;
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
}
}
public void showUpButton(boolean show) {
if(upView != null) {
if(show) {
upView.setVisibility(View.VISIBLE);
} else {
upView.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onMessageViewReady() {
if(shouldFadeIn) {
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
AlphaAnimation anim = new AlphaAnimation(0, 1);
anim.setDuration(100);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = false;
}
}
}
|
/*
* EDIT: 02/09/2004 - Renamed original WidgetViewport to WidgetViewRectangle.
* GOP
*/
package com.jme.renderer.lwjgl;
import java.io.File;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.Window;
import org.lwjgl.opengl.glu.GLU;
import com.jme.bounding.BoundingVolume;
import com.jme.curve.Curve;
import com.jme.effects.Tint;
import com.jme.input.Mouse;
import com.jme.math.Quaternion;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.RenderQueue;
import com.jme.renderer.Renderer;
import com.jme.scene.Clone;
import com.jme.scene.CloneNode;
import com.jme.scene.Geometry;
import com.jme.scene.Line;
import com.jme.scene.Point;
import com.jme.scene.Spatial;
import com.jme.scene.Text;
import com.jme.scene.TriMesh;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.AttributeState;
import com.jme.scene.state.CullState;
import com.jme.scene.state.DitherState;
import com.jme.scene.state.FogState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.ShadeState;
import com.jme.scene.state.StencilState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.VertexProgramState;
import com.jme.scene.state.WireframeState;
import com.jme.scene.state.ZBufferState;
import com.jme.scene.state.lwjgl.LWJGLAlphaState;
import com.jme.scene.state.lwjgl.LWJGLAttributeState;
import com.jme.scene.state.lwjgl.LWJGLCullState;
import com.jme.scene.state.lwjgl.LWJGLDitherState;
import com.jme.scene.state.lwjgl.LWJGLFogState;
import com.jme.scene.state.lwjgl.LWJGLLightState;
import com.jme.scene.state.lwjgl.LWJGLMaterialState;
import com.jme.scene.state.lwjgl.LWJGLShadeState;
import com.jme.scene.state.lwjgl.LWJGLStencilState;
import com.jme.scene.state.lwjgl.LWJGLTextureState;
import com.jme.scene.state.lwjgl.LWJGLVertexProgramState;
import com.jme.scene.state.lwjgl.LWJGLWireframeState;
import com.jme.scene.state.lwjgl.LWJGLZBufferState;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
import com.jme.widget.WidgetRenderer;
/**
* <code>LWJGLRenderer</code> provides an implementation of the
* <code>Renderer</code> interface using the LWJGL API.
*
* @see com.jme.renderer.Renderer
* @author Mark Powell
* @author Joshua Slack - Optimizations
* @version $Id: LWJGLRenderer.java,v 1.26 2004-06-29 23:20:57 renanse Exp $
*/
public class LWJGLRenderer implements Renderer {
//clear color
private ColorRGBA backgroundColor;
//width and height of renderer
private int width;
private int height;
private FloatBuffer worldBuffer;
private Vector3f vRot = new Vector3f();
private LWJGLCamera camera;
private LWJGLFont font;
private float[] modelToWorld = new float[16];
private long numberOfVerts;
private long numberOfTris;
private boolean statisticsOn;
private boolean usingVBO = false;
private LWJGLWireframeState boundsWireState = new LWJGLWireframeState();
private LWJGLTextureState boundsTextState = new LWJGLTextureState();
private LWJGLZBufferState boundsZState = new LWJGLZBufferState();
private boolean inOrthoMode;
private boolean processingQueue;
private RenderQueue queue;
/**
* Constructor instantiates a new <code>LWJGLRenderer</code> object. The
* size of the rendering window is passed during construction.
*
* @param width
* the width of the rendering context.
* @param height
* the height of the rendering context.
*/
public LWJGLRenderer(int width, int height) {
if (width <= 0 || height <= 0) {
LoggingSystem.getLogger().log(Level.WARNING,
"Invalid width " + "and/or height values.");
throw new JmeException("Invalid width and/or height values.");
}
this.width = width;
this.height = height;
worldBuffer = BufferUtils.createFloatBuffer(16); //ByteBuffer.allocateDirect(64).order(ByteOrder.nativeOrder()).asFloatBuffer();
LoggingSystem.getLogger().log(Level.INFO,
"LWJGLRenderer created. W: " + width + "H: " +
height);
queue = new RenderQueue(this);
}
/**
* <code>setCamera</code> sets the camera this renderer is using. It
* asserts that the camera is of type <code>LWJGLCamera</code>.
*
* @see com.jme.renderer.Renderer#setCamera(com.jme.renderer.Camera)
*/
public void setCamera(Camera camera) {
if (camera instanceof LWJGLCamera) {
this.camera = (LWJGLCamera) camera;
}
}
/**
* <code>getCamera</code> returns the camera used by this renderer.
*
* @see com.jme.renderer.Renderer#getCamera()
*/
public Camera getCamera() {
return camera;
}
/**
* <code>getCamera</code> returns a default camera for use with the LWJGL
* renderer.
*
* @param width
* the width of the frame.
* @param height
* the height of the frame.
* @return a default LWJGL camera.
*/
public Camera getCamera(int width, int height) {
return new LWJGLCamera(width, height, this);
}
/**
* <code>getAlphaState</code> returns a new LWJGLAlphaState object as a
* regular AlphaState.
*
* @return an AlphaState object.
*/
public AlphaState getAlphaState() {
return new LWJGLAlphaState();
}
/**
* <code>getAttributeState</code> returns a new LWJGLAttributeState object
* as a regular AttributeState.
*
* @return an AttributeState object.
*/
public AttributeState getAttributeState() {
return new LWJGLAttributeState();
}
/**
* <code>getCullState</code> returns a new LWJGLCullState object as a
* regular CullState.
*
* @return a CullState object.
* @see com.jme.renderer.Renderer#getCullState()
*/
public CullState getCullState() {
return new LWJGLCullState();
}
/**
* <code>getDitherState</code> returns a new LWJGLDitherState object as a
* regular DitherState.
*
* @return an DitherState object.
*/
public DitherState getDitherState() {
return new LWJGLDitherState();
}
/**
* <code>getFogState</code> returns a new LWJGLFogState object as a
* regular FogState.
*
* @return an FogState object.
*/
public FogState getFogState() {
return new LWJGLFogState();
}
/**
* <code>getLightState</code> returns a new LWJGLLightState object as a
* regular LightState.
*
* @return an LightState object.
*/
public LightState getLightState() {
return new LWJGLLightState();
}
/**
* <code>getMaterialState</code> returns a new LWJGLMaterialState object
* as a regular MaterialState.
*
* @return an MaterialState object.
*/
public MaterialState getMaterialState() {
return new LWJGLMaterialState();
}
/**
* <code>getShadeState</code> returns a new LWJGLShadeState object as a
* regular ShadeState.
*
* @return an ShadeState object.
*/
public ShadeState getShadeState() {
return new LWJGLShadeState();
}
/**
* <code>getTextureState</code> returns a new LWJGLTextureState object as
* a regular TextureState.
*
* @return an TextureState object.
*/
public TextureState getTextureState() {
return new LWJGLTextureState();
}
/**
* <code>getWireframeState</code> returns a new LWJGLWireframeState object
* as a regular WireframeState.
*
* @return an WireframeState object.
*/
public WireframeState getWireframeState() {
return new LWJGLWireframeState();
}
/**
* <code>getZBufferState</code> returns a new LWJGLZBufferState object as
* a regular ZBufferState.
*
* @return a ZBufferState object.
*/
public ZBufferState getZBufferState() {
return new LWJGLZBufferState();
}
/**
* <code>getVertexProgramState</code> returns a new
* LWJGLVertexProgramState object as a regular VertexProgramState.
*
* @return a VertexProgramState object.
*/
public VertexProgramState getVertexProgramState() {
return new LWJGLVertexProgramState();
}
/**
* <code>getStencilState</code> returns a new LWJGLStencilState object as
* a regular StencilState.
*
* @return a StencilState object.
*/
public StencilState getStencilState() {
return new LWJGLStencilState();
}
/**
* <code>setBackgroundColor</code> sets the OpenGL clear color to the
* color specified.
*
* @see com.jme.renderer.Renderer#setBackgroundColor(com.jme.renderer.ColorRGBA)
* @param c
* the color to set the background color to.
*/
public void setBackgroundColor(ColorRGBA c) {
//if color is null set background to white.
if (c == null) {
backgroundColor.a = 1.0f;
backgroundColor.b = 1.0f;
backgroundColor.g = 1.0f;
backgroundColor.r = 1.0f;
} else {
backgroundColor = c;
}
GL11.glClearColor(backgroundColor.r, backgroundColor.g,
backgroundColor.b, backgroundColor.a);
}
/**
* <code>getBackgroundColor</code> retrieves the clear color of the
* current OpenGL context.
*
* @see com.jme.renderer.Renderer#getBackgroundColor()
* @return the current clear color.
*/
public ColorRGBA getBackgroundColor() {
return backgroundColor;
}
/**
* <code>clearZBuffer</code> clears the OpenGL depth buffer.
*
* @see com.jme.renderer.Renderer#clearZBuffer()
*/
public void clearZBuffer() {
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, width, height);
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glEnable(GL11.GL_DITHER);
}
/**
* <code>clearBackBuffer</code> clears the OpenGL color buffer.
*
* @see com.jme.renderer.Renderer#clearBackBuffer()
*/
public void clearBackBuffer() {
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, width, height);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glEnable(GL11.GL_DITHER);
}
/**
* <code>clearBuffers</code> clears both the color and the depth buffer.
*
* @see com.jme.renderer.Renderer#clearBuffers()
*/
public void clearBuffers() {
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, width, height);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glEnable(GL11.GL_DITHER);
}
/**
* <code>displayBackBuffer</code> renders any queued items then
* flips the rendered buffer (back) with the currently displayed buffer.
*
* @see com.jme.renderer.Renderer#displayBackBuffer()
*/
public void displayBackBuffer() {
// render queue if needed
processingQueue = true;
queue.renderBuckets();
processingQueue = false;
GL11.glFlush();
Window.update();
}
public void setOrtho() {
if (inOrthoMode) {throw new JmeException(
"Already in Orthographic mode.");
}
//set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(0, Window.getWidth(), 0, Window.getHeight());
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
public void setOrthoCenter() {
if (inOrthoMode) {throw new JmeException(
"Already in Orthographic mode.");
}
//set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D( -Window.getWidth() / 2, Window.getWidth() / 2, -Window
.getHeight() / 2, Window.getHeight() / 2);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
public void unsetOrtho() {
if (!inOrthoMode) {throw new JmeException("Not in Orthographic mode.");
}
//remove ortho mode, and go back to original
// state
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
inOrthoMode = false;
}
/**
* <code>takeScreenShot</code> saves the current buffer to a file. The
* file name is provided, and .png will be appended. True is returned if the
* capture was successful, false otherwise.
*
* @param filename
* the name of the file to save.
* @return true if successful, false otherwise.
*/
public boolean takeScreenShot(String filename) {
if (null == filename) {throw new JmeException(
"Screenshot filename cannot be null");
}
LoggingSystem.getLogger().log(Level.INFO,
"Taking screenshot: " + filename + ".png");
//Create a pointer to the image info and create a buffered image to
//hold it.
IntBuffer buff = BufferUtils.createIntBuffer(width * height); //ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.nativeOrder()).asIntBuffer();
GL11.glReadPixels(0, 0, width, height, GL12.GL_BGRA,
GL11.GL_UNSIGNED_BYTE, buff);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
//Grab each pixel information and set it to the BufferedImage info.
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
img.setRGB(x, y, buff.get( (height - y - 1) * width + x));
}
}
//write out the screenshot image to a file.
try {
File out = new File(filename + ".png");
return ImageIO.write(img, "png", out);
}
catch (IOException e) {
LoggingSystem.getLogger().log(Level.WARNING,
"Could not create file: " + filename +
".png");
return false;
}
}
/**
* <code>draw</code> renders a tint to the back buffer
*
* @param t
* is the tint to render.
*/
public void draw(Tint t) {
// set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(0, Window.getWidth(), 0, Window.getHeight());
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
// set the color of the tint
GL11.glColor4f(t.getTintColor().r, t.getTintColor().g,
t.getTintColor().b, t.getTintColor().a);
// drawQuad
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glVertex2f(0, 0);
GL11.glVertex2f(0, Window.getHeight());
GL11.glVertex2f(Window.getWidth(), Window.getHeight());
GL11.glVertex2f(Window.getWidth(), 0);
}
GL11.glEnd();
// remove ortho mode, and go back to original
// state
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* <code>draw</code> draws a point object where a point contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Point)
* @param p
* the point object to render.
*/
public void draw(Point p) {
// set world matrix
Quaternion rotation = p.getWorldRotation();
Vector3f translation = p.getWorldTranslation();
Vector3f scale = p.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_POINTS);
// draw points
Vector3f[] vertex = p.getVertices();
Vector3f[] normal = p.getNormals();
ColorRGBA[] color = p.getColors();
Vector2f[] texture = p.getTextures();
if (statisticsOn) {
numberOfVerts += vertex.length;
}
if (normal != null) {
if (color != null) {
if (texture != null) {
// N,C,T
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
} else {
if (color != null) {
if (texture != null) {
for (int i = 0; i < vertex.length; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length; i++) {
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
// none
for (int i = 0; i < vertex.length; i++) {
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
}
GL11.glEnd();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* <code>draw</code> draws a line object where a line contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Line)
* @param l
* the line object to render.
*/
public void draw(Line l) {
// set world matrix
Quaternion rotation = l.getWorldRotation();
Vector3f translation = l.getWorldTranslation();
Vector3f scale = l.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_LINES);
// draw line
Vector3f[] vertex = l.getVertices();
Vector3f[] normal = l.getNormals();
ColorRGBA[] color = l.getColors();
Vector2f[] texture = l.getTextures();
if (statisticsOn) {
numberOfVerts += vertex.length;
}
if (normal != null) {
if (color != null) {
if (texture != null) {
// N,C,T
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
} else {
if (color != null) {
if (texture != null) {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
// none
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
}
GL11.glEnd();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* <code>draw</code> renders a curve object.
*
* @param c
* the curve object to render.
*/
public void draw(Curve c) {
// set world matrix
Quaternion rotation = c.getWorldRotation();
Vector3f translation = c.getWorldTranslation();
Vector3f scale = c.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_LINE_STRIP);
ColorRGBA[] color = c.getColors();
float colorInterval = 0;
float colorModifier = 0;
int colorCounter = 0;
if (null != color) {
GL11.glColor4f(color[0].r, color[0].g, color[0].b, color[0].a);
colorInterval = 1f / c.getColors().length;
colorModifier = colorInterval;
colorCounter = 0;
}
Vector3f point;
float limit = (1 + (1.0f / c.getSteps()));
for (float t = 0; t <= limit; t += 1.0f / c.getSteps()) {
if (t >= colorInterval && color != null) {
colorInterval += colorModifier;
GL11.glColor4f(c.getColors()[colorCounter].r,
c.getColors()[colorCounter].g,
c.getColors()[colorCounter].b,
c.getColors()[colorCounter].a);
colorCounter++;
}
point = c.getPoint(t);
GL11.glVertex3f(point.x, point.y, point.z);
}
if (statisticsOn) {
numberOfVerts += limit;
}
GL11.glEnd();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param t
* the mesh to render.
*/
public void draw(TriMesh t) {
// set world matrix
Quaternion rotation = t.getWorldRotation();
Vector3f translation = t.getWorldTranslation();
Vector3f scale = t.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
prepVBO(t);
// render the object
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
if (t.isVBOVertexEnabled() && GLContext.OpenGL15) {
usingVBO = true;
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t.getVBOVertexID());
GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL11.glVertexPointer(3, 0, t.getVerticeAsFloatBuffer());
}
FloatBuffer normals = t.getNormalAsFloatBuffer();
if (normals != null || t.getVBONormalID() > 0) {
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
if (t.isVBONormalEnabled() && GLContext.OpenGL15) {
usingVBO = true;
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t.getVBONormalID());
GL11.glNormalPointer(GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL11.glNormalPointer(0, normals);
}
} else {
GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY);
}
FloatBuffer colors = t.getColorAsFloatBuffer();
if (colors != null || t.getVBOColorID() > 0) {
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
if (t.isVBOColorEnabled() && GLContext.OpenGL15) {
usingVBO = true;
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t.getVBOColorID());
GL11.glColorPointer(4, GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL11.glColorPointer(4, 0, colors);
}
} else {
GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
}
for (int i = 0; i < t.getNumberOfUnits(); i++) {
FloatBuffer textures = t.getTextureAsFloatBuffer(i);
if (textures != null) {
if (GLContext.GL_ARB_multitexture && GLContext.OpenGL13) {
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
}
if (textures != null || t.getVBOTextureID(i) > 0) {
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
if (t.isVBOTextureEnabled() && GLContext.OpenGL15) {
usingVBO = true;
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER,
t.getVBOTextureID(i));
GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL11.glTexCoordPointer(2, 0, textures);
}
} else {
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
}
}
IntBuffer indices = t.getIndexAsBuffer();
if (statisticsOn) {
int adder = t.getIndexAsBuffer().capacity();
int vertAdder = t.getIndexAsBuffer().capacity();
numberOfTris += adder / 3;
numberOfVerts += vertAdder;
}
GL12.glDrawRangeElements(GL11.GL_TRIANGLES, 0, t.getVertQuantity(), indices);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
IntBuffer buf = BufferUtils.createIntBuffer(16);
public void prepVBO(Geometry g) {
if (!GLContext.OpenGL15)return;
int verts = g.getVertQuantity();
if (verts < 0) verts = g.getVertices().length;
if (g.isVBOVertexEnabled() && g.getVBOVertexID() <= 0) {
GL15.glGenBuffers(buf);
g.setVBOVertexID(buf.get(0));
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, g.getVBOVertexID());
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 3 * 4,
(FloatBuffer)null,
GL15.GL_STATIC_DRAW);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 3 * 4,
g.getVerticeAsFloatBuffer(),
GL15.GL_STATIC_DRAW);
buf.clear();
}
if (g.isVBONormalEnabled() && g.getVBONormalID() <= 0) {
GL15.glGenBuffers(buf);
g.setVBONormalID(buf.get(0));
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, g.getVBONormalID());
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 3 * 4,
(FloatBuffer)null,
GL15.GL_STATIC_DRAW);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 3 * 4,
g.getNormalAsFloatBuffer(),
GL15.GL_STATIC_DRAW);
buf.clear();
}
if (g.isVBOColorEnabled() && g.getVBOColorID() <= 0) {
GL15.glGenBuffers(buf);
g.setVBOColorID(buf.get(0));
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, g.getVBOColorID());
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 4 * 4,
(FloatBuffer)null,
GL15.GL_STATIC_DRAW);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verts * 4 * 4,
g.getColorAsFloatBuffer(),
GL15.GL_STATIC_DRAW);
buf.clear();
}
if (g.isVBOTextureEnabled()) {
for (int i = 0; i < g.getNumberOfUnits(); i++) {
if (g.getVBOTextureID(i) <= 0) {
GL15.glGenBuffers(buf);
g.setVBOTextureID(i, buf.get(0));
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER,
g.getVBOTextureID(i));
GL15.glBufferData(GL15.GL_ARRAY_BUFFER,
verts * 2 * 4,
(FloatBuffer)null,
GL15.GL_STATIC_DRAW);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER,
verts * 2 * 4,
g.getTextureAsFloatBuffer(i),
GL15.GL_STATIC_DRAW);
buf.clear();
}
}
}
buf.clear();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param t
* the mesh to render.
*/
public void drawBounds(Geometry g) {
// get the bounds
if (! (g.getWorldBound() instanceof TriMesh))return;
drawBounds(g.getWorldBound());
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param t
* the mesh to render.
*/
public void drawBounds(BoundingVolume bv) {
// get the bounds
if (! (bv instanceof TriMesh))return;
bv.recomputeMesh();
setBoundsStates(true);
draw( (TriMesh) bv);
setBoundsStates(false);
}
/**
* <code>draw</code> draws a clone node object. The data for the geometry
* defined in the clone node is set but not rendered. The rendering occurs
* by the clone node's children (Clones).
*
* @param cn
* the clone node to render.
* @see com.jme.renderer.Renderer#draw(com.jme.scene.CloneNode)
*/
public void draw(CloneNode cn) {
TriMesh t = cn.getGeometry();
// render the object
GL11.glVertexPointer(3, 0, t.getVerticeAsFloatBuffer());
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
FloatBuffer normals = t.getNormalAsFloatBuffer();
if (normals != null) {
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
GL11.glNormalPointer(0, normals);
} else {
GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY);
}
FloatBuffer colors = t.getColorAsFloatBuffer();
if (colors != null) {
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
GL11.glColorPointer(4, 0, colors);
} else {
GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
}
FloatBuffer textures = t.getTextureAsFloatBuffer();
if (textures != null) {
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
GL11.glTexCoordPointer(2, 0, textures);
} else {
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
}
/**
* <code>draw</code> renders a clone object. The depends on the data for
* geometry previously being set by a clone node. The world transformations
* are then made and the geometry is rendered.
*
* @param c
* the clone object.
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Clone)
*/
public void draw(Clone c) {
//set world matrix
Quaternion rotation = c.getWorldRotation();
Vector3f translation = c.getWorldTranslation();
Vector3f scale = c.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
IntBuffer indices = c.getIndexBuffer();
if (statisticsOn) {
int adder = indices.capacity();
numberOfTris += adder / 3;
}
GL11.glDrawElements(GL11.GL_TRIANGLES, indices);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* <code>draw</code> renders a scene by calling the nodes
* <code>onDraw</code> method.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial)
*/
public void draw(Spatial s) {
if (s != null) {
s.onDraw(this);
}
}
/**
* <code>drawBounds</code> renders a scene by calling the nodes
* <code>onDraw</code> method.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial)
*/
public void drawBounds(Spatial s) {
if (s != null) {
s.onDrawBounds(this);
}
}
/**
* <code>drawBounds</code> renders the bounds of a scene by calling the
* nodes <code>onDrawBounds</code> method.
*
* @see com.jme.renderer.Renderer#drawBounds(com.jme.scene.Spatial)
*/
public void drawBounds(Clone c) {
drawBounds(c.getWorldBound());
}
/**
* <code>draw</code> renders a text object using a predefined font.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Text)
*/
public void draw(Text t) {
if (font == null) {
font = new LWJGLFont();
}
font.print( (int) t.getLocalTranslation().x, (int) t
.getLocalTranslation().y, t.getLocalScale(), t.getText(), 0);
}
/**
* <code>draw</code> renders a mouse object using a defined mouse texture.
*
* @see com.jme.renderer.Renderer#draw(com.jme.input.Mouse)
*/
public void draw(Mouse m) {
if (!m.hasCursor()) {return;
}
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GL11.glOrtho(0, Window.getWidth(), 0, Window.getHeight(), -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GL11.glTranslatef(m.getLocalTranslation().x, m.getLocalTranslation().y,
0);
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
//render the cursor
int width = m.getImageWidth();
int height = m.getImageHeight();
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(width, 0);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(width, height);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(0, height);
GL11.glEnd();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
}
/**
* <code>draw</code> renders a WidgetRenderer object to the back buffer.
*
* @see com.jme.renderer.Renderer#draw(WidgetRenderer)
*/
public void draw(WidgetRenderer wr) {
wr.render();
}
/**
* <code>enableStatistics</code> will turn on statistics gathering.
*
* @param value
* true to use statistics, false otherwise.
*/
public void enableStatistics(boolean value) {
statisticsOn = value;
}
/**
* <code>clearStatistics</code> resets the vertices and triangles counter
* for the statistics information.
*/
public void clearStatistics() {
numberOfVerts = 0;
numberOfTris = 0;
}
/**
* <code>getStatistics</code> returns a string value of the rendering
* statistics information (number of triangles and number of vertices).
*
* @return the string representation of the current statistics.
*/
public String getStatistics() {
return "Number of Triangles: " + numberOfTris
+ " : Number of Vertices: " + numberOfVerts;
}
/**
*
* <code>setBoundsStates</code> sets the rendering states for bounding
* volumes, this includes wireframe and zbuffer.
*
* @param enabled
* true if these states are to be enabled, false otherwise.
*/
private void setBoundsStates(boolean enabled) {
boundsTextState.apply(); // not enabled -- no texture
boundsWireState.setEnabled(enabled);
boundsWireState.apply();
boundsZState.setEnabled(enabled);
boundsZState.apply();
}
public boolean checkAndAdd(Spatial s) {
int rqMode = s.getRenderQueueMode();
if (rqMode != Renderer.QUEUE_SKIP) {
getQueue().addToQueue(s, rqMode);
return true;
}
return false;
}
public RenderQueue getQueue() {
return queue;
}
public boolean isProcessingQueue() {
return processingQueue;
}
public boolean supportsVBO() {
return GLContext.OpenGL15;
}
}
|
package com.novell.spsample.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.Widget;
import com.novell.spiffyui.client.MessageUtil;
import com.novell.spiffyui.client.widgets.FormFeedback;
import com.novell.spiffyui.client.widgets.button.FancyButton;
import com.novell.spiffyui.client.widgets.button.FancySaveButton;
/**
* This is the form sample panel
*
*/
public class FormPanel extends HTMLPanel implements KeyUpHandler
{
private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);
private static final String CONTENTS =
"<fieldset id=\"Page2Fields\">" +
"<h2 class=\"sectionTitle\">Sample user form fieldset</h2>" +
"<ol class=\"dialogformsection\">" +
"<li id=\"firstNameRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"firstNameTxt\">First name: " +
"</label><div id=\"firstName\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"lastNameRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"lastNameTxt\">Last name: " +
"</label><div id=\"lastName\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"emailRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"emailTxt\">Email address: " +
"</label><div id=\"email\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"userDescRow\" class=\"extratallformrow\"><label class=\"dialogformlabel\" for=\"userDescTxt\">Short description: " +
"</label><div id=\"userDesc\" class=\"formcontrolssection\"></div></li>" +
"<h3 class=\"subSectionTitle\">Passwords</h3>" +
"<li id=\"passwordRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"passwordTxt\">Password: " +
"</label><div id=\"password\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"passwordRepeatRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"passwordRepeatTxt\">Repeat password: " +
"</label><div id=\"passwordRepeat\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"securityQuestionRow\" class=\"extratallformrow\"><label class=\"dialogformlabel\" for=\"securityQuestionTxt\">Security question: " +
"</label><div id=\"securityQuestion\" class=\"formcontrolssection\"></div>" +
"</li>" +
"<li id=\"securityAnswerRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"securityAnswerTxt\">Security Answer: " +
"</label><div id=\"securityAnswer\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"page2ButtonsRow\" class=\"dialogformrow\"><div id=\"page2Buttons\" class=\"formcontrolssection formbuttons\"></div></li>" +
"</ol>" +
"</fieldset>";
private TextBox m_firstName;
private FormFeedback m_firstNameFeedback;
private TextBox m_lastName;
private FormFeedback m_lastNameFeedback;
private TextBox m_email;
private FormFeedback m_emailFeedback;
private TextBox m_password;
private FormFeedback m_passwordFeedback;
private TextBox m_passwordRepeat;
private FormFeedback m_passwordRepeatFeedback;
private TextArea m_userDesc;
private FormFeedback m_userDescFeedback;
private TextArea m_securityQuestion;
private FormFeedback m_securityQuestionFeedback;
private TextBox m_securityAnswer;
private FormFeedback m_securityAnswerFeedback;
private FancyButton m_save;
/**
* Creates a new import panel
*/
public FormPanel()
{
super("div", "<h1>Spiffy Forms</h1>" + STRINGS.FormPanel_html() + CONTENTS);
getElement().setId("formPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
/*
First name
*/
m_firstName = new TextBox();
m_firstName.addKeyUpHandler(this);
m_firstName.getElement().setId("firstNameTxt");
m_firstName.getElement().addClassName("wideTextField");
add(m_firstName, "firstName");
m_firstNameFeedback = new FormFeedback();
add(m_firstNameFeedback, "firstNameRow");
/*
Last name
*/
m_lastName = new TextBox();
m_lastName.addKeyUpHandler(this);
m_lastName.getElement().setId("lastNameTxt");
m_lastName.getElement().addClassName("wideTextField");
add(m_lastName, "lastName");
m_lastNameFeedback = new FormFeedback();
add(m_lastNameFeedback, "lastNameRow");
/*
email
*/
m_email = new TextBox();
m_email.addKeyUpHandler(this);
m_email.getElement().setId("emailTxt");
m_email.getElement().addClassName("wideTextField");
add(m_email, "email");
m_emailFeedback = new FormFeedback();
add(m_emailFeedback, "emailRow");
/*
User description
*/
m_userDesc = new TextArea();
m_userDesc.addKeyUpHandler(this);
m_userDesc.getElement().setId("userDescTxt");
m_userDesc.getElement().addClassName("wideTextField");
add(m_userDesc, "userDesc");
m_userDescFeedback = new FormFeedback();
add(m_userDescFeedback, "userDescRow");
/*
Password
*/
m_password = new PasswordTextBox();
m_password.addKeyUpHandler(this);
m_password.getElement().setId("passwordTxt");
m_password.getElement().addClassName("slimTextField");
add(m_password, "password");
m_passwordFeedback = new FormFeedback();
add(m_passwordFeedback, "passwordRow");
/*
Password repeat
*/
m_passwordRepeat = new PasswordTextBox();
m_passwordRepeat.addKeyUpHandler(this);
m_passwordRepeat.getElement().setId("passwordRepeatTxt");
m_passwordRepeat.getElement().addClassName("slimTextField");
add(m_passwordRepeat, "passwordRepeat");
m_passwordRepeatFeedback = new FormFeedback();
add(m_passwordRepeatFeedback, "passwordRepeatRow");
/*
Security Question
*/
m_securityQuestion = new TextArea();
m_securityQuestion.addKeyUpHandler(this);
m_securityQuestion.getElement().setId("securityQuestionTxt");
m_securityQuestion.getElement().addClassName("wideTextField");
add(m_securityQuestion, "securityQuestion");
m_securityQuestionFeedback = new FormFeedback();
add(m_securityQuestionFeedback, "securityQuestionRow");
/*
Security answer
*/
m_securityAnswer = new TextBox();
m_securityAnswer.addKeyUpHandler(this);
m_securityAnswer.getElement().setId("securityAnswerTxt");
m_securityAnswer.getElement().addClassName("wideTextField");
add(m_securityAnswer, "securityAnswer");
m_securityAnswerFeedback = new FormFeedback();
add(m_securityAnswerFeedback, "securityAnswerRow");
/*
The big save button
*/
m_save = new FancySaveButton("Save");
m_save.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event)
{
save();
}
});
add(m_save, "page2Buttons");
updateFormStatus(null);
}
@Override
public void onKeyUp(KeyUpEvent event)
{
if (event.getNativeKeyCode() != KeyCodes.KEY_TAB) {
updateFormStatus((Widget) event.getSource());
}
}
private void updateFormStatus(Widget w)
{
if (w == m_firstName) {
if (m_firstName.getText().length() > 2) {
m_firstNameFeedback.setStatus(FormFeedback.VALID);
} else {
m_firstNameFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_lastName) {
if (m_lastName.getText().length() > 2) {
m_lastNameFeedback.setStatus(FormFeedback.VALID);
} else {
m_lastNameFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_email) {
if (m_email.getText().length() > 2) {
m_emailFeedback.setStatus(FormFeedback.VALID);
} else {
m_emailFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_password) {
if (m_password.getText().length() > 2) {
m_passwordFeedback.setStatus(FormFeedback.VALID);
} else {
m_passwordFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_securityQuestion) {
if (m_securityQuestion.getText().length() > 2) {
m_securityQuestionFeedback.setStatus(FormFeedback.VALID);
} else {
m_securityQuestionFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_securityAnswer) {
if (m_securityAnswer.getText().length() > 4) {
m_securityAnswerFeedback.setStatus(FormFeedback.VALID);
} else {
m_securityAnswerFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_passwordRepeat) {
if (m_passwordRepeat.getText().length() > 2) {
if (m_passwordRepeat.getText().equals(m_password.getText())) {
m_passwordRepeatFeedback.setStatus(FormFeedback.VALID);
m_passwordRepeatFeedback.setTitle("");
} else {
m_passwordRepeatFeedback.setStatus(FormFeedback.ERROR);
m_passwordRepeatFeedback.setTitle("Make sure your two passwords match.");
}
} else {
m_passwordRepeatFeedback.setStatus(FormFeedback.WARNING);
m_passwordRepeatFeedback.setTitle("");
}
} else if (w == m_userDesc) {
if (m_userDesc.getText().length() > 8) {
m_userDescFeedback.setStatus(FormFeedback.VALID);
} else {
m_userDescFeedback.setStatus(FormFeedback.WARNING);
}
}
m_save.setEnabled(m_firstName.getText().length() > 2 &&
m_lastName.getText().length() > 2 &&
m_email.getText().length() > 2 &&
m_password.getText().length() > 2 &&
m_passwordRepeat.getText().length() > 2 &&
m_passwordRepeat.getText().equals(m_password.getText()) &&
m_userDesc.getText().length() > 8 &&
m_securityQuestion.getText().length() > 8 &&
m_securityAnswer.getText().length() > 4);
}
private void save()
{
MessageUtil.showMessage("This form doesn't save anything.");
}
}
|
package com.opencms.workplace;
import com.opencms.core.*;
import com.opencms.file.*;
import com.opencms.template.*;
public abstract class A_CmsWpElement implements I_CmsLogChannels, I_CmsWpElement, I_CmsWpConstants {
/**
* Reference to to buttons definition file
*/
protected static CmsXmlWpButtonsDefFile m_buttondef = null;
/**
* Reference to icons definition file
*/
protected static CmsXmlWpTemplateFile m_icondef = null;
/**
* Reference to projectlist definition file
*/
protected static CmsXmlWpTemplateFile m_projectlistdef = null;
/**
* Reference to projectlist definition file
*/
protected static CmsXmlWpTemplateFile m_tasklistdef = null;
/**
* Reference to projectlist definition file
*/
protected static CmsXmlWpTemplateFile m_contextdef = null;
/**
* Reference to the label defintion file
*/
protected static CmsXmlWpLabelDefFile m_labeldef = null;
/**
* Reference to the input defintion file
*/
protected static CmsXmlWpInputDefFile m_inputdef = null;
/**
* Reference to the error defintion file
*/
protected static CmsXmlWpErrorDefFile m_errordef = null;
/**
* Reference to the radio button defintion file
*/
protected static CmsXmlWpRadioDefFile m_radiodef = null;
/**
* Reference to the box defintion file
*/
protected static CmsXmlWpBoxDefFile m_boxdef = null;
/**
* Path to all worplace definition files (will be read once
* from workplace.ini)
*/
protected static String m_workplaceElementPath = null;
/** Reference to the config file */
private static CmsXmlWpConfigFile m_configFile = null;
/**
* Gets a reference to the default config file.
* The path to this file ist stored in <code>C_WORKPLACE_INI</code>
*
* @param cms A_CmsObject Object for accessing system resources.
* @return Reference to the config file.
* @exception CmsException
*/
public CmsXmlWpConfigFile getConfigFile(A_CmsObject cms) throws CmsException {
//if(m_configFile == null) {
m_configFile = new CmsXmlWpConfigFile(cms);
return m_configFile;
}
/**
* Reads the buttons definition file.
* @param cms The actual cms object
* @return Reference to the buttons defintion file.
* @exception CmsException
*/
public CmsXmlWpButtonsDefFile getButtonDefinitions(A_CmsObject cms) throws CmsException {
//if(m_buttondef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_buttondef = new CmsXmlWpButtonsDefFile(cms, m_workplaceElementPath + C_BUTTONTEMPLATE);
return m_buttondef;
}
/**
* Reads the icons definition file.
* @param cms The actual cms object
* @return Reference to the icons defintion file.
* @exception CmsException
*/
public CmsXmlWpTemplateFile getIconDefinitions(A_CmsObject cms) throws CmsException {
//if(m_icondef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_icondef = new CmsXmlWpTemplateFile(cms, m_workplaceElementPath + C_ICON_TEMPLATEFILE);
return m_icondef;
}
/**
* Reads the projectlist definition file.
* @param cms The actual cms object
* @return Reference to the list defintion file.
* @exception CmsException
*/
public CmsXmlWpTemplateFile getProjectlistDefinitions(A_CmsObject cms) throws CmsException {
//if(m_projectlistdef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_projectlistdef = new CmsXmlWpTemplateFile(cms, m_workplaceElementPath + C_PROJECTLIST_TEMPLATEFILE);
return m_projectlistdef;
}
/**
* Reads the projectlist definition file.
* @param cms The actual cms object
* @return Reference to the list defintion file.
* @exception CmsException
*/
public CmsXmlWpTemplateFile getTaskListDefinitions(A_CmsObject cms) throws CmsException {
//if(m_tasklistdef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_tasklistdef = new CmsXmlWpTemplateFile(cms, m_workplaceElementPath + C_TASKLIST_TEMPLATEFILE);
return m_tasklistdef;
}
/**
* Reads the contextmenue definition file.
* @param cms The actual cms object
* @return Reference to the list defintion file.
* @exception CmsException
*/
public CmsXmlWpTemplateFile getContextmenueDefinitions(A_CmsObject cms) throws CmsException {
//if(m_contextdef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_contextdef = new CmsXmlWpTemplateFile(cms, m_workplaceElementPath + C_CONTEXTMENUE_TEMPLATEFILE);
return m_contextdef;
}
/**
* Reads the label definition file.
* @param cms The actual cms object
* @return Reference to the label defintion file.
* @exception CmsException
*/
public CmsXmlWpLabelDefFile getLabelDefinitions(A_CmsObject cms) throws CmsException {
//if(m_labeldef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_labeldef = new CmsXmlWpLabelDefFile(cms, m_workplaceElementPath + C_LABELTEMPLATE);
return m_labeldef;
}
/**
* Reads the input field definition file.
* @param cms The actual cms object
* @return Reference to the label defintion file.
* @exception CmsException
*/
public CmsXmlWpInputDefFile getInputDefinitions(A_CmsObject cms) throws CmsException {
//if(m_inputdef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_inputdef = new CmsXmlWpInputDefFile(cms, m_workplaceElementPath + C_INPUTTEMPLATE);
return m_inputdef;
}
/**
* Reads the error definition file.
* @param cms The actual cms object
* @return Reference to the label defintion file.
* @exception CmsException
*/
public CmsXmlWpErrorDefFile getErrorDefinitions(A_CmsObject cms) throws CmsException {
//if(m_errordef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_errordef = new CmsXmlWpErrorDefFile(cms, m_workplaceElementPath + C_ERRORTEMPLATE);
return m_errordef;
}
/**
* Reads the box definition file.
* @param cms The actual cms object
* @return Reference to the box defintion file.
* @exception CmsException
*/
public CmsXmlWpBoxDefFile getBoxDefinitions(A_CmsObject cms) throws CmsException {
//if(m_boxdef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_boxdef = new CmsXmlWpBoxDefFile(cms, m_workplaceElementPath + C_BOXTEMPLATE);
return m_boxdef;
}
/**
* Reads the radiobutton definition file.
* @param cms The actual cms object
* @return Reference to the radiobutton defintion file.
* @exception CmsException
*/
public CmsXmlWpRadioDefFile getRadioDefinitions(A_CmsObject cms) throws CmsException {
//if(m_radiodef == null) {
if(m_workplaceElementPath == null) {
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
m_workplaceElementPath = configFile.getWorkplaceElementPath();
}
m_radiodef = new CmsXmlWpRadioDefFile(cms, m_workplaceElementPath + C_RADIOTEMPLATE);
return m_radiodef;
}
/**
* Help method to print nice classnames in error messages
* @return class name in [ClassName] format
*/
protected String getClassName() {
String name = getClass().getName();
return "[" + name.substring(name.lastIndexOf(".") + 1) + "] ";
}
/**
* Help method that handles any occuring exception by writing
* an error message to the OpenCms logfile and throwing a
* CmsException of the type "unknown".
* @param errorMessage String with the error message to be printed.
* @exception CmsException
*/
protected void throwException(String errorMessage) throws CmsException {
throwException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION);
}
/**
* Help method that handles any occuring exception by writing
* an error message to the OpenCms logfile and throwing a
* CmsException of the given type.
* @param errorMessage String with the error message to be printed.
* @param type Type of the exception to be thrown.
* @exception CmsException
*/
protected void throwException(String errorMessage, int type) throws CmsException {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage);
} throw new CmsException(errorMessage, type);
}
}
|
package com.team254.lib.util.gyro;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.team254.lib.util.Util;
/**
* Thread which is responsible for reading the gyro
*/
public class GyroThread {
private static final int K_READING_RATE = 200;
private static final int K_ZEROING_SAMPLES = 6 * K_READING_RATE;
private static final int K_STARTUP_SAMPLES = 2 * K_READING_RATE;
// synchronized access object
private final Timer mTimer = new Timer("Gyro", true);
// owned by the background thread
private final GyroInterface mGyroInterface = new GyroInterface();
// thread communication variables
private volatile boolean mVolatileHasData = false;
private volatile double mVolatileAngle = 0;
private volatile double mVolatileRate = 0;
private volatile boolean mVolatileShouldReZero = true;
// owned by the accesser of this object
private double mZeroHeading = 0;
public void start() {
synchronized (mTimer) {
mTimer.schedule(new InitTask(), 0);
}
}
public boolean hasData() {
return mVolatileHasData;
}
public double getAngle() {
return mVolatileAngle - mZeroHeading;
}
public double getRate() {
return mVolatileRate;
}
public void rezero() {
mVolatileShouldReZero = true;
}
public void reset() {
mZeroHeading = mVolatileAngle;
}
/**
* Initializes the gyro, verifying the its self-test results
*/
private class InitTask extends TimerTask {
@Override
public void run() {
while (true) {
try {
mGyroInterface.initializeGyro();
break;
} catch (GyroInterface.GyroException e) {
System.out.println("Gyro failed to initialize: " + e.getMessage());
synchronized (mTimer) {
mTimer.schedule(new InitTask(), 500);
}
}
}
System.out.println("gyo initialized, part ID: 0x" + Integer.toHexString(mGyroInterface.readPartId()));
synchronized (mTimer) {
mTimer.scheduleAtFixedRate(new UpdateTask(), 0, (int) (1000.0 / K_READING_RATE));
}
}
}
/**
* Updates the actual gyro data (zeroing and accumulation)
*/
private class UpdateTask extends TimerTask {
private int mRemainingStartupCycles = K_STARTUP_SAMPLES;
private boolean mIsZerod = false;
private double[] mZeroRateSamples = new double[K_ZEROING_SAMPLES];
private int mZeroRateSampleIndex = 0;
private boolean mHasEnoughZeroingSamples;
private double mZeroBias;
private double mAngle = 0;
private double mLastAngle = 0;
private double mLastTime = 0;
@Override
public void run() {
int reading;
try {
reading = mGyroInterface.getReading();
} catch (GyroInterface.GyroException e) {
System.out.println("Gyro read failed: " + e.getMessage());
return;
}
GyroInterface.StatusFlag status = GyroInterface.extractStatus(reading);
List<GyroInterface.ErrorFlag> errors = GyroInterface.extractErrors(reading);
if (GyroInterface.StatusFlag.VALID_DATA != status || !errors.isEmpty()) {
System.out.println("Gyro read failed. Status: " + status + ". Errors: " + Util.joinStrings(", ", errors));
return;
}
if (mRemainingStartupCycles > 0) {
mRemainingStartupCycles
return;
}
if (mVolatileShouldReZero) {
mVolatileShouldReZero = false;
mVolatileHasData = false;
mIsZerod = false;
}
double unbiasedAngleRate = GyroInterface.extractAngleRate(reading);
mZeroRateSamples[mZeroRateSampleIndex] = unbiasedAngleRate;
mZeroRateSampleIndex++;
if (mZeroRateSampleIndex >= K_ZEROING_SAMPLES) {
mZeroRateSampleIndex = 0;
mHasEnoughZeroingSamples = true;
}
if (!mIsZerod) {
if (!mHasEnoughZeroingSamples) {
return;
}
mZeroBias = 0;
for (Double sample : mZeroRateSamples) {
mZeroBias += sample / K_ZEROING_SAMPLES;
}
mIsZerod = true;
return;
}
double now = edu.wpi.first.wpilibj.Timer.getFPGATimestamp();
double timeElapsed = mLastTime == 0 ? 1.0 / K_READING_RATE : now - mLastTime;
mLastTime = now;
mVolatileRate = unbiasedAngleRate - mZeroBias;
mAngle += mVolatileRate * timeElapsed;
mVolatileAngle = mAngle;
mVolatileHasData = true;
}
}
}
|
package com.winterwell.gson;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Type;
import com.winterwell.gson.stream.JsonReader;
import com.winterwell.gson.stream.JsonToken;
import com.winterwell.gson.stream.JsonWriter;
import com.winterwell.utils.MathUtils;
import com.winterwell.utils.Utils;
import com.winterwell.utils.time.Time;
import com.winterwell.utils.time.TimeUtils;
import com.winterwell.utils.web.IHasJson;
/**
* TODO move some of our adapters in here for our convenience
* @author daniel
* @testedby {@link StandardAdaptersTest}
*/
public class StandardAdapters {
public static final JsonSerializer IHASJSONADAPTER = new JsonSerializer<IHasJson>() {
@Override
public JsonElement serialize(IHasJson src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.toJson2());
}
};
/**
* Time <-> iso-string
* Warning: This loses the type info!
* It looks cleaner, but the inverse only works if the field is of type Time (and it is is slightly slower).
* Use-case: good for Elastic-Search
* Experimental: This can handle flexible time inputs, like "tomorrow".
* But ISO format yyyy-mm-dd is strongly recommended!
* @author daniel
*/
public static class TimeTypeAdapter implements JsonSerializer<Time>, JsonDeserializer<Time> {
@Override
public JsonElement serialize(Time src, Type srcType,
JsonSerializationContext context) {
return new JsonPrimitive(src.toISOString());
}
@Override
public Time deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonObject()) {
// a vanilla Gson will turn Time into {ut: }
JsonObject jobj = (JsonObject) json;
JsonPrimitive ut = jobj.getAsJsonPrimitive("ut");
long utv = ut.getAsLong();
return new Time(utv);
}
String s = json.getAsString();
if (Utils.isBlank(s)) {
return null;
}
Time t = TimeUtils.parseExperimental(s);
return t;
}
}
/**
* Treat any CharSequence class like a String
* Warning: This loses the type info!
* Use-case: good for special "type-safe" String-like classes, e.g. Dataspace
* Experimental: This can handle flexible time inputs, like "tomorrow".
* But ISO format yyyy-mm-dd is strongly recommended!
* @author daniel
*/
public static final class CharSequenceTypeAdapter implements JsonSerializer<CharSequence>, JsonDeserializer<CharSequence> {
private Class<? extends CharSequence> klass;
private Constructor<? extends CharSequence> scon;
public CharSequenceTypeAdapter(Class<? extends CharSequence> klass) {
this.klass = klass;
try {
scon = klass.getConstructor(String.class);
} catch (NoSuchMethodException e) {
try {
scon = klass.getConstructor(CharSequence.class);
} catch (NoSuchMethodException e1) {
throw Utils.runtime(e);
}
}
scon.setAccessible(true);
}
@Override
public CharSequence deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
String s = null;
try {
s = json.getAsString();
CharSequence ni = scon.newInstance(s);
return ni;
} catch(Exception ex) {
throw new JsonParseException(s, ex);
}
}
@Override
public JsonElement serialize(CharSequence src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
/**
* Can coerce floating points into Longs -- this allows for robustness against floating point issues.
* Can be registered for Long.class and/or long.class -- they are separate.
* @author daniel
*
*/
public static class LenientLongAdapter extends TypeAdapter<Long>{
private final Long nullValue;
public LenientLongAdapter() {
this(null);
}
/**
* @param nullValue 0 or null
*/
public LenientLongAdapter(Long nullValue) {
this.nullValue = nullValue;
assert nullValue == 0 || nullValue == null : nullValue;
}
@Override
public Long read(JsonReader reader) throws IOException {
if(reader.peek() == JsonToken.NULL){
reader.nextNull();
return nullValue;
}
String stringValue = reader.nextString();
try{
Long value = Long.valueOf(stringValue);
return value;
} catch(NumberFormatException e){
Double v = Double.valueOf(stringValue);
return (long) Math.round(v);
}
}
@Override
public void write(JsonWriter writer, Long value) throws IOException {
if (value == null) {
if (nullValue==null) {
writer.nullValue();
} else {
writer.value(nullValue);
}
return;
}
writer.value(value);
}
}
/**
* @deprecated Not sure why we have this!
* @author daniel
*/
public static class ClassTypeAdapter implements JsonSerializer<Class>,
JsonDeserializer<Class> {
@Override
public JsonElement serialize(Class src, Type srcType,
JsonSerializationContext context) {
return new JsonPrimitive(src.getCanonicalName());
}
@Override
public Class deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
try {
return Class.forName(json.getAsString());
} catch (ClassNotFoundException e) {
throw new JsonParseException(e);
}
}
}
}
|
package com.woniu.eaypay.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("WEB-INF/manage/index.jsp").forward(request, response);
}
}
|
// Parameter.java
package imagej.plugin;
import imagej.plugin.gui.WidgetStyle;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TODO
*
* @author Johannes Schindelin
* @author Grant Harris
* @author Curtis Rueden
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Parameter {
/** Defines if the parameter is an output. */
boolean output() default false;
/** Defines a label for the parameter. */
String label() default "";
/** Defines a description for the parameter. */
String description() default "";
/** Defines whether the parameter is required (i.e., no default). */
boolean required() default false;
/** Defines whether to remember the most recent value of the parameter. */
boolean persist() default true;
/** Defines a key to use for saving the value persistently. */
String persistKey() default "";
/** Defines the preferred widget style. */
WidgetStyle style() default imagej.plugin.gui.WidgetStyle.DEFAULT;
/** Defines the minimum allowed value (numeric parameters only). */
String min() default "";
/** Defines the maximum allowed value (numeric parameters only). */
String max() default "";
/** Defines the step size to use (numeric parameters only). */
String stepSize() default "";
/**
* Defines the width of the input field in characters
* (text field parameters only).
*/
int columns() default 6;
/** Defines the list of possible values (multiple choice text fields only). */
String[] choices() default {};
}
|
package com.blogspot.ludumdaresforfun;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
public class MainScreen extends BaseScreen {
public boolean pause = false;
public boolean toggle = false;
ConfigControllers configControllers;
Rectangle playerRect;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;
private Player player;
private ShapeRenderer shapeRenderer;
private TiledMap map;
private boolean normalGravity = true;
private boolean bossActive = false;
private Array<Enemy> enemies = new Array<Enemy>();
private Array<Rectangle> tiles = new Array<Rectangle>();
private Array<Rectangle> spikes = new Array<Rectangle>();
private Array<Shot> shotArray = new Array<Shot>();
private Array<Vector2> spawns = new Array<Vector2>();
private Array<Vector2> lifes = new Array<Vector2>();
private Boss boss;
private Pool<Rectangle> rectPool = new Pool<Rectangle>() {
@Override
protected Rectangle newObject () {
return new Rectangle();
}
};
private final float GRAVITY = -10f;
final int SCREEN_HEIGHT = 240;
final int SCREEN_WIDTH = 400;
final int MAP_HEIGHT;
final int MAP_WIDTH;
final int POS_UPPER_WORLD;
final int POS_LOWER_WORLD;
final int DISTANCESPAWN = 410;
final int TILED_SIZE;
final float activateBossXPosition = 420;
private float xRightBossWall = 420 + 200;
private float xLeftBossWall = 420;
float UpOffset = 0;
public MainScreen() {
this.shapeRenderer = new ShapeRenderer();
this.map = new TmxMapLoader().load("newtiles.tmx");
this.MAP_HEIGHT = (Integer) this.map.getProperties().get("height");
this.MAP_WIDTH = (Integer) this.map.getProperties().get("width");
this.TILED_SIZE = (Integer) this.map.getProperties().get("tileheight");
this.POS_LOWER_WORLD = ((this.MAP_HEIGHT / 2) * this.TILED_SIZE) - this.TILED_SIZE;
this.POS_UPPER_WORLD = this.MAP_HEIGHT * this.TILED_SIZE ;
this.renderer = new OrthogonalTiledMapRenderer(this.map, 1);
this.camera = new OrthographicCamera();
this.camera.setToOrtho(false, this.SCREEN_WIDTH, this.SCREEN_HEIGHT);
this.camera.position.y = this.POS_UPPER_WORLD - this.MAP_HEIGHT;
this.camera.update();
this.player = new Player(Assets.playerStand);
this.boss = new Boss(Assets.bossStanding);
this.configControllers = new ConfigControllers();
this.configControllers.init();
TiledMapTileLayer layerSpawn = (TiledMapTileLayer)(this.map.getLayers().get("Spawns"));
this.rectPool.freeAll(this.tiles);
this.tiles.clear();
for (int x = 0; x <= layerSpawn.getWidth(); x++) {
for (int y = 0; y <= layerSpawn.getHeight(); y++) {
Cell cell = layerSpawn.getCell(x, y);
if (cell != null) {
String type = (String) cell.getTile().getProperties().get("type");
if (type != null) {
if (type.equals("enemy")) {
this.spawns.add(new Vector2(x * this.TILED_SIZE, y * this.TILED_SIZE));
}
else if (type.equals("pollo")) {
this.lifes.add(new Vector2(x * this.TILED_SIZE, y * this.TILED_SIZE));
}
else if (type.equals("player")) {
this.player.setPosition(x * this.TILED_SIZE, y * this.TILED_SIZE);
}
else if (type.equals("boss")) {
this.boss.setPosition(x * this.TILED_SIZE, y * this.TILED_SIZE);
}
}
}
}
}
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
this.updatePlayer(delta);
this.player.act(delta);
this.activateBoss();
if (!this.bossActive){
//update x
if ((this.player.getX() - (this.SCREEN_WIDTH / 2)) < this.TILED_SIZE)
this.camera.position.x = (this.SCREEN_WIDTH / 2) + this.TILED_SIZE;
else if ((this.player.getX() + (this.SCREEN_WIDTH / 2)) > (this.MAP_WIDTH * this.TILED_SIZE))
this.camera.position.x = (this.MAP_WIDTH * 16) - (this.SCREEN_WIDTH / 2);
else
this.camera.position.x = this.player.getX();
//update y
if ((this.player.getY() - (this.SCREEN_HEIGHT / 2)) >= this.POS_LOWER_WORLD)
this.camera.position.y = this.player.getY();
else if (this.player.getY() > this.POS_LOWER_WORLD)
this.camera.position.y = this.POS_LOWER_WORLD + (this.SCREEN_HEIGHT / 2);
else if ((this.player.getY() + (this.SCREEN_HEIGHT / 2)) >= this.POS_LOWER_WORLD)
this.camera.position.y = this.POS_LOWER_WORLD - (this.SCREEN_HEIGHT / 2);
else
this.camera.position.y = this.player.getY();
this.camera.update();
}
if (this.spawns.size > 0) {
Vector2 auxNextSpawn = this.spawns.first();
if ((this.camera.position.x + this.DISTANCESPAWN) >= auxNextSpawn.x) {
Enemy auxShadow = new Enemy(Assets.enemyWalk);
if (auxNextSpawn.y < 240) {
auxNextSpawn.y -= 5; // Offset fixed collision
}
auxShadow.setPosition(auxNextSpawn.x, auxNextSpawn.y);
this.enemies.add(auxShadow);
this.spawns.removeIndex(0);
}
}
this.collisionLifes(delta);
this.updateEnemies(delta);
this.renderer.setView(this.camera);
this.renderer.render(new int[]{0, 1, 3});
this.renderEnemies(delta);
this.renderPlayer(delta);
for (Shot shot : this.shotArray){
if (shot != null)
this.renderShot(shot, delta);
}
if (this.bossActive) {
this.updateBoss(delta);
this.renderBoss(delta);
}
}
private void updateBoss(float delta) {
if (this.player.getRect().overlaps(this.boss.getRect())) {
this.player.beingHit();
}
this.boss.desiredPosition.y = this.boss.getY();
this.boss.stateTime += delta;
if (this.normalGravity)
this.boss.velocity.add(0, this.GRAVITY);
else
this.boss.velocity.add(0, -this.GRAVITY);
this.boss.velocity.scl(delta);
this.collisionForBoss(this.boss);
// unscale the velocity by the inverse delta time and set the latest position
this.boss.desiredPosition.add(this.boss.velocity);
this.boss.velocity.scl(1 / delta);
this.flowBoss(delta);
this.boss.setPosition(this.boss.desiredPosition.x, this.boss.desiredPosition.y);
if (this.boss.setToDie && Assets.bossDie.isAnimationFinished(this.boss.stateTime))
this.boss = null;
}
private void flowBoss(float delta) {
this.changeOfStatesInCaseOfAnimationFinish();
if (this.boss.flowState == Boss.FlowState.WalkingLeft){
this.boss.velocity.x = -100;
this.boss.flowState = Boss.FlowState.Transition;
this.boss.state = Boss.State.Walking;
}
else if (this.boss.flowState == Boss.FlowState.WalkingRight){
this.boss.velocity.x = 100;
this.boss.flowState = Boss.FlowState.Transition;
this.boss.state = Boss.State.Walking;
}
else if (this.boss.flowState == Boss.FlowState.Jumping){
if ((this.boss.getX() - this.player.getX()) > 0)
this.boss.velocity.x = -200;
else
this.boss.velocity.x = 200;
this.boss.velocity.y = 400;
this.boss.flowState = Boss.FlowState.Transition;
this.boss.state = Boss.State.Jumping;
}
else if (this.boss.flowState == Boss.FlowState.Attack){
if ((this.boss.getX() - this.player.getX()) > 0)
this.boss.facesRight = false;
else
this.boss.facesRight = true;
this.boss.velocity.x = 0;
//attack to character(detect position and collision)
this.boss.flowState = Boss.FlowState.Transition;
this.boss.state = Boss.State.Attack;
}
else if (this.boss.flowState == Boss.FlowState.Summon){
this.boss.velocity.x = 0;
this.Summon();
this.boss.velocity.y = 200; //only to differentiate right now
this.boss.flowState = Boss.FlowState.Transition;
this.boss.state = Boss.State.Summon;
}
else if (this.boss.flowState == Boss.FlowState.Standing){
this.boss.velocity.x = 0;
this.boss.flowState = Boss.FlowState.Transition;
this.boss.counter.gainLife(3);
this.boss.state = Boss.State.Standing;
}
else if (this.boss.flowState == Boss.FlowState.Die){
this.boss.velocity.x = 0;
this.boss.velocity.y = 0;
}
else if (this.boss.flowState == Boss.FlowState.Transition){
if (this.boss.getX() > (420 + 300)) //if going to hit wall turns back
this.boss.flowState = Boss.FlowState.WalkingLeft;
else if (this.boss.getX() < 420) //same for other wall
this.boss.flowState = Boss.FlowState.WalkingRight;
else if (this.boss.flowTime > 2){ //takes pseudo-random action
int nextState = (int)Math.round(Math.random() * 7);
if ((Math.abs(this.boss.getX() -
this.player.getX()) < 48) && ((nextState % 2) == 0)) //3 tiles far: attacks 50% time
this.boss.flowState = Boss.FlowState.Attack;
else if ((nextState == 0) || (nextState == 1)) //one possibility is jump
this.boss.flowState = Boss.FlowState.Jumping;
else if ((nextState == 2) || (nextState == 3))
this.boss.flowState = Boss.FlowState.Summon; //another summon
else if ((nextState == 4) || (nextState == 5)){ //or move in your direction
if ((this.boss.getX() - this.player.getX()) > 0)
this.boss.flowState = Boss.FlowState.WalkingLeft;
else
this.boss.flowState = Boss.FlowState.WalkingRight;
}
else
this.boss.flowState = Boss.FlowState.Standing;
this.boss.flowTime = 0;
}
}
this.boss.flowTime += delta;
}
private void Summon() {
this.spawns.add(new Vector2(this.boss.getX(), this.boss.getY() + 50));
if ((this.boss.getX() + 30) < this.xRightBossWall)
this.spawns.add(new Vector2(this.boss.getX() + 30, this.boss.getY() + 5));
if ((this.boss.getX() - 30) > this.xLeftBossWall)
this.spawns.add(new Vector2(this.boss.getX() - 30, this.boss.getY() + 5));
}
private void changeOfStatesInCaseOfAnimationFinish() {
if ((this.boss.state == Boss.State.Jumping) && (this.boss.velocity.y < 0))
this.boss.state = Boss.State.Falling;
if (this.boss.setToDie)
this.boss.flowState = Boss.FlowState.Die;
}
private void renderBoss(float delta) {
AtlasRegion frame = null;
if (this.boss.velocity.x > 0)
this.boss.facesRight = true;
else if (this.boss.velocity.x < 0)
this.boss.facesRight = false;
if (this.boss.state == Boss.State.Standing)
frame = (AtlasRegion)Assets.bossStanding.getKeyFrame(this.boss.stateTime);
else if (this.boss.state == Boss.State.Walking)
frame = (AtlasRegion)Assets.bossWalking.getKeyFrame(this.boss.stateTime);
else if (this.boss.state == Boss.State.Attack)
frame = (AtlasRegion)Assets.bossAttack.getKeyFrame(this.boss.stateTime);
else if (this.boss.state == Boss.State.Jumping)
frame = (AtlasRegion)Assets.bossJumping.getKeyFrame(this.boss.stateTime);
else if (this.boss.state == Boss.State.Falling)
frame = (AtlasRegion)Assets.bossFalling.getKeyFrame(this.boss.stateTime);
else if (this.boss.state == Boss.State.Hurting)
frame = (AtlasRegion)Assets.bossGethit.getKeyFrame(this.boss.stateTime);
else if (this.boss.state == Boss.State.Die)
frame = (AtlasRegion)Assets.bossDie.getKeyFrame(this.boss.stateTime);
else if (this.boss.state == Boss.State.Summon)
frame = (AtlasRegion)Assets.bossSummon.getKeyFrame(this.boss.stateTime);
if (this.boss.invincible && this.boss.toggle) {
frame = (AtlasRegion)Assets.bossGethit.getKeyFrame(this.player.stateTime);
this.boss.toggle = !this.boss.toggle;
}
else if (this.boss.invincible && !this.boss.toggle) {
this.boss.toggle = !this.boss.toggle;
}
else if (!this.boss.invincible) {
this.boss.toggle = false;
}
Batch batch = this.renderer.getSpriteBatch();
batch.begin();
if (this.boss.facesRight) {
if (frame.isFlipX())
frame.flip(true, false);
batch.draw(frame, this.boss.getX() + frame.offsetX, this.boss.getY() + frame.offsetY);
} else {
if (!frame.isFlipX())
frame.flip(true, false);
batch.draw(frame, this.boss.getX() + frame.offsetX, this.boss.getY() + frame.offsetY);
}
batch.end();
}
private void renderShot(Shot shot, float deltaTime){
AtlasRegion frame = null;
frame = (AtlasRegion) Assets.playerShot.getKeyFrame(shot.stateTime);
Batch batch = this.renderer.getSpriteBatch();
batch.begin();
if (shot.shotGoesRight) {
if (frame.isFlipX())
frame.flip(true, false);
batch.draw(frame, shot.getX() + frame.offsetX, shot.getY() + frame.offsetY);
} else {
if (!frame.isFlipX())
frame.flip(true, false);
batch.draw(frame, shot.getX() + frame.offsetX, shot.getY() + frame.offsetY);
}
batch.end();
}
public boolean updateShot(Shot shot, float deltaTime){
shot.desiredPosition.y = shot.getY();
shot.stateTime += deltaTime;
if (this.normalGravity)
shot.velocity.add(0, this.GRAVITY);
else
shot.velocity.add(0, -this.GRAVITY);
shot.velocity.scl(deltaTime);
//collision (destroy if necessary)
boolean collided = this.collisionShotEnemy(shot);
if (!collided) {
collided = this.collisionShot(shot);
if (collided)
Assets.playSound("holyWaterBroken");
}
// unscale the velocity by the inverse delta time and set
// the latest position
if (shot != null){
shot.desiredPosition.add(shot.velocity);
shot.velocity.scl(1 / deltaTime);
shot.setPosition(shot.desiredPosition.x, shot.desiredPosition.y);
if (shot.normalGravity && (shot.getY() < this.POS_LOWER_WORLD))
collided = true; //dont traspass to the other world
else if (!shot.normalGravity && (shot.getY() >= this.POS_LOWER_WORLD))
collided = true;
else if ((shot.getY() > (this.MAP_HEIGHT * this.TILED_SIZE)) || (shot.getY() < 0))
collided = true;
}
return collided;
}
private boolean collisionShotEnemy(Shot shot) {
boolean collided = false;
this.playerRect = this.rectPool.obtain();
shot.desiredPosition.y = Math.round(shot.getY());
shot.desiredPosition.x = Math.round(shot.getX());
this.playerRect.set(shot.desiredPosition.x, (shot.desiredPosition.y), shot.getWidth(), shot.getHeight());
for (Enemy enemy : this.enemies){
if (this.playerRect.overlaps(enemy.rect)) {
if (!enemy.dying){
enemy.die();
collided = true;
break;
}
}
}
if ((this.boss != null) && this.playerRect.overlaps(this.boss.rect)) {
this.boss.beingHit();
if (!this.boss.setToDie){
this.boss.invincible = true; //activates also the flickering
}
else {
this.boss.state = Boss.State.Die;
this.boss.stateTime = 0;
}
collided = true;
}
return collided;
}
private boolean collisionShot(Shot shot) {
this.playerRect = this.rectPool.obtain();
shot.desiredPosition.y = Math.round(shot.getY());
shot.desiredPosition.x = Math.round(shot.getX());
this.playerRect.set(shot.desiredPosition.x + shot.offSetX, (shot.desiredPosition.y), shot.getWidth(), shot.getHeight());
int startX, startY, endX, endY;
if (shot.velocity.x > 0) { //this.raya.velocity.x > 0
startX = endX = (int)((shot.desiredPosition.x + shot.velocity.x + shot.getWidth() + shot.offSetX) / 16);
}
else {
startX = endX = (int)((shot.desiredPosition.x + shot.velocity.x + shot.offSetX) / 16);
}
startY = (int)((shot.desiredPosition.y) / 16);
endY = (int)((shot.desiredPosition.y + shot.getHeight()) / 16);
this.getTiles(startX, startY, endX, endY, this.tiles);
this.playerRect.x += shot.velocity.x;
for (Rectangle tile : this.tiles){
if (this.playerRect.overlaps(tile)) {
shot = null;
return true;
}
}
this.playerRect.x = shot.desiredPosition.x;
if (this.normalGravity){
if (shot.velocity.y > 0) {
startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y + shot.getHeight()) / 16f);
}
else {
startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y) / 16f);
}
}
else{
if (shot.velocity.y < 0) {
startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y) / 16f);
}
else {
startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y + shot.getHeight() ) / 16f);
}
}
startX = (int)((shot.desiredPosition.x + shot.offSetX) / 16); //16 tile size
endX = (int)((shot.desiredPosition.x + shot.getWidth() + shot.offSetX) / 16);
// System.out.println(startX + " " + startY + " " + endX + " " + endY);
this.getTiles(startX, startY, endX, endY, this.tiles);
shot.desiredPosition.y += (int)(shot.velocity.y);
for (Rectangle tile : this.tiles) {
if (this.playerRect.overlaps(tile)) {
shot = null;
return true;
}
}
return false;
}
private void renderPlayer (float deltaTime) {
AtlasRegion frame = null;
switch (this.player.state) {
case Standing:
frame = (AtlasRegion)Assets.playerStand.getKeyFrame(this.player.stateTime);
break;
case Walking:
frame = (AtlasRegion)Assets.playerWalk.getKeyFrame(this.player.stateTime);
break;
case Jumping:
frame = (AtlasRegion)Assets.playerJump.getKeyFrame(this.player.stateTime);
break;
case Intro:
frame = (AtlasRegion)Assets.playerIntro.getKeyFrame(this.player.stateTime);
break;
case Attacking:
frame = (AtlasRegion)Assets.playerAttack.getKeyFrame(this.player.stateTime);
break;
case Die:
frame = (AtlasRegion)Assets.playerDie.getKeyFrame(this.player.stateTime);
break;
case BeingHit:
frame = (AtlasRegion)Assets.playerBeingHit.getKeyFrame(this.player.stateTime);
break;
}
if (this.player.invincible && this.toggle) {
frame = (AtlasRegion)Assets.playerEmpty.getKeyFrame(this.player.stateTime);
this.toggle = !this.toggle;
}
else if (this.player.invincible && !this.toggle) {
this.toggle = !this.toggle;
}
else if (!this.player.invincible) {
this.toggle = false;
}
// draw the koala, depending on the current velocity
// on the x-axis, draw the koala facing either right
// or left
Batch batch = this.renderer.getSpriteBatch();
batch.begin();
if (this.player.facesRight && frame.isFlipX()) {
frame.flip(true, false);
this.player.rightOffset = 1f; //fix differences
}
else if (!this.player.facesRight && !frame.isFlipX()) {
frame.flip(true, false);
this.player.rightOffset = -4f; //fix differences
}
if (this.normalGravity && frame.isFlipY()) {
frame.flip(false, true);
this.UpOffset = 0;
}
else if (!this.normalGravity && !frame.isFlipY()){
frame.flip(false, true);
this.UpOffset = -2;
}
//batch.draw(frame, this.player.getX() + frame.offsetX, this.player.getY() + frame.offsetY + this.UpOffset);
batch.draw(frame, this.player.getX() + frame.offsetX + this.player.rightOffset, this.player.getY() + frame.offsetY + this.UpOffset);
batch.end();
this.shapeRenderer.begin(ShapeType.Filled);
this.shapeRenderer.setColor(Color.BLACK);
this.getTiles(0, 0, 25, 15, this.tiles);
//for (Rectangle tile : this.tiles) {
// shapeRenderer.rect(tile.x * 1.6f, tile.y * 2, tile.width * 2, tile.height * 2);
this.shapeRenderer.setColor(Color.RED);
//shapeRenderer.rect(playerRect.x * 1.6f, playerRect.y * 2, playerRect.width * 2, playerRect.height * 2);
this.shapeRenderer.end();
}
private void renderEnemies(float deltaTime) {
for (Enemy enemy : this.enemies) {
AtlasRegion frame = null;
switch (enemy.state) {
case Walking:
frame = (AtlasRegion)Assets.enemyWalk.getKeyFrame(enemy.stateTime);
break;
case Running:
frame = (AtlasRegion)Assets.enemyRun.getKeyFrame(enemy.stateTime);
break;
case Hurting:
frame = (AtlasRegion)Assets.enemyHurt.getKeyFrame(enemy.stateTime);
break;
}
Batch batch = this.renderer.getSpriteBatch();
batch.begin();
if (enemy.facesRight) {
if (frame.isFlipX())
frame.flip(true, false);
batch.draw(frame, enemy.getX() + frame.offsetX, enemy.getY() + frame.offsetY);
} else {
if (!frame.isFlipX())
frame.flip(true, false);
batch.draw(frame, enemy.getX() + frame.offsetX, enemy.getY() + frame.offsetY);
}
batch.end();
this.shapeRenderer.begin(ShapeType.Filled);
this.shapeRenderer.setColor(Color.BLACK);
this.getTiles(0, 0, 25, 15, this.tiles);
this.shapeRenderer.setColor(Color.RED);
this.shapeRenderer.end();
}
}
private void collisionLifes(float deltaTime) {
Array<Vector2> obtainLifes = new Array<Vector2>();
for (Vector2 life : this.lifes) {
if ((life.dst(this.player.getX(), this.player.getY()) < this.player.getWidth()) &&
(this.player.getLifes() < this.player.MAX_LIFES)) {
this.player.counter.gainLife(1);
obtainLifes.add(life);
// Remove life in map
TiledMapTileLayer layerPlantfs = (TiledMapTileLayer)(this.map.getLayers().get("Platfs"));
layerPlantfs.setCell((int)life.x / this.TILED_SIZE, (int)life.y / this.TILED_SIZE, null);
}
}
this.lifes.removeAll(obtainLifes, false);
}
private void updateEnemies(float deltaTime) {
for (Enemy enemy : this.enemies) {
isEnemyInScreen(enemy);
// Collision between player vs enemy
if (!enemy.dying){
if (this.player.getX() > enemy.getX()){
if (this.player.getRect().overlaps(enemy.getRect())) {
this.player.beingHit();
}
}
else{ //tricking because it doesnt work ok. only in the left side
Rectangle enemyRect = new Rectangle(enemy.getRect().x + 20, enemy.getY(), enemy.getWidth(), enemy.getHeight());
if (this.player.getRect().overlaps(enemyRect)) {
this.player.beingHit();
}
}
}
enemy.stateTime += deltaTime;
// Check if player is invincible and check distance to player for attack him.
if (!enemy.running && !enemy.dying && enemy.inScreen){
if (!this.player.invincible &&
((enemy.getY() - (enemy.getWidth() / 2)) <= this.player.getY()) &&
(this.player.getY() <= (enemy.getY() + (enemy.getWidth() / 2)))) {
if (enemy.getX() < this.player.getX()) {
if ((enemy.getX() + enemy.ATTACK_DISTANCE) >= (this.player.getX() + this.player.getWidth())) {
enemy.dir = Enemy.Direction.Right;
enemy.facesRight = true;
enemy.run();
enemy.attackHereX = this.player.getX();
enemy.attackRight = true;
}
}
else {
if ((enemy.getX() - enemy.ATTACK_DISTANCE) <= this.player.getX()) {
enemy.dir = Enemy.Direction.Left;
enemy.facesRight = false;
enemy.run();
enemy.attackHereX = this.player.getX();
enemy.attackRight = false;
}
}
}
else if (enemy.dir == Enemy.Direction.Left) {
if (-enemy.RANGE >= enemy.diffInitialPos) {
enemy.dir = Enemy.Direction.Right;
enemy.facesRight = true;
}
enemy.walk();
}
else if (enemy.dir == Enemy.Direction.Right) {
if (enemy.diffInitialPos >= enemy.RANGE) {
enemy.dir = Enemy.Direction.Left;
enemy.facesRight = false;
}
enemy.walk();
}
}
else if ((enemy.getX() > enemy.attackHereX) && enemy.attackRight)
enemy.running = false;
else if ((enemy.getX() < enemy.attackHereX) && !enemy.attackRight)
enemy.running = false;
enemy.velocity.scl(deltaTime);
// Enviroment collision
enemy.desiredPosition.y = Math.round(enemy.getY());
enemy.desiredPosition.x = Math.round(enemy.getX());
int startX, startY, endX, endY;
if (enemy.velocity.x > 0) {
startX = endX = (int)((enemy.desiredPosition.x + enemy.velocity.x + enemy.getWidth()) / this.TILED_SIZE);
}
else {
startX = endX = (int)((enemy.desiredPosition.x + enemy.velocity.x) / this.TILED_SIZE);
}
startY = (int) enemy.getY() / this.TILED_SIZE;
endY = (int) (enemy.getY() + enemy.getHeight()) / this.TILED_SIZE;
this.getTiles(startX, startY, endX, endY, this.tiles);
enemy.getRect();
enemy.rect.x += enemy.velocity.x;
for (Rectangle tile : this.tiles) {
if (enemy.rect.overlaps(tile)) {
enemy.velocity.x = 0;
enemy.running = false;
break;
}
}
enemy.rect.x = enemy.desiredPosition.x;
enemy.desiredPosition.add(enemy.velocity);
enemy.velocity.scl(1 / deltaTime);
enemy.setPosition(enemy.desiredPosition.x, enemy.desiredPosition.y);
if (Assets.playerDie.isAnimationFinished(enemy.stateTime) && enemy.dying){
enemy.setToDie = true;
}
}
int i = 0;
boolean[] toBeDeleted = new boolean[this.enemies.size];
for (Enemy enemy : this.enemies){
if (enemy != null){
if(enemy.setToDie == true) //&& animation finished
toBeDeleted[i] = true;
}
i++;
}
for(int j = 0; j < toBeDeleted.length; j++){
if (toBeDeleted[j] && (this.enemies.size >= (j + 1)))
this.enemies.removeIndex(j);
}
}
private void isEnemyInScreen(Enemy enemy) {
//TODO: Maybe change so that they activate a little bit before they enter the screen
if (enemy.getX() > (camera.position.x - (SCREEN_WIDTH / 2))
&& (enemy.getX() < (camera.position.x + (SCREEN_WIDTH / 2)))
&& (enemy.getY() > (camera.position.y - (SCREEN_HEIGHT / 2))
&& (enemy.getX() < (camera.position.x + (SCREEN_HEIGHT / 2))))){
enemy.inScreen = true;
}
}
private void updatePlayer(float deltaTime) {
if (deltaTime == 0)
return;
this.player.stateTime += deltaTime;
this.player.desiredPosition.x = this.player.getX();
this.player.desiredPosition.y = this.player.getY();
this.movingShootingJumping(deltaTime);
this.gravityAndClamping();
this.player.velocity.scl(deltaTime);
//retreat if noControl //velocity y is changed in beingHit
if (this.player.noControl){
if (this.player.facesRight)
this.player.velocity.x = -120f * deltaTime;
else
this.player.velocity.x = 120 * deltaTime;
}
boolean collisionSpike = this.collisionWallsAndSpike();
// unscale the velocity by the inverse delta time and set the latest position
this.player.desiredPosition.add(this.player.velocity);
this.player.velocity.scl(1 / deltaTime);
if (Assets.playerBeingHit.isAnimationFinished(this.player.stateTime) && !this.player.dead)
this.player.noControl = false;
if (this.player.noControl == false)
this.player.velocity.x *= 0; //0 is totally stopped if not pressed
if ((((this.player.desiredPosition.x - this.player.offSetX) + this.player.velocity.x) < 0 )
|| ((this.player.desiredPosition.x + this.player.getWidth() + this.player.velocity.x)
> (this.MAP_WIDTH * this.TILED_SIZE)))
this.player.desiredPosition.x = 1;
this.player.setPosition(this.player.desiredPosition.x, this.player.desiredPosition.y);
if (Assets.playerDie.isAnimationFinished(this.player.stateTime) && this.player.dead){
this.gameOver();
}
if (collisionSpike) {
this.player.beingHit();
}
}
private void gameOver() {
LD.getInstance().GAMEOVER_SCREEN = new GameOverScreen();
LD.getInstance().setScreen(LD.getInstance().GAMEOVER_SCREEN);
}
private void activateBoss() {
if ((this.player.getX() >= (this.boss.getX() - this.boss.ACTIVATE_DISTANCE)) && !this.bossActive) {
this.bossActive = true;
this.camera.position.x = this.boss.getX();
this.camera.update();
Assets.musicStage.stop();
Assets.musicBoss.setLooping(true);
Assets.musicBoss.play();
//close door
TiledMapTileLayer layerSpawn = (TiledMapTileLayer)(this.map.getLayers().get(0));
Cell cell = layerSpawn.getCell(25, 16); //has to be solid block
layerSpawn.setCell(25, 17, cell);
layerSpawn.setCell(25, 18, cell);
layerSpawn.setCell(25, 19, cell);
layerSpawn = (TiledMapTileLayer)(this.map.getLayers().get(1));
layerSpawn.setCell(25, 17, cell);
layerSpawn.setCell(25, 18, cell);
layerSpawn.setCell(25, 19, cell);
}
}
private void gravityAndClamping() {
if (this.normalGravity)
this.player.velocity.add(0, this.GRAVITY);
else
this.player.velocity.add(0, -this.GRAVITY);
if (this.player.getY() < this.POS_LOWER_WORLD){
//this.camera.position.y = this.POS_LOWER_WORLD;
if (this.normalGravity == true){
this.normalGravity = false;
this.player.velocity.y = -this.player.JUMP_VELOCITY * 1.01f;
}
}
else {
//this.camera.position.y = 0;//this.yPosUpperWorld;
if (this.normalGravity == false){
this.normalGravity = true;
this.player.velocity.y = this.player.JUMP_VELOCITY / 1.3f;
}
}
// clamp the velocity to the maximum, x-axis only
if (Math.abs(this.player.velocity.x) > this.player.MAX_VELOCITY) {
this.player.velocity.x = Math.signum(this.player.velocity.x) * this.player.MAX_VELOCITY;
}
// clamp the velocity to 0 if it's < 1, and set the state to standign
if (Math.abs(this.player.velocity.x) < 1) {
this.player.velocity.x = 0;
if (this.player.grounded && Assets.playerAttack.isAnimationFinished(this.player.stateTime) &&
Assets.playerBeingHit.isAnimationFinished(this.player.stateTime) && !this.player.invincible)
this.player.state = Player.State.Standing;
}
}
private void movingShootingJumping(float deltaTime) {
if (this.player.noControl == false){
if ((Gdx.input.isKeyJustPressed(Keys.S) || this.configControllers.jumpPressed) && this.player.grounded){
Assets.playSound("playerJump");
if (this.normalGravity)
this.player.velocity.y = this.player.JUMP_VELOCITY;
else
this.player.velocity.y = -this.player.JUMP_VELOCITY;
this.player.grounded = false;
this.player.state = Player.State.Jumping;
//this.player.stateTime = 0;
}
if (Gdx.input.isKeyPressed(Keys.LEFT) || this.configControllers.leftPressed){
this.player.velocity.x = -this.player.MAX_VELOCITY;
if (this.player.grounded && Assets.playerAttack.isAnimationFinished(this.player.stateTime)
&& Assets.playerBeingHit.isAnimationFinished(this.player.stateTime)){
this.player.state = Player.State.Walking;
//this.player.stateTime = 0;
}
this.player.facesRight = false;
}
if (Gdx.input.isKeyPressed(Keys.RIGHT) || this.configControllers.rightPressed){
this.player.velocity.x = this.player.MAX_VELOCITY;
if (this.player.grounded && Assets.playerAttack.isAnimationFinished(this.player.stateTime)
&& Assets.playerBeingHit.isAnimationFinished(this.player.stateTime)){
this.player.state = Player.State.Walking;
//this.player.stateTime = 0;
}
this.player.facesRight = true;
}
if ((Gdx.input.isKeyJustPressed(Keys.D) || this.configControllers.shootPressed) && (this.shotArray.size < 3)){
Assets.playSound("playerAttack");
Shot shot = new Shot(Assets.playerShot);
if (this.player.facesRight){
//-1 necessary to be exactly the same as the other facing
shot.Initialize((this.player.getX() + (this.player.getHeight() / 2)) - 1, (this.player.getY() + (this.player.getWidth() / 2)), this.player.facesRight, this.normalGravity);
}
else {
shot.Initialize(this.player.getX(), (this.player.getY() + (this.player.getWidth() / 2)), this.player.facesRight, this.normalGravity);
}
this.shotArray.add(shot);
this.player.state = Player.State.Attacking;
this.player.stateTime = 0;
this.player.shooting = true;
}
}
if (Assets.playerAttack.isAnimationFinished(this.player.stateTime))
this.player.shooting = false;
int i = 0;
boolean[] toBeDeleted = new boolean[3];
for (Shot shot : this.shotArray){
if (shot != null){
if(this.updateShot(shot, deltaTime) == true)
toBeDeleted[i] = true;
//pool of shots?
}
i++;
}
for(int j = 0; j < toBeDeleted.length; j++){
if (toBeDeleted[j] && (this.shotArray.size >= (j + 1)))
this.shotArray.removeIndex(j);
}
}
private boolean collisionForBoss(Boss boss) {
//collision detection
// perform collision detection & response, on each axis, separately
// if the raya is moving right, check the tiles to the right of it's
// right bounding box edge, otherwise check the ones to the left
this.playerRect = this.rectPool.obtain();
boss.desiredPosition.y = Math.round(boss.getY());
boss.desiredPosition.x = Math.round(boss.getX());
this.playerRect.set(boss.desiredPosition.x, boss.desiredPosition.y, boss.getWidth(), boss.getHeight());
int startX, startY, endX, endY;
if (this.player.velocity.x > 0) {
startX = endX = (int)((boss.desiredPosition.x + boss.velocity.x + boss.getWidth()) / this.TILED_SIZE);
}
else {
startX = endX = (int)((boss.desiredPosition.x + boss.velocity.x) / this.TILED_SIZE);
}
if (boss.grounded && this.normalGravity){
startY = (int)((boss.desiredPosition.y) / this.TILED_SIZE) + 1;
endY = (int)((boss.desiredPosition.y + boss.getHeight()) / this.TILED_SIZE) + 1;
}
else if (boss.grounded && !this.normalGravity){
startY = (int)((boss.desiredPosition.y) / this.TILED_SIZE) - 1;
endY = (int)((boss.desiredPosition.y + boss.getHeight()) / this.TILED_SIZE) - 1;
}
else{
startY = (int)((boss.desiredPosition.y) / this.TILED_SIZE);
endY = (int)((boss.desiredPosition.y + boss.getHeight()) / this.TILED_SIZE);
}
this.getTiles(startX, startY, endX, endY, this.tiles);
this.playerRect.x += boss.velocity.x;
for (Rectangle tile : this.tiles) {
if (this.playerRect.overlaps(tile)) {
this.player.velocity.x = 0;
break;
}
}
this.playerRect.x = boss.desiredPosition.x;
// if the koala is moving upwards, check the tiles to the top of it's
// top bounding box edge, otherwise check the ones to the bottom
if (this.normalGravity){
if (boss.velocity.y > 0) {
startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y + boss.getHeight()) / this.TILED_SIZE);
}
else {
startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y) / this.TILED_SIZE);
}
}
else{
if (this.player.velocity.y < 0) {
startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y) / this.TILED_SIZE);
}
else {
startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y + boss.getHeight() ) / this.TILED_SIZE);
}
}
startX = (int)(boss.desiredPosition.x / this.TILED_SIZE); //16 tile size
endX = (int)((boss.desiredPosition.x + boss.getWidth()) / this.TILED_SIZE);
// System.out.println(startX + " " + startY + " " + endX + " " + endY);
this.getTiles(startX, startY, endX, endY, this.tiles);
this.playerRect.y += (int)(boss.velocity.y);
boolean grounded = boss.grounded;
for (Rectangle tile : this.tiles) {
// System.out.println(playerRect.x + " " + playerRect.y + " " + tile.x + " " + tile.y);
if (this.playerRect.overlaps(tile)) {
// we actually reset the koala y-position here
// so it is just below/above the tile we collided with
// this removes bouncing :)
if (this.normalGravity){
if (boss.velocity.y > 0) {
boss.desiredPosition.y = tile.y - boss.getHeight() - 1;
// we hit a block jumping upwards, let's destroy it!
}
else {
boss.desiredPosition.y = (tile.y + tile.height) - 4; //in this way he is in the ground
// if we hit the ground, mark us as grounded so we can jump
grounded = true;
}
}
else{
if (boss.velocity.y > 0) {
//this.player.desiredPosition.y = tile.y - tile.height- 1;
// if we hit the ground, mark us as grounded so we can jump
grounded = true;
}
else {
boss.desiredPosition.y = (tile.y + tile.height) - 1;
// we hit a block jumping upwards, let's destroy it!
}
}
boss.velocity.y = 0;
break;
}
}
if (this.tiles.size == 0)
grounded = false;
//goes together with get
this.rectPool.free(this.playerRect);
return grounded;
}
private boolean collisionWallsAndSpike() {
//collision detection
// perform collision detection & response, on each axis, separately
// if the raya is moving right, check the tiles to the right of it's
// right bounding box edge, otherwise check the ones to the left
boolean collisionSpike = false;
this.playerRect = this.rectPool.obtain();
this.player.desiredPosition.y = Math.round(this.player.getY());
this.player.desiredPosition.x = Math.round(this.player.getX());
this.playerRect.set(this.player.desiredPosition.x + this.player.offSetX, this.player.desiredPosition.y
, this.player.getWidth(), this.player.getHeight());
int startX, startY, endX, endY;
if (this.player.velocity.x > 0) {
startX = endX = (int)((this.player.desiredPosition.x + this.player.velocity.x + this.player.getWidth() + this.player.offSetX) / this.TILED_SIZE);
}
else {
startX = endX = (int)((this.player.desiredPosition.x + this.player.velocity.x + this.player.offSetX) / this.TILED_SIZE);
}
if (this.player.grounded && this.normalGravity){
startY = (int)((this.player.desiredPosition.y) / this.TILED_SIZE) + 1;
endY = (int)((this.player.desiredPosition.y + this.player.getHeight()) / this.TILED_SIZE) + 1;
}
else if (this.player.grounded && !this.normalGravity){
startY = (int)((this.player.desiredPosition.y) / this.TILED_SIZE) - 1;
endY = (int)((this.player.desiredPosition.y + this.player.getHeight()) / this.TILED_SIZE) - 1;
}
else{
startY = (int)((this.player.desiredPosition.y) / this.TILED_SIZE) + 1;
endY = (int)((this.player.desiredPosition.y + this.player.getHeight()) / this.TILED_SIZE) + 1;
}
this.getTiles(startX, startY, endX, endY, this.tiles, this.spikes);
this.playerRect.x += this.player.velocity.x;
for (Rectangle spike : this.spikes) {
if (this.playerRect.overlaps(spike)) {
this.player.velocity.x = 0;
collisionSpike = true;
break;
}
}
for (Rectangle tile : this.tiles) {
if (this.playerRect.overlaps(tile)) {
this.player.velocity.x = 0;
break;
}
}
this.playerRect.x = this.player.desiredPosition.x;
// if the koala is moving upwards, check the tiles to the top of it's
// top bounding box edge, otherwise check the ones to the bottom
if (this.normalGravity){
if (this.player.velocity.y > 0) {
startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y + this.player.getHeight()) / this.TILED_SIZE);
}
else {
startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y) / this.TILED_SIZE);
}
}
else{
if (this.player.velocity.y < 0) {
startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y) / this.TILED_SIZE);
}
else {
startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y + this.player.getHeight() ) / this.TILED_SIZE);
}
}
startX = (int)((this.player.desiredPosition.x + this.player.offSetX)/ this.TILED_SIZE); //16 tile size
endX = (int)((this.player.desiredPosition.x + this.player.getWidth() + this.player.offSetX) / this.TILED_SIZE);
// System.out.println(startX + " " + startY + " " + endX + " " + endY);
this.getTiles(startX, startY, endX, endY, this.tiles, this.spikes);
this.playerRect.y += (int)(this.player.velocity.y);
for (Rectangle spike : this.spikes) {
if (this.playerRect.overlaps(spike)) {
if (this.normalGravity){
if (this.player.velocity.y > 0) // we hit a block jumping upwards
this.player.desiredPosition.y = spike.y - this.player.getHeight() - 2;
else {
// if we hit the ground, mark us as grounded so we can jump
this.player.desiredPosition.y = (spike.y + spike.height) - 2;
this.player.grounded = true;
}
}
else{ //upside down
if (this.player.velocity.y > 0) {
this.player.desiredPosition.y = (spike.y - this.player.getHeight()) + 1;
this.player.grounded = true;
}
else
this.player.desiredPosition.y = (spike.y + spike.height);
}
collisionSpike = true;
break;
}
}
for (Rectangle tile : this.tiles) {
if (this.playerRect.overlaps(tile)) {
if (this.normalGravity){
if (this.player.velocity.y > 0) // we hit a block jumping upwards
this.player.desiredPosition.y = tile.y - this.player.getHeight() - 2;
else {
// if we hit the ground, mark us as grounded so we can jump
this.player.desiredPosition.y = (tile.y + tile.height) - 2;
this.player.grounded = true;
}
}
else{ //upside down
if (this.player.velocity.y > 0) {
this.player.desiredPosition.y = (tile.y - this.player.getHeight()) + 1;
this.player.grounded = true;
}
else
this.player.desiredPosition.y = (tile.y + tile.height);
}
this.player.velocity.y = 0;
break;
}
}
if (this.tiles.size == 0)
this.player.grounded = false;
//goes together with get
this.rectPool.free(this.playerRect);
return collisionSpike;
}
private void getTiles(int startX, int startY, int endX, int endY, Array<Rectangle> tiles) {
this.getTiles(startX, startY, endX, endY, tiles, null);
}
private void getTiles(int startX, int startY, int endX, int endY, Array<Rectangle> tiles, Array<Rectangle> spikes) {
TiledMapTileLayer layer = (TiledMapTileLayer)(this.map.getLayers().get("Collisions"));
TiledMapTileLayer layer2 = (TiledMapTileLayer)(this.map.getLayers().get("Spikes"));
this.rectPool.freeAll(tiles);
tiles.clear();
if (spikes != null) {
this.rectPool.freeAll(spikes);
spikes.clear();
}
for (int y = startY; y <= endY; y++) {
for (int x = startX; x <= endX; x++) {
Cell cell = layer.getCell(x, y);
if (cell != null) {
Rectangle rect = this.rectPool.obtain();
rect.set(x * this.TILED_SIZE, y * this.TILED_SIZE, this.TILED_SIZE, this.TILED_SIZE);
tiles.add(rect);
}
if (spikes != null) {
Cell cell2 = layer2.getCell(x, y);
if (cell2 != null) {
Rectangle rect = this.rectPool.obtain();
rect.set(x * this.TILED_SIZE, y * this.TILED_SIZE, this.TILED_SIZE, this.TILED_SIZE);
spikes.add(rect);
tiles.add(rect);
}
}
}
}
}
@Override
public void backButtonPressed() {
LD.getInstance().MENU_SCREEN = new MenuScreen();
LD.getInstance().setScreen(LD.getInstance().MENU_SCREEN);
}
@Override
public void enterButtonPressed() {
if (!this.pause) {
this.pause();
}
else {
this.resume();
}
}
@Override
public void pause() {
this.pause = true;
}
@Override
public void resume() {
this.pause = false;
}
}
|
package com.cloud.storage.template;
import java.io.File;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.log4j.Logger;
import com.cloud.exception.InternalErrorException;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageLayer;
import com.cloud.utils.script.Script;
@Local(value=Processor.class)
public class VmdkProcessor implements Processor {
private static final Logger s_logger = Logger.getLogger(VmdkProcessor.class);
String _name;
StorageLayer _storage;
@Override
public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException {
if (format != null) {
if(s_logger.isInfoEnabled())
s_logger.info("We currently don't handle conversion from " + format + " to VMDK.");
return null;
}
s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName);
String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension();
if (!_storage.exists(templateFilePath)) {
if(s_logger.isInfoEnabled())
s_logger.info("Unable to find the vmware template file: " + templateFilePath);
return null;
}
s_logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName);
String templateFileFullPath = templatePath + templateName + "." + ImageFormat.OVA.getFileExtension();
File templateFile = new File(templateFileFullPath);
Script command = new Script("tar", 0, s_logger);
command.add("--no-same-owner");
command.add("-xf", templateFileFullPath);
command.setWorkDir(templateFile.getParent());
String result = command.execute();
if (result != null) {
s_logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName);
return null;
}
FormatInfo info = new FormatInfo();
info.format = ImageFormat.OVA;
info.filename = templateName + "." + ImageFormat.OVA.getFileExtension();
info.size = _storage.getSize(templateFilePath);
info.virtualSize = getTemplateVirtualSize(templatePath, info.filename);
// delete original OVA file
// templateFile.delete();
return info;
}
public long getTemplateVirtualSize(String templatePath, String templateName) throws InternalErrorException {
// get the virtual size from the OVF file meta data
long virtualSize=0;
String templateFileFullPath = templatePath.endsWith(File.separator) ? templatePath : templatePath + File.separator;
templateFileFullPath += templateName.endsWith(ImageFormat.OVA.getFileExtension()) ? templateName : templateName + "." + ImageFormat.OVA.getFileExtension();
String ovfFileName = getOVFFilePath(templateFileFullPath);
if(ovfFileName == null) {
String msg = "Unable to locate OVF file in template package directory: " + templatePath;
s_logger.error(msg);
throw new InternalErrorException(msg);
}
try {
Document ovfDoc = null;
ovfDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(ovfFileName));
Element disk = (Element) ovfDoc.getElementsByTagName("Disk").item(0);
virtualSize = Long.parseLong(disk.getAttribute("ovf:capacity"));
String allocationUnits = disk.getAttribute("ovf:capacityAllocationUnits");
if ((virtualSize != 0) && (allocationUnits != null)) {
long units = 1;
if (allocationUnits.equalsIgnoreCase("KB") || allocationUnits.equalsIgnoreCase("KiloBytes") || allocationUnits.equalsIgnoreCase("byte * 2^10")) {
units = 1024;
} else if (allocationUnits.equalsIgnoreCase("MB") || allocationUnits.equalsIgnoreCase("MegaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^20")) {
units = 1024 * 1024;
} else if (allocationUnits.equalsIgnoreCase("GB") || allocationUnits.equalsIgnoreCase("GigaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^30")) {
units = 1024 * 1024 * 1024;
}
virtualSize = virtualSize * units;
} else {
throw new InternalErrorException("Failed to read capacity and capacityAllocationUnits from the OVF file: " + ovfFileName);
}
return virtualSize;
} catch (Exception e) {
String msg = "Unable to parse OVF XML document to get the virtual disk size due to"+e;
s_logger.error(msg);
throw new InternalErrorException(msg);
}
}
private String getOVFFilePath(String srcOVAFileName) {
File file = new File(srcOVAFileName);
assert(_storage != null);
String[] files = _storage.listFiles(file.getParent());
if(files != null) {
for(String fileName : files) {
if(fileName.toLowerCase().endsWith(".ovf")) {
File ovfFile = new File(fileName);
return file.getParent() + File.separator + ovfFile.getName();
}
}
}
return null;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
_storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey);
if (_storage == null) {
throw new ConfigurationException("Unable to get storage implementation");
}
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
}
|
package hu.zhuren.shuai.utils;
import android.util.Log;
public class LogUtils {
private static final String TAG = LogUtils.class.getSimpleName();
private static final boolean enableLog = true;
private LogUtils() {
}
public static void debug(String tag, String msg) {
if (enableLog)
Log.d(tag, msg);
}
public static void debug(String msg) {
debug(TAG, msg);
}
public static void error(String tag, String msg) {
if (enableLog)
Log.e(tag, msg);
}
public static void error(String msg) {
error(TAG, msg);
}
public static void verbose(String tag, String msg) {
if (enableLog)
Log.v(tag, msg);
}
public static void verbose(String msg) {
verbose(TAG, msg);
}
public static void warning(String tag, String msg) {
if (enableLog)
Log.i(tag, msg);
}
public static void warning(String msg) {
warning(TAG, msg);
}
public static void info(String tag, String msg) {
if (enableLog)
Log.i(tag, msg);
}
public static void info(String msg) {
info(TAG, msg);
}
public static void writeFileLog(String msg) {
}
}
|
package hudson.maven;
import hudson.Launcher;
import hudson.maven.reporters.MavenAbstractArtifactRecord;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import net.sf.json.JSONObject;
import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.embedder.MavenEmbedderException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
/**
* {@link Publisher} for {@link MavenModuleSetBuild} to deploy artifacts
* after a build is fully succeeded.
*
* @author Kohsuke Kawaguchi
* @since 1.191
*/
public class RedeployPublisher extends Publisher {
public final String id;
/**
* Repository URL to deploy artifacts to.
*/
public final String url;
public final boolean uniqueVersion;
@DataBoundConstructor
public RedeployPublisher(String id, String url, boolean uniqueVersion) {
this.id = id;
this.url = url;
this.uniqueVersion = uniqueVersion;
}
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
if(build.getResult().isWorseThan(Result.SUCCESS))
return true; // build failed. Don't publish
MavenAbstractArtifactRecord mar = getAction(build);
if(mar==null) {
listener.getLogger().println("No artifacts are recorded. Is this a Maven project?");
build.setResult(Result.FAILURE);
return true;
}
listener.getLogger().println("Deploying artifacts to "+url);
try {
MavenEmbedder embedder = MavenUtil.createEmbedder(listener, null);
ArtifactRepositoryLayout layout =
(ArtifactRepositoryLayout) embedder.getContainer().lookup( ArtifactRepositoryLayout.ROLE,"default");
ArtifactRepositoryFactory factory =
(ArtifactRepositoryFactory) embedder.lookup(ArtifactRepositoryFactory.ROLE);
ArtifactRepository repository = factory.createDeploymentArtifactRepository(
id, url, layout, uniqueVersion);
mar.deploy(embedder,repository,listener);
embedder.stop();
return true;
} catch (MavenEmbedderException e) {
e.printStackTrace(listener.error(e.getMessage()));
} catch (ComponentLookupException e) {
e.printStackTrace(listener.error(e.getMessage()));
} catch (ArtifactDeploymentException e) {
e.printStackTrace(listener.error(e.getMessage()));
}
// failed
build.setResult(Result.FAILURE);
return true;
}
/**
* Obtains the {@link MavenAbstractArtifactRecord} that we'll work on.
* <p>
* This allows promoted-builds plugin to reuse the code for delayed deployment.
*/
protected MavenAbstractArtifactRecord getAction(AbstractBuild<?, ?> build) {
return build.getAction(MavenAbstractArtifactRecord.class);
}
public BuildStepDescriptor<Publisher> getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public DescriptorImpl() {
super(RedeployPublisher.class);
}
protected DescriptorImpl(Class<? extends Publisher> clazz) {
super(clazz);
}
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return jobType==MavenModuleSet.class;
}
public String getHelpFile() {
return "/help/maven/redeploy.html";
}
public RedeployPublisher newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return req.bindJSON(RedeployPublisher.class,formData);
}
public String getDisplayName() {
return Messages.RedeployPublisher_getDisplayName();
}
}
}
|
package net.meeusen.crypto;
import java.io.File;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.Certificate;
import java.util.Random;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import net.meeusen.util.ByteString;
public class TestKeyStores {
private static String pwd_entry = "our test entry password";
private static SecretKey testSecKey = null;
private static Certificate testCert = null;
static void doTest(KeyStore ks) throws Exception {
System.out.println("Start of test for KeyStore type " + ks.getType() + " of provider " + ks.getProvider());
ks.load(null, null);
trySetKeyEntry(ks, getOurTestSecretKey());
trySetCertEntry(ks, getOurTestCertificate());
}
public static void main(String[] args) throws Exception {
System.out.println("Testing capabilities of different keystore types");
KeyStore[] keyStoresToTest = new KeyStore[] { KeyStore.getInstance("jceks"), KeyStore.getInstance("jks"),
KeyStore.getInstance("PKCS12"), };
for (KeyStore ks : keyStoresToTest) {
doTest(ks);
}
}
private static void trySetKeyEntry(KeyStore ourks, Key ourkey) {
String message = "Storing " + ourkey.getClass() + " in " + ourks.getType() + " ";
System.out.print(message);
try {
String alias = getRandomAlias();
ourks.setKeyEntry(alias, ourkey, pwd_entry.toCharArray(), null);
System.out.println("SUCCEEDED for alias " + alias);
} catch (Exception e) {
System.out.println("FAILED. " + e.getMessage());
}
}
private static void trySetCertEntry(KeyStore ourks, Certificate c) {
String message = "Storing " + c.getClass() + " in " + ourks.getType() + " ";
System.out.print(message);
try {
String alias = getRandomAlias();
ourks.setCertificateEntry(alias, c);
System.out.println("SUCCEEDED for alias " + alias);
} catch (Exception e) {
System.out.println("FAILED. " + e.getMessage());
}
}
private static String getRandomAlias() {
Random rng = new Random();
byte[] ranbytes = new byte[8];
rng.nextBytes(ranbytes);
return new ByteString(ranbytes).toHexString();
}
private static SecretKey getOurTestSecretKey() throws NoSuchAlgorithmException, NoSuchProviderException {
if (testSecKey == null) {
testSecKey = KeyGenerator.getInstance("AES").generateKey();
}
return testSecKey;
}
private static Certificate getOurTestCertificate() throws Exception {
if (testCert == null) {
String basepath = System.getProperty("java.home");
File cacertfile = new File(basepath + "/lib/security/cacerts");
if (!cacertfile.exists()) {
throw new Exception("mmm");
}
KeyStore systemTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
systemTrustStore.load(new FileInputStream(cacertfile), "changeit".toCharArray());
String firstEntryAlias = systemTrustStore.aliases().nextElement();
testCert = systemTrustStore.getCertificate(firstEntryAlias);
}
return testCert;
}
}
|
package de.st_ddt.crazylogin;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import de.st_ddt.crazyplugin.exceptions.CrazyCommandErrorException;
import de.st_ddt.crazyplugin.exceptions.CrazyCommandException;
import de.st_ddt.crazyutil.ChatHelper;
import de.st_ddt.crazyutil.ObjectSaveLoadHelper;
import de.st_ddt.crazyutil.databases.ConfigurationDatabaseEntry;
import de.st_ddt.crazyutil.databases.FlatDatabaseEntry;
import de.st_ddt.crazyutil.databases.MySQLConnection;
import de.st_ddt.crazyutil.databases.MySQLDatabaseEntry;
public class LoginPlayerData implements ConfigurationDatabaseEntry, MySQLDatabaseEntry, FlatDatabaseEntry
{
private final String player;
private String password;
private final ArrayList<String> ips = new ArrayList<String>();
private boolean online;
private Date lastAction;
public LoginPlayerData(final Player player)
{
this(player.getName(), player.getAddress().getAddress().getHostAddress());
online = true;
lastAction = new Date();
}
public LoginPlayerData(final String player, final String ip)
{
super();
this.player = player;
ips.add(ip);
online = false;
lastAction = new Date();
}
// aus Config-Datenbank laden
public LoginPlayerData(final ConfigurationSection config, final String[] columnNames)
{
super();
final String colName = columnNames[0];
final String colPassword = columnNames[1];
final String colIPs = columnNames[2];
final String colAction = columnNames[3];
this.player = config.getString(colName);
this.password = config.getString(colPassword);
for (final String ip : config.getStringList(colIPs))
ips.add(ip);
lastAction = ObjectSaveLoadHelper.StringToDate(config.getString(colAction), new Date());
online = false;
}
// in Config-Datenbank speichern
@Override
public void saveToConfigDatabase(final ConfigurationSection config, final String path, final String[] columnNames)
{
final String colName = columnNames[0];
final String colPassword = columnNames[1];
final String colIPs = columnNames[2];
final String colAction = columnNames[3];
config.set(path + colName, this.player);
config.set(path + colPassword, this.password);
config.set(path + colIPs, this.ips);
config.set(path + colAction, lastAction);
}
// aus MySQL-Datenbank laden
public LoginPlayerData(final ResultSet rawData, final String[] columnNames)
{
super();
final String colName = columnNames[0];
final String colPassword = columnNames[1];
final String colIPs = columnNames[2];
final String colAction = columnNames[3];
String name = null;
try
{
name = rawData.getString(colName);
}
catch (final Exception e)
{
name = "ERROR";
e.printStackTrace();
}
finally
{
this.player = name;
}
try
{
password = rawData.getString(colPassword);
}
catch (final SQLException e)
{
password = "FAILEDLOADING";
e.printStackTrace();
}
try
{
final String ipsString = rawData.getString(colIPs);
if (ipsString != null)
{
final String[] ips = ipsString.split(",");
for (final String ip : ips)
this.ips.add(ip);
}
}
catch (final SQLException e)
{
e.printStackTrace();
}
try
{
lastAction = rawData.getTimestamp(colAction);
}
catch (final SQLException e)
{
e.printStackTrace();
}
online = false;
}
// in MySQL-Datenbank speichern
@Override
public void saveToMySQLDatabase(final MySQLConnection connection, final String table, final String[] columnNames)
{
Statement query = null;
final String colName = columnNames[0];
final String colPassword = columnNames[1];
final String colIPs = columnNames[2];
final String colAction = columnNames[3];
final String IPs = ChatHelper.listingString(",", ips);
try
{
query = connection.getConnection().createStatement();
final Timestamp timestamp = new Timestamp(lastAction.getTime());
query.executeUpdate("INSERT INTO " + table + " (" + colName + "," + colPassword + "," + colIPs + "," + colAction + ") VALUES ('" + player + "','" + password + "','" + IPs + "','" + timestamp + "') " + " ON DUPLICATE KEY UPDATE " + colPassword + "='" + password + "', " + colIPs + "='" + IPs + "'," + colAction + "='" + timestamp + "'");
}
catch (final SQLException e)
{
e.printStackTrace();
}
finally
{
if (query != null)
try
{
query.close();
}
catch (final SQLException e)
{}
connection.closeConnection();
}
}
// aus Flat-Datenbank laden
public LoginPlayerData(final String[] rawData)
{
super();
this.player = rawData[0];
this.password = rawData[1];
try
{
final String[] ips = rawData[2].split(",");
for (final String ip : ips)
this.ips.add(ip);
lastAction = ObjectSaveLoadHelper.StringToDate(rawData[3], new Date());
}
catch (final IndexOutOfBoundsException e)
{
lastAction = new Date();
}
online = false;
}
// in Flat-Datenbank speichern
@Override
public String[] saveToFlatDatabase()
{
final String[] strings = new String[4];
strings[0] = player;
strings[1] = password;
strings[2] = ChatHelper.listingString(",", ips);
if (strings[2].equals(""))
strings[2] = ".";
strings[3] = ObjectSaveLoadHelper.DateToString(lastAction);
return strings;
}
@Override
public String getName()
{
return player;
}
@Override
public int hashCode()
{
return player.toLowerCase().hashCode();
}
public void setPassword(final String password) throws CrazyCommandException
{
try
{
this.password = CrazyLogin.getPlugin().getEncryptor().encrypt(player, genSeed(), password);
}
catch (final UnsupportedEncodingException e)
{
throw new CrazyCommandErrorException(e);
}
catch (final NoSuchAlgorithmException e)
{
throw new CrazyCommandErrorException(e);
}
}
private String genSeed()
{
while (true)
{
final long value = Math.round(Math.random() * Long.MAX_VALUE);
final String seed = String.valueOf(value);
if (seed.length() > 11)
return seed.substring(1, 10);
}
}
public boolean isPassword(final String password)
{
return CrazyLogin.getPlugin().getEncryptor().match(player, password, this.password);
}
public void addIP(final String ip)
{
if (!ips.contains(ip))
ips.add(0, ip);
while (ips.size() > 5)
ips.remove(5);
}
public boolean hasIP(final String ip)
{
return ips.contains(ip);
}
protected void notifyAction()
{
lastAction = new Date();
}
public Date getLastActionTime()
{
return lastAction;
}
public boolean isOnline()
{
return online;
}
public boolean login(final String password)
{
this.online = isPassword(password);
if (online)
lastAction = new Date();
return online;
}
public void logout()
{
logout(false);
}
public void logout(final boolean removeIPs)
{
this.online = false;
lastAction = new Date();
if (removeIPs)
ips.clear();
}
}
|
package org.jetbrains.plugins.groovy;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.codeInsight.completion.CompletionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.compiler.GroovyCompiler;
import org.jetbrains.plugins.groovy.compiler.CompilationUnitsFactory;
import java.util.HashSet;
import java.util.Set;
/**
* Main application component, that loads Groovy language support
*
* @author Ilya.Sergey
*/
public class GroovyLoader implements ApplicationComponent {
@NotNull
public static final String GROOVY_EXTENTION = "groovy";
@NotNull
public static final String GVY_EXTENTION = "gvy";
@NotNull
public static final String GY_EXTENTION = "gy";
@NotNull
public static final String GROOVY_SCRIPT_EXTENTION = "gsh";
@NotNull
public static final Set<String> GROOVY_EXTENTIONS = new HashSet<String>();
static {
GROOVY_EXTENTIONS.add(GROOVY_EXTENTION);
GROOVY_EXTENTIONS.add(GVY_EXTENTION);
GROOVY_EXTENTIONS.add(GY_EXTENTION);
GROOVY_EXTENTIONS.add(GROOVY_SCRIPT_EXTENTION);
}
public GroovyLoader() {
}
public void initComponent() {
loadGroovy();
}
public static void loadGroovy() {
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
public void run() {
FileTypeManager.getInstance().registerFileType(GroovyFileType.GROOVY_FILE_TYPE, GROOVY_EXTENTIONS.toArray(new String[GROOVY_EXTENTIONS.size()]));
}
}
);
/*
CompletionUtil.registerCompletionData(ScalaFileType.SCALA_FILE_TYPE,
ScalaToolsFactory.getInstance().createScalaCompletionData());
*/
ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() {
public void projectOpened(Project project) {
CompilerManager compilerManager = CompilerManager.getInstance(project);
compilerManager.addCompiler(new GroovyCompiler(new CompilationUnitsFactory()));
compilerManager.addCompilableFileType(GroovyFileType.GROOVY_FILE_TYPE);
}
});
}
public void disposeComponent() {
}
@NotNull
public String getComponentName() {
return "groovy.support.loader";
}
}
|
package bakatxt.core;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
public class BakaTxtSession implements BakaTxtSessionInterface {
private static final String MESSAGE_ADD_NO_TITLE = "Invalid add command, please add a title!";
private static final String STRING_EMPTY = "";
private static final String STRING_SPACE = " ";
private static final String STRING_ADD = "@";
private static final String STRING_DASH = "
private static final String STRING_AT = "at";
private static final String STRING_ON = "on";
private static final String STRING_DASH_DATE = "-";
private static final String STRING_YEAR = "2014";
private static final String STRING_YEAR_FRAG = "20";
private static final String DATE_FORMAT_DDMMYY_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])[/-](\\d\\d)";
private static final String DATE_FORMAT_DDMMYYYY_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])[/-]((19|2[01])\\d\\d)";
private static final String DATE_FORMAT_DDMM_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])";
private static final String DATE_FORMAT_DIVIDER_REGEX = "[/-]";
private static final String DATE_FORMAT_STANDARD = "yyyy-MM-dd";
private static boolean _isDate;
private static boolean _isTime;
private static boolean _isVenue;
private static boolean _isDescription;
private static String _title;
private static String _date;
private static String _time;
private static String _venue;
private static String _description;
private static String _originalDateFormat;
private static String _originalTimeFormat;
private static String _originalDigitDateFormat;
Database database;
public BakaTxtSession(String fileName) {
database = new Database(fileName);
_isDate = false;
_isTime = false;
_isVenue = false;
_isDescription = false;
}
@Override
public String add(String input) {
// TODO Auto-generated method stub
String str = input;
if (str.contains(STRING_DASH)) {
str.replace(STRING_DASH + STRING_SPACE, STRING_DASH);
identifyDescription(str);
}
identifyDate(str);
if (_date != null) {
_isDate = true;
}
identifyTime(str);
if (_time != null) {
_isTime = true;
}
if (str.contains(STRING_ADD)) {
str = str.replace(STRING_ADD + STRING_SPACE, STRING_ADD);
identifyVenue(str);
}
identifyTitle(str);
if (_title.equals(STRING_EMPTY)) {
return MESSAGE_ADD_NO_TITLE;
}
Task task = new Task(_title);
task.addDate(_date);
task.addTime(_time);
task.addVenue(_venue);
task.addDescription(_description);
if (!_isDate && !_isTime) {
task.setFloating(true);
}
database.add(task);
return task.toDisplayString();
}
private String replaceDateTimeDescription(String input) {
String inputTemp = input;
if (_isDate) {
inputTemp = inputTemp.replace(_originalDateFormat, " ");
if (_originalDigitDateFormat != null) {
inputTemp = inputTemp.replace(_originalDigitDateFormat, " ");
}
}
if (_isTime) {
inputTemp = inputTemp.replace(_originalTimeFormat, " ");
}
if (_isDescription) {
String descriptionTemp = "--" + _description;
inputTemp = inputTemp.replace(descriptionTemp, " ");
}
return inputTemp;
}
private String removePrepositions(String input) {
String inputTemp = input;
String part[] = inputTemp.trim().split(STRING_SPACE);
if (part[part.length - 1].contains(STRING_ON)
|| part[part.length - 1].contains(STRING_AT)) {
inputTemp = inputTemp.replace(STRING_ON, STRING_EMPTY);
inputTemp = inputTemp.replace(STRING_AT, STRING_EMPTY);
}
return inputTemp;
}
private void identifyTitle(String input) {
String newInput = replaceDateTimeDescription(input);
String inputTemp = newInput;
if (_isVenue) {
String venueTemp = STRING_ADD + _venue;
inputTemp = inputTemp.replace(venueTemp, STRING_SPACE);
}
_title = removePrepositions(inputTemp).trim();
}
private void identifyDescription(String input) {
String[] part = input.split(STRING_DASH);
_description = part[1].trim();
_isDescription = true;
}
private void identifyVenue(String input) {
String newInput = replaceDateTimeDescription(input);
int index = newInput.indexOf(STRING_ADD) + 1;
_isVenue = true;
newInput = newInput.substring(index).trim();
_venue = removePrepositions(newInput).trim();
}
private void identifyDate(String input) {
Parser parser = new Parser();
String[] temp = input.split(STRING_SPACE);
String newDate;
String[] dateFragment;
try {
for (int i = 0; i < temp.length; i++) {
String messageFragment = temp[i];
String originalFragment = temp[i];
// dd/MM/YY or dd/MM/YYYY or dd/MM
if (messageFragment.matches(DATE_FORMAT_DDMMYYYY_REGEX)
|| messageFragment.matches(DATE_FORMAT_DDMMYY_REGEX)
|| messageFragment.matches(DATE_FORMAT_DDMM_REGEX)) {
// dd/MM
if (messageFragment.length() <= 5
&& messageFragment.length() > 2) {
messageFragment = messageFragment + STRING_DASH_DATE
+ STRING_YEAR;
}
dateFragment = messageFragment
.split(DATE_FORMAT_DIVIDER_REGEX);
if (dateFragment[2].length() == 2) {
dateFragment[2] = STRING_YEAR_FRAG + dateFragment[2];
}
newDate = dateFragment[2] + STRING_DASH_DATE
+ dateFragment[1] + STRING_DASH_DATE
+ dateFragment[0];
input = input.replace(originalFragment, newDate);
_originalDigitDateFormat = originalFragment;
}
}
List<DateGroup> dateGroup = parser.parse(input);
Date date = dateGroup.get(0).getDates().get(0);
_originalDateFormat = dateGroup.get(0).getText();
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
DATE_FORMAT_STANDARD);
String output = DATE_FORMAT.format(date);
_date = output;
} catch (Exception ex) {
_date = null;
}
}
private void identifyTime(String input) {
try {
if (_originalDigitDateFormat != null) {
input = input.replace(_originalDigitDateFormat, STRING_SPACE);
}
Parser parser = new Parser();
List<DateGroup> dateGroup = parser.parse(input);
Date timeStart = null;
Date timeEnd = null;
String output;
if (dateGroup.get(0).getDates().size() == 1) {
timeStart = dateGroup.get(0).getDates().get(0);
} else {
timeStart = dateGroup.get(0).getDates().get(0);
timeEnd = dateGroup.get(0).getDates().get(1);
}
_originalTimeFormat = dateGroup.get(0).getText();
SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HHmm");
String outputStart = TIME_FORMAT.format(timeStart);
if (timeEnd != null) {
String outputEnd = TIME_FORMAT.format(timeEnd);
output = outputStart + " - " + outputEnd;
} else {
output = outputStart;
}
_time = output;
} catch (Exception ex) {
_time = null;
}
}
@Override
public String delete(String input) {
// TODO Auto-generated method stub
return null;
}
@Override
public String display(String input) {
// TODO Auto-generated method stub
return null;
}
@Override
public String display() {
// TODO Auto-generated method stub
return null;
}
@Override
public void sort() {
// TODO Auto-generated method stub
}
@Override
public void exit() {
// TODO Auto-generated method stub
}
@Override
public String getFileName() {
return database.getFileName();
}
@Override
public String getPrevious() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getTotal() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getUndone() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getDone() {
// TODO Auto-generated method stub
return null;
}
@Override
public String done(String input) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getTask(String title) {
// TODO Auto-generated method stub
return null;
}
@Override
public String deleteDone() {
// TODO Auto-generated method stub
return null;
}
}
|
package battleships.gui;
import battleships.model.Square;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JPanel;
/**
* The JPanel which displays the ship.
* <p>
* This class is a panel that displays a ship which it is passed to. The grid is
* resized and scaled automatically based on it's size and the squares of the
* ship.
* <p>
* @author Shen Yichen <2007.yichen@gmail.com>
* @since v1.0.0
*/
public class ShipDisplay extends JPanel {
private int cols;
private int rows;
private Iterable<Square> ship;
/**
* Creates a new ShipDisplay.
*/
public ShipDisplay() {
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (ship != null && rows > 0 && cols > 0) {
final Graphics2D g2 = (Graphics2D) g.create();
try {
//Draw grid
double sqrSize = Math.min((getWidth() - 2) * 1.0 / cols, (getHeight() - 2) * 1.0 / rows);
double xOffset = (getWidth() - sqrSize * cols) / 2;
double yOffset = (getHeight() - sqrSize * rows) / 2;
for (int x = 0; x <= cols; x++) {
double xSquareStart = x * sqrSize;
Line2D.Double xGrid = new Line2D.Double(xSquareStart + xOffset, yOffset, xSquareStart + xOffset, rows * sqrSize + yOffset);
g2.draw(xGrid);
}
for (int y = 0; y <= rows; y++) {
double ySquareStart = y * sqrSize;
Line2D.Double yGrid = new Line2D.Double(xOffset, ySquareStart + yOffset, cols * sqrSize + xOffset, ySquareStart + yOffset);
g2.draw(yGrid);
}
//End of draw grid
} finally {
g2.dispose();
}
}
}
}
|
package com.health.input;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.health.Table;
/**
* Implements a parser for xls input files.
*
*/
public class XlsParser implements Parser {
private ArrayList<Row> list;
/**
* Given a path to a xls file and an input descriptor, parses the input file into a {@link Table}.
*
* @param path
* the path of the input file.
* @param config
* the input descriptor.
* @return a table representing the parsed input file.
* @throws IOException
* if any IO errors occur.
* @throws InputException
* if any input errors occur.
*/
@Override
public Table parse(String path, InputDescriptor config) throws InputException, IOException {
Objects.requireNonNull(path);
Objects.requireNonNull(config);
Table table = config.buildTable();
FileInputStream io = new FileInputStream(path);
HSSFWorkbook wb = new HSSFWorkbook(io);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
list.add(row);
}
wb.close();
return table;
}
}
|
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name implements Comparable {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_EXTENDED = 0x40;
private static final int LABEL_MASK = 0xC0;
private static final int EXT_LABEL_BITSTRING = 1;
private Object [] name;
private byte offset;
private byte labels;
private boolean qualified;
private boolean hasBitString;
private int hashcode;
/** The root name */
public static final Name root = Name.fromConstantString(".");
/** The maximum number of labels in a Name */
static final int MAXLABELS = 128;
/* The number of labels initially allocated. */
private static final int STARTLABELS = 4;
/* Used for printing non-printable characters */
private static final DecimalFormat byteFormat = new DecimalFormat();
/* Used to efficiently convert bytes to lowercase */
private static final byte lowercase[] = new byte[256];
/* Used in wildcard names. */
private static final Name wildcardName = Name.fromConstantString("*");
private static final byte wildcardLabel[] = (byte []) wildcardName.name[0];
static {
byteFormat.setMinimumIntegerDigits(3);
for (int i = 0; i < lowercase.length; i++) {
if (i < 'A' || i > 'Z')
lowercase[i] = (byte)i;
else
lowercase[i] = (byte)(i - 'A' + 'a');
}
}
private
Name() {
}
private final void
grow(int n) {
if (n > MAXLABELS)
throw new ArrayIndexOutOfBoundsException("name too long");
Object [] newarray = new Object[n];
System.arraycopy(name, 0, newarray, 0, labels);
name = newarray;
}
private final void
grow() {
grow(labels * 2);
}
private final void
compact() {
for (int i = labels - 1 + offset; i > offset; i
if (!(name[i] instanceof BitString) ||
!(name[i - 1] instanceof BitString))
continue;
BitString bs = (BitString) name[i];
BitString bs2 = (BitString) name[i - 1];
if (bs.nbits == 256)
continue;
int nbits = bs.nbits + bs2.nbits;
bs.join(bs2);
if (nbits <= 256) {
System.arraycopy(name, i, name, i - 1, labels - i);
labels
}
}
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is unqualified, the origin to be appended
* @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s, Name origin) {
Name n;
try {
n = Name.fromString(s, origin);
}
catch (TextParseException e) {
StringBuffer sb = new StringBuffer();
sb.append(s);
if (origin != null) {
sb.append(".");
sb.append(origin);
}
sb.append(": ");
sb.append(e.getMessage());
System.err.println(sb.toString());
name = null;
labels = 0;
return;
}
labels = n.labels;
name = n.name;
qualified = n.qualified;
if (!qualified) {
/*
* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
if (Options.check("pqdn"))
qualified = false;
else
qualified = (labels > 1);
}
}
/**
* Create a new name from a string
* @param s The string to be converted
* @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from a string and an origin. This does not automatically
* make the name absolute; it will be absolute if it has a trailing dot or an
* absolute origin is appended.
* @param s The string to be converted
* @param origin If the name is unqualified, the origin to be appended.
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
name.labels = 0;
name.name = new Object[1];
if (s.equals("@")) {
if (origin != null)
return origin;
else
return name;
} else if (s.equals(".")) {
name.qualified = true;
return name;
}
int labelstart = -1;
int pos = 0;
byte [] label = new byte[64];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean bitstring = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (pos == 0 && b == '[')
bitstring = true;
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10 + (b - '0');
intval += (b - '0');
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= label.length)
throw new TextParseException("label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
byte [] newlabel = new byte[pos];
System.arraycopy(label, 0, newlabel, 0, pos);
if (name.labels == MAXLABELS)
throw new TextParseException("too many labels");
if (name.labels == name.name.length)
name.grow();
if (bitstring) {
bitstring = false;
name.name[name.labels++] =
new BitString(newlabel);
name.hasBitString = true;
}
else
name.name[name.labels++] = newlabel;
labelstart = -1;
pos = 0;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= label.length)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1)
name.qualified = true;
else {
byte [] newlabel = new byte[pos];
System.arraycopy(label, 0, newlabel, 0, pos);
if (name.labels == MAXLABELS)
throw new TextParseException("too many labels");
if (name.labels == name.name.length)
name.grow();
if (bitstring) {
bitstring = false;
name.name[name.labels++] = new BitString(newlabel);
name.hasBitString = true;
}
else
name.name[name.labels++] = newlabel;
}
if (name.hasBitString)
name.compact();
if (origin != null)
return concatenate(name, origin);
return (name);
}
/**
* Create a new name from a string. This does not automatically make the name
* absolute; it will be absolute if it has a trailing dot.
* @param s The string to be converted
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s) throws TextParseException {
return fromString(s, null);
}
public static Name
fromConstantString(String s) {
try {
return fromString(s, null);
}
catch (TextParseException e) {
throw new IllegalArgumentException("Invalid name '" + s + "'");
}
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
*/
public
Name(DataByteInputStream in) throws IOException {
int len, start, pos, count = 0, savedpos;
Name name2;
labels = 0;
name = new Object[STARTLABELS];
start = in.getPos();
loop:
while ((len = in.readUnsignedByte()) != 0) {
count++;
switch(len & LABEL_MASK) {
case LABEL_NORMAL:
byte [] b = new byte[len];
in.read(b);
if (labels == name.length)
grow();
name[labels++] = b;
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
if (Options.check("verbosecompression"))
System.err.println("currently " + in.getPos() +
", pointer to " + pos);
if (pos >= in.getPos())
throw new WireParseException("bad compression");
savedpos = in.getPos();
in.setPos(pos);
if (Options.check("verbosecompression"))
System.err.println("current name '" + this +
"', seeking to " + pos);
try {
name2 = new Name(in);
}
finally {
in.setPos(savedpos);
}
if (labels + name2.labels > name.length)
grow(labels + name2.labels);
System.arraycopy(name2.name, 0, name, labels,
name2.labels);
labels += name2.labels;
break loop;
case LABEL_EXTENDED:
int type = len & ~LABEL_MASK;
switch (type) {
case EXT_LABEL_BITSTRING:
int bits = in.readUnsignedByte();
if (bits == 0)
bits = 256;
int bytes = (bits + 7) / 8;
byte [] data = new byte[bytes];
in.read(data);
if (labels == name.length)
grow();
name[labels++] = new BitString(bits, data);
hasBitString = true;
break;
default:
throw new WireParseException(
"Unknown name format");
} /* switch */
break;
} /* switch */
}
qualified = true;
if (hasBitString)
compact();
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param src An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
public
Name(Name src, int n) {
name = src.name;
offset = (byte)(src.offset + n);
labels = (byte)(src.labels - n);
qualified = src.qualified;
if (!src.hasBitString)
hasBitString = false;
else {
for (int i = 0; i < labels; i++)
if (name[i + offset] instanceof BitString)
hasBitString = true;
}
}
/**
* Creates a new name by concatenating two existing names.
* @param prefix The prefix name.
* @param suffix The suffix name.
* @return The concatenated name.
*/
public static Name
concatenate(Name prefix, Name suffix) {
if (prefix.qualified)
return (prefix);
int nlabels = prefix.labels + suffix.labels;
if (nlabels > MAXLABELS)
return null;
Name newname = new Name();
newname.labels = (byte)nlabels;
newname.name = new Object[nlabels];
System.arraycopy(prefix.name, prefix.offset, newname.name,
0, prefix.labels);
System.arraycopy(suffix.name, suffix.offset, newname.name,
prefix.labels, suffix.labels);
newname.qualified = suffix.qualified;
newname.hasBitString = (prefix.hasBitString || suffix.hasBitString);
if (newname.hasBitString)
newname.compact();
return newname;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
return concatenate(wildcardName, new Name(this, n));
}
/**
* Generates a new Name to be used when following a DNAME.
* @return The new name, or null if the DNAME is invalid.
*/
public Name
fromDNAME(DNAMERecord dname) {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
int nlabels;
int saved;
if (!subdomain(dnameowner))
return null;
saved = labels - dnameowner.labels;
nlabels = saved + dnametarget.labels;
if (nlabels > MAXLABELS)
return null;
Name newname = new Name();
newname.labels = (byte)nlabels;
newname.name = new Object[labels];
System.arraycopy(this.name, 0, newname.name, 0, saved);
System.arraycopy(dnametarget.name, 0, newname.name, saved,
dnametarget.labels);
newname.qualified = true;
for (int i = 0; i < newname.labels; i++)
if (newname.name[i] instanceof BitString)
newname.hasBitString = true;
if (newname.hasBitString)
newname.compact();
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels == 0 || (name[0] instanceof BitString))
return false;
if (name[0] == wildcardLabel)
return true;
byte [] b = (byte []) name[0];
return (b.length == 1 && b[0] == '*');
}
/**
* Is this name fully qualified?
*/
public boolean
isQualified() {
return qualified;
}
/**
* The length of the name.
*/
public short
length() {
short total = 0;
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString)
total += (((BitString)name[i]).bytes() + 2);
else
total += (((byte [])name[i]).length + 1);
}
return ++total;
}
/**
* The number of labels in the name.
*/
public byte
labels() {
return labels;
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
if (domain == null || domain.labels > labels)
return false;
Name tname = new Name(this, labels - domain.labels);
return (tname.equals(domain));
}
private String
byteString(byte [] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
/* Ick. */
short b = (short)(array[i] & 0xFF);
if (b <= 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
}
else if (b == '"' || b == '(' || b == ')' || b == '.' ||
b == ';' || b == '\\' || b == '@' || b == '$')
{
sb.append('\\');
sb.append((char)b);
}
else
sb.append((char)b);
}
return sb.toString();
}
/**
* Convert Name to a String
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
if (labels == 0)
sb.append(".");
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString)
sb.append(name[i]);
else
sb.append(byteString((byte [])name[i]));
if (qualified || i < labels)
sb.append(".");
}
return sb.toString();
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String
*/
public String
getLabelString(int n) {
n += offset;
if (name[n] instanceof BitString)
return name[n].toString();
else
return byteString((byte [])name[n]);
}
/**
* Convert Name to DNS wire format
*/
public void
toWire(DataByteOutputStream out, Compression c) throws IOException {
for (int i = offset; i < labels + offset; i++) {
Name tname;
if (i == offset)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null)
pos = c.get(tname);
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
}
else {
if (c != null)
c.add(out.getPos(), tname);
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED |
EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else
out.writeString((byte []) name[i]);
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public void
toWireCanonical(DataByteOutputStream out) throws IOException {
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else {
byte [] b = (byte []) name[i];
byte [] bc = new byte[b.length];
for (int j = 0; j < b.length; j++)
bc[j] = lowercase[b[j]];
out.writeString(bc);
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public byte []
toWireCanonical() throws IOException {
DataByteOutputStream out = new DataByteOutputStream();
toWireCanonical(out);
return out.toByteArray();
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == this)
return true;
if (arg == null || !(arg instanceof Name))
return false;
Name d = (Name) arg;
if (d.labels != labels)
return false;
for (int i = 0; i < labels; i++) {
Object nobj = name[offset + i];
Object dnobj = d.name[d.offset + i];
if (nobj.getClass() != dnobj.getClass())
return false;
if (nobj instanceof BitString) {
if (!nobj.equals(dnobj))
return false;
} else {
byte [] b1 = (byte []) nobj;
byte [] b2 = (byte []) dnobj;
if (b1.length != b2.length)
return false;
for (int j = 0; j < b1.length; j++) {
if (lowercase[b1[j]] != lowercase[b2[j]])
return false;
}
}
}
return true;
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
if (hashcode != 0)
return (hashcode);
int code = labels;
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString) {
BitString b = (BitString) name[i];
for (int j = 0; j < b.bytes(); j++)
code += ((code << 3) + b.data[j]);
}
else {
byte [] b = (byte []) name[i];
for (int j = 0; j < b.length; j++)
code += ((code << 3) + lowercase[b[j]]);
}
}
hashcode = code;
return hashcode;
}
/**
* Compares this Name to another Object.
* @param The Object to be compared.
* @return The value 0 if the argument is a name equivalent to this name;
* a value less than 0 if the argument is less than this name in the canonical
* ordering, and a value greater than 0 if the argument is greater than this
* name in the canonical ordering.
* @throws ClassCastException if the argument is not a Name.
*/
public int
compareTo(Object o) {
Name arg = (Name) o;
if (this == arg)
return (0);
int compares = labels > arg.labels ? arg.labels : labels;
for (int i = 1; i <= compares; i++) {
Object label = name[labels - i + offset];
Object alabel = arg.name[arg.labels - i + arg.offset];
if (label.getClass() != alabel.getClass()) {
if (label instanceof BitString)
return (-1);
else
return (1);
}
if (label instanceof BitString) {
BitString bs = (BitString)label;
BitString abs = (BitString)alabel;
int bits = bs.nbits > abs.nbits ? abs.nbits : bs.nbits;
int n = bs.compareBits(abs, bits);
if (n != 0)
return (n);
if (bs.nbits == abs.nbits)
continue;
/*
* If label X has more bits than label Y, then the
* name with X is greater if Y is the first label
* of its name. Otherwise, the name with Y is greater.
*/
if (bs.nbits > abs.nbits)
return (i == arg.labels ? 1 : -1);
else
return (i == labels ? -1 : 1);
}
else {
byte [] b = (byte []) label;
byte [] ab = (byte []) alabel;
for (int j = 0; j < b.length && j < ab.length; j++) {
int n = lowercase[b[j]] - lowercase[ab[j]];
if (n != 0)
return (n);
}
if (b.length != ab.length)
return (b.length - ab.length);
}
}
return (labels - arg.labels);
}
}
|
package org.xbill.DNS;
import java.io.*;
import java.net.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* Transaction signature handling. This class generates and verifies
* TSIG records on messages, which provide transaction security,
* @see TSIGRecord
*
* @author Brian Wellington
*/
public class TSIG {
/**
* The domain name representing the HMAC-MD5 algorithm (the only supported
* algorithm)
*/
public static final String HMAC = "HMAC-MD5.SIG-ALG.REG.INT";
private Name name;
private byte [] key;
private hmacSigner axfrSigner = null;
/**
* Creates a new TSIG object, which can be used to sign or verify a message.
* @param name The name of the shared key
* @param key The shared key's data
*/
public
TSIG(String name, byte [] key) {
this.name = new Name(name);
this.key = key;
}
/**
* Generates a TSIG record for a message and adds it to the message
* @param m The message
* @param old If this message is a response, the TSIG from the request
*/
public void
apply(Message m, TSIGRecord old) throws IOException {
Date timeSigned = new Date();
short fudge = 300;
hmacSigner h = new hmacSigner(key);
Name alg = new Name(HMAC);
try {
if (old != null) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(old.getSignature());
}
/* Digest the message */
h.addData(m.toWire());
DataByteOutputStream out = new DataByteOutputStream();
name.toWireCanonical(out);
out.writeShort(DClass.ANY); /* class */
out.writeInt(0); /* ttl */
alg.toWireCanonical(out);
long time = timeSigned.getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(fudge);
out.writeShort(0); /* No error */
out.writeShort(0); /* No other data */
h.addData(out.toByteArray());
}
catch (IOException e) {
return;
}
Record r = new TSIGRecord(name, DClass.ANY, 0, alg, timeSigned, fudge,
h.sign(), m.getHeader().getID(),
Rcode.NOERROR, null);
m.addRecord(r, Section.ADDITIONAL);
}
/**
* Verifies a TSIG record on an incoming message. Since this is only called
* in the context where a TSIG is expected to be present, it is an error
* if one is not present.
* @param m The message
* @param b The message in unparsed form. This is necessary since TSIG
* signs the message in wire format, and we can't recreate the exact wire
* format (with the same name compression).
* @param old If this message is a response, the TSIG from the request
*/
public boolean
verify(Message m, byte [] b, TSIGRecord old) {
TSIGRecord tsig = m.getTSIG();
hmacSigner h = new hmacSigner(key);
if (tsig == null)
return false;
/*System.out.println("found TSIG");*/
try {
if (old != null && tsig.getError() == Rcode.NOERROR) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(old.getSignature());
/*System.out.println("digested query TSIG");*/
}
m.getHeader().decCount(Section.ADDITIONAL);
byte [] header = m.getHeader().toWire();
m.getHeader().incCount(Section.ADDITIONAL);
h.addData(header);
int len = b.length - header.length;
len -= tsig.wireLength;
h.addData(b, header.length, len);
/*System.out.println("digested message");*/
DataByteOutputStream out = new DataByteOutputStream();
tsig.getName().toWireCanonical(out);
out.writeShort(tsig.dclass);
out.writeInt(tsig.ttl);
tsig.getAlg().toWireCanonical(out);
long time = tsig.getTimeSigned().getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(tsig.getFudge());
out.writeShort(tsig.getError());
if (tsig.getOther() != null) {
out.writeShort(tsig.getOther().length);
out.write(tsig.getOther());
}
else
out.writeShort(0);
h.addData(out.toByteArray());
/*System.out.println("digested variables");*/
}
catch (IOException e) {
return false;
}
if (axfrSigner != null) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)tsig.getSignature().length);
axfrSigner.addData(dbs.toByteArray());
axfrSigner.addData(tsig.getSignature());
}
if (h.verify(tsig.getSignature()))
return true;
else
return false;
}
/** Prepares the TSIG object to verify an AXFR */
public void
verifyAXFRStart() {
axfrSigner = new hmacSigner(key);
}
/**
* Verifies a TSIG record on an incoming message that is part of an AXFR.
* TSIG records must be present on the first and last messages, and
* at least every 100 records in between (the last rule is not enforced).
* @param m The message
* @param b The message in unparsed form
* @param old The TSIG from the AXFR request
* @param required True if this message is required to include a TSIG.
* @param first True if this message is the first message of the AXFR
*/
public boolean
verifyAXFR(Message m, byte [] b, TSIGRecord old,
boolean required, boolean first)
{
TSIGRecord tsig = m.getTSIG();
hmacSigner h = axfrSigner;
if (first)
return verify(m, b, old);
try {
if (tsig != null)
m.getHeader().decCount(Section.ADDITIONAL);
byte [] header = m.getHeader().toWire();
if (tsig != null)
m.getHeader().incCount(Section.ADDITIONAL);
h.addData(header);
int len = b.length - header.length;
if (tsig != null)
len -= tsig.wireLength;
h.addData(b, header.length, len);
if (tsig == null) {
if (required)
return false;
else
return true;
}
DataByteOutputStream out = new DataByteOutputStream();
long time = tsig.getTimeSigned().getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(tsig.getFudge());
h.addData(out.toByteArray());
}
catch (IOException e) {
return false;
}
if (h.verify(tsig.getSignature()) == false) {
return false;
}
h.clear();
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(tsig.getSignature());
return true;
}
}
|
package org.xbill.DNS;
import org.xbill.DNS.utils.*;
/**
* Constants and functions relating to DNS Types
*
* @author Brian Wellington
*/
public final class Type {
private static StringValueTable types = new StringValueTable();
/** Address */
public static final short A = 1;
/** Name server */
public static final short NS = 2;
/** Mail destination */
public static final short MD = 3;
/** Mail forwarder */
public static final short MF = 4;
/** Canonical name (alias) */
public static final short CNAME = 5;
/** Start of authority */
public static final short SOA = 6;
/** Mailbox domain name */
public static final short MB = 7;
/** Mail group member */
public static final short MG = 8;
/** Mail rename name */
public static final short MR = 9;
/** Null record */
public static final short NULL = 10;
/** Well known services */
public static final short WKS = 11;
/** Domain name pointer */
public static final short PTR = 12;
/** Host information */
public static final short HINFO = 13;
/** Mailbox information */
public static final short MINFO = 14;
/** Mail routing information */
public static final short MX = 15;
/** Text strings */
public static final short TXT = 16;
/** Responsible person */
public static final short RP = 17;
/** AFS cell database */
public static final short AFSDB = 18;
/** X_25 calling address */
public static final short X25 = 19;
/** ISDN calling address */
public static final short ISDN = 20;
/** Router */
public static final short RT = 21;
/** NSAP address */
public static final short NSAP = 22;
/** Reverse NSAP address (deprecated) */
public static final short NSAP_PTR = 23;
/** Signature */
public static final short SIG = 24;
/** Key */
public static final short KEY = 25;
/** X.400 mail mapping */
public static final short PX = 26;
/** Geographical position (withdrawn) */
public static final short GPOS = 27;
/** IPv6 address (old) */
public static final short AAAA = 28;
/** Location */
public static final short LOC = 29;
/** Next valid name in zone */
public static final short NXT = 30;
/** Endpoint identifier */
public static final short EID = 31;
/** Nimrod locator */
public static final short NIMLOC = 32;
/** Server selection */
public static final short SRV = 33;
/** ATM address */
public static final short ATMA = 34;
/** Naming authority pointer */
public static final short NAPTR = 35;
/** Key exchange */
public static final short KX = 36;
/** Certificate */
public static final short CERT = 37;
/** IPv6 address */
public static final short A6 = 38;
/** Non-terminal name redirection */
public static final short DNAME = 39;
/** Kitchen sink record - free form binary record (and a bad idea) */
public static final short SINK = 40;
/** Options - contains EDNS metadata */
public static final short OPT = 41;
/** Transaction key - used to compute a shared secret or exchange a key */
public static final short TKEY = 249;
/** Transaction signature */
public static final short TSIG = 250;
/** Incremental zone transfer */
public static final short IXFR = 251;
/** Zone transfer */
public static final short AXFR = 252;
/** Transfer mailbox records */
public static final short MAILB = 253;
/** Transfer mail agent records */
public static final short MAILA = 254;
/** Matches any type */
public static final short ANY = 255;
/** Address */
static {
types.put2(A, "A");
types.put2(NS, "NS");
types.put2(MD, "MD");
types.put2(MF, "MF");
types.put2(CNAME, "CNAME");
types.put2(SOA, "SOA");
types.put2(MB, "MB");
types.put2(MG, "MG");
types.put2(MR, "MR");
types.put2(NULL, "NULL");
types.put2(WKS, "WKS");
types.put2(PTR, "PTR");
types.put2(HINFO, "HINFO");
types.put2(MINFO, "MINFO");
types.put2(MX, "MX");
types.put2(TXT, "TXT");
types.put2(RP, "RP");
types.put2(AFSDB, "AFSDB");
types.put2(X25, "X25");
types.put2(ISDN, "ISDN");
types.put2(RT, "RT");
types.put2(NSAP, "NSAP");
types.put2(NSAP_PTR, "NSAP_PTR");
types.put2(SIG, "SIG");
types.put2(KEY, "KEY");
types.put2(PX, "PX");
types.put2(GPOS, "GPOS");
types.put2(AAAA, "AAAA");
types.put2(LOC, "LOC");
types.put2(NXT, "NXT");
types.put2(EID, "EID");
types.put2(NIMLOC, "NIMLOC");
types.put2(SRV, "SRV");
types.put2(ATMA, "ATMA");
types.put2(NAPTR, "NAPTR");
types.put2(KX, "KX");
types.put2(CERT, "CERT");
types.put2(A6, "A6");
types.put2(DNAME, "DNAME");
types.put2(SINK, "SINK");
types.put2(OPT, "OPT");
types.put2(TKEY, "TKEY");
types.put2(TSIG, "TSIG");
types.put2(IXFR, "IXFR");
types.put2(AXFR, "AXFR");
types.put2(MAILB, "MAILB");
types.put2(MAILA, "MAILA");
types.put2(ANY, "ANY");
}
private
Type() {
}
/** Converts a numeric Type into a String */
public static String
string(int i) {
String s = types.getString(i);
return (s != null) ? s : new Integer(i).toString();
}
/** Converts a String representation of an Type into its numeric value */
public static short
value(String s) {
short i = (short) types.getValue(s.toUpperCase());
if (i >= 0)
return i;
try {
return Short.parseShort(s);
}
catch (Exception e) {
return (-1);
}
}
/** Is this type valid for a record (a non-meta type)? */
public static boolean
isRR(int type) {
switch (type) {
case OPT:
case TKEY:
case TSIG:
case IXFR:
case AXFR:
case MAILB:
case MAILA:
case ANY:
return false;
default:
return true;
}
}
}
|
package com.qwertygid.deutschsim.GUI;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.MouseEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.event.MouseInputListener;
import com.qwertygid.deutschsim.Logic.Circuit;
import com.qwertygid.deutschsim.Logic.Gate;
import com.qwertygid.deutschsim.Logic.Table;
import com.qwertygid.deutschsim.Miscellaneous.Tools;
public class GateTable extends JPanel{
private static final long serialVersionUID = 3779004937588318481L;
public GateTable(final int gate_table_cell_size, final int gate_table_row_height,
final JFrame frame) {
table = new Table<Gate>();
this.gate_table_cell_size = gate_table_cell_size;
this.gate_table_row_height = gate_table_row_height;
this.gate_table_col_width = gate_table_cell_size + 2;
dot_image = new ImageIcon(getClass().getResource(Tools.dot_image_path));
setBackground(Color.WHITE);
handler = new MouseHandler(this);
addMouseListener(handler);
addMouseMotionListener(handler);
setTransferHandler(new GateTableTransferHandler(frame, this));
table.add_col();
update_size();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
for (int y = gate_table_row_height / 2; y < get_canvas_height(); y += gate_table_row_height) {
g2d.drawLine(0, y, get_canvas_width(), y);
}
for (int row = 0; row < table.get_row_count(); row++)
for (int col = 0; col < table.get_col_count(); col++) {
Gate gate = table.get_element(row, col);
if (gate != null) {
final int x = gate_table_col_width * col, y = gate_table_row_height * row,
gate_height = gate_table_row_height * (gate.get_ports_number() - 1) + gate_table_cell_size;
g2d.setStroke(new BasicStroke(1));
g2d.setColor(Color.WHITE);
g2d.fillRect(x + 1, y + 1, gate_table_cell_size - 1, gate_height - 1);
g2d.setColor(Color.BLACK);
g2d.drawRect(x, y, gate_table_cell_size, gate_height);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (gate.get_id().equals(Tools.CONTROL_ID))
dot_image.paintIcon(this, g2d, x, y);
else {
g2d.setFont(Tools.gate_font);
FontRenderContext frc = g2d.getFontRenderContext();
final int text_width = (int) Tools.gate_font.getStringBounds(gate.get_id(), frc).
getWidth();
LineMetrics lm = Tools.gate_font.getLineMetrics(gate.get_id(), frc);
final int text_height = (int) (lm.getAscent() + lm.getDescent());
final int text_x = x + (gate_table_cell_size - text_width) / 2,
text_y = (int) (y + (gate_height + text_height) / 2 - lm.getDescent());
// TODO add text cut-off
g2d.drawString(gate.get_id(), text_x, text_y);
}
}
}
if (handler.get_last_mouse_point() != null) {
g2d.setStroke(new BasicStroke(1));
final int x = handler.get_last_mouse_point().x - handler.get_last_mouse_point().x % gate_table_col_width,
y = handler.get_last_mouse_point().y - handler.get_last_mouse_point().y % gate_table_row_height;
Color inner_transparent = new Color(255, 0, 0, 255 / 4);
g2d.setColor(inner_transparent);
g2d.fillRect(x, y, gate_table_cell_size, gate_table_cell_size);
g2d.setColor(Color.RED);
g2d.drawRect(x, y, gate_table_cell_size, gate_table_cell_size);
}
}
public void update_size() {
setPreferredSize(new Dimension(get_canvas_width(), get_canvas_height()));
revalidate();
}
public void set_table(final Table<Gate> table) {
if (!table.valid())
throw new RuntimeException("Provided table is not valid");
this.table = table;
}
public Table<Gate> get_table() {
return table;
}
public int get_gate_table_row_height() {
return gate_table_row_height;
}
public int get_gate_table_col_width() {
return gate_table_col_width;
}
private int get_canvas_width() {
return table.get_col_count() * gate_table_col_width;
}
private int get_canvas_height() {
return table.get_row_count() * gate_table_row_height;
}
private Table<Gate> table;
private final int gate_table_cell_size, gate_table_row_height, gate_table_col_width;
private final ImageIcon dot_image;
private final MouseHandler handler;
private static class MouseHandler implements MouseInputListener {
public MouseHandler(final GateTable table) {
this.table = table;
}
@Override
public void mouseClicked(MouseEvent ev) {
if (SwingUtilities.isRightMouseButton(ev)) {
final int row = last_mouse_point.y / table.get_gate_table_row_height(),
col = last_mouse_point.x / table.get_gate_table_col_width();
for (int first_row = row; first_row >= 0; first_row
final Gate current = table.get_table().get_element(first_row, col);
if (current != null && row - first_row + 1 <= current.get_ports_number()) {
table.get_table().remove_element(first_row, col);
if (table.get_table().get_col_count() > 1 &&
col == table.get_table().get_col_count() - 2 &&
table.get_table().is_col_empty(col)) {
// Delete unnecessary empty columns
for (int current_col = col; current_col >= 0; current_col
if (table.get_table().is_col_empty(current_col))
table.get_table().remove_last_col();
else
break;
table.update_size();
}
table.repaint();
break;
}
}
table.repaint();
}
}
@Override
public void mouseEntered(MouseEvent ev) {
last_mouse_point = ev.getPoint();
}
@Override
public void mouseExited(MouseEvent ev) {
last_mouse_point = null;
table.repaint();
}
@Override
public void mousePressed(MouseEvent ev) {
}
@Override
public void mouseReleased(MouseEvent ev) {
}
@Override
public void mouseDragged(MouseEvent ev) {
mouse_move_action(ev.getPoint());
}
@Override
public void mouseMoved(MouseEvent ev) {
mouse_move_action(ev.getPoint());
}
public Point get_last_mouse_point() {
return last_mouse_point;
}
private void mouse_move_action(final Point point) {
last_mouse_point = point;
table.repaint();
}
private Point last_mouse_point;
private final GateTable table;
}
private static class GateTableTransferHandler extends TransferHandler {
private static final long serialVersionUID = 1978163502085092717L;
public GateTableTransferHandler(final JFrame frame, final GateTable table) {
this.frame = frame;
this.table = table;
}
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(GateTransferable.GATE_DATA_FLAVOR);
}
@Override
public boolean importData(TransferSupport support) {
if (canImport(support)) {
try {
Transferable transferable = support.getTransferable();
Object value = transferable.getTransferData(GateTransferable.GATE_DATA_FLAVOR);
if (value instanceof Gate) {
Gate gate = (Gate) value;
Point drop_location = support.getDropLocation().getDropPoint();
final int row = drop_location.y / table.get_gate_table_row_height(),
col = drop_location.x / table.get_gate_table_col_width();
table.get_table().insert_element(gate, row, col);
try {
// Circuit constructor automatically calls valid() on itself
// and throws an exception if valid() returns false
new Circuit(table.get_table());
} catch(RuntimeException ex) {
table.get_table().remove_element(row, col);
return false;
}
if (col == table.get_table().get_col_count() - 1) {
table.get_table().add_col();
table.update_size();
}
table.repaint();
}
} catch (UnsupportedFlavorException | IOException | NullPointerException ex) {
Tools.error(frame, "Failed to import data into the gate table");
}
}
return false;
}
private final JFrame frame;
private final GateTable table;
}
}
|
package de.duenndns.ssl;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.util.SparseArray;
import android.os.Handler;
import java.io.File;
import java.security.cert.*;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* A X509 trust manager implementation which asks the user about invalid
* certificates and memorizes their decision.
* <p>
* The certificate validity is checked using the system default X509
* TrustManager, creating a query Dialog if the check fails.
* <p>
* <b>WARNING:</b> This only works if a dedicated thread is used for
* opening sockets!
*/
public class MemorizingTrustManager implements X509TrustManager {
final static String TAG = "MemorizingTrustManager";
final static String DECISION_INTENT = "de.duenndns.ssl.DECISION";
final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId";
final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert";
final static String DECISION_INTENT_CHOICE = DECISION_INTENT + ".decisionChoice";
private final static int NOTIFICATION_ID = 100509;
static String KEYSTORE_DIR = "KeyStore";
static String KEYSTORE_FILE = "KeyStore.bks";
Context master;
Activity foregroundAct;
NotificationManager notificationManager;
private static int decisionId = 0;
private static SparseArray<MTMDecision> openDecisions = new SparseArray<MTMDecision>();
Handler masterHandler;
private File keyStoreFile;
private KeyStore appKeyStore;
private X509TrustManager defaultTrustManager;
private X509TrustManager appTrustManager;
/** Creates an instance of the MemorizingTrustManager class.
*
* You need to supply the application context. This has to be one of:
* - Application
* - Activity
* - Service
*
* The context is used for file management, to display the dialog /
* notification and for obtaining translated strings.
*
* @param m Context for the application.
* @param appTrustManager Delegate trust management to this TM first.
* @param defaultTrustManager Delegate trust management to this TM second, if non-null.
*/
public MemorizingTrustManager(Context m, X509TrustManager appTrustManager, X509TrustManager defaultTrustManager) {
init(m);
this.appTrustManager = appTrustManager;
this.defaultTrustManager = defaultTrustManager;
}
/** Creates an instance of the MemorizingTrustManager class.
*
* You need to supply the application context. This has to be one of:
* - Application
* - Activity
* - Service
*
* The context is used for file management, to display the dialog /
* notification and for obtaining translated strings.
*
* @param m Context for the application.
*/
public MemorizingTrustManager(Context m) {
init(m);
this.appTrustManager = getTrustManager(appKeyStore);
this.defaultTrustManager = getTrustManager(null);
}
void init(Context m) {
master = m;
masterHandler = new Handler(m.getMainLooper());
notificationManager = (NotificationManager)master.getSystemService(Context.NOTIFICATION_SERVICE);
Application app;
if (m instanceof Application) {
app = (Application)m;
} else if (m instanceof Service) {
app = ((Service)m).getApplication();
} else if (m instanceof Activity) {
app = ((Activity)m).getApplication();
} else throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!");
File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE);
keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE);
appKeyStore = loadAppKeyStore();
}
/**
* Returns a X509TrustManager list containing a new instance of
* TrustManagerFactory.
*
* This function is meant for convenience only. You can use it
* as follows to integrate TrustManagerFactory for HTTPS sockets:
*
* <pre>
* SSLContext sc = SSLContext.getInstance("TLS");
* sc.init(null, MemorizingTrustManager.getInstanceList(this),
* new java.security.SecureRandom());
* HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
* </pre>
* @param c Activity or Service to show the Dialog / Notification
*/
public static X509TrustManager[] getInstanceList(Context c) {
return new X509TrustManager[] { new MemorizingTrustManager(c) };
}
/**
* Binds an Activity to the MTM for displaying the query dialog.
*
* This is useful if your connection is run from a service that is
* triggered by user interaction -- in such cases the activity is
* visible and the user tends to ignore the service notification.
*
* You should never have a hidden activity bound to MTM! Use this
* function in onResume() and @see unbindDisplayActivity in onPause().
*
* @param act Activity to be bound
*/
public void bindDisplayActivity(Activity act) {
foregroundAct = act;
}
/**
* Removes an Activity from the MTM display stack.
*
* Always call this function when the Activity added with
* @see bindDisplayActivity is hidden.
*
* @param act Activity to be unbound
*/
public void unbindDisplayActivity(Activity act) {
// do not remove if it was overridden by a different activity
if (foregroundAct == act)
foregroundAct = null;
}
/**
* Changes the path for the KeyStore file.
*
* The actual filename relative to the app's directory will be
* <code>app_<i>dirname</i>/<i>filename</i></code>.
*
* @param dirname directory to store the KeyStore.
* @param filename file name for the KeyStore.
*/
public static void setKeyStoreFile(String dirname, String filename) {
KEYSTORE_DIR = dirname;
KEYSTORE_FILE = filename;
}
X509TrustManager getTrustManager(KeyStore ks) {
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ks);
for (TrustManager t : tmf.getTrustManagers()) {
if (t instanceof X509TrustManager) {
return (X509TrustManager)t;
}
}
} catch (Exception e) {
// Here, we are covering up errors. It might be more useful
// however to throw them out of the constructor so the
// embedding app knows something went wrong.
Log.e(TAG, "getTrustManager(" + ks + ")", e);
}
return null;
}
KeyStore loadAppKeyStore() {
KeyStore ks;
try {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
Log.e(TAG, "getAppKeyStore()", e);
return null;
}
try {
ks.load(null, null);
ks.load(new java.io.FileInputStream(keyStoreFile), "MTM".toCharArray());
} catch (java.io.FileNotFoundException e) {
Log.i(TAG, "getAppKeyStore(" + keyStoreFile + ") - file does not exist");
} catch (Exception e) {
Log.e(TAG, "getAppKeyStore(" + keyStoreFile + ")", e);
}
return ks;
}
void storeCert(X509Certificate[] chain) {
// add all certs from chain to appKeyStore
try {
for (X509Certificate c : chain)
appKeyStore.setCertificateEntry(c.getSubjectDN().toString(), c);
} catch (KeyStoreException e) {
Log.e(TAG, "storeCert(" + chain + ")", e);
return;
}
// reload appTrustManager
appTrustManager = getTrustManager(appKeyStore);
// store KeyStore to file
try {
java.io.FileOutputStream fos = new java.io.FileOutputStream(keyStoreFile);
appKeyStore.store(fos, "MTM".toCharArray());
fos.close();
} catch (Exception e) {
Log.e(TAG, "storeCert(" + keyStoreFile + ")", e);
}
}
// if the certificate is stored in the app key store, it is considered "known"
private boolean isCertKnown(X509Certificate cert) {
try {
return appKeyStore.getCertificateAlias(cert) != null;
} catch (KeyStoreException e) {
return false;
}
}
private boolean isExpiredException(Throwable e) {
do {
if (e instanceof CertificateExpiredException)
return true;
e = e.getCause();
} while (e != null);
return false;
}
public void checkCertTrusted(X509Certificate[] chain, String authType, boolean isServer)
throws CertificateException
{
Log.d(TAG, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")");
try {
Log.d(TAG, "checkCertTrusted: trying appTrustManager");
if (isServer)
appTrustManager.checkServerTrusted(chain, authType);
else
appTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException ae) {
// if the cert is stored in our appTrustManager, we ignore expiredness
ae.printStackTrace();
if (isExpiredException(ae)) {
Log.i(TAG, "checkCertTrusted: accepting expired certificate from keystore");
return;
}
if (isCertKnown(chain[0])) {
Log.i(TAG, "checkCertTrusted: accepting cert already stored in keystore");
return;
}
try {
if (defaultTrustManager == null)
throw new CertificateException();
Log.d(TAG, "checkCertTrusted: trying defaultTrustManager");
if (isServer)
defaultTrustManager.checkServerTrusted(chain, authType);
else
defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException e) {
e.printStackTrace();
interact(chain, authType, e);
}
}
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
checkCertTrusted(chain, authType, false);
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
checkCertTrusted(chain, authType, true);
}
public X509Certificate[] getAcceptedIssuers()
{
Log.d(TAG, "getAcceptedIssuers()");
return defaultTrustManager.getAcceptedIssuers();
}
private int createDecisionId(MTMDecision d) {
int myId;
synchronized(openDecisions) {
myId = decisionId;
openDecisions.put(myId, d);
decisionId += 1;
}
return myId;
}
private static String hexString(byte[] data) {
StringBuffer si = new StringBuffer();
for (int i = 0; i < data.length; i++) {
si.append(String.format("%02x", data[i]));
if (i < data.length - 1)
si.append(":");
}
return si.toString();
}
private static String certHash(final X509Certificate cert, String digest) {
try {
MessageDigest md = MessageDigest.getInstance(digest);
md.update(cert.getEncoded());
return hexString(md.digest());
} catch (java.security.cert.CertificateEncodingException e) {
return e.getMessage();
} catch (java.security.NoSuchAlgorithmException e) {
return e.getMessage();
}
}
private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
Throwable e = cause;
Log.d(TAG, "certChainMessage for " + e);
StringBuffer si = new StringBuffer();
if (e.getCause() != null) {
e = e.getCause();
si.append(e.getLocalizedMessage());
//si.append("\n");
}
for (X509Certificate c : chain) {
si.append("\n\n");
si.append(c.getSubjectDN().toString());
si.append("\nSHA-256: ");
si.append(certHash(c, "SHA-256"));
si.append("\nSHA-1: ");
si.append(certHash(c, "SHA-1"));
si.append("\nSigned by: ");
si.append(c.getIssuerDN().toString());
}
return si.toString();
}
void startActivityNotification(Intent intent, int decisionId, String certName) {
Notification n = new Notification(android.R.drawable.ic_lock_lock,
master.getString(R.string.mtm_notification),
System.currentTimeMillis());
PendingIntent call = PendingIntent.getActivity(master, 0, intent, 0);
n.setLatestEventInfo(master.getApplicationContext(),
master.getString(R.string.mtm_notification),
certName, call);
n.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_ID + decisionId, n);
}
/**
* Returns the top-most entry of the activity stack.
*
* @return the Context of the currently bound UI or the master context if none is bound
*/
Context getUI() {
return (foregroundAct != null) ? foregroundAct : master;
}
void interact(final X509Certificate[] chain, String authType, CertificateException cause)
throws CertificateException
{
/* prepare the MTMDecision blocker object */
MTMDecision choice = new MTMDecision();
final int myId = createDecisionId(choice);
final String certMessage = certChainMessage(chain, cause);
masterHandler.post(new Runnable() {
public void run() {
Intent ni = new Intent(master, MemorizingActivity.class);
ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
ni.putExtra(DECISION_INTENT_ID, myId);
ni.putExtra(DECISION_INTENT_CERT, certMessage);
// we try to directly start the activity and fall back to
// making a notification
try {
getUI().startActivity(ni);
} catch (Exception e) {
Log.e(TAG, "startActivity: " + e);
startActivityNotification(ni, myId, certMessage);
}
}
});
Log.d(TAG, "openDecisions: " + openDecisions);
Log.d(TAG, "waiting on " + myId);
try {
synchronized(choice) { choice.wait(); }
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "finished wait on " + myId + ": " + choice.state);
switch (choice.state) {
case MTMDecision.DECISION_ALWAYS:
storeCert(chain);
case MTMDecision.DECISION_ONCE:
break;
default:
throw (cause);
}
}
protected static void interactResult(int decisionId, int choice) {
MTMDecision d;
synchronized(openDecisions) {
d = openDecisions.get(decisionId);
openDecisions.remove(decisionId);
}
if (d == null) {
Log.e(TAG, "interactResult: aborting due to stale decision reference!");
return;
}
synchronized(d) {
d.state = choice;
d.notify();
}
}
}
|
package de.eric_wiltfang.dictionary;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.*;
import java.util.EnumSet;
import java.util.Vector;
import de.eric_wiltfang.dictionary.DictionaryEvent.DictionaryEventType;
import de.eric_wiltfang.dictionary.Exporter.ExporterSettings;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
public class Dictionary {
private DictionarySettings settings;
private Path workingDirectory;
private Connection connection;
private Vector<DictionaryListener> listeners;
private Dictionary() throws IOException {
listeners = new Vector<>();
settings = new DictionarySettings();
try {
workingDirectory = Files.createTempDirectory("dict");
} catch (IOException e) {
throw new IOException("Couldn't create temporary directory: " + e);
}
}
/**
* Since temporary files are used for the Dictionary, cleanup() has to be called
* once the Dictionary will not be used anymore, so that no files remain to clutter
* the user's system
*/
public void cleanup() throws IOException {
try {
connection.close();
File[] files = workingDirectory.toFile().listFiles();
for (File f : files) {
f.delete();
}
workingDirectory.toFile().delete();
} catch(Exception e) {
throw new IOException("Couldn't clean up: " + e);
}
}
private void connectDatabase() throws IOException {
try {
connection = DriverManager.getConnection("jdbc:h2:" + workingDirectory + "/db", "sa", "");
} catch (SQLException e) {
throw new IOException("Couldn't connect to Database: " + e);
}
}
private void init() throws IOException, SQLException {
connectDatabase();
Statement s = connection.createStatement();
s.execute("create table entry (" +
" entry_id bigint not null auto_increment," +
" word varchar(255)," +
" definition varchar(10000)," +
" notes varchar(10000)," +
" category varchar(127)," +
" tags array," +
" primary key (entry_id)" +
");");
}
/**
* Loads dictionary files
*/
private void load(File from) throws IOException {
try {
ZipFile zip = new ZipFile(from);
zip.extractAll(workingDirectory.toString());
InputStreamReader reader = new InputStreamReader(new FileInputStream(workingDirectory + "/settings.json"), Charset.forName("UTF-8"));
settings.load(reader);
connectDatabase();
} catch(Exception e) {
throw new IOException("Coulnd't load file: " + e);
}
}
/**
* Saves dictionary files to disk
*/
public void save(File target) throws IOException, Exception {
try {
connection.close();
} catch(Exception e) {
throw new Exception("Coulnd't release database for saving: " + e);
}
if (Files.exists(target.toPath())) {
try {
Files.delete(target.toPath());
} catch (IOException e) {
throw new IOException("Coulnd't save; File " + target + " already exists and can't be deleted: " + e);
}
}
try {
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(workingDirectory + "/VERSION"), Charset.forName("UTF-8"));
writer.write("1.0");
writer.close();
writer = new OutputStreamWriter(new FileOutputStream(workingDirectory + "/settings.json"), Charset.forName("UTF-8"));
settings.save(writer);
writer.close();
ZipFile zip = new ZipFile(target);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
File[] files = workingDirectory.toFile().listFiles();
for (File f : files) {
zip.addFile(f, parameters);
}
} catch (Exception e) {
throw new IOException("Coulnd't save: " + e);
}
connectDatabase();
}
/**
* Creates a new dictionary
*/
public static Dictionary createNew(DictionarySettings settings) throws IOException, SQLException {
Dictionary dic = new Dictionary();
dic.settings = settings;
dic.init();
return dic;
}
/**
* Creates a dictionary with contents from a file
*/
public static Dictionary createFromFile(File file) throws IOException, SQLException {
Dictionary dic = new Dictionary();
dic.load(file);
return dic;
}
public Entry getEntry(long id) throws IllegalArgumentException, SQLException {
return new Entry(id, connection);
}
public void insertEntry(Entry entry) throws SQLException {
boolean fresh = entry.insertSelf(connection);
DictionaryEventType evtype = fresh ? DictionaryEventType.NEW : DictionaryEventType.UPDATE;
DictionaryEvent e = new DictionaryEvent(this, evtype, entry.getId());
broadcast(e);
}
public void deleteEntry(Entry entry) throws SQLException {
deleteEntry(entry.getId());
}
public void deleteEntry(long entryID) throws SQLException {
PreparedStatement s = connection.prepareStatement("DELETE FROM entry WHERE entry_id = ?");
s.setLong(1, entryID);
s.execute();
broadcast(new DictionaryEvent(this, DictionaryEventType.DELETE, entryID));
}
/**
* Exports the dictionary via an exporter
*/
public void export(Exporter ex) throws SQLException, IOException {
ex.start(settings.getName());
String query = "SELECT entry_id FROM entry";
EnumSet<ExporterSettings> expSetting = ex.getSettings();
if (expSetting == null) {
expSetting = EnumSet.noneOf(ExporterSettings.class);
}
if (expSetting.contains(ExporterSettings.ALPHABETICAL)) {
query = query + " ORDER BY LOWER(word)";
}
query = query + ";";
ResultSet res = connection.createStatement().executeQuery(query);
while (res.next()) {
ex.addEntry(getEntry(res.getLong("entry_id")));
}
ex.finish();
}
/**
* Imports entries from an Importer.
* @return
*/
public int importEntries(Importer im) throws IOException, SQLException {
int num = 0;
im.initialize();
Entry entry;
while ((entry = im.nextEntry()) != null) {
entry.insertSelf(connection);
num++;
}
broadcast(new DictionaryEvent(this, DictionaryEventType.OTHER, -1));
return num;
}
public String getName() {
return settings.getName();
}
public void setSettings(DictionarySettings settings) {
this.settings = settings;
}
public DictionarySettings getSettings() {
return settings;
}
/**
* Searches for entries that contain the specified key.
* @param key The key to search for.
* @return A vector of ids for matching entries.
*/
public Vector<Long> searchID(String key) throws SQLException {
PreparedStatement s = connection.prepareStatement(
"SELECT entry_id" +
" FROM entry WHERE word like '%'||?||'%' OR definition like '%'||?||'%';");
s.setString(1, key);
s.setString(2, key);
ResultSet result = s.executeQuery();
Vector<Long> ids = new Vector<Long>();
while (result.next()) {
ids.add(result.getLong("entry_id"));
}
return ids;
}
public Vector<Long> getAllIDs() throws SQLException {
ResultSet result = connection.createStatement().executeQuery("SELECT entry_id FROM entry");
Vector<Long> ids = new Vector<Long>();
while (result.next()) {
ids.add(result.getLong("entry_id"));
}
return ids;
}
public Vector<Entry> searchEntry(String key) throws SQLException {
Vector<Long> ids = searchID(key);
Vector<Entry> entries = new Vector<Entry>(ids.size());
for (int i = 0; i < ids.size(); i++) {
entries.add(getEntry(ids.get(i)));
}
return entries;
}
public void addDictionaryListener(DictionaryListener l) {
listeners.add(l);
}
public void removeDictionaryListener(DictionaryListener l) {
listeners.remove(l);
}
private void broadcast(DictionaryEvent e) {
for (DictionaryListener l : listeners) {
l.recieveEvent(e);
}
}
}
|
package de.gurkenlabs.litiengine.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.IntConsumer;
import de.gurkenlabs.litiengine.Align;
import de.gurkenlabs.litiengine.graphics.ShapeRenderer;
import de.gurkenlabs.litiengine.graphics.Spritesheet;
import de.gurkenlabs.litiengine.input.Input;
/**
* The Class ListField.
*/
public class ListField extends GuiComponent {
private boolean arrowKeyNavigation;
private Spritesheet buttonSprite;
private Spritesheet entrySprite;
private final List<IntConsumer> changeConsumer;
private final Object[][] content;
private int nbOfColumns;
private final CopyOnWriteArrayList<CopyOnWriteArrayList<ImageComponent>> listEntries;
private int verticalLowerBound = 0;
private int horizontalLowerBound = 0;
private ImageComponent selectedComponent;
private int selectionColumn;
private int selectionRow;
private boolean selectEntireColumn = false;
private boolean selectEntireRow = false;
private final int shownRows;
private final int shownColumns;
private VerticalSlider verticalSlider;
private HorizontalSlider horizontalSlider;
private final double sliderSize = 100.0;
private boolean sliderInside = false;
/**
* Creates a vertical list field.
* <br><br>
* The <b>content</b> of this list field can only be accessed through the first column (column 0).
* <br>
* Examples:
* <blockquote>
* content[0][0] - ok<br>
* content[0][1] - ok<br>
* content[0][8] - ok<br>
* content[1][5] - NOK<br>
* content[2][0] - NOK<br>
* </blockquote>
*
* @param x
* the x
* @param y
* the y
* @param width
* the width
* @param height
* the height
* @param content
* the 1D content
* @param shownElements
* the number of rows/elements to
* display before the user needs to scroll for more possible rows/elements
* @param entrySprite
* the entrySprite
* @param buttonSprite
* the buttonSprite
*/
public ListField(final double x, final double y, final double width, final double height, final Object[] content, final int shownRows, final Spritesheet entrySprite, final Spritesheet buttonSprite) {
this(x, y, width, height, new Object[][] {content}, shownRows, 1, false, entrySprite, buttonSprite);
}
public ListField(final double x, final double y, final double width, final double height, final Object[] content, final int shownRows, final boolean sliderInside, final Spritesheet entrySprite, final Spritesheet buttonSprite) {
this(x, y, width, height, new Object[][] {content}, shownRows, 1, sliderInside, entrySprite, buttonSprite);
}
/**
* Creates a 2D vertical list field.
* <br><br>
* The given <b>content</b> should be arranged as columns of elements.
* <br>
* Examples:
* <blockquote>
* content[0][0] - column 0, row 0<br>
* content[0][1] - column 0, row 1<br>
* content[2][8] - column 2, row 8<br>
* </blockquote>
*
* @param x
* the x
* @param y
* the y
* @param width
* the width
* @param height
* the height
* @param content
* the 2D content
* @param shownElements
* the number of rows/elements to
* display before the user needs to scroll for more possible rows/elements
* @param entrySprite
* the entrySprite
* @param buttonSprite
* the buttonSprite
*/
public ListField(final double x, final double y, final double width, final double height, final Object[][] content, final int shownRows, final int shownColumns, final Spritesheet entrySprite, final Spritesheet buttonSprite) {
this(x, y, width, height, new Object[][] {content}, shownRows, shownColumns, false, entrySprite, buttonSprite);
}
public ListField(final double x, final double y, final double width, final double height, final Object[][] content, final int shownRows, final int shownColumns, final boolean sliderInside, final Spritesheet entrySprite, final Spritesheet buttonSprite) {
super(x, y, width, height);
this.changeConsumer = new CopyOnWriteArrayList<>();
this.content = content;
this.nbOfColumns = this.content.length;
this.listEntries = new CopyOnWriteArrayList<>();
this.buttonSprite = buttonSprite;
this.entrySprite = entrySprite;
this.sliderInside = sliderInside;
this.shownRows = shownRows;
this.shownColumns = shownColumns;
this.initSliders();
this.initContentList();
this.prepareInput();
}
public Spritesheet getButtonSprite() {
return this.buttonSprite;
}
public List<IntConsumer> getChangeConsumer() {
return this.changeConsumer;
}
public Object[][] getContent() {
return this.content;
}
public Spritesheet getEntrySprite() {
return this.entrySprite;
}
public int getHorizontalLowerBound() {
return this.horizontalLowerBound;
}
public HorizontalSlider getHorizontalSlider() {
return this.horizontalSlider;
}
/**
* Returns all list items of a specified column.
*
* @param column
* the column
* @return a list of items
*/
public List<ImageComponent> getListEntry(final int column) {
if (column < 0 || column >= this.listEntries.size()) {
return null;
}
return this.listEntries.get(column);
}
/**
* Returns the number of rows of the tallest column.
*
* @return
* int representing the length of the tallest column
*/
public int getMaxRows() {
int result = 0;
for (Object[] o : this.getContent()) {
if (o.length > result) {
result = o.length;
}
}
return result;
}
public int getNumberOfShownRows() {
return this.shownRows;
}
public int getNumberOfShownColumns() {
return this.shownColumns;
}
public ImageComponent getSelectedComponent() {
return this.selectedComponent;
}
public Object getSelectedObject() {
return this.getContent()[this.selectionColumn][this.selectionRow];
}
/**
* Returns the selected column.
*
* @return number of the column; -1 if isEntireRowSelected() is true
*/
public int getSelectionColumn() {
if (this.isEntireRowSelected()) {
return -1;
}
return this.selectionColumn;
}
/**
* Returns the selected row.
*
* @return number of the row
*/
public int getSelectionRow() {
return this.selectionRow;
}
public int getVerticalLowerBound() {
return this.verticalLowerBound;
}
public VerticalSlider getVerticalSlider() {
return this.verticalSlider;
}
public boolean isArrowKeyNavigation() {
return this.arrowKeyNavigation;
}
public void onChange(final IntConsumer c) {
this.getChangeConsumer().add(c);
}
public void refresh() {
for (int column = 0; column < this.getNumberOfShownColumns(); column++) {
for (int row = 0; row < this.getNumberOfShownRows(); row++) {
if (this.getContent()[column].length <= row) {
continue;
}
if (this.getListEntry(column).get(row) != null) {
this.getListEntry(column).get(row).setText(this.getContent()[column + this.getHorizontalLowerBound()][row + this.getVerticalLowerBound()].toString());
}
}
}
if (!this.isEntireRowSelected() && this.selectionColumn >= this.getHorizontalLowerBound() && this.selectionColumn < this.getHorizontalLowerBound() + this.getNumberOfShownColumns() && this.selectionRow >= this.getVerticalLowerBound() && this.selectionRow < this.getVerticalLowerBound() + this.getNumberOfShownRows()) {
this.selectedComponent = this.getListEntry(this.selectionColumn - this.getHorizontalLowerBound()).get(this.selectionRow - this.getVerticalLowerBound());
}
else if (this.isEntireRowSelected() && this.selectionColumn >= 0 && this.selectionColumn < this.nbOfColumns && this.selectionRow >= this.getVerticalLowerBound() && this.selectionRow < this.getVerticalLowerBound() + this.getNumberOfShownRows()) {
this.selectedComponent = this.getListEntry(0).get(this.selectionRow - this.getVerticalLowerBound());
}
else {
this.selectedComponent = null;
}
if (this.selectedComponent != null) {
this.selectedComponent.setSelected(true);
}
}
@Override
public void render(final Graphics2D g) {
super.render(g);
if (this.selectedComponent != null) {
Rectangle2D border;
double borderWidth = this.selectedComponent.getWidth() + 2;
double borderHeight = this.selectedComponent.getHeight() + 2;
if (this.isEntireRowSelected()) {
borderWidth = this.getWidth() + 2;
}
if (this.getVerticalSlider() != null && this.getVerticalSlider().isVisible() && this.isSliderInside()) {
borderWidth = borderWidth - this.getVerticalSlider().getWidth();
}
if (this.isEntireColumnSelected()) {
borderHeight = this.getHeight() + 2;
}
border = new Rectangle2D.Double(this.getX() - 1, this.selectedComponent.getY() - 1, borderWidth, borderHeight);
g.setColor(Color.WHITE);
ShapeRenderer.renderOutline(g, border, 2);
}
}
public void setArrowKeyNavigation(final boolean arrowKeyNavigation) {
this.arrowKeyNavigation = arrowKeyNavigation;
}
public void setButtonSprite(final Spritesheet buttonSprite) {
this.buttonSprite = buttonSprite;
}
public void setEntrySprite(final Spritesheet entrySprite) {
this.entrySprite = entrySprite;
}
public void setForwardMouseEvents(final int column, final boolean forwardMouseEvents) {
if (column < 0 && column >= this.nbOfColumns) {
return;
}
for (ImageComponent comp : this.getListEntry(column)) {
comp.setForwardMouseEvents(forwardMouseEvents);
}
}
public void setHorizontalLowerBound(final int lowerBound) {
this.horizontalLowerBound = lowerBound;
}
public void setSelection(final int column, final int row) {
if (column < 0 || column >= this.nbOfColumns || row < 0 || row >= this.getContent()[column].length) {
return;
}
this.selectionColumn = column;
this.selectionRow = row;
if (this.selectionRow >= this.getVerticalLowerBound() + this.getNumberOfShownRows()) {
this.setVerticalLowerBound(this.getVerticalLowerBound() + 1);
} else if (this.selectionRow < this.getVerticalLowerBound() && this.getVerticalLowerBound() > 0) {
this.setVerticalLowerBound(this.getVerticalLowerBound() - 1);
}
if (this.selectionColumn >= this.getHorizontalLowerBound() + this.getNumberOfShownColumns()) {
this.setHorizontalLowerBound(this.getHorizontalLowerBound() + 1);
} else if (this.selectionColumn < this.getHorizontalLowerBound() && this.getHorizontalLowerBound() > 0) {
this.setHorizontalLowerBound(this.getHorizontalLowerBound() - 1);
}
this.getChangeConsumer().forEach(consumer -> consumer.accept(this.selectionRow));
this.refresh();
}
/**
* If set to true, selecting a element will show a selection of
* the entire row on which that element is on. Without taking
* account of its column.
* <br><br>
* Set to <b>false</b> as default.
*
* @param selectEntireRow
* a boolean
*/
public void setSelectEntireColumn(boolean selectEntireColumn) {
this.selectEntireColumn = selectEntireColumn;
}
/**
* If set to true, the slider will show inside the ListField.
* <br>
* This can be used, for example, if the ListField's width matches the screen's width.
* <br><br>
* Set to <b>false</b> as default.
*
* @param sliderInside
* a boolean
*/
public void setSelectEntireRow(boolean selectEntireRow) {
this.selectEntireRow = selectEntireRow;
}
public void setVerticalLowerBound(final int lowerBound) {
this.verticalLowerBound = lowerBound;
}
private void initContentList() {
final double columnWidth = this.getWidth() / this.getNumberOfShownColumns();
final double rowHeight = this.getHeight() / this.getNumberOfShownRows();
for (int column = 0; column < this.getNumberOfShownColumns(); column++) {
this.listEntries.add(new CopyOnWriteArrayList<ImageComponent>());
for (int row = 0; row < this.getNumberOfShownRows(); row++) {
if (this.getContent()[column].length <= row) {
continue;
}
ImageComponent entryComponent;
if (this.getContent()[column][row] == null) {
entryComponent = new ImageComponent(this.getX() + (columnWidth * column), this.getY() + (rowHeight * row), columnWidth, rowHeight, this.entrySprite, "", null);
}
else {
entryComponent = new ImageComponent(this.getX() + (columnWidth * column), this.getY() + (rowHeight * row), columnWidth, rowHeight, this.entrySprite, this.getContent()[column][row].toString(), null);
}
if (this.isSliderInside()) {
entryComponent.setX(this.getX() + ((columnWidth - (this.getVerticalSlider().getWidth() / this.getNumberOfShownColumns())) * column));
entryComponent.setY(this.getY() + ((rowHeight - (this.getHorizontalSlider().getHeight() / this.getNumberOfShownRows())) * row));
entryComponent.setWidth(entryComponent.getWidth() - (this.getVerticalSlider().getWidth() / this.getNumberOfShownColumns()));
entryComponent.setHeight(entryComponent.getHeight() - (this.getHorizontalSlider().getHeight() / this.getNumberOfShownRows()));
}
entryComponent.setTextAlign(Align.LEFT);
this.getListEntry(column).add(entryComponent);
}
this.getComponents().addAll(this.getListEntry(column));
final int col = column;
for (final ImageComponent comp : this.getListEntry(col)) {
comp.onClicked(e -> {
this.setSelection(this.getHorizontalLowerBound() + col % this.getNumberOfShownColumns(), this.getVerticalLowerBound() + this.getListEntry(col).indexOf(comp) % this.getNumberOfShownRows());
this.refresh();
});
}
}
this.onChange(s -> {
if (this.getVerticalSlider() != null) {
this.getVerticalSlider().setCurrentValue(this.getVerticalLowerBound());
this.getVerticalSlider().getSliderComponent().setLocation(this.getVerticalSlider().getRelativeSliderPosition());
}
if (this.getHorizontalSlider() != null) {
this.getHorizontalSlider().setCurrentValue(this.getHorizontalLowerBound());
this.getHorizontalSlider().getSliderComponent().setLocation(this.getHorizontalSlider().getRelativeSliderPosition());
}
});
if (this.getVerticalSlider() != null) {
this.getVerticalSlider().onChange(sliderValue -> {
this.setVerticalLowerBound(sliderValue.intValue());
this.getVerticalSlider().getSliderComponent().setLocation(this.getVerticalSlider().getRelativeSliderPosition());
this.refresh();
});
}
if (this.getHorizontalSlider() != null) {
this.getHorizontalSlider().onChange(sliderValue -> {
this.setHorizontalLowerBound(sliderValue.intValue());
this.getHorizontalSlider().getSliderComponent().setLocation(this.getHorizontalSlider().getRelativeSliderPosition());
this.refresh();
});
}
}
private void initSliders() {
final int maxNbOfRows = this.getMaxRows() - this.getNumberOfShownRows();
if (maxNbOfRows > 0) {
if (this.isSliderInside()) {
this.verticalSlider = new VerticalSlider(this.getX() + this.getWidth() - this.sliderSize, this.getY(), this.sliderSize, this.getHeight() - this.sliderSize, 0, this.getMaxRows() - this.getNumberOfShownRows(), 1);
this.horizontalSlider = new HorizontalSlider(this.getX(), this.getY() + this.getHeight() - this.sliderSize, this.getWidth() - this.sliderSize, this.sliderSize, 0, this.nbOfColumns - this.getNumberOfShownColumns(), 1);
}
else {
this.verticalSlider = new VerticalSlider(this.getX() + this.getWidth(), this.getY(), this.sliderSize, this.getHeight(), 0, this.getMaxRows() - this.getNumberOfShownRows(), 1);
this.horizontalSlider = new HorizontalSlider(this.getX(), this.getY() + this.getHeight(), this.getWidth(), this.sliderSize, 0, this.nbOfColumns - this.getNumberOfShownColumns(), 1);
}
this.getVerticalSlider().setCurrentValue(this.getVerticalLowerBound());
this.getHorizontalSlider().setCurrentValue(this.getHorizontalLowerBound());
this.getComponents().add(this.getVerticalSlider());
this.getComponents().add(this.getHorizontalSlider());
}
}
public boolean isEntireColumnSelected() {
return this.selectEntireColumn;
}
/**
* See {@link #setSelectEntireRow(boolean)}
*
* @return
* true if selection is set to select the entire row; false otherwise
*/
public boolean isEntireRowSelected() {
return this.selectEntireRow;
}
/**
* See {@link #setSliderInside(boolean)}
*
* @return
* true if slider is set to be inside the ListField; false otherwise
*/
public boolean isSliderInside() {
return this.sliderInside;
}
private void prepareInput() {
Input.keyboard().onKeyTyped(KeyEvent.VK_UP, e -> {
if (this.isSuspended() || !this.isVisible() || !this.isArrowKeyNavigation()) {
return;
}
this.setSelection(this.getHorizontalLowerBound(), this.selectionRow - 1);
});
Input.keyboard().onKeyTyped(KeyEvent.VK_DOWN, e -> {
if (this.isSuspended() || !this.isVisible() || !this.isArrowKeyNavigation()) {
return;
}
this.setSelection(this.getHorizontalLowerBound(), this.selectionRow + 1);
});
Input.keyboard().onKeyTyped(KeyEvent.VK_LEFT, e -> {
if (this.isSuspended() || !this.isVisible() || !this.isArrowKeyNavigation()) {
return;
}
this.setSelection(this.getHorizontalLowerBound() - 1, this.selectionRow);
});
Input.keyboard().onKeyTyped(KeyEvent.VK_RIGHT, e -> {
if (this.isSuspended() || !this.isVisible() || !this.isArrowKeyNavigation()) {
return;
}
this.setSelection(this.getHorizontalLowerBound() + 1, this.selectionRow);
});
this.onMouseWheelScrolled(e -> {
if (this.isSuspended() || !this.isVisible()) {
return;
}
if (this.isHovered()) {
if (e.getEvent().getWheelRotation() < 0) {
this.setSelection(this.getHorizontalLowerBound(), this.selectionRow - 1);
} else {
this.setSelection(this.getHorizontalLowerBound(), this.selectionRow + 1);
}
return;
}
});
}
}
|
package de.jungblut.math.cuda;
import java.util.Random;
import jcuda.Pointer;
import jcuda.Sizeof;
import jcuda.jcublas.JCublas2;
import jcuda.jcublas.cublasHandle;
import jcuda.jcublas.cublasOperation;
import jcuda.jcublas.cublasPointerMode;
import jcuda.runtime.JCuda;
import jcuda.runtime.cudaDeviceProp;
import de.jungblut.math.DenseDoubleMatrix;
// -Djava.library.path="/lib/;${env_var:PATH}" must be added to the running VM
public class JCUDAMatrixUtils {
public static boolean CUDA_AVAILABLE = false;
static {
try {
// Disable exceptions and omit subsequent error checks
JCublas2.setExceptionsEnabled(true);
JCuda.setExceptionsEnabled(true);
cudaDeviceProp cudaDeviceProp = new cudaDeviceProp();
JCuda.cudaGetDeviceProperties(cudaDeviceProp, 0);
// actually here is only cublas2 available.
if (Integer.parseInt(cudaDeviceProp.getName().replaceAll("[^\\d]", "")) > 400) {
JCublas2.initialize();
CUDA_AVAILABLE = true;
System.out
.println("Using device " + cudaDeviceProp.getName()
+ " with total RAM of " + cudaDeviceProp.totalGlobalMem
+ " bytes!");
}
} catch (Throwable e) {
// e.printStackTrace();
System.out.println(e.getLocalizedMessage());
}
}
// TODO transpose can be actually done on GPU as well
public static DenseDoubleMatrix multiply(DenseDoubleMatrix a,
DenseDoubleMatrix b) {
Pointer matrixPointerA = memcpyMatrix(a);
Pointer matrixPointerB = memcpyMatrix(b);
// Prepare the pointer for the result in DEVICE memory
Pointer deviceResultPointer = new Pointer();
int resMatrixSize = a.getRowCount() * b.getColumnCount();
JCuda.cudaMalloc(deviceResultPointer, Sizeof.DOUBLE * resMatrixSize);
Pointer alpha = Pointer.to(new double[] { 1.0d });
Pointer beta = Pointer.to(new double[] { 0.0d });
cublasHandle handle = new cublasHandle();
JCublas2.cublasCreate(handle);
JCublas2.cublasSetPointerMode(handle,
cublasPointerMode.CUBLAS_POINTER_MODE_HOST);
JCublas2.cublasDgemm(handle, cublasOperation.CUBLAS_OP_N,
cublasOperation.CUBLAS_OP_N, a.getRowCount(), b.getColumnCount(),
a.getColumnCount(), alpha, matrixPointerA, a.getRowCount(),
matrixPointerB, b.getRowCount(), beta, deviceResultPointer,
a.getRowCount());
JCuda.cudaDeviceSynchronize();
DenseDoubleMatrix matrix = getMatrix(deviceResultPointer, a.getRowCount(),
b.getColumnCount());
freePointer(matrixPointerA);
freePointer(matrixPointerB);
freePointer(deviceResultPointer);
cublasDestroy(handle);
return matrix;
}
private static Pointer memcpyMatrix(DenseDoubleMatrix a) {
int matrixSizeA = a.getColumnCount() * a.getRowCount();
double[] matrix = new double[matrixSizeA];
// store in column major format
for (int i = 0; i < a.getColumnCount(); i++) {
double[] column = a.getColumn(i);
System.arraycopy(column, 0, matrix, i * column.length, column.length);
}
Pointer deviceMatrixA = new Pointer();
JCuda.cudaMalloc(deviceMatrixA, matrixSizeA * Sizeof.DOUBLE);
JCublas2.cublasSetMatrix(a.getRowCount(), a.getColumnCount(),
Sizeof.DOUBLE, Pointer.to(matrix), a.getRowCount(), deviceMatrixA,
a.getRowCount());
return deviceMatrixA;
}
private static DenseDoubleMatrix getMatrix(Pointer src, int rows, int columns) {
double[] raw = new double[rows * columns];
Pointer dst = Pointer.to(raw);
JCublas2
.cublasGetMatrix(rows, columns, Sizeof.DOUBLE, src, rows, dst, rows);
return new DenseDoubleMatrix(raw, rows, columns);
}
// seems to have problems with latest CUDA?
private static final void cublasDestroy(cublasHandle handle) {
JCublas2.cublasDestroy(handle);
}
private static void freePointer(Pointer p) {
JCuda.cudaFree(p);
}
public static void main(String[] args) {
for (int i = 2; i < 2000; i++) {
DenseDoubleMatrix a = new DenseDoubleMatrix(i, i, new Random());
DenseDoubleMatrix b = new DenseDoubleMatrix(i, i, new Random());
// DenseDoubleMatrix multiplyCPU = a.multiply(b);
DenseDoubleMatrix multiplyGPU = multiply(a, b);
System.out.println(i + " "
+ multiplyGPU.sumElements());
}
}
}
|
package nars.inference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import nars.storage.Memory;
import nars.config.Parameters;
import nars.control.DerivationContext;
import nars.entity.BudgetValue;
import nars.entity.Sentence;
import nars.entity.Stamp;
import nars.entity.Task;
import nars.entity.TaskLink;
import nars.entity.TermLink;
import nars.entity.TruthValue;
import nars.io.Symbols;
import nars.language.CompoundTerm;
import nars.language.Conjunction;
import nars.language.Equivalence;
import nars.language.Implication;
import nars.language.Inheritance;
import nars.language.Interval;
import nars.language.Product;
import nars.language.Similarity;
import nars.language.Statement;
import nars.language.Term;
import nars.language.Terms;
import nars.language.Variable;
import nars.operator.Operation;
/**
*
* @author peiwang
*/
public class TemporalRules {
public static final int ORDER_NONE = 2;
public static final int ORDER_FORWARD = 1;
public static final int ORDER_CONCURRENT = 0;
public static final int ORDER_BACKWARD = -1;
public static final int ORDER_INVALID = -2;
public final static int reverseOrder(final int order) {
if (order == ORDER_NONE) {
return ORDER_NONE;
} else {
return -order;
}
}
public final static boolean matchingOrder(final Sentence a, final Sentence b) {
return matchingOrder(a.getTemporalOrder(), b.getTemporalOrder());
}
public final static boolean matchingOrder(final int order1, final int order2) {
return (order1 == order2) || (order1 == ORDER_NONE) || (order2 == ORDER_NONE);
}
public final static int dedExeOrder(final int order1, final int order2) {
int order = ORDER_INVALID;
if ((order1 == order2) || (order2 == TemporalRules.ORDER_NONE)) {
order = order1;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = order2;
} else if (order2 == TemporalRules.ORDER_CONCURRENT) {
order = order1;
}
return order;
}
public final static int abdIndComOrder(final int order1, final int order2) {
int order = ORDER_INVALID;
if (order2 == TemporalRules.ORDER_NONE) {
order = order1;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = reverseOrder(order2);
} else if ((order2 == TemporalRules.ORDER_CONCURRENT) || (order1 == -order2)) {
order = order1;
}
return order;
}
public final static int analogyOrder(final int order1, final int order2, final int figure) {
int order = ORDER_INVALID;
if ((order2 == TemporalRules.ORDER_NONE) || (order2 == TemporalRules.ORDER_CONCURRENT)) {
order = order1;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = (figure < 20) ? order2 : reverseOrder(order2);
} else if (order1 == order2) {
if ((figure == 12) || (figure == 21)) {
order = order1;
}
} else if ((order1 == -order2)) {
if ((figure == 11) || (figure == 22)) {
order = order1;
}
}
return order;
}
public static final int resemblanceOrder(final int order1, final int order2, final int figure) {
int order = ORDER_INVALID;
int order1Reverse = reverseOrder(order1);
if ((order2 == TemporalRules.ORDER_NONE)) {
order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = (figure % 10 == 1) ? order2 : reverseOrder(order2); // switch when 12 or 22
} else if (order2 == TemporalRules.ORDER_CONCURRENT) {
order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12
} else if (order1 == order2) {
order = (figure == 21) ? order1 : -order1;
}
return order;
}
public static final int composeOrder(final int order1, final int order2) {
int order = ORDER_INVALID;
if (order2 == TemporalRules.ORDER_NONE) {
order = order1;
} else if (order1 == TemporalRules.ORDER_NONE) {
order = order2;
} else if (order1 == order2) {
order = order1;
}
return order;
}
/** whether temporal induction can generate a task by avoiding producing wrong terms; only one temporal operator is allowed */
public final static boolean tooMuchTemporalStatements(final Term t) {
return (t == null) || (t.containedTemporalRelations() > 1);
}
/** whether a term can be used in temoralInduction(,,) */
protected static boolean termForTemporalInduction(final Term t) {
return (t instanceof Inheritance) || (t instanceof Similarity);
}
public static List<Task> temporalInduction(final Sentence s1, final Sentence s2, final nars.control.DerivationContext nal, boolean SucceedingEventsInduction) {
if ((s1.truth==null) || (s2.truth==null) || s1.punctuation!=Symbols.JUDGMENT_MARK || s2.punctuation!=Symbols.JUDGMENT_MARK
|| s1.isEternal() || s2.isEternal())
return Collections.EMPTY_LIST;
Term t1 = s1.term;
Term t2 = s2.term;
boolean deriveSequenceOnly = Statement.invalidStatement(t1, t2, true);
if (Statement.invalidStatement(t1, t2, false))
return Collections.EMPTY_LIST;
Term t11=null;
Term t22=null;
if (!deriveSequenceOnly && termForTemporalInduction(t1) && termForTemporalInduction(t2)) {
Statement ss1 = (Statement) t1;
Statement ss2 = (Statement) t2;
Variable var1 = new Variable("$0");
Variable var2 = new Variable("$1");
/* if (ss1.getSubject().equals(ss2.getSubject())) {
t11 = Statement.make(ss1, var1, ss1.getPredicate());
t22 = Statement.make(ss2, var2, ss2.getPredicate());
} else if (ss1.getPredicate().equals(ss2.getPredicate())) {
t11 = Statement.make(ss1, ss1.getSubject(), var1);
t22 = Statement.make(ss2, ss2.getSubject(), var2);
}*/
if(ss2.containsTermRecursively(ss1.getSubject())) {
HashMap<Term,Term> subs=new HashMap();
subs.put(ss1.getSubject(), var1);
if(ss2.containsTermRecursively(ss1.getPredicate())) {
subs.put(ss1.getPredicate(), var2);
}
t11=ss1.applySubstitute(subs);
t22=ss2.applySubstitute(subs);
}
if(ss1.containsTermRecursively(ss2.getSubject())) {
HashMap<Term,Term> subs=new HashMap();
subs.put(ss2.getSubject(), var1);
if(ss1.containsTermRecursively(ss2.getPredicate())) {
subs.put(ss2.getPredicate(), var2);
}
t11=ss1.applySubstitute(subs);
t22=ss2.applySubstitute(subs);
}
//allow also temporal induction on operator arguments:
if(ss2 instanceof Operation ^ ss1 instanceof Operation) {
if(ss2 instanceof Operation && !(ss2.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term
Term comp=ss1.getSubject();
Term ss2_term = ((Operation)ss2).getSubject();
boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep());
if(ss2_term instanceof Product) {
Product ss2_prod=(Product) ss2_term;
if(applicableVariableType && Terms.contains(ss2_prod.term, comp)) { //only if there is one and it isnt a variable already
Term[] ars = ss2_prod.cloneTermsReplacing(comp, var1);
t11 = Statement.make(ss1, var1, ss1.getPredicate());
Operation op=(Operation) Operation.make(
new Product(ars),
ss2.getPredicate()
);
t22 = op;
}
}
}
if(ss1 instanceof Operation && !(ss1.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term
Term comp=ss2.getSubject();
Term ss1_term = ((Operation)ss1).getSubject();
boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep());
if(ss1_term instanceof Product) {
Product ss1_prod=(Product) ss1_term;
if(applicableVariableType && Terms.contains(ss1_prod.term, comp)) { //only if there is one and it isnt a variable already
Term[] ars = ss1_prod.cloneTermsReplacing(comp, var1);
t22 = Statement.make(ss2, var1, ss2.getPredicate());
Operation op=(Operation) Operation.make(
new Product(ars),
ss1.getPredicate()
);
t11 = op;
}
}
}
}
}
int durationCycles = Parameters.DURATION;
long time1 = s1.getOccurenceTime();
long time2 = s2.getOccurenceTime();
long timeDiff = time2 - time1;
List<Interval> interval=null;
if (!concurrent(time1, time2, durationCycles)) {
interval = Interval.intervalTimeSequence(Math.abs(timeDiff), Parameters.TEMPORAL_INTERVAL_PRECISION, nal.mem());
if (timeDiff > 0) {
t1 = Conjunction.make(t1, interval, ORDER_FORWARD);
if(t11!=null) {
t11 = Conjunction.make(t11, interval, ORDER_FORWARD);
}
} else {
t2 = Conjunction.make(t2, interval, ORDER_FORWARD);
if(t22!=null) {
t22 = Conjunction.make(t22, interval, ORDER_FORWARD);
}
}
}
int order = order(timeDiff, durationCycles);
TruthValue givenTruth1 = s1.truth;
TruthValue givenTruth2 = s2.truth;
//This code adds a penalty for large time distance (TODO probably revise)
Sentence s3 = s2.projection(s1.getOccurenceTime(), nal.memory.time());
givenTruth2 = s3.truth;
// TruthFunctions.
TruthValue truth1 = TruthFunctions.induction(givenTruth1, givenTruth2);
TruthValue truth2 = TruthFunctions.induction(givenTruth2, givenTruth1);
TruthValue truth3 = TruthFunctions.comparison(givenTruth1, givenTruth2);
TruthValue truth4 = TruthFunctions.intersection(givenTruth1, givenTruth2);
BudgetValue budget1 = BudgetFunctions.forward(truth1, nal);
budget1.setPriority(budget1.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY);
BudgetValue budget2 = BudgetFunctions.forward(truth2, nal);
budget2.setPriority(budget2.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY);
BudgetValue budget3 = BudgetFunctions.forward(truth3, nal);
budget3.setPriority(budget3.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY);
BudgetValue budget4 = BudgetFunctions.forward(truth4, nal); //this one is sequence in sequenceBag, no need to reduce here
if(!SucceedingEventsInduction) { //reduce priority according to temporal distance
//it was not "semantically" connected by temporal succession
int tt1=(int) s1.getOccurenceTime();
int tt2=(int) s1.getOccurenceTime();
int d=Math.abs(tt1-tt2)/Parameters.DURATION;
if(d!=0) {
double mul=1.0/((double)d);
budget1.setPriority((float) (budget1.getPriority()*mul));
budget2.setPriority((float) (budget2.getPriority()*mul));
budget3.setPriority((float) (budget3.getPriority()*mul));
budget4.setPriority((float) (budget4.getPriority()*mul));
}
}
Statement statement1 = Implication.make(t1, t2, order);
Statement statement2 = Implication.make(t2, t1, reverseOrder(order));
Statement statement3 = Equivalence.make(t1, t2, order);
Term statement4 = null;
switch (order) {
case TemporalRules.ORDER_FORWARD:
statement4 = Conjunction.make(t1, interval, s2.term, order);
break;
case TemporalRules.ORDER_BACKWARD:
statement4 = Conjunction.make(s2.term, interval, t1, reverseOrder(order));
break;
default:
statement4 = Conjunction.make(t1, s2.term, order);
break;
}
//maybe this way is also the more flexible and intelligent way to introduce variables for the case above
//TODO: rethink this for 1.6.3
if(!deriveSequenceOnly && statement2!=null) { //there is no general form
//ok then it may be the (&/ =/> case which
Statement st=statement2;
if(st.getPredicate() instanceof Inheritance && (st.getSubject() instanceof Conjunction || st.getSubject() instanceof Operation)) {
Term precon=(Term) st.getSubject();
Inheritance consequence=(Inheritance) st.getPredicate();
Term pred=consequence.getPredicate();
Term sub=consequence.getSubject();
//look if subject is contained in precon:
boolean SubsSub=precon.containsTermRecursively(sub);
boolean SubsPred=precon.containsTermRecursively(pred);
Variable v1=new Variable("$91");
Variable v2=new Variable("$92");
HashMap<Term,Term> app=new HashMap<Term,Term>();
if(SubsSub || SubsPred) {
if(SubsSub)
app.put(sub, v1);
if(SubsPred)
app.put(pred,v2);
Term res=((CompoundTerm) statement2).applySubstitute(app);
if(res!=null) { //ok we applied it, all we have to do now is to use it
t22=((Statement)res).getSubject();
t11=((Statement)res).getPredicate();
}
}
}
}
List<Task> success=new ArrayList<Task>();
if(!deriveSequenceOnly && t11!=null && t22!=null) {
Statement statement11 = Implication.make(t11, t22, order);
Statement statement22 = Implication.make(t22, t11, reverseOrder(order));
Statement statement33 = Equivalence.make(t11, t22, order);
if(!tooMuchTemporalStatements(statement11)) {
List<Task> t=nal.doublePremiseTask(statement11, truth1, budget1,true, false);
if(t!=null) {
success.addAll(t);
}
}
if(!tooMuchTemporalStatements(statement22)) {
List<Task> t=nal.doublePremiseTask(statement22, truth2, budget2,true, false);
if(t!=null) {
success.addAll(t);
}
}
if(!tooMuchTemporalStatements(statement33)) {
List<Task> t=nal.doublePremiseTask(statement33, truth3, budget3,true, false);
if(t!=null) {
success.addAll(t);
}
}
}
if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement1)) {
List<Task> t=nal.doublePremiseTask(statement1, truth1, budget1,true, false);
if(t!=null) {
success.addAll(t);
for(Task task : t) {
task.setObservablePrediction(true); //we assume here that this function is used for observable events currently
}
}
}
if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement2)) {
List<Task> t=nal.doublePremiseTask(statement2, truth2, budget2,true, false);
if(t!=null) {
success.addAll(t);
for(Task task : t) {
task.setObservablePrediction(true); //we assume here that this function is used for observable events currently
}
/*Task task=t;
//micropsi inspired strive for knowledge
//get strongest belief of that concept and use the revison truth, if there is no, use this truth
double conf=task.sentence.truth.getConfidence();
Concept C=nal.memory.concept(task.sentence.term);
if(C!=null && C.beliefs!=null && C.beliefs.size()>0) {
Sentence bel=C.beliefs.get(0).sentence;
TruthValue cur=bel.truth;
conf=Math.max(cur.getConfidence(), conf); //no matter if revision is possible, it wont be below max
//if there is no overlapping evidental base, use revision:
boolean revisable=true;
for(long l: bel.stamp.evidentialBase) {
for(long h: task.sentence.stamp.evidentialBase) {
if(l==h) {
revisable=false;
break;
}
}
}
if(revisable) {
conf=TruthFunctions.revision(task.sentence.truth, bel.truth).getConfidence();
}
}
questionFromLowConfidenceHighPriorityJudgement(task, conf, nal); */
}
}
if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement3)) {
List<Task> t=nal.doublePremiseTask(statement3, truth3, budget3,true, false);
if(t!=null) {
for(Task task : t) {
task.setObservablePrediction(true); //we assume here that this function is used for observable events currently
}
success.addAll(t);
}
}
if(!tooMuchTemporalStatements(statement4)) {
List<Task> tl=nal.doublePremiseTask(statement4, truth4, budget4,true, false);
if(tl!=null) {
for(Task t : tl) {
//fill sequenceTask buffer due to the new derived sequence
if(t.sentence.isJudgment() &&
!t.sentence.isEternal() &&
t.sentence.term instanceof Conjunction &&
((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_NONE &&
((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_INVALID) {
nal.memory.addToSequenceTasks(t);
}
success.add(t);
}
}
}
return success;
}
private static void questionFromLowConfidenceHighPriorityJudgement(Task task, double conf, final DerivationContext nal) {
if(nal.memory.emotion.busy()<Parameters.CURIOSITY_BUSINESS_THRESHOLD && Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF && task.sentence.punctuation==Symbols.JUDGMENT_MARK && conf<Parameters.CURIOSITY_CONFIDENCE_THRESHOLD && task.getPriority()>Parameters.CURIOSITY_PRIORITY_THRESHOLD) {
if(task.sentence.term instanceof Implication) {
boolean valid=false;
if(task.sentence.term instanceof Implication) {
Implication equ=(Implication) task.sentence.term;
if(equ.getTemporalOrder()!=TemporalRules.ORDER_NONE) {
valid=true;
}
}
if(valid) {
Sentence tt2=new Sentence(task.sentence.term.clone(),Symbols.QUESTION_MARK,null,new Stamp(task.sentence.stamp.clone(),nal.memory.time()));
BudgetValue budg=task.budget.clone();
budg.setPriority(budg.getPriority()*Parameters.CURIOSITY_DESIRE_PRIORITY_MUL);
budg.setDurability(budg.getPriority()*Parameters.CURIOSITY_DESIRE_DURABILITY_MUL);
nal.singlePremiseTask(tt2, task.budget.clone());
}
}
}
}
/**
* Evaluate the quality of the judgment as a solution to a problem
*
* @param problem A goal or question
* @param solution The solution to be evaluated
* @return The quality of the judgment as the solution
*/
public static float solutionQuality(boolean rateByConfidence, final Task probT, final Sentence solution, Memory memory) {
Sentence problem = probT.sentence;
if (!matchingOrder(problem.getTemporalOrder(), solution.getTemporalOrder())) {
return 0.0F;
}
TruthValue truth = solution.truth;
if (problem.getOccurenceTime()!=solution.getOccurenceTime()) {
truth = solution.projectionTruth(problem.getOccurenceTime(), memory.time());
}
//when the solutions are comparable, we have to use confidence!! else truth expectation.
//this way negative evidence can update the solution instead of getting ignored due to lower truth expectation.
//so the previous handling to let whether the problem has query vars decide was wrong.
if (!rateByConfidence) {
return (float) (truth.getExpectation() / Math.sqrt(Math.sqrt(Math.sqrt(solution.term.getComplexity()*Parameters.COMPLEXITY_UNIT))));
} else {
return truth.getConfidence();
}
}
/**
* Evaluate the quality of a belief as a solution to a problem, then reward
* the belief and de-prioritize the problem
*
* @param problem The problem (question or goal) to be solved
* @param solution The belief as solution
* @param task The task to be immediately processed, or null for continued
* process
* @return The budget for the new task which is the belief activated, if
* necessary
*/
public static BudgetValue solutionEval(final Task problem, final Sentence solution, Task task, final nars.control.DerivationContext nal) {
BudgetValue budget = null;
boolean feedbackToLinks = false;
if (task == null) {
task = nal.getCurrentTask();
feedbackToLinks = true;
}
boolean judgmentTask = task.sentence.isJudgment();
boolean rateByConfidence = problem.getTerm().hasVarQuery(); //here its whether its a what or where question for budget adjustment
final float quality = TemporalRules.solutionQuality(rateByConfidence, problem, solution, nal.mem());
if (problem.sentence.isGoal()) {
nal.memory.emotion.adjustHappy(quality, task.getPriority(), nal);
}
if (judgmentTask) {
task.incPriority(quality);
} else {
float taskPriority = task.getPriority();
budget = new BudgetValue(UtilityFunctions.or(taskPriority, quality), task.getDurability(), BudgetFunctions.truthToQuality(solution.truth));
task.setPriority(Math.min(1 - quality, taskPriority));
}
if (feedbackToLinks) {
TaskLink tLink = nal.getCurrentTaskLink();
tLink.setPriority(Math.min(1 - quality, tLink.getPriority()));
TermLink bLink = nal.getCurrentBeliefLink();
bLink.incPriority(quality);
}
return budget;
}
public static int order(final long timeDiff, final int durationCycles) {
final int halfDuration = durationCycles/2;
if (timeDiff > halfDuration) {
return ORDER_FORWARD;
} else if (timeDiff < -halfDuration) {
return ORDER_BACKWARD;
} else {
return ORDER_CONCURRENT;
}
}
/** if (relative) event B after (stationary) event A then order=forward;
* event B before then order=backward
* occur at the same time, relative to duration: order = concurrent
*/
public static int order(final long a, final long b, final int durationCycles) {
if ((a == Stamp.ETERNAL) || (b == Stamp.ETERNAL))
throw new RuntimeException("order() does not compare ETERNAL times");
return order(b - a, durationCycles);
}
public static boolean concurrent(final long a, final long b, final int durationCycles) {
//since Stamp.ETERNAL is Integer.MIN_VALUE,
//avoid any overflow errors by checking eternal first
if (a == Stamp.ETERNAL) {
//if both are eternal, consider concurrent. this is consistent with the original
//method of calculation which compared equivalent integer values only
return (b == Stamp.ETERNAL);
}
else if (b == Stamp.ETERNAL) {
return false; //a==b was compared above
}
else {
return order(a, b, durationCycles) == ORDER_CONCURRENT;
}
}
}
|
package dr.app.beauti.generator;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.options.*;
import dr.app.beauti.types.ClockType;
import dr.app.beauti.types.FixRateType;
import dr.app.beauti.types.TreePriorType;
import dr.app.beauti.util.XMLWriter;
import dr.evolution.datatype.DataType;
import dr.evolution.util.Taxa;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.tree.TreeModel;
import dr.evomodelxml.branchratemodel.DiscretizedBranchRatesParser;
import dr.evomodelxml.branchratemodel.RandomLocalClockModelParser;
import dr.evomodelxml.branchratemodel.StrictClockBranchRatesParser;
import dr.evomodelxml.clock.ACLikelihoodParser;
import dr.evomodelxml.coalescent.CoalescentLikelihoodParser;
import dr.evomodelxml.speciation.*;
import dr.evomodelxml.tree.TMRCAStatisticParser;
import dr.evomodelxml.tree.TreeLoggerParser;
import dr.evomodelxml.tree.TreeModelParser;
import dr.inference.model.ParameterParser;
import dr.inferencexml.distribution.MixedDistributionLikelihoodParser;
import dr.inferencexml.loggers.ColumnsParser;
import dr.inferencexml.loggers.LoggerParser;
import dr.inferencexml.model.CompoundLikelihoodParser;
import dr.inferencexml.model.CompoundParameterParser;
import dr.util.Attribute;
import dr.xml.XMLParser;
import java.util.ArrayList;
import java.util.List;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Walter Xie
*/
public class LogGenerator extends Generator {
private final static String TREE_FILE_LOG = "treeFileLog";
private final static String SUB_TREE_FILE_LOG = "substTreeFileLog";
public LogGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
}
/**
* write log to screen
*
* @param writer XMLWriter
* @param branchRatesModelGenerator BranchRatesModelGenerator
*/
public void writeLogToScreen(XMLWriter writer, BranchRatesModelGenerator branchRatesModelGenerator,
SubstitutionModelGenerator substitutionModelGenerator) {
writer.writeComment("write log to screen");
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "screenLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.echoEvery + "")
});
if (options.hasData()) {
writer.writeOpenTag(ColumnsParser.COLUMN,
new Attribute[]{
new Attribute.Default<String>(ColumnsParser.LABEL, "Posterior"),
new Attribute.Default<String>(ColumnsParser.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(ColumnsParser.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihoodParser.POSTERIOR, "posterior");
writer.writeCloseTag(ColumnsParser.COLUMN);
}
writer.writeOpenTag(ColumnsParser.COLUMN,
new Attribute[]{
new Attribute.Default<String>(ColumnsParser.LABEL, "Prior"),
new Attribute.Default<String>(ColumnsParser.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(ColumnsParser.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihoodParser.PRIOR, "prior");
writer.writeCloseTag(ColumnsParser.COLUMN);
if (options.hasData()) {
writer.writeOpenTag(ColumnsParser.COLUMN,
new Attribute[]{
new Attribute.Default<String>(ColumnsParser.LABEL, "Likelihood"),
new Attribute.Default<String>(ColumnsParser.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(ColumnsParser.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihoodParser.LIKELIHOOD, "likelihood");
writer.writeCloseTag(ColumnsParser.COLUMN);
}
if (options.useStarBEAST) { // species
writer.writeOpenTag(ColumnsParser.COLUMN,
new Attribute[]{
new Attribute.Default<String>(ColumnsParser.LABEL, "PopMean"),
new Attribute.Default<String>(ColumnsParser.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(ColumnsParser.WIDTH, "12")
}
);
writer.writeIDref(ParameterParser.PARAMETER, TraitData.TRAIT_SPECIES + "." + options.starBEASTOptions.POP_MEAN);
writer.writeCloseTag(ColumnsParser.COLUMN);
}
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeOpenTag(ColumnsParser.COLUMN,
new Attribute[]{
new Attribute.Default<String>(ColumnsParser.LABEL, model.getPrefix() + TreeModelParser.ROOT_HEIGHT),
new Attribute.Default<String>(ColumnsParser.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(ColumnsParser.WIDTH, "12")
}
);
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
writer.writeCloseTag(ColumnsParser.COLUMN);
}
for (PartitionClockModel model : options.getPartitionClockModels()) {
writer.writeOpenTag(ColumnsParser.COLUMN,
new Attribute[]{
new Attribute.Default<String>(ColumnsParser.LABEL, branchRatesModelGenerator.getClockRateString(model)),
new Attribute.Default<String>(ColumnsParser.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(ColumnsParser.WIDTH, "12")
}
);
branchRatesModelGenerator.writeAllClockRateRefs(model, writer);
// if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
// writer.writeIDref(ParameterParser.PARAMETER, "allClockRates");
// for (PartitionClockModel model : options.getPartitionClockModels()) {
// if (model.getClockType() == ClockType.UNCORRELATED_LOGNORMAL)
// writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_STDEV);
// } else {
// for (PartitionClockModel model : options.getPartitionClockModels()) {
// branchRatesModelGenerator.writeAllClockRateRefs(model, writer);
writer.writeCloseTag(ColumnsParser.COLUMN);
}
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
if (model.getDataType().getType() == DataType.MICRO_SAT)
substitutionModelGenerator.writeMicrosatSubstModelParameterRef(model, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_SCREEN_LOG, writer);
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SCREEN_LOG, writer);
}
/**
* write log to file
*
* @param writer XMLWriter
* @param treePriorGenerator TreePriorGenerator
* @param branchRatesModelGenerator BranchRatesModelGenerator
* @param substitutionModelGenerator SubstitutionModelGenerator
* @param treeLikelihoodGenerator TreeLikelihoodGenerator
*/
public void writeLogToFile(XMLWriter writer,
TreePriorGenerator treePriorGenerator,
BranchRatesModelGenerator branchRatesModelGenerator,
SubstitutionModelGenerator substitutionModelGenerator,
TreeLikelihoodGenerator treeLikelihoodGenerator) {
writer.writeComment("write log to file");
if (options.logFileName == null) {
options.logFileName = options.fileNameStem + ".log";
}
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "fileLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(LoggerParser.FILE_NAME, options.logFileName),
new Attribute.Default<Boolean>(LoggerParser.ALLOW_OVERWRITE_LOG, options.allowOverwriteLog)
});
if (options.hasData()) {
writer.writeIDref(CompoundLikelihoodParser.POSTERIOR, "posterior");
}
writer.writeIDref(CompoundLikelihoodParser.PRIOR, "prior");
if (options.hasData()) {
writer.writeIDref(CompoundLikelihoodParser.LIKELIHOOD, "likelihood");
}
if (options.useStarBEAST) { // species
// coalescent prior
writer.writeIDref(MultiSpeciesCoalescentParser.SPECIES_COALESCENT, TraitData.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePriorType.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihoodParser.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// prior on species tree
writer.writeIDref(SpeciationLikelihoodParser.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
writer.writeIDref(ParameterParser.PARAMETER, TraitData.TRAIT_SPECIES + "." + options.starBEASTOptions.POP_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, SpeciesTreeModelParser.SPECIES_TREE + "." + SPLIT_POPS);
if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_BIRTH_DEATH) {
writer.writeIDref(ParameterParser.PARAMETER, TraitData.TRAIT_SPECIES + "." + BirthDeathModelParser.MEAN_GROWTH_RATE_PARAM_NAME);
writer.writeIDref(ParameterParser.PARAMETER, TraitData.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME);
} else if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_YULE ||
options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_YULE_CALIBRATION) {
writer.writeIDref(ParameterParser.PARAMETER, TraitData.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE);
} else {
throw new IllegalArgumentException("Get wrong species tree prior using *BEAST : " + options.getPartitionTreePriors().get(0).getNodeHeightPrior().toString());
}
//Species Tree: tmrcaStatistic
writer.writeIDref(TMRCAStatisticParser.TMRCA_STATISTIC, SpeciesTreeModelParser.SPECIES_TREE + "." + TreeModelParser.ROOT_HEIGHT);
}
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
if (options.useStarBEAST) {
for (Taxa taxa : options.speciesSets) {
// make tmrca(tree.name) eay to read in log for Tracer
writer.writeIDref(TMRCAStatisticParser.TMRCA_STATISTIC, "tmrca(" + taxa.getId() + ")");
}
} else {
for (Taxa taxa : options.taxonSets) {
// make tmrca(tree.name) eay to read in log for Tracer
PartitionTreeModel treeModel = options.taxonSetsTreeModel.get(taxa);
writer.writeIDref(TMRCAStatisticParser.TMRCA_STATISTIC, "tmrca(" + treeModel.getPrefix() + taxa.getId() + ")");
}
}
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeParameterLog(options.activedSameTreePrior, writer);
// } else { // no species
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // priorName.treeModel
treePriorGenerator.writeParameterLog(prior, writer);
}
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeLog(model, writer);
if (model.hasCodon()) {
writer.writeIDref(CompoundParameterParser.COMPOUND_PARAMETER, model.getPrefix() + "allMus");
}
}
for (ClockModelGroup clockModelGroup : options.clockModelOptions.getClockModelGroups()) {
if (clockModelGroup.getRateTypeOption() == FixRateType.FIX_MEAN) {
writer.writeIDref(ParameterParser.PARAMETER, clockModelGroup.getName());
for (PartitionClockModel model : options.getPartitionClockModels(clockModelGroup)) {
if (model.getClockType() == ClockType.UNCORRELATED) {
switch (model.getClockDistributionType()) {
case LOGNORMAL:
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_STDEV);
break;
case GAMMA:
throw new UnsupportedOperationException("Uncorrelated gamma model not implemented yet");
// break;
case CAUCHY:
throw new UnsupportedOperationException("Uncorrelated Cauchy model not implemented yet");
// break;
case EXPONENTIAL:
// nothing required
break;
}
}
}
} else {
for (PartitionClockModel model : options.getPartitionClockModels(clockModelGroup)) {
branchRatesModelGenerator.writeLog(model, writer);
}
}
}
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeLogStatistic(model, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_PARAMETERS, writer);
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
branchRatesModelGenerator.writeClockLikelihoodReferences(writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_LIKELIHOODS, writer);
// coalescentLikelihood
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior = model.getPartitionTreePrior();
treePriorGenerator.writePriorLikelihoodReferenceLog(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePriorType.EXTENDED_SKYLINE)
writer.writeIDref(CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD, prior.getPrefix() + COALESCENT); // only 1 coalescent
}
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_FILE_LOG, writer);
}
/**
* write tree log to file
*
* @param writer XMLWriter
*/
public void writeTreeLogToFile(XMLWriter writer) {
writer.writeComment("write tree log to file");
if (options.useStarBEAST) { // species
// species tree log
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, TraitData.TRAIT_SPECIES + "." + TREE_FILE_LOG), // speciesTreeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + options.starBEASTOptions.SPECIES_TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(SpeciesTreeModelParser.SPECIES_TREE, SP_TREE);
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
// gene tree log
//TODO make code consistent to MCMCPanel
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
String treeFileName;
if (options.substTreeLog) {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + "(time)." + STARBEASTOptions.TREE_FILE_NAME;
} else {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + STARBEASTOptions.TREE_FILE_NAME; // stem.partitionName.tree
}
if (options.treeFileName.get(0).endsWith(".txt")) {
treeFileName += ".txt";
}
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + TREE_FILE_LOG)); // partionName.treeFileLog
attributes.add(new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""));
attributes.add(new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"));
attributes.add(new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, treeFileName));
attributes.add(new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true"));
//if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.RElATIVE_TO && tree.containsUncorrelatedRelaxClock()) { //TODO: Sibon's discretized branch length stuff
// double aveFixedRate = options.clockModelOptions.getSelectedRate(options.getPartitionClockModels());
// attributes.add(new Attribute.Default<String>(TreeLoggerParser.NORMALISE_MEAN_RATE_TO, Double.toString(aveFixedRate)));
// generate <logTree>
writer.writeOpenTag(TreeLoggerParser.LOG_TREE, attributes);
// writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
// new Attribute[]{
// new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + TREE_FILE_LOG), // partionName.treeFileLog
// new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
// new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
// new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, treeFileName),
// new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
writeTreeTraits(writer, tree);
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TREES_LOG, tree, writer);
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
} // end For loop
if (options.substTreeLog) {
if (options.useStarBEAST) { // species
//TODO: species sub tree
}
// gene tree
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
// write tree log to file
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + SUB_TREE_FILE_LOG),
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + tree.getPrefix() +
"(subst)." + STARBEASTOptions.TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.BRANCH_LENGTHS, TreeLoggerParser.SUBSTITUTIONS)
});
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
writeTreeTraits(writer, tree);
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREES_LOG, writer);
}
private void writeTreeTraits(XMLWriter writer, PartitionTreeModel tree) {
for (PartitionClockModel model : options.getPartitionClockModels(options.getDataPartitions(tree))) {
switch (model.getClockType()) {
case STRICT_CLOCK:
writeTreeTrait(writer, StrictClockBranchRatesParser.STRICT_CLOCK_BRANCH_RATES,
model.getPrefix() + BranchRateModel.BRANCH_RATES,
BranchRateModel.RATE, model.getPrefix() + BranchRateModel.RATE);
break;
case UNCORRELATED:
writeTreeTrait(writer, DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES,
options.noDuplicatedPrefix(model.getPrefix(), tree.getPrefix()) + BranchRateModel.BRANCH_RATES,
BranchRateModel.RATE, model.getPrefix() + BranchRateModel.RATE);
break;
case RANDOM_LOCAL_CLOCK:
writeTreeTrait(writer, RandomLocalClockModelParser.LOCAL_BRANCH_RATES,
model.getPrefix() + BranchRateModel.BRANCH_RATES,
BranchRateModel.RATE, model.getPrefix() + BranchRateModel.RATE);
break;
case AUTOCORRELATED:
writer.writeIDref(ACLikelihoodParser.AC_LIKELIHOOD,
options.noDuplicatedPrefix(model.getPrefix(), tree.getPrefix()) + BranchRateModel.BRANCH_RATES);
writeTreeTrait(writer, ACLikelihoodParser.AC_LIKELIHOOD,
options.noDuplicatedPrefix(model.getPrefix(), tree.getPrefix()) + BranchRateModel.BRANCH_RATES,
BranchRateModel.RATE, model.getPrefix() + BranchRateModel.RATE);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
}
private void writeTreeTrait(XMLWriter writer, String treeTraitTag, String treeTraitID, String traitName, String traitTag) {
writer.writeOpenTag(TreeLoggerParser.TREE_TRAIT,
new Attribute[]{
new Attribute.Default<String>(TreeLoggerParser.NAME, traitName),
new Attribute.Default<String>(TreeLoggerParser.TAG, traitTag)
});
writer.writeIDref(treeTraitTag, treeTraitID);
writer.writeCloseTag(TreeLoggerParser.TREE_TRAIT);
}
}
|
package dr.inference.model;
import dr.math.matrixAlgebra.Matrix;
import dr.util.Citable;
import dr.util.Citation;
import java.util.List;
/**
* @author Max Tolkoff
* @author Marc Suchard
*/
public class LatentFactorModel extends AbstractModelLikelihood implements Citable {
// private Matrix data;
// private Matrix factors;
// private Matrix loadings;
private final MatrixParameter data;
private final MatrixParameter factors;
private final MatrixParameter loadings;
private MatrixParameter sData;
private final DiagonalMatrix rowPrecision;
private final DiagonalMatrix colPrecision;
private final Parameter continuous;
private final boolean scaleData;
private final int dimFactors;
private final int dimData;
private final int nTaxa;
private boolean newModel;
private boolean likelihoodKnown = false;
private boolean isDataScaled=false;
private boolean storedLikelihoodKnown;
private boolean residualKnown=false;
private boolean LxFKnown=false;
private boolean storedResidualKnown=false;
private boolean storedLxFKnown;
private boolean traceKnown=false;
private boolean storedTraceKnown;
private boolean logDetColKnown=false;
private boolean storedLogDetColKnown;
private double trace;
private double storedTrace;
private double logLikelihood;
private double storedLogLikelihood;
private double logDetCol;
private double storedLogDetCol;
private boolean[][] changed;
private boolean[][] storedChanged;
private double[] residual;
private double[] LxF;
private double[] storedResidual;
private double[] storedLxF;
private double pathParameter=1.0;
public LatentFactorModel(MatrixParameter data, MatrixParameter factors, MatrixParameter loadings,
DiagonalMatrix rowPrecision, DiagonalMatrix colPrecision,
boolean scaleData, Parameter continuous, boolean newModel
) {
super("");
// data = new Matrix(dataIn.getParameterAsMatrix());
// factors = new Matrix(factorsIn.getParameterAsMatrix());
// loadings = new Matrix(loadingsIn.getParameterAsMatrix());
this.newModel=newModel;
this.scaleData=scaleData;
this.data = data;
this.factors = factors;
// Put default bounds on factors
for (int i = 0; i < factors.getParameterCount(); ++i) {
Parameter p = factors.getParameter(i);
System.err.println(p.getId() + " " + p.getDimension());
p.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, p.getDimension()));
}
this.continuous=continuous;
this.loadings = loadings;
// storedData=new MatrixParameter(null);
// for (int i = 0; i <continuous.getDimension(); i++) {
// if(continuous.getParameterValue(i)==0)
// storedData.addParameter(new Parameter.Default(data.getColumnDimension()));
// Put default bounds on loadings
// loadings.addBounds();
changed=new boolean[loadings.getRowDimension()][factors.getColumnDimension()];
storedChanged=new boolean[loadings.getRowDimension()][factors.getColumnDimension()];
for (int i = 0; i <loadings.getRowDimension() ; i++) {
for (int j = 0; j <factors.getColumnDimension() ; j++) {
changed[i][j]=true;
}
}
this.rowPrecision = rowPrecision;
this.colPrecision = colPrecision;
addVariable(data);
addVariable(factors);
addVariable(loadings);
addVariable(rowPrecision);
addVariable(colPrecision);
dimFactors = factors.getRowDimension();
dimData = loadings.getRowDimension();
// nTaxa = factors.getParameterCount();
// nTaxa = factors.getParameter(0).getDimension();
nTaxa = factors.getColumnDimension();
// System.out.print(nTaxa);
// System.out.print("\n");
// System.out.print(dimData);
// System.out.print("\n");
// System.out.println(dimFactors);
// System.out.println(data.getDimension());
// System.out.println(data.getRowDimension());
// System.out.println(data.getColumnDimension());
// System.out.println(new Matrix(data.getParameterAsMatrix()));
// System.out.println(new Matrix(factors.getParameterAsMatrix()));
if (nTaxa * dimData != data.getDimension()) {
throw new RuntimeException("LOADINGS MATRIX AND FACTOR MATRIX MUST HAVE EXTERNAL DIMENSIONS WHOSE PRODUCT IS EQUAL TO THE NUMBER OF DATA POINTS\n");
// System.exit(10);
}
if (dimData < dimFactors) {
throw new RuntimeException("MUST HAVE FEWER FACTORS THAN DATA POINTS\n");
}
residual=new double[loadings.getRowDimension()*factors.getColumnDimension()];
LxF=new double[loadings.getRowDimension()*factors.getColumnDimension()];
storedResidual=new double[residual.length];
storedLxF=new double[LxF.length];
if(!isDataScaled & !scaleData){
sData=this.data;
isDataScaled=true;
}
if(!isDataScaled){
sData = computeScaledData();
isDataScaled=true;
for (int i = 0; i <sData.getRowDimension() ; i++) {
for (int j = 0; j <sData.getColumnDimension() ; j++) {
this.data.setParameterValue(i,j,sData.getParameterValue(i,j));
// System.out.println(this.data.getParameterValue(i,j));
}
}
data.fireParameterChangedEvent();
}
double sum=0;
for(int i=0; i<sData.getRowDimension(); i++){
for (int j = 0; j <sData.getColumnDimension() ; j++) {
if(continuous.getParameterValue(i)==0 && sData.getParameterValue(i,j)!=0)
{sum+=-.5*Math.log(2*StrictMath.PI)-.5*sData.getParameterValue(i,j)*sData.getParameterValue(i,j);}
}
}
System.out.println("Constant Value for Path Sampling (normal 0,1): " + -1*sum);
computeResiduals();
// System.out.print(new Matrix(residual.toComponents()));
// System.out.print(calculateLogLikelihood());
}
// public Matrix getData(){
// Matrix ans=data;
// return ans;
// public Matrix getFactors(){
// Matrix ans=factors;
// return ans;
// public Matrix getLoadings(){
// Matrix ans=loadings;
// return ans;
// public Matrix getResidual(){
// Matrix ans=residual;
// return ans;
public MatrixParameter getFactors(){return factors;}
public MatrixParameter getColumnPrecision(){return colPrecision;}
public MatrixParameter getLoadings(){return loadings;}
public MatrixParameter getData(){return data;}
public Parameter returnIntermediate(){
if(!residualKnown && checkLoadings()){
computeResiduals();
}
return data;
}
// public Parameter returnIntermediate(int PID)
// { //residualKnown=false;
// if(!residualKnown && checkLoadings()){
// computeResiduals();
// return data.getParameter(PID);
public MatrixParameter getScaledData(){return data;}
public Parameter getContinuous(){return continuous;}
public int getFactorDimension(){return factors.getRowDimension();}
private void Multiply(MatrixParameter Left, MatrixParameter Right, double[] answer){
int dim=Left.getColumnDimension();
int n=Left.getRowDimension();
int p=Right.getColumnDimension();
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
if((changed[i][j]==true && continuous.getParameterValue(i)!=0) || newModel){
double sum = 0;
for (int k = 0; k < dim; k++)
sum += Left.getParameterValue(i, k) * Right.getParameterValue(k,j);
answer[i*p+j]=sum;
//changed[i][j]=false;
}
}
}
}
private void add(MatrixParameter Left, MatrixParameter Right, double[] answer){
int row=Left.getRowDimension();
int col=Left.getColumnDimension();
for (int i = 0; i <row ; i++) {
for (int j = 0; j < col; j++) {
answer[i*col+j]=Left.getParameterValue(i,j)+Right.getParameterValue(i,j);
}
}
}
private void subtract(MatrixParameter Left, double[] Right, double[] answer){
int row=Left.getRowDimension();
int col=Left.getColumnDimension();
for (int i = 0; i <row ; i++) {
if(continuous.getParameterValue(i)!=0 ||newModel){
for (int j = 0; j < col; j++) {
answer[i*col+j]=Left.getParameterValue(i,j)-Right[i*col+j];
}
}
// else{
// for (int j = 0; j <col; j++) {
// Left.setParameterValueQuietly(i,j, Right[i*col+j]);
// containsDiscrete=true;
}
// if(containsDiscrete){
// Left.fireParameterChangedEvent();}
}
private double TDTTrace(double[] array, DiagonalMatrix middle){
int innerDim=middle.getRowDimension();
int outerDim=array.length/innerDim;
double sum=0;
for (int j = 0; j <innerDim ; j++){
if(continuous.getParameterValue(j)!=0 || newModel) {
for (int i = 0; i < outerDim; i++) {
double s1 = array[j * outerDim + i];
double s2 = middle.getParameterValue(j, j);
sum += s1 * s1 * s2;
}
}
}
return sum;
}
private MatrixParameter computeScaledData(){
MatrixParameter answer=new MatrixParameter(data.getParameterName() + ".scaled");
answer.setDimensions(data.getRowDimension(), data.getColumnDimension());
// Matrix answer=new Matrix(data.getRowDimension(), data.getColumnDimension());
double[][] aData=data.getParameterAsMatrix();
double[] meanList=new double[data.getRowDimension()];
double[] varList=new double[data.getRowDimension()];
double[] count=new double[data.getRowDimension()];
for(int i=0; i<data.getColumnDimension(); i++){
for (int j=0; j<data.getRowDimension(); j++){
if(data.getParameterValue(j,i)!=0) {
meanList[j] += data.getParameterValue(j, i);
count[j]++;
}
}
}
for(int i=0; i<data.getRowDimension(); i++){
if(continuous.getParameterValue(i)==1)
meanList[i]=meanList[i]/count[i];
else
meanList[i]=0;
}
double[][] answerTemp=new double[data.getRowDimension()][data.getColumnDimension()];
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
if(aData[j][i]!=0) {
answerTemp[j][i] = aData[j][i] - meanList[j];
}
}
}
// System.out.println(new Matrix(answerTemp));
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
varList[j]+=answerTemp[j][i]*answerTemp[j][i];
}
}
for(int i=0; i<data.getRowDimension(); i++){
if(continuous.getParameterValue(i)==1){
varList[i]=varList[i]/(count[i]-1);
varList[i]=StrictMath.sqrt(varList[i]);}
else{
varList[i]=1;
}
}
// System.out.println(data.getColumnDimension());
// System.out.println(data.getRowDimension());
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
answer.setParameterValue(j,i, answerTemp[j][i]/varList[j]);
}
}
// System.out.println(new Matrix(answerTemp));
// computeResiduals();
return answer;
}
private Matrix copy(CompoundParameter parameter, int dimMajor, int dimMinor) {
return new Matrix(parameter.getParameterValues(), dimMajor, dimMinor);
}
private void computeResiduals() {
// LxFKnown=false;
// if(firstTime || (!factorVariablesChanged.empty() && !loadingVariablesChanged.empty())){
if(!LxFKnown){
Multiply(loadings, factors, LxF);
LxFKnown=true;
}
subtract(data, LxF, residual);
residualKnown=true;
// firstTime=false;}
// else{
// while(!factorVariablesChanged.empty()){
// while(!loadingVariablesChanged.empty()){
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
// Do nothing
}
/**
* Additional state information, outside of the sub-model is stored by this call.
*/
@Override
protected void storeState() {
data.storeParameterValues();
loadings.storeValues();
factors.storeValues();
storedLogLikelihood = logLikelihood;
storedLikelihoodKnown = likelihoodKnown;
storedLogDetColKnown=logDetColKnown;
storedLogDetCol=logDetCol;
storedTrace=trace;
storedTraceKnown=traceKnown;
storedResidualKnown=residualKnown;
storedLxFKnown=LxFKnown;
System.arraycopy(residual, 0, storedResidual, 0, residual.length);
System.arraycopy(LxF, 0, storedLxF, 0, residual.length);
System.arraycopy(changed, 0, storedChanged, 0, changed.length);
}
/**
* After this call the model is guaranteed to have returned its extra state information to
* the values coinciding with the last storeState call.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
@Override
protected void restoreState() {
changed=storedChanged;
data.restoreParameterValues();
loadings.restoreValues();
factors.restoreValues();
logLikelihood = storedLogLikelihood;
likelihoodKnown = storedLikelihoodKnown;
trace=storedTrace;
traceKnown=storedTraceKnown;
residualKnown=storedResidualKnown;
LxFKnown=storedLxFKnown;
residual=storedResidual;
storedResidual=new double[residual.length];
LxF=storedLxF;
storedLxF=new double[LxF.length];
logDetCol=storedLogDetCol;
logDetColKnown=storedLogDetColKnown;
// System.out.println(data.getParameterValue(10, 19));
// int index=0;
// for (int i = 0; i <continuous.getDimension() ; i++) {
// if(continuous.getParameterValue(i)==0){
// for (int j = 0; j <data.getParameter(i).getDimension() ; j++) {
// data.getParameter(i).setParameterValueQuietly(j, storedData.getParameter(index).getParameterValue(j));
// index++;
}
/**
* This call specifies that the current state is accept. Most models will not need to do anything.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
@Override
protected void acceptState() {
// Do nothing
}
/**
* This method is called whenever a parameter is changed.
* <p/>
* It is strongly recommended that the model component sets a "dirty" flag and does no
* further calculations. Recalculation is typically done when the model component is asked for
* some information that requires them. This mechanism is 'lazy' so that this method
* can be safely called multiple times with minimal computational cost.
*/
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
if(variable==getScaledData()){
residualKnown=false;
traceKnown=false;
likelihoodKnown=false;
}
if(variable==factors){
// for (int i = 0; i <loadings.getRowDimension() ; i++) {
// changed[i][index/factors.getRowDimension()]=true;
// factorVariablesChanged.push(index);
LxFKnown=false;
residualKnown=false;
traceKnown=false;
likelihoodKnown = false;
}
if(variable==loadings){
// System.out.println("Loadings Changed");
// System.out.println(index);
// System.out.println(index/loadings.getRowDimension());
// for (int i = 0; i <factors.getColumnDimension(); i++) {
// changed[index%loadings.getRowDimension()][i]=true;
// factorVariablesChanged.push(index);
LxFKnown=false;
residualKnown=false;
traceKnown=false;
likelihoodKnown = false;
}
if(variable==colPrecision){
logDetColKnown=false;
traceKnown=false;
likelihoodKnown = false;
}
}
/**
* @return a list of citations associated with this object
*/
@Override
public List<Citation> getCitations() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Get the model.
*
* @return the model.
*/
@Override
public Model getModel() {
return this;
}
/**
* Get the log likelihood.
*
* @return the log likelihood.
*/
@Override
public double getLogLikelihood() {
likelihoodKnown=false;
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
/**
* Forces a complete recalculation of the likelihood next time getLikelihood is called
*/
@Override
public void makeDirty() {
likelihoodKnown = false;
}
private boolean checkLoadings(){
for(int i=0; i<StrictMath.min(loadings.getRowDimension(),loadings.getColumnDimension()); i++)
{
if(loadings.getParameterValue(i,i)<0)
{
return false;
}
}
return true;
}
private double calculateLogLikelihood() {
// if(!checkLoadings()){
// if(pathParameter==1)
// return Double.NEGATIVE_INFINITY;
// else{
// return Math.log(1-pathParameter);}}
// Matrix tRowPrecision= new Matrix(rowPrecision.getParameterAsMatrix());
// Matrix tColPrecision= new Matrix(colPrecision.getParameterAsMatrix());
// residualKnown=false;
if(!residualKnown){
computeResiduals();
}
// expPart = residual.productInPlace(rowPrecision.productInPlace(residual.transposeThenProductInPlace(colPrecision, TResidualxC), RxTRxC), expPart);
// logDetRow=StrictMath.log(rowPrecision.getDeterminant());
// logDetColKnown=false;
if(!logDetColKnown){
logDetColKnown=true;
double product=1;
for (int i = 0; i <colPrecision.getRowDimension() ; i++) {
if (continuous.getParameterValue(i)!=0)
product*=colPrecision.getParameterValue(i,i);
}
logDetCol=StrictMath.log(product);
}
// System.out.println(logDetCol);
// System.out.println(logDetRow);
// traceKnown=false;
if(!traceKnown){
traceKnown=true;
trace=TDTTrace(residual, colPrecision);
}
// if(expPart.getRowDimension()!=expPart.getColumnDimension())
// System.err.print("Matrices are not conformable");
// System.exit(0);
// else{
// for(int i=0; i<expPart.getRowDimension(); i++){
// trace+=expPart.getParameterValue(i, i);
// System.out.println(expPart);
return -.5*trace + .5*data.getColumnDimension()*logDetCol
-.5*data.getRowDimension()*data.getColumnDimension()*Math.log(2.0 * StrictMath.PI);
}
// public void setPathParameter(double beta){
// pathParameter=beta;
// data.product(pathParameter);
// @Override
// public double getLikelihoodCorrection() {
// return 0;
}
|
package es.ucm.fdi.tp.views.swing;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import es.ucm.fdi.tp.basecode.bgame.control.Controller;
import es.ucm.fdi.tp.basecode.bgame.control.Player;
public class QuitDialog extends JDialog implements ActionListener{
private static final long serialVersionUID = 4321185942579015448L;
private JButton yesButton;
private JButton notButton;
private JLabel pregunta;
private JPanel panelPregunta;
private JPanel panelBotones;
private JPanel panel;
private Controller cntrl;
public QuitDialog(String tittle, Controller c){
super.setTitle(tittle);
this.cntrl = c;
setSize(300,100);
setLocationRelativeTo(null);
panelPregunta = new JPanel();
this.pregunta = new JLabel("Are sure you want to quit?");
panelPregunta.add(pregunta);
panelBotones = new JPanel();
this.yesButton = new JButton(" Yes ");
this.yesButton.addActionListener(this);
panelBotones.add(yesButton);
this.notButton = new JButton(" Not ");
this.notButton.addActionListener(this);
panelBotones.add(notButton);
panel = new JPanel(new BorderLayout());
panel.add(panelPregunta, BorderLayout.NORTH);
panel.add(panelBotones,BorderLayout.SOUTH);
this.add(panel);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton target = (JButton) e.getSource();
if(target == this.yesButton) {
dispose();
cntrl.stop();
} else if (target == this.notButton) {
dispose();
}
}
}
|
package com.indeed.proctor.store;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import java.io.File;
import java.util.TimerTask;
/**
* Timer task used to periodically run git fetch/reset in a git directory
*/
public class GitDirectoryRefresher extends TimerTask {
private static final Logger LOGGER = Logger.getLogger(GitDirectoryRefresher.class);
private static final TextProgressMonitor PROGRESS_MONITOR = new TextProgressMonitor(new LoggerPrintWriter(LOGGER, Level.DEBUG));
private final File directory;
private final GitProctorCore gitProctorCore;
private final UsernamePasswordCredentialsProvider user;
GitDirectoryRefresher(final File directory,
final GitProctorCore git,
final String username,
final String password) {
this.directory = directory;
this.gitProctorCore = git;
this.user = new UsernamePasswordCredentialsProvider(username, password);
}
@Override
public void run() {
try {
synchronized (directory) {
gitProctorCore.getGit().fetch().setProgressMonitor(PROGRESS_MONITOR).setCredentialsProvider(user).call();
gitProctorCore.undoLocalChanges();
gitProctorCore.getGit().gc().call(); /** clean garbage **/
}
} catch (final Exception e) {
LOGGER.error("Error when refreshing git directory " + directory, e);
}
}
public String getDirectoryPath() {
return directory.getPath();
}
}
|
package com.intellij.refactoring.changeSignature.inCallers;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Iconable;
import com.intellij.psi.*;
import com.intellij.psi.presentation.java.ClassPresentationUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.CheckedTreeNode;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.ui.UIUtil;
import com.intellij.refactoring.RefactoringBundle;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.jetbrains.annotations.Nullable;
/**
* @author ven
*/
public class MethodNode extends CheckedTreeNode {
private PsiMethod myMethod;
private boolean myOldChecked;
public MethodNode(final PsiMethod method) {
super(method);
myMethod = method;
isChecked = false;
}
public PsiMethod getMethod() {
return myMethod;
}
//IMPORTANT: do not build children in children()
private void buildChildren () {
if (children == null) {
final PsiMethod[] callers = findCallers();
children = new Vector(callers.length);
for (PsiMethod caller : callers) {
final MethodNode child = new MethodNode(caller);
children.add(child);
child.parent = this;
}
}
}
public TreeNode getChildAt(int index) {
buildChildren();
return super.getChildAt(index);
}
public int getChildCount() {
buildChildren();
return super.getChildCount();
}
public int getIndex(TreeNode aChild) {
buildChildren();
return super.getIndex(aChild);
}
private PsiMethod[] findCallers() {
if (myMethod == null) return PsiMethod.EMPTY_ARRAY;
final Project project = myMethod.getProject();
final List<PsiMethod> callers = new ArrayList<PsiMethod>();
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
public void run() {
final PsiSearchHelper searchHelper = PsiManager.getInstance(project).getSearchHelper();
final PsiReference[] refs = searchHelper.findReferencesIncludingOverriding(myMethod, GlobalSearchScope.allScope(project), true);
for (PsiReference ref : refs) {
final PsiElement element = ref.getElement();
if (!(element instanceof PsiReferenceExpression) ||
!(((PsiReferenceExpression) element).getQualifierExpression() instanceof PsiSuperExpression)) {
final PsiElement enclosingContext = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class);
if (enclosingContext instanceof PsiMethod) {
callers.add((PsiMethod) enclosingContext);
}
}
}
}
}, RefactoringBundle.message("caller.chooser.looking.for.callers"), false, project);
return callers.toArray(new PsiMethod[callers.size()]);
}
public void customizeRenderer (ColoredTreeCellRenderer renderer) {
if (myMethod == null) return;
int flags = Iconable.ICON_FLAG_VISIBILITY | Iconable.ICON_FLAG_READ_STATUS;
renderer.setIcon(myMethod.getIcon(flags));
final StringBuffer buffer = new StringBuffer(128);
final PsiClass containingClass = myMethod.getContainingClass();
if (containingClass != null) {
buffer.append(ClassPresentationUtil.getNameForClass(containingClass, false));
buffer.append('.');
}
final String methodText = PsiFormatUtil.formatMethod(
myMethod,
PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_PARAMETERS,
PsiFormatUtil.SHOW_TYPE
);
buffer.append(methodText);
final SimpleTextAttributes attributes = isEnabled() ?
new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UIUtil.getTreeForeground()) :
SimpleTextAttributes.EXCLUDED_ATTRIBUTES;
renderer.append(buffer.toString(), attributes);
final String packageName = getPackageName(myMethod.getContainingClass());
renderer.append(" (" + packageName + ")", new SimpleTextAttributes(SimpleTextAttributes.STYLE_ITALIC, Color.GRAY));
}
@Nullable
private static String getPackageName(final PsiClass aClass) {
final PsiFile file = aClass.getContainingFile();
if (file instanceof PsiJavaFile) {
return ((PsiJavaFile)file).getPackageName();
}
return null;
}
public void setEnabled(final boolean enabled) {
super.setEnabled(enabled);
if (!enabled) {
myOldChecked = isChecked();
setChecked(false);
}
else {
setChecked(myOldChecked);
}
}
}
|
package com.sg.java8.training.jool;
import org.jooq.lambda.Unchecked;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* A few {@link org.jooq.lambda.Unchecked} usage samples
*/
public class UncheckedMain {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) {
final String convertedDate = "2017-04-20";
final Date date = dateConversionFunction().apply(convertedDate);
System.out.println("The converted date is " + date);
uncheckedConversion(convertedDate);
final List<String> datesToBeParsed = Arrays.asList("2017-04-20", "2017-04-21");
uncheckedFunction(datesToBeParsed);
uncheckedConsumer(datesToBeParsed);
uncheckedSupplier();
uncheckedPredicate(datesToBeParsed);
}
private static Function<String, Date> dateConversionFunction() {
return date -> {
try {
return parseDate(date);
} catch (final ParseException e) {
throw new IllegalArgumentException("Cannot parse '" + date + "'");
}
};
}
private static Date uncheckedConversion(final String date) {
return Unchecked.function(it -> parseDate(it.toString()))
.apply(date);
}
private static void uncheckedFunction(final List<String> datesToBeParsed) {
final Set<Date> parsedDates = datesToBeParsed.stream()
.map(Unchecked.function(UncheckedMain::parseDate))
.collect(Collectors.toSet());
parsedDates.forEach(System.out::println);
}
private static void uncheckedConsumer(final List<String> datesToBeParsed) {
final Consumer<String> consumer = Unchecked.consumer(it -> System.out.println(parseDate(it)));
datesToBeParsed.forEach(consumer);
}
private static Date uncheckedSupplier() {
return Unchecked.supplier(() -> parseDate("2017-04-25"))
.get();
}
private static boolean uncheckedPredicate(final List<String> datesToBeParsed) {
final Date today = new Date();
return datesToBeParsed.stream()
.anyMatch(Unchecked.predicate(value -> parseDate(value).equals(today)));
}
private static Date parseDate(final String date) throws ParseException {
return DATE_FORMAT.parse(date);
}
}
|
package org.openscore.lang.systemtests;
import org.openscore.events.ScoreEvent;
import org.openscore.events.ScoreEventListener;
import org.openscore.lang.api.Slang;
import org.openscore.lang.entities.CompilationArtifact;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import static com.google.common.collect.Sets.newHashSet;
import static org.openscore.events.EventConstants.*;
import static org.openscore.lang.entities.ScoreLangConstants.*;
public class TriggerFlows {
private final static HashSet<String> FINISHED_EVENT =
newHashSet(SCORE_FINISHED_EVENT, SCORE_FAILURE_EVENT, SLANG_EXECUTION_EXCEPTION);
private final static HashSet<String> TASK_EVENTS =
newHashSet(EVENT_INPUT_END, EVENT_OUTPUT_END);
@Autowired
private Slang slang;
private BlockingQueue<ScoreEvent> finishEvent;
public ScoreEvent runSync(CompilationArtifact compilationArtifact, Map<String, Serializable> userInputs) {
finishEvent = new LinkedBlockingQueue<>();
ScoreEventListener finishListener = new ScoreEventListener() {
@Override
public void onEvent(ScoreEvent event) throws InterruptedException {
finishEvent.add(event);
}
};
slang.subscribeOnEvents(finishListener, FINISHED_EVENT);
slang.run(compilationArtifact, userInputs);
try {
ScoreEvent event = finishEvent.take();
slang.unSubscribeOnEvents(finishListener);
return event;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public Map<String, PathData> run(CompilationArtifact compilationArtifact, Map<String, Serializable> userInputs) {
RunDataAggregatorListener listener = new RunDataAggregatorListener();
slang.subscribeOnEvents(listener, TASK_EVENTS);
runSync(compilationArtifact, userInputs);
// //Damn ugly workaround for unknown events sync issues.
// try {
// Thread.sleep(2000);
// } catch (InterruptedException ignored) {}
Map<String, PathData> tasks = listener.aggregate();
slang.unSubscribeOnEvents(listener);
return tasks;
}
}
|
package com.altamiracorp.securegraph.test;
import static com.altamiracorp.securegraph.test.util.IterableUtils.assertContains;
import static com.altamiracorp.securegraph.util.IterableUtils.count;
import static com.altamiracorp.securegraph.util.IterableUtils.toList;
import static org.junit.Assert.*;
import com.altamiracorp.securegraph.Authorizations;
import com.altamiracorp.securegraph.Direction;
import com.altamiracorp.securegraph.Edge;
import com.altamiracorp.securegraph.ElementMutation;
import com.altamiracorp.securegraph.Graph;
import com.altamiracorp.securegraph.Path;
import com.altamiracorp.securegraph.Property;
import com.altamiracorp.securegraph.Text;
import com.altamiracorp.securegraph.TextIndexHint;
import com.altamiracorp.securegraph.Vertex;
import com.altamiracorp.securegraph.Visibility;
import com.altamiracorp.securegraph.property.PropertyValue;
import com.altamiracorp.securegraph.property.StreamingPropertyValue;
import com.altamiracorp.securegraph.query.Compare;
import com.altamiracorp.securegraph.query.DefaultGraphQuery;
import com.altamiracorp.securegraph.query.GeoCompare;
import com.altamiracorp.securegraph.query.TextPredicate;
import com.altamiracorp.securegraph.test.util.LargeStringInputStream;
import com.altamiracorp.securegraph.type.GeoCircle;
import com.altamiracorp.securegraph.type.GeoPoint;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public abstract class GraphTestBase {
public static final Visibility VISIBILITY_A = new Visibility("a");
public static final Visibility VISIBILITY_B = new Visibility("b");
public static final Visibility VISIBILITY_EMPTY = new Visibility("");
public final Authorizations AUTHORIZATIONS_A;
public final Authorizations AUTHORIZATIONS_B;
public final Authorizations AUTHORIZATIONS_C;
public final Authorizations AUTHORIZATIONS_A_AND_B;
public final Authorizations AUTHORIZATIONS_EMPTY;
public static final int LARGE_PROPERTY_VALUE_SIZE = 1024 + 1;
protected Graph graph;
protected abstract Graph createGraph() throws Exception;
public Graph getGraph() {
return graph;
}
public GraphTestBase() {
AUTHORIZATIONS_A = createAuthorizations("a");
AUTHORIZATIONS_B = createAuthorizations("b");
AUTHORIZATIONS_C = createAuthorizations("c");
AUTHORIZATIONS_A_AND_B = createAuthorizations("a", "b");
AUTHORIZATIONS_EMPTY = createAuthorizations();
}
protected abstract Authorizations createAuthorizations(String... auths);
@Before
public void before() throws Exception {
graph = createGraph();
}
@After
public void after() throws Exception {
graph = null;
}
@Test
public void testAddVertexWithId() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_A, v.getVisibility());
}
@Test
public void testAddVertexWithoutId() {
Vertex v = graph.addVertex(VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(v);
Object vertexId = v.getId();
assertNotNull(vertexId);
v = graph.getVertex(vertexId, AUTHORIZATIONS_A);
assertNotNull(v);
assertNotNull(vertexId);
}
@Test
public void testAddStreamingPropertyValue() throws IOException, InterruptedException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()), String.class);
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty("propLarge", propLarge, VISIBILITY_A)
.save();
Iterable<Object> propSmallValues = v1.getPropertyValues("propSmall");
assertEquals(1, count(propSmallValues));
Object propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
StreamingPropertyValue value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
Iterable<Object> propLargeValues = v1.getPropertyValues("propLarge");
assertEquals(1, count(propLargeValues));
Object propLargeValue = propLargeValues.iterator().next();
assertTrue("propLargeValue was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
propSmallValues = v1.getPropertyValues("propSmall");
assertEquals(1, count(propSmallValues));
propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
propLargeValues = v1.getPropertyValues("propLarge");
assertEquals(1, count(propLargeValues));
propLargeValue = propLargeValues.iterator().next();
assertTrue("propLargeValue was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
}
@Test
public void testAddVertexPropertyWithMetadata() {
Map<String, Object> prop1Metadata = new HashMap<String, Object>();
prop1Metadata.put("metadata1", "metadata1Value");
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save();
Vertex v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
Property prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertNotNull(prop1Metadata);
assertEquals(1, prop1Metadata.keySet().size());
assertEquals("metadata1Value", prop1Metadata.get("metadata1"));
prop1Metadata.put("metadata2", "metadata2Value");
v.prepareMutation()
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(2, prop1Metadata.keySet().size());
assertEquals("metadata1Value", prop1Metadata.get("metadata1"));
assertEquals("metadata2Value", prop1Metadata.get("metadata2"));
// make sure we clear out old values
prop1Metadata = new HashMap<String, Object>();
v.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(0, prop1Metadata.keySet().size());
}
@Test
public void testAddVertexWithProperties() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save();
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
}
@Test
public void testMultivaluedProperties() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.addPropertyValue("propid3a", "prop3", "value3a", VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("value1a", v.getPropertyValues("prop1").iterator().next());
assertEquals("value2a", v.getPropertyValues("prop2").iterator().next());
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
assertEquals(3, count(v.getProperties()));
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2b", VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getPropertyValues("prop1")));
assertEquals("value1b", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getPropertyValues("prop2")));
assertEquals("value2b", v.getPropertyValues("prop2").iterator().next());
assertEquals(1, count(v.getPropertyValues("prop3")));
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
assertEquals(3, count(v.getProperties()));
v.addPropertyValue("propid1b", "prop1", "value1a-new", VISIBILITY_A);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertContains("value1b", v.getPropertyValues("prop1"));
assertContains("value1a-new", v.getPropertyValues("prop1"));
assertEquals(4, count(v.getProperties()));
}
@Test
public void testMultivaluedPropertyOrder() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.addPropertyValue("a", "prop", "a", VISIBILITY_A)
.addPropertyValue("aa", "prop", "aa", VISIBILITY_A)
.addPropertyValue("b", "prop", "b", VISIBILITY_A)
.addPropertyValue("0", "prop", "0", VISIBILITY_A)
.addPropertyValue("A", "prop", "A", VISIBILITY_A)
.addPropertyValue("Z", "prop", "Z", VISIBILITY_A)
.save();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("0", v1.getPropertyValue("prop", 0));
assertEquals("A", v1.getPropertyValue("prop", 1));
assertEquals("Z", v1.getPropertyValue("prop", 2));
assertEquals("a", v1.getPropertyValue("prop", 3));
assertEquals("aa", v1.getPropertyValue("prop", 4));
assertEquals("b", v1.getPropertyValue("prop", 5));
}
@Test
public void testRemoveProperty() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid1b", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
v.removeProperty("prop1");
assertEquals(1, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties()));
v.removeProperty("propid2a", "prop2");
assertEquals(0, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v.getProperties()));
}
@Test
public void testAddVertexWithVisibility() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_A);
Iterable<Vertex> cVertices = graph.getVertices(AUTHORIZATIONS_C);
assertEquals(0, count(cVertices));
Iterable<Vertex> aVertices = graph.getVertices(AUTHORIZATIONS_A);
assertEquals(1, count(aVertices));
assertEquals("v1", aVertices.iterator().next().getId());
Iterable<Vertex> bVertices = graph.getVertices(AUTHORIZATIONS_B);
assertEquals(1, count(bVertices));
assertEquals("v2", bVertices.iterator().next().getId());
Iterable<Vertex> allVertices = graph.getVertices(AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(allVertices));
}
@Test
public void testGetVerticesWithIds() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v1", VISIBILITY_A)
.save();
graph.prepareVertex("v1b", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v1b", VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v2", VISIBILITY_A)
.save();
graph.prepareVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v3", VISIBILITY_A)
.save();
List<Object> ids = new ArrayList<Object>();
ids.add("v1");
ids.add("v2");
Iterable<Vertex> vertices = graph.getVertices(ids, AUTHORIZATIONS_A);
boolean foundV1 = false, foundV2 = false;
for (Vertex v : vertices) {
if (v.getId().equals("v1")) {
assertEquals("v1", v.getPropertyValue("prop1"));
foundV1 = true;
} else if (v.getId().equals("v2")) {
assertEquals("v2", v.getPropertyValue("prop1"));
foundV2 = true;
} else {
assertTrue("Unexpected vertex id: " + v.getId(), false);
}
}
assertTrue("v1 not found", foundV1);
assertTrue("v2 not found", foundV2);
}
@Test
public void testGetEdgesWithIds() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e1", VISIBILITY_A)
.save();
graph.prepareEdge("e1a", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e1a", VISIBILITY_A)
.save();
graph.prepareEdge("e2", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e2", VISIBILITY_A)
.save();
graph.prepareEdge("e3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e3", VISIBILITY_A)
.save();
List<Object> ids = new ArrayList<Object>();
ids.add("e1");
ids.add("e2");
Iterable<Edge> edges = graph.getEdges(ids, AUTHORIZATIONS_A);
boolean foundE1 = false, foundE2 = false;
for (Edge e : edges) {
if (e.getId().equals("e1")) {
assertEquals("e1", e.getPropertyValue("prop1"));
foundE1 = true;
} else if (e.getId().equals("e2")) {
assertEquals("e2", e.getPropertyValue("prop1"));
foundE2 = true;
} else {
assertTrue("Unexpected vertex id: " + e.getId(), false);
}
}
assertTrue("e1 not found", foundE1);
assertTrue("e2 not found", foundE2);
}
@Test
public void testRemoveVertex() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
try {
graph.removeVertex("v1", AUTHORIZATIONS_B);
} catch (IllegalArgumentException e) {
// expected
}
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.removeVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A)));
}
@Test
public void testRemoveVertexWithProperties() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", VISIBILITY_B)
.save();
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
try {
graph.removeVertex("v1", AUTHORIZATIONS_B);
} catch (IllegalArgumentException e) {
// expected
}
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.removeVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
}
@Test
public void testAddEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
e = graph.getEdge("e1", AUTHORIZATIONS_B);
assertNull(e);
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
}
@Test
public void testGetEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label2", v1, v2, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2to1", v2, v1, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(3, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(Direction.IN, AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.BOTH, "label1", AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.OUT, "label1", AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, "label1", AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.OUT, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
}
@Test
public void testAddEdgeWithProperties() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.setProperty("propB", "valueB", VISIBILITY_B)
.save();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals(0, count(e.getPropertyValues("propB")));
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals("valueB", e.getPropertyValues("propB").iterator().next());
assertEquals("valueA", e.getPropertyValue("propA"));
assertEquals("valueB", e.getPropertyValue("propB"));
}
@Test
public void testRemoveEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
try {
graph.removeEdge("e1", AUTHORIZATIONS_B);
} catch (IllegalArgumentException e) {
// expected
}
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.removeEdge("e1", AUTHORIZATIONS_A);
assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_A)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(0, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
}
@Test
public void testAddEdgeWithVisibility() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_B, AUTHORIZATIONS_B);
Iterable<Edge> aEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A);
assertEquals(1, count(aEdges));
Edge e1 = aEdges.iterator().next();
assertNotNull(e1);
assertEquals("edgeA", e1.getLabel());
Iterable<Edge> bEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_B);
assertEquals(1, count(bEdges));
Edge e2 = bEdges.iterator().next();
assertNotNull(e2);
assertEquals("edgeB", e2.getLabel());
Iterable<Edge> allEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(allEdges));
}
@Test
public void testGraphQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).limit(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(2).vertices();
assertEquals(0, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(2).vertices();
assertEquals(1, count(vertices));
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A).edges();
assertEquals(1, count(edges));
}
@Test
public void testGraphQueryWithQueryString() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.setProperty("description", "This is vertex 1 - dog.", VISIBILITY_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
v2.setProperty("description", "This is vertex 2 - cat.", VISIBILITY_A);
Iterable<Vertex> vertices = graph.query("vertex", AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_A).vertices();
assertEquals(1, count(vertices));
// TODO elastic search can't filter based on authorizations
// vertices = graph.query("dog", AUTHORIZATIONS_B).vertices();
// assertEquals(0, count(vertices));
}
@Test
public void testGraphQueryHas() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_A)
.setProperty("birthDate", createDate(1989, 1, 5), VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 30, VISIBILITY_A)
.setProperty("birthDate", createDate(1984, 1, 5), VISIBILITY_A)
.save();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN_EQUAL, 25)
.vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25})
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25, 30})
.vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN, 26)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN_EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.NOT_EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryHasWithSpaces() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("name", "Joe Ferner", VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("name", "Joe Smith", VISIBILITY_A)
.save();
Iterable<Vertex> vertices = graph.query("Ferner", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query("joe", AUTHORIZATIONS_A)
.vertices();
assertEquals(2, count(vertices));
if (!isUsingDefaultQuery(graph)) {
vertices = graph.query("joe AND ferner", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
}
if (!isUsingDefaultQuery(graph)) {
vertices = graph.query("name:\"joe ferner\"", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
}
if (!isUsingDefaultQuery(graph)) {
vertices = graph.query("joe smith", AUTHORIZATIONS_A)
.vertices();
List<Vertex> verticesList = toList(vertices);
assertEquals(2, verticesList.size());
assertEquals("v2", verticesList.get(0).getId());
assertEquals("v1", verticesList.get(1).getId());
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe")
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
assertEquals(1, count(vertices));
// TODO should this work?
// vertices = graph.query(AUTHORIZATIONS_A)
// .has("name", "Joe Ferner")
// .vertices();
// assertEquals(1, count(vertices));
}
protected boolean isUsingDefaultQuery(Graph graph) {
return graph.query(AUTHORIZATIONS_A) instanceof DefaultGraphQuery;
}
@Test
public void testGraphQueryGeoPoint() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297), VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("location", new GeoPoint(38.9544, -77.3464), VISIBILITY_A)
.save();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 1))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 15))
.vertices();
assertEquals(2, count(vertices));
}
private Date createDate(int year, int month, int day) {
return new GregorianCalendar(year, month, day).getTime();
}
@Test
public void testGraphQueryRange() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 30, VISIBILITY_A)
.save();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 20, 29)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 30)
.vertices();
assertEquals(2, count(vertices));
}
@Test
public void testVertexQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.setProperty("prop1", "value1", VISIBILITY_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
v2.setProperty("prop1", "value2", VISIBILITY_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
v3.setProperty("prop1", "value3", VISIBILITY_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Iterable<Vertex> vertices = v1.query(AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
assertContains(v2, vertices);
assertContains(v3, vertices);
vertices = v1.query(AUTHORIZATIONS_A)
.has("prop1", "value2")
.vertices();
assertEquals(1, count(vertices));
assertContains(v2, vertices);
Iterable<Edge> edges = v1.query(AUTHORIZATIONS_A).edges();
assertEquals(2, count(edges));
assertContains(ev1v2, edges);
assertContains(ev1v3, edges);
edges = v1.query(AUTHORIZATIONS_A).edges(Direction.OUT);
assertEquals(2, count(edges));
assertContains(ev1v2, edges);
assertContains(ev1v3, edges);
}
@Test
public void testFindPaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v2
graph.addEdge(v2, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
List<Path> paths = toList(graph.findPaths(v1, v4, 2, AUTHORIZATIONS_A));
// v1 -> v2 -> v4
// v1 -> v3 -> v4
assertEquals(2, paths.size());
boolean found2 = false;
boolean found3 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v2.getId().equals(id)) {
found2 = true;
} else if (v3.getId().equals(id)) {
found3 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v4.getId());
}
i++;
}
}
assertTrue("v2 not found in path", found2);
assertTrue("v3 not found in path", found3);
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
paths = toList(graph.findPaths(v4, v1, 2, AUTHORIZATIONS_A));
// v4 -> v2 -> v1
// v4 -> v3 -> v1
assertEquals(2, paths.size());
found2 = false;
found3 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v4.getId());
} else if (i == 1) {
if (v2.getId().equals(id)) {
found2 = true;
} else if (v3.getId().equals(id)) {
found3 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v1.getId());
}
i++;
}
}
assertTrue("v2 not found in path", found2);
assertTrue("v3 not found in path", found3);
}
@Test
public void testGetVerticesFromVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(3, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(0, count(v1.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(2, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(1, count(v2.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v2.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A);
assertEquals(2, count(v3.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(0, count(v3.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(2, count(v3.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
assertEquals(1, count(v4.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(0, count(v4.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v4.getVertices(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testBlankVisibilityString() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
v = graph.getVertex("v1", AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_EMPTY, v.getVisibility());
}
@Test
public void testElementMutationDoesntChangeObjectUntilSave() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
v.setProperty("prop1", "value1", VISIBILITY_A);
ElementMutation<Vertex> m = v.prepareMutation()
.setProperty("prop1", "value2", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A);
assertEquals(1, count(v.getProperties()));
assertEquals("value1", v.getPropertyValue("prop1"));
m.save();
assertEquals(2, count(v.getProperties()));
assertEquals("value2", v.getPropertyValue("prop1"));
assertEquals("value2", v.getPropertyValue("prop2"));
}
@Test
public void testFindRelatedEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev2v3 = graph.addEdge("e v2->v3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev3v1 = graph.addEdge("e v3->v1", v3, v1, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
List<Object> vertexIds = new ArrayList<Object>();
vertexIds.add("v1");
vertexIds.add("v2");
vertexIds.add("v3");
Iterable<Object> edges = toList(graph.findRelatedEdges(vertexIds, AUTHORIZATIONS_A));
assertEquals(4, count(edges));
assertContains(ev1v2.getId(), edges);
assertContains(ev1v3.getId(), edges);
assertContains(ev2v3.getId(), edges);
assertContains(ev3v1.getId(), edges);
}
@Test
public void testEmptyPropertyMutation() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.prepareMutation().save();
}
@Test
public void testTextIndex() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("none", new Text("Test Value", TextIndexHint.NONE), VISIBILITY_A)
.setProperty("both", new Text("Test Value", TextIndexHint.ALL), VISIBILITY_A)
.setProperty("fullText", new Text("Test Value", TextIndexHint.FULL_TEXT), VISIBILITY_A)
.setProperty("exactMatch", new Text("Test Value", TextIndexHint.EXACT_MATCH), VISIBILITY_A)
.save();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("Test Value", v1.getPropertyValue("none"));
assertEquals("Test Value", v1.getPropertyValue("both"));
assertEquals("Test Value", v1.getPropertyValue("fullText"));
assertEquals("Test Value", v1.getPropertyValue("exactMatch"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("fullText", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals("exact match shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals("unindexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", "Test Value").vertices()));
assertEquals("default has predicate is equals which shouldn't work for full text", 0, count(graph.query(AUTHORIZATIONS_A).has("fullText", "Test Value").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test Value").vertices()));
assertEquals("default has predicate is equals which shouldn't work for unindexed", 0, count(graph.query(AUTHORIZATIONS_A).has("none", "Test Value").vertices()));
}
}
|
package nl.sense_os.service.subscription;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* Manager class for keeping track of DataProducers and DataConsumers
* </p>
*
* @author Steven Mulder <steven@sense-os.nl>
*/
public class SubscriptionManager {
/** Singleton instance */
private static SubscriptionManager sInstance;
/**
* Factory method for singleton pattern
*
* @return The singleton instance of the subscription manager
*/
public static SubscriptionManager getInstance() {
if (null == sInstance) {
sInstance = new SubscriptionManager();
}
return sInstance;
}
/** All DataConsumers, mapped by the name of the producer they are subscribed to. */
private Map<String, List<DataConsumer>> mConsumers;
/** All registered DataProducers, mapped by their name. */
private Map<String, List<DataProducer>> mProducers;
/**
* Constructor.
*
* @param context
* @see #getInstance()
*/
protected SubscriptionManager() {
mConsumers = new HashMap<String, List<DataConsumer>>();
mProducers = new HashMap<String, List<DataProducer>>();
}
/**
* @param name
* The name of the DataProducer
* @return A List of DataProducer that are registered under the given sensor name
*/
public List<DataProducer> getRegisteredProducers(String name) {
return mProducers.get(name);
}
/**
* @param name
* The name of the DataProcessor
* @return A List of DataConsumer that are subscribed to the given sensor name
*/
public List<DataConsumer> getSubscribedConsumers(String name) {
return mConsumers.get(name);
}
/**
* @param name
* The name of the DataProducer
* @param consumer
* The data consumer instance to check for
* @return <code>true</code> if this consumer is already subscribed for producers with this name
*/
public boolean isConsumerSubscribed(String name, DataConsumer consumer) {
if (!mConsumers.containsKey(name)) {
// nothing is subscribed to this sensor name
return false;
}
// check if dataProcessor is in the list of subscribed processors
List<DataConsumer> processors = mConsumers.get(name);
for (DataConsumer registeredProcessor : processors) {
if (registeredProcessor.equals(consumer)) {
return true;
}
}
return false;
}
/**
* @param name
* The name of the DataProducer
* @return true if any data producer is already registered under this sensor name
*/
public boolean isProducerRegistered(String name) {
return mProducers.containsKey(name);
}
/**
* @param name
* The name of the DataProducer
* @param producer
* The DataProducer instance to check for
* @return true if the data producer is already registered under this sensor name
*/
public boolean isProducerRegistered(String name, DataProducer producer) {
if (!isProducerRegistered(name)) {
// nothing is registered under this sensor name
return false;
}
// check if producer is already in the list of registered producers
List<DataProducer> producers = mProducers.get(name);
for (DataProducer registeredProducer : producers) {
if (registeredProducer.equals(producer)) {
return true;
}
}
return false;
}
/**
* <p>
* Registers a DataProducer with the given name at the SenseService.
* </p>
* <p>
* When a data producer is registered, data consumers can subscribe to its sensor data.
* Registering a data producer with an existing name will add the new data producer only if this
* data producer is a different instance from the other data producer.
* </p>
*
* @param name
* The name of the data producer
* @param producer
* The data producer
*/
public synchronized void registerProducer(String name, DataProducer producer) {
if (isProducerRegistered(name, producer)) {
// data producer is already registered
return;
}
// add the producer to the list of registered producers
List<DataProducer> producers = mProducers.get(name);
if (null == producers) {
producers = new ArrayList<DataProducer>();
}
producers.add(producer);
mProducers.put(name, producers);
// see if there are any data processors subscribed to this sensor name
if (!mConsumers.containsKey(name)) {
return;
}
// subscribe existing DataProcessors to the new DataProducer
List<DataConsumer> subscribers = mConsumers.get(name);
for (DataConsumer subscriber : subscribers) {
producer.addSubscriber(subscriber);
}
}
/**
* Subscribe to a DataProducer<br/>
* <br/>
* This method subscribes a DataProcessor to receive SensorDataPoints from a DataProducer. If
* the DataProducer with name to subscribe to is not registered yet then the data processor will
* be put in the queue and will be subscribed to the DataProducer when it is registered.
*
* @param name
* The name of the registered DataProducer
* @param consumer
* The DataConsumer that receives the sensor data
* @return true if the DataConsumer successfully subscribed to the DataProducer.
*/
public synchronized boolean subscribeConsumer(String name, DataConsumer consumer) {
if (isConsumerSubscribed(name, consumer)) {
// consumer is already subscribed
return false;
}
// add the consumer to the list of subscribed consumers
List<DataConsumer> processors = mConsumers.get(name);
if (null == processors) {
processors = new ArrayList<DataConsumer>();
}
processors.add(consumer);
mConsumers.put(name, processors);
// see if there are any producers for this sensor name
List<DataProducer> producers = mProducers.get(name);
if (producers == null) {
return false;
}
// subscribe the new processor to the existing producers
boolean subscribed = false;
for (DataProducer producer : producers) {
subscribed |= producer.addSubscriber(consumer);
}
return subscribed;
}
/**
* Unregisters a DataProducer.<br/>
* <br/>
* No new data consumers can subscribe to the DataProducer anymore, but DataConsumer which have
* already subscribed to the DataProducer will remain subscribed.
*
* @param name
* The name that the DataProducer is registered under
* @param producer
* The DataProducer to unregister
*/
public synchronized void unregisterProducer(String name, DataProducer producer) {
if (!mProducers.containsKey(name)) {
// this producer is not registered under this name
return;
}
// remove the producer from the list of registered producers for this sensor name
List<DataProducer> dataProducers = mProducers.get(name);
dataProducers.remove(producer);
if (dataProducers.size() == 0) {
mProducers.remove(name);
} else {
mProducers.put(name, dataProducers);
}
}
/**
* Unsubscribes a data consumer from a data producer.
*
* @param name
* The name of the DataProducer that the consumer registered for
* @param consumer
* The DataConsumer that receives the sensor data
*/
public synchronized void unsubscribeConsumer(String name, DataConsumer consumer) {
if (!mProducers.containsKey(name)) {
// there are no data producers to unsubscribe from
return;
}
if (!mConsumers.containsKey(name)) {
// this processor is not registered (?)
return;
}
// remove the processor from the list of subscribed processors
List<DataConsumer> processors = mConsumers.get(name);
processors.remove(consumer);
if (processors.size() == 0) {
mConsumers.remove(name);
} else {
mConsumers.put(name, processors);
}
// unsubscribe the processor from the producers for this sensor name
List<DataProducer> producers = mProducers.get(name);
for (DataProducer registeredProducer : producers) {
registeredProducer.removeSubscriber(consumer);
}
mProducers.remove(name);
}
}
|
package com.java110.api.listener.owner;
import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.owner.IOwnerBMO;
import com.java110.api.bmo.user.IUserBMO;
import com.java110.api.listener.AbstractServiceApiPlusListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.core.factory.SendSmsFactory;
import com.java110.core.smo.common.ISmsInnerServiceSMO;
import com.java110.core.smo.community.ICommunityInnerServiceSMO;
import com.java110.core.smo.common.IFileInnerServiceSMO;
import com.java110.core.smo.user.IOwnerAppUserInnerServiceSMO;
import com.java110.core.smo.user.IOwnerInnerServiceSMO;
import com.java110.core.smo.user.IUserInnerServiceSMO;
import com.java110.dto.community.CommunityDto;
import com.java110.dto.msg.SmsDto;
import com.java110.dto.owner.OwnerAppUserDto;
import com.java110.dto.owner.OwnerDto;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.ServiceCodeConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.List;
import java.util.Map;
/**
* @ClassName AppUserBindingOwnerListener
* @Description
* @Author wuxw
* @Date 2019/4/26 14:51
* @Version 1.0
* add by wuxw 2019/4/26
**/
@Java110Listener("ownerRegisterListener")
public class OwnerRegisterListener extends AbstractServiceApiPlusListener {
private static final int DEFAULT_SEQ_COMMUNITY_MEMBER = 2;
@Autowired
private IOwnerBMO ownerBMOImpl;
@Autowired
private IUserBMO userBMOImpl;
@Autowired
private IFileInnerServiceSMO fileInnerServiceSMOImpl;
@Autowired
private ISmsInnerServiceSMO smsInnerServiceSMOImpl;
@Autowired
private ICommunityInnerServiceSMO communityInnerServiceSMOImpl;
@Autowired
private IOwnerInnerServiceSMO ownerInnerServiceSMOImpl;
@Autowired
private IOwnerAppUserInnerServiceSMO ownerAppUserInnerServiceSMOImpl;
@Autowired
private IUserInnerServiceSMO userInnerServiceSMOImpl;
private static Logger logger = LoggerFactory.getLogger(OwnerRegisterListener.class);
@Override
public String getServiceCode() {
return ServiceCodeConstant.SERVICE_CODE_OWNER_REGISTER;
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
Assert.hasKeyAndValue(reqJson, "communityName", "");
Assert.hasKeyAndValue(reqJson, "areaCode", "");
Assert.hasKeyAndValue(reqJson, "appUserName", "");
Assert.hasKeyAndValue(reqJson, "idCard", "");
Assert.hasKeyAndValue(reqJson, "link", "");
Assert.hasKeyAndValue(reqJson, "msgCode", "");
Assert.hasKeyAndValue(reqJson, "password", "");
SmsDto smsDto = new SmsDto();
smsDto.setTel(reqJson.getString("link"));
smsDto.setCode(reqJson.getString("msgCode"));
smsDto = smsInnerServiceSMOImpl.validateCode(smsDto);
if (!smsDto.isSuccess() && "ON".equals(MappingCache.getValue(SendSmsFactory.SMS_SEND_SWITCH))) {
throw new IllegalArgumentException(smsDto.getMsg());
}
}
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
logger.debug("ServiceDataFlowEvent : {}", event);
OwnerAppUserDto ownerAppUserDto = BeanConvertUtil.covertBean(reqJson, OwnerAppUserDto.class);
ownerAppUserDto.setStates(new String[]{"10000", "12000"});
List<OwnerAppUserDto> ownerAppUserDtos = ownerAppUserInnerServiceSMOImpl.queryOwnerAppUsers(ownerAppUserDto);
//Assert.listOnlyOne(ownerAppUserDtos, "");
if (ownerAppUserDtos != null && ownerAppUserDtos.size() > 0) {
throw new IllegalArgumentException("");
}
CommunityDto communityDto = new CommunityDto();
communityDto.setCityCode(reqJson.getString("areaCode"));
communityDto.setName(reqJson.getString("communityName"));
communityDto.setState("1100");
List<CommunityDto> communityDtos = communityInnerServiceSMOImpl.queryCommunitys(communityDto);
Assert.listOnlyOne(communityDtos, "");
CommunityDto tmpCommunityDto = communityDtos.get(0);
OwnerDto ownerDto = new OwnerDto();
ownerDto.setCommunityId(tmpCommunityDto.getCommunityId());
ownerDto.setIdCard(reqJson.getString("idCard"));
ownerDto.setName(reqJson.getString("appUserName"));
ownerDto.setLink(reqJson.getString("link"));
List<OwnerDto> ownerDtos = ownerInnerServiceSMOImpl.queryOwnerMembers(ownerDto);
Assert.listOnlyOne(ownerDtos, "");
OwnerDto tmpOwnerDto = ownerDtos.get(0);
DataFlowContext dataFlowContext = event.getDataFlowContext();
String paramIn = dataFlowContext.getReqData();
JSONObject paramObj = JSONObject.parseObject(paramIn);
String appId = context.getAppId();
if ("992020061452450002".equals(appId)) {
paramObj.put("appType",OwnerAppUserDto.APP_TYPE_WECHAT);
} else if ("992019111758490006".equals(appId)) {
paramObj.put("appType",OwnerAppUserDto.APP_TYPE_WECHAT_MINA);
} else {//app
paramObj.put("appType",OwnerAppUserDto.APP_TYPE_APP);
}
paramObj.put("userId", GenerateCodeFactory.getUserId());
if (reqJson.containsKey("openId")) {
paramObj.put("openId", reqJson.getString("openId"));
} else {
paramObj.put("openId", "-1");
}
ownerBMOImpl.addOwnerAppUser(paramObj, tmpCommunityDto, tmpOwnerDto, dataFlowContext);
paramObj.put("name", paramObj.getString("appUserName"));
paramObj.put("tel", paramObj.getString("link"));
userBMOImpl.registerUser(paramObj, dataFlowContext);
}
@Override
public int getOrder() {
return 0;
}
public IFileInnerServiceSMO getFileInnerServiceSMOImpl() {
return fileInnerServiceSMOImpl;
}
public void setFileInnerServiceSMOImpl(IFileInnerServiceSMO fileInnerServiceSMOImpl) {
this.fileInnerServiceSMOImpl = fileInnerServiceSMOImpl;
}
public ICommunityInnerServiceSMO getCommunityInnerServiceSMOImpl() {
return communityInnerServiceSMOImpl;
}
public void setCommunityInnerServiceSMOImpl(ICommunityInnerServiceSMO communityInnerServiceSMOImpl) {
this.communityInnerServiceSMOImpl = communityInnerServiceSMOImpl;
}
public IOwnerInnerServiceSMO getOwnerInnerServiceSMOImpl() {
return ownerInnerServiceSMOImpl;
}
public void setOwnerInnerServiceSMOImpl(IOwnerInnerServiceSMO ownerInnerServiceSMOImpl) {
this.ownerInnerServiceSMOImpl = ownerInnerServiceSMOImpl;
}
public IOwnerAppUserInnerServiceSMO getOwnerAppUserInnerServiceSMOImpl() {
return ownerAppUserInnerServiceSMOImpl;
}
public void setOwnerAppUserInnerServiceSMOImpl(IOwnerAppUserInnerServiceSMO ownerAppUserInnerServiceSMOImpl) {
this.ownerAppUserInnerServiceSMOImpl = ownerAppUserInnerServiceSMOImpl;
}
public IUserInnerServiceSMO getUserInnerServiceSMOImpl() {
return userInnerServiceSMOImpl;
}
public void setUserInnerServiceSMOImpl(IUserInnerServiceSMO userInnerServiceSMOImpl) {
this.userInnerServiceSMOImpl = userInnerServiceSMOImpl;
}
}
|
package cz.muni.fi.pa165.methanolmanager.service.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDto {
private Integer id;
private String name;
private String username;
private String password;
private String roleName;
}
|
package org.cytoscape.session.internal;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.group.CyGroup;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyNetworkTableManager;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.CyTableManager;
import org.cytoscape.model.CyTableMetadata;
import org.cytoscape.model.SavePolicy;
import org.cytoscape.model.subnetwork.CyRootNetwork;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.property.CyProperty;
import org.cytoscape.property.bookmark.Bookmarks;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.session.CySession;
import org.cytoscape.session.CySessionManager;
import org.cytoscape.session.events.SessionAboutToBeSavedEvent;
import org.cytoscape.session.events.SessionLoadedEvent;
import org.cytoscape.session.events.SessionSavedEvent;
import org.cytoscape.session.events.SessionSavedListener;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.view.model.VisualLexicon;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.presentation.RenderingEngineManager;
import org.cytoscape.view.presentation.property.BasicVisualLexicon;
import org.cytoscape.view.vizmap.VisualMappingFunction;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.undo.UndoSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of {@link org.cytoscape.session.CySessionManager}.
*
* @author Christian Lopes
*/
public class CySessionManagerImpl implements CySessionManager, SessionSavedListener {
private String currentFileName;
private CySession currentSession;
private final CyEventHelper eventHelper;
private final CyApplicationManager appMgr;
private final CyNetworkManager netMgr;
private final CyTableManager tblMgr;
private final CyNetworkTableManager netTblMgr;
private final VisualMappingManager vmMgr;
private final CyNetworkViewManager nvMgr;
private final CyRootNetworkManager rootNetMgr;
private final RenderingEngineManager renderingEngineMgr;
private final CyGroupManager grMgr;
private final CyServiceRegistrar registrar;
private final UndoSupport undo;
private final Set<CyProperty<?>> sessionProperties;
private CyProperty<Bookmarks> bookmarks;
private static final Logger logger = LoggerFactory.getLogger(CySessionManagerImpl.class);
public CySessionManagerImpl(final CyEventHelper eventHelper,
final CyApplicationManager appMgr,
final CyNetworkManager netMgr,
final CyTableManager tblMgr,
final CyNetworkTableManager netTblMgr,
final VisualMappingManager vmMgr,
final CyNetworkViewManager nvMgr,
final CyRootNetworkManager rootNetMgr,
final RenderingEngineManager renderingEngineMgr,
final CyGroupManager grMgr,
final CyServiceRegistrar registrar,
final UndoSupport undo) {
this.eventHelper = eventHelper;
this.appMgr = appMgr;
this.netMgr = netMgr;
this.tblMgr = tblMgr;
this.netTblMgr = netTblMgr;
this.vmMgr = vmMgr;
this.nvMgr = nvMgr;
this.rootNetMgr = rootNetMgr;
this.renderingEngineMgr = renderingEngineMgr;
this.grMgr = grMgr;
this.registrar = registrar;
this.sessionProperties = new HashSet<CyProperty<?>>();
this.undo = undo;
}
@Override
public CySession getCurrentSession() {
// Apps who want to save anything to a session will have to listen for this event
// and will then be responsible for adding files through SessionAboutToBeSavedEvent.addAppFiles(..)
final SessionAboutToBeSavedEvent savingEvent = new SessionAboutToBeSavedEvent(this);
eventHelper.fireEvent(savingEvent);
final Set<CyNetwork> networks = getSerializableNetworks();
final Set<CyNetworkView> netViews = nvMgr.getNetworkViewSet();
// Visual Styles Map
final Map<CyNetworkView, String> stylesMap = new HashMap<CyNetworkView, String>();
if (netViews != null) {
for (final CyNetworkView nv : netViews) {
final VisualStyle style = vmMgr.getVisualStyle(nv);
if (style != null)
stylesMap.put(nv, style.getTitle());
}
}
final Map<String, List<File>> appMap = savingEvent.getAppFileListMap();
final Set<CyTableMetadata> metadata = createTablesMetadata(networks);
final Set<VisualStyle> styles = vmMgr.getAllVisualStyles();
final Set<CyProperty<?>> props = getAllProperties();
// Build the session
final CySession sess = new CySession.Builder().properties(props).appFileListMap(appMap)
.tables(metadata).networks(networks).networkViews(netViews).visualStyles(styles)
.viewVisualStyleMap(stylesMap).build();
return sess;
}
@SuppressWarnings("unchecked")
private static Class<? extends CyIdentifiable>[] TYPES = new Class[] { CyNetwork.class, CyNode.class, CyEdge.class };
private Set<CyNetwork> getSerializableNetworks() {
final Set<CyNetwork> serializableNetworks = new HashSet<CyNetwork>();
final Set<CyNetwork> allNetworks = netTblMgr.getNetworkSet();
for (final CyNetwork net : allNetworks) {
if (net.getSavePolicy() == SavePolicy.SESSION_FILE)
serializableNetworks.add(net);
}
return serializableNetworks;
}
private Set<CyTableMetadata> createTablesMetadata(final Set<CyNetwork> networks) {
final Set<CyTableMetadata> result = new HashSet<CyTableMetadata>();
result.addAll(createNetworkTablesMetadata(networks));
result.addAll(createGlobalTablesMetadata(tblMgr.getGlobalTables()));
return result;
}
private Set<CyTableMetadata> createNetworkTablesMetadata(final Set<CyNetwork> networks) {
final Set<CyTableMetadata> result = new HashSet<CyTableMetadata>();
// Create the metadata object for each network table
for (final CyNetwork network : networks) {
for (final Class<? extends CyIdentifiable> type : TYPES) {
final Map<String, CyTable> tableMap = netTblMgr.getTables(network, type);
for (final Entry<String, CyTable> entry : tableMap.entrySet()) {
final CyTable tbl = entry.getValue();
if (tbl.getSavePolicy() == SavePolicy.SESSION_FILE) {
final String namespace = entry.getKey();
final CyTableMetadata metadata = new CyTableMetadataImpl.CyTableMetadataBuilder()
.setCyTable(tbl).setNamespace(namespace).setType(type).setNetwork(network)
.build();
result.add(metadata);
}
}
}
}
return result;
}
private Collection<? extends CyTableMetadata> createGlobalTablesMetadata(final Set<CyTable> tables) {
final Set<CyTableMetadata> result = new HashSet<CyTableMetadata>();
for (final CyTable tbl : tables) {
if (tbl.getSavePolicy() == SavePolicy.SESSION_FILE)
result.add(new CyTableMetadataImpl.CyTableMetadataBuilder().setCyTable(tbl));
}
return result;
}
@Override
public void setCurrentSession(CySession sess, final String fileName) {
// Always remove the current session first
disposeCurrentSession();
if (sess == null) {
logger.debug("Creating empty session...");
final Set<VisualStyle> styles = vmMgr.getAllVisualStyles();
final Set<CyProperty<?>> props = getAllProperties();
sess = new CySession.Builder().properties(props).visualStyles(styles).build();
} else {
logger.debug("Restoring the session...");
// Save the selected networks first, so the selection state can be restored later.
final List<CyNetwork> selectedNetworks = new ArrayList<CyNetwork>();
final Set<CyNetwork> networks = sess.getNetworks();
for (CyNetwork n : networks) {
final Boolean selected = n.getDefaultNetworkTable().getRow(n.getSUID())
.get(CyNetwork.SELECTED, Boolean.class);
if (Boolean.TRUE.equals(selected))
selectedNetworks.add(n);
}
restoreProperties(sess);
restoreNetworks(sess);
restoreTables(sess);
restoreNetworkViews(sess, selectedNetworks);
restoreNetworkSelection(sess, selectedNetworks);
restoreVisualStyles(sess);
restoreCurrentVisualStyle();
}
currentSession = sess;
currentFileName = fileName;
eventHelper.fireEvent(new SessionLoadedEvent(this, currentSession, getCurrentSessionFileName()));
}
/**
* Update current session session object when session is saved.
*/
@Override
public void handleEvent(SessionSavedEvent e) {
if (currentSession != e.getSavedSession())
currentSession = e.getSavedSession();
if (currentFileName != e.getSavedFileName())
currentFileName = e.getSavedFileName();
}
@Override
public String getCurrentSessionFileName() {
return currentFileName;
}
@SuppressWarnings("unchecked")
public void addCyProperty(final CyProperty<?> newCyProperty, final Map<String, String> properties) {
CyProperty.SavePolicy sp = newCyProperty.getSavePolicy();
if (sp == CyProperty.SavePolicy.SESSION_FILE || sp == CyProperty.SavePolicy.SESSION_FILE_AND_CONFIG_DIR) {
if (Bookmarks.class.isAssignableFrom(newCyProperty.getPropertyType()))
bookmarks = (CyProperty<Bookmarks>) newCyProperty;
else
sessionProperties.add(newCyProperty);
}
}
public void removeCyProperty(final CyProperty<?> oldCyProperty, final Map<String, String> properties) {
CyProperty.SavePolicy sp = oldCyProperty.getSavePolicy();
if (sp == CyProperty.SavePolicy.SESSION_FILE || sp == CyProperty.SavePolicy.SESSION_FILE_AND_CONFIG_DIR) {
if (Bookmarks.class.isAssignableFrom(oldCyProperty.getPropertyType()))
bookmarks = null;
else
sessionProperties.remove(oldCyProperty);
}
}
private Set<CyProperty<?>> getAllProperties() {
final Set<CyProperty<?>> set = new HashSet<CyProperty<?>>(sessionProperties);
if (bookmarks != null)
set.add(bookmarks);
return set;
}
private void restoreProperties(final CySession sess) {
for (CyProperty<?> cyProps : sess.getProperties()) {
final Properties serviceProps = new Properties();
serviceProps.setProperty("cyPropertyName", cyProps.getName());
registrar.registerAllServices(cyProps, serviceProps);
}
}
private void restoreNetworks(final CySession sess) {
logger.debug("Restoring networks...");
Set<CyNetwork> networks = sess.getNetworks();
for (CyNetwork n : networks) {
netMgr.addNetwork(n);
}
}
private void restoreNetworkViews(final CySession sess, List<CyNetwork> selectedNetworks) {
logger.debug("Restoring network views...");
Set<CyNetworkView> netViews = sess.getNetworkViews();
List<CyNetworkView> selectedViews = new ArrayList<CyNetworkView>();
for (CyNetworkView nv : netViews) {
CyNetwork network = nv.getModel();
if (selectedNetworks.contains(network)) {
selectedViews.add(nv);
}
}
Map<CyNetworkView, Map<VisualProperty<?>, Object>> viewVPMap =
new HashMap<CyNetworkView, Map<VisualProperty<?>,Object>>();
if (netViews != null) {
for (CyNetworkView nv : netViews) {
if (nv != null) {
// Save the original values of these visual properties,
// because we will have to set them again after the views are rendered
Map<VisualProperty<?>, Object> vpMap = new HashMap<VisualProperty<?>, Object>();
viewVPMap.put(nv, vpMap);
vpMap.put(BasicVisualLexicon.NETWORK_HEIGHT, nv.getVisualProperty(BasicVisualLexicon.NETWORK_HEIGHT));
vpMap.put(BasicVisualLexicon.NETWORK_WIDTH, nv.getVisualProperty(BasicVisualLexicon.NETWORK_WIDTH));
nvMgr.addNetworkView(nv);
}
}
}
// Let's guarantee the network views are rendered
eventHelper.flushPayloadEvents();
// Set the saved visual properties again, because the renderer may have overwritten the original values
for (Entry<CyNetworkView, Map<VisualProperty<?>, Object>> entry1 : viewVPMap.entrySet()) {
CyNetworkView nv = entry1.getKey();
for (Entry<VisualProperty<?>, Object> entry2 : entry1.getValue().entrySet())
nv.setVisualProperty(entry2.getKey(), entry2.getValue());
}
if (!selectedViews.isEmpty())
appMgr.setCurrentNetworkView(selectedViews.get(0));
appMgr.setSelectedNetworkViews(selectedViews);
}
private void restoreTables(final CySession sess) {
final Set<CyTable> allTables = new HashSet<CyTable>();
// Register all tables sent through the CySession, if not already registered
for (final CyTableMetadata metadata : sess.getTables()) {
allTables.add(metadata.getTable());
}
// There may be other network tables in the CyNetworkTableManager that were not serialized in the session file
// (e.g. Table Facades), so it's necessary to add them to CyTableManager as well
for (final CyNetwork net : sess.getNetworks()) {
allTables.addAll(netTblMgr.getTables(net, CyNetwork.class).values());
allTables.addAll(netTblMgr.getTables(net, CyNode.class).values());
allTables.addAll(netTblMgr.getTables(net, CyEdge.class).values());
if (!(net instanceof CyRootNetwork)) {
final CyRootNetwork root = rootNetMgr.getRootNetwork(net);
allTables.addAll(netTblMgr.getTables(root, CyNetwork.class).values());
allTables.addAll(netTblMgr.getTables(root, CyNode.class).values());
allTables.addAll(netTblMgr.getTables(root, CyEdge.class).values());
}
}
// Register all tables sent through the CySession, if not already registered
for (final CyTable tbl : allTables) {
if (tblMgr.getTable(tbl.getSUID()) == null)
tblMgr.addTable(tbl);
}
}
private void restoreVisualStyles(final CySession sess) {
logger.debug("Restoring visual styles...");
// Register visual styles
final VisualStyle defStyle = vmMgr.getDefaultVisualStyle();
final String DEFAULT_STYLE_NAME = defStyle.getTitle();
final Set<VisualStyle> styles = sess.getVisualStyles();
final Map<String, VisualStyle> stylesMap = new HashMap<String, VisualStyle>();
if (styles != null) {
for (VisualStyle vs : styles) {
if (vs.getTitle().equals(DEFAULT_STYLE_NAME)) {
// Update the current default style, because it can't be replaced or removed
updateVisualStyle(vs, defStyle);
vs = defStyle;
}
stylesMap.put(vs.getTitle(), vs);
if (!vs.equals(defStyle))
vmMgr.addVisualStyle(vs);
}
}
// Set visual styles to network views
final Map<CyNetworkView, String> viewStyleMap = sess.getViewVisualStyleMap();
if (viewStyleMap != null) {
for (Entry<CyNetworkView, String> entry : viewStyleMap.entrySet()) {
final CyNetworkView netView = entry.getKey();
final String stName = entry.getValue();
VisualStyle vs = stylesMap.get(stName);
if (vs == null)
vs = defStyle;
if (vs != null) {
vmMgr.setVisualStyle(vs, netView);
vs.apply(netView);
}
}
}
}
/**
* @param source the Visual Style that will provide the new properties and values.
* @param target the Visual Style that will be updated.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private void updateVisualStyle(final VisualStyle source, final VisualStyle target) {
// First clean up the target
final HashSet<VisualMappingFunction<?, ?>> mapingSet =
new HashSet<VisualMappingFunction<?, ?>>(target.getAllVisualMappingFunctions());
for (final VisualMappingFunction<?, ?> mapping : mapingSet)
target.removeVisualMappingFunction(mapping.getVisualProperty());
final Set<VisualPropertyDependency<?>> depList =
new HashSet<VisualPropertyDependency<?>>(target.getAllVisualPropertyDependencies());
for (final VisualPropertyDependency<?> dep : depList)
target.removeVisualPropertyDependency(dep);
// Copy the default visual properties, mappings and dependencies from source to target
final VisualLexicon lexicon = renderingEngineMgr.getDefaultVisualLexicon();
final Set<VisualProperty<?>> properties = lexicon.getAllVisualProperties();
for (final VisualProperty vp : properties) {
if (!vp.equals(BasicVisualLexicon.NETWORK)
&& !vp.equals(BasicVisualLexicon.NODE)
&& !vp.equals(BasicVisualLexicon.EDGE))
target.setDefaultValue(vp, source.getDefaultValue(vp));
}
for (final VisualPropertyDependency<?> dep : source.getAllVisualPropertyDependencies())
target.addVisualPropertyDependency(dep);
for (final VisualMappingFunction<?, ?> mapping : source.getAllVisualMappingFunctions())
target.addVisualMappingFunction(mapping);
}
private void restoreNetworkSelection(final CySession sess, final List<CyNetwork> selectedNets) {
// If the current view/network was not set, set the first selected network as current
if (!selectedNets.isEmpty()) {
final CyNetwork cn = selectedNets.get(0);
appMgr.setCurrentNetwork(cn);
// Also set the current view, if there is one
final Collection<CyNetworkView> cnViews = nvMgr.getNetworkViews(cn);
final CyNetworkView cv = cnViews.isEmpty() ? null : cnViews.iterator().next();
appMgr.setCurrentNetworkView(cv);
// The selected networks must be set after setting the current one!
appMgr.setSelectedNetworks(selectedNets);
}
}
private void restoreCurrentVisualStyle() {
// Make sure the current visual style is the one applied to the current network view
eventHelper.flushPayloadEvents();
final CyNetworkView cv = appMgr.getCurrentNetworkView();
if (cv != null) {
final VisualStyle style = vmMgr.getVisualStyle(cv);
if (style != null && !style.equals(vmMgr.getCurrentVisualStyle()))
vmMgr.setCurrentVisualStyle(style);
}
}
private void disposeCurrentSession() {
logger.debug("Disposing current session...");
// Destroy groups
final Set<CyGroup> groups = new HashSet<CyGroup>();
for (final CyNetwork n : netMgr.getNetworkSet())
groups.addAll(grMgr.getGroupSet(n));
for (final CyGroup gr : groups)
grMgr.destroyGroup(gr);
// TODO: This can't be done, because the Group Manager may contain groups from the new session, which are being registered in io-impl
// grMgr.reset();
// Destroy network views
final Set<CyNetworkView> netViews = nvMgr.getNetworkViewSet();
for (final CyNetworkView nv : netViews) {
nvMgr.destroyNetworkView(nv);
}
nvMgr.reset();
// Destroy networks
final Set<CyNetwork> networks = netMgr.getNetworkSet();
for (final CyNetwork n : networks) {
netMgr.destroyNetwork(n);
}
netMgr.reset();
// Destroy styles
logger.debug("Removing current visual styles...");
final VisualStyle defaultStyle = vmMgr.getDefaultVisualStyle();
final List<VisualStyle> allStyles = new ArrayList<VisualStyle>(vmMgr.getAllVisualStyles());
for (final VisualStyle vs : allStyles) {
if (!vs.equals(defaultStyle))
vmMgr.removeVisualStyle(vs);
}
// Destroy tables
tblMgr.reset();
// Unregister session properties
final Set<CyProperty<?>> cyPropsClone = getAllProperties();
for (CyProperty<?> cyProps : cyPropsClone) {
if (cyProps.getSavePolicy().equals(CyProperty.SavePolicy.SESSION_FILE)) {
registrar.unregisterAllServices(cyProps);
sessionProperties.remove(cyProps);
}
}
// Clear undo stack
undo.reset();
// Reset current table and rendering engine
appMgr.reset();
}
}
|
package gov.nih.nci.cananolab.dto.common;
import gov.nih.nci.cananolab.service.security.UserBean;
import gov.nih.nci.cananolab.util.Constants;
import java.util.ArrayList;
import java.util.List;
public class SecuredDataBean {
private List<AccessibilityBean> userAccesses = new ArrayList<AccessibilityBean>();
private List<AccessibilityBean> groupAccesses = new ArrayList<AccessibilityBean>();
private AccessibilityBean theAccess = new AccessibilityBean();
private List<AccessibilityBean> allAccesses = new ArrayList<AccessibilityBean>();
private Boolean publicStatus = false;
private UserBean user;
protected String createdBy;
private Boolean userUpdatable = false;
private Boolean userDeletable = false;
private Boolean userIsOwner = false;
public List<AccessibilityBean> getUserAccesses() {
return userAccesses;
}
public void setUserAccesses(List<AccessibilityBean> userAccesses) {
this.userAccesses = userAccesses;
}
public List<AccessibilityBean> getGroupAccesses() {
return groupAccesses;
}
public void setGroupAccesses(List<AccessibilityBean> groupAccesses) {
this.groupAccesses = groupAccesses;
}
public AccessibilityBean getTheAccess() {
return theAccess;
}
public void setTheAccess(AccessibilityBean theAccess) {
this.theAccess = theAccess;
}
public List<AccessibilityBean> getAllAccesses() {
allAccesses.addAll(getGroupAccesses());
allAccesses.addAll(getUserAccesses());
return allAccesses;
}
public Boolean getPublicStatus() {
publicStatus = this.retrievPublicStatus();
return publicStatus;
}
public Boolean getUserUpdatable() {
if (userAccesses.isEmpty() && groupAccesses.isEmpty()) {
return userUpdatable;
}
userUpdatable = this.retrieveUserUpdatable(user);
return userUpdatable;
}
public void setUserUpdatable(Boolean userUpdatable) {
this.userUpdatable = userUpdatable;
}
public Boolean getUserDeletable() {
if (userAccesses.isEmpty() && groupAccesses.isEmpty()) {
return userDeletable;
}
userDeletable = this.retrieveUserDeletable(user);
return userDeletable;
}
public void setUserDeletable(Boolean userDeletable) {
this.userDeletable = userDeletable;
}
public Boolean getUserIsOwner() {
userIsOwner = this.retrieveUserIsOwner(user, createdBy);
return userIsOwner;
}
private Boolean retrieveUserUpdatable(UserBean user) {
if (user == null) {
return false;
}
if (user.isCurator()) {
return true;
}
for (AccessibilityBean access : userAccesses) {
if (access.getUserBean().getLoginName().equals(user.getLoginName())
&& (access.getRoleName().equals(
AccessibilityBean.CSM_CURD_ROLE) || access
.getRoleName().equals(
AccessibilityBean.CSM_CUR_ROLE))) {
return true;
}
}
for (AccessibilityBean access : groupAccesses) {
for (String groupName : user.getGroupNames()) {
if (access.getGroupName().equals(groupName)
&& access.getRoleName().equals(
AccessibilityBean.CSM_CURD_ROLE)
|| access.getRoleName().equals(
AccessibilityBean.CSM_CUR_ROLE)) {
return true;
}
}
}
return false;
}
private Boolean retrieveUserDeletable(UserBean user) {
if (user == null) {
return false;
}
if (user.isCurator()) {
return true;
}
for (AccessibilityBean access : userAccesses) {
if (access.getUserBean().getLoginName().equals(user.getLoginName())
&& (access.getRoleName().equals(
AccessibilityBean.CSM_CURD_ROLE) || access
.getRoleName().equals(
AccessibilityBean.CSM_DELETE_ROLE))) {
return true;
}
}
for (AccessibilityBean access : groupAccesses) {
for (String groupName : user.getGroupNames()) {
if (access.getGroupName().equals(groupName)
&& access.getRoleName().equals(
AccessibilityBean.CSM_CURD_ROLE)
|| access.getRoleName().equals(
AccessibilityBean.CSM_DELETE_ROLE)) {
return true;
}
}
}
return false;
}
public Boolean retrieveUserIsOwner(UserBean user, String createdBy) {
if (user == null || createdBy == null) {
return false;
}
// user is either a curator or the creator of the data
// or if the data created from COPY and contains the creator info
if (user != null
&& (user.getLoginName().equalsIgnoreCase(createdBy)
|| createdBy.contains(createdBy + ":"
+ Constants.AUTO_COPY_ANNOTATION_PREFIX) || user
.isCurator())) {
return true;
} else {
return false;
}
}
private Boolean retrievPublicStatus() {
for (AccessibilityBean access : groupAccesses) {
if (access.getGroupName()
.equals(AccessibilityBean.CSM_PUBLIC_GROUP)) {
return true;
}
}
return false;
}
public void setUser(UserBean user) {
this.user = user;
}
public UserBean getUser() {
return user;
}
}
|
package com.jetbrains.python.psi.resolve;
import com.jetbrains.python.psi.types.TypeEvalContext;
/**
* @author yole
*/
public class PyResolveContext {
private final boolean myAllowImplicits;
private final TypeEvalContext myTypeEvalContext;
private PyResolveContext(boolean allowImplicits) {
myAllowImplicits = allowImplicits;
myTypeEvalContext = null;
}
private PyResolveContext(boolean allowImplicits, TypeEvalContext typeEvalContext) {
myAllowImplicits = allowImplicits;
myTypeEvalContext = typeEvalContext;
}
public boolean allowImplicits() {
return myAllowImplicits;
}
private static final PyResolveContext ourDefaultContext = new PyResolveContext(true);
private static final PyResolveContext ourNoImplicitsContext = new PyResolveContext(false);
public static PyResolveContext defaultContext() {
return ourDefaultContext;
}
public static PyResolveContext noImplicits() {
return ourNoImplicitsContext;
}
public PyResolveContext withTypeEvalContext(TypeEvalContext context) {
return new PyResolveContext(myAllowImplicits, context);
}
public TypeEvalContext getTypeEvalContext() {
return myTypeEvalContext != null ? myTypeEvalContext : TypeEvalContext.fast();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PyResolveContext that = (PyResolveContext)o;
if (myAllowImplicits != that.myAllowImplicits) return false;
if (myTypeEvalContext != null ? !myTypeEvalContext.equals(that.myTypeEvalContext) : that.myTypeEvalContext != null) return false;
return true;
}
@Override
public int hashCode() {
int result = (myAllowImplicits ? 1 : 0);
result = 31 * result + (myTypeEvalContext != null ? myTypeEvalContext.hashCode() : 0);
return result;
}
}
|
// ImprovisionTiffReader.java
package loci.formats.in;
import java.io.IOException;
import java.util.*;
import loci.formats.*;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
public class ImprovisionTiffReader extends BaseTiffReader {
// -- Fields --
private String[] cNames;
private int pixelSizeT;
private float pixelSizeX, pixelSizeY, pixelSizeZ;
// -- Constructor --
public ImprovisionTiffReader() {
super("Improvision TIFF", new String[] {"tif", "tiff"});
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
try {
RandomAccessStream stream = new RandomAccessStream(block);
boolean isThisType = isThisType(stream);
stream.close();
return isThisType;
}
catch (IOException e) {
if (debug) trace(e);
}
return false;
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (!open) return false;
try {
RandomAccessStream stream = new RandomAccessStream(name);
boolean isThisType = isThisType(stream);
stream.close();
return isThisType;
}
catch (IOException e) {
if (debug) trace(e);
}
return false;
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
cNames = null;
pixelSizeT = 1;
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
put("Improvision", "yes");
// parse key/value pairs in the comment
String comment = TiffTools.getComment(ifds[0]);
String tz = null, tc = null, tt = null;
if (comment != null) {
StringTokenizer st = new StringTokenizer(comment, "\n");
while (st.hasMoreTokens()) {
String line = st.nextToken();
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
addMeta(key, value);
if (key.equals("TotalZPlanes")) tz = value;
else if (key.equals("TotalChannels")) tc = value;
else if (key.equals("TotalTimepoints")) tt = value;
else if (key.equals("XCalibrationMicrons")) {
pixelSizeX = Float.parseFloat(value);
}
else if (key.equals("YCalibrationMicrons")) {
pixelSizeY = Float.parseFloat(value);
}
else if (key.equals("ZCalibrationMicrons")) {
pixelSizeZ = Float.parseFloat(value);
}
}
metadata.remove("Comment");
}
if (tz == null) tz = "1";
if (tc == null) tc = "1";
if (tt == null) tt = "1";
core.sizeZ[0] = Integer.parseInt(tz);
core.sizeC[0] = Integer.parseInt(tc);
core.sizeT[0] = Integer.parseInt(tt);
if (core.sizeZ[0] * core.sizeC[0] * core.sizeT[0] < core.imageCount[0]) {
core.sizeC[0] = core.imageCount[0];
}
// parse each of the comments to determine axis ordering
long[] stamps = new long[ifds.length];
int[][] coords = new int[ifds.length][3];
cNames = new String[core.sizeC[0]];
for (int i=0; i<ifds.length; i++) {
comment = TiffTools.getComment(ifds[i]);
comment = comment.replaceAll("\r\n", "\n");
comment = comment.replaceAll("\r", "\n");
StringTokenizer st = new StringTokenizer(comment, "\n");
String channelName = null;
while (st.hasMoreTokens()) {
String line = st.nextToken();
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
if (key.equals("TimeStampMicroSeconds")) {
stamps[i] = Long.parseLong(value);
}
else if (key.equals("ZPlane")) coords[i][0] = Integer.parseInt(value);
else if (key.equals("ChannelNo")) {
coords[i][1] = Integer.parseInt(value);
}
else if (key.equals("TimepointName")) {
coords[i][2] = Integer.parseInt(value);
}
else if (key.equals("ChannelName")) {
channelName = value;
}
else if (key.equals("ChannelNo")) {
int ndx = Integer.parseInt(value);
if (cNames[ndx] == null) cNames[ndx] = channelName;
}
}
}
// determine average time per plane
long sum = 0;
for (int i=1; i<stamps.length; i++) {
long diff = stamps[i] - stamps[i - 1];
if (diff > 0) sum += diff;
}
pixelSizeT = (int) (sum / core.sizeT[0]);
// determine dimension order
core.currentOrder[0] = "XY";
for (int i=1; i<coords.length; i++) {
int zDiff = coords[i][0] - coords[i - 1][0];
int cDiff = coords[i][1] - coords[i - 1][1];
int tDiff = coords[i][2] - coords[i - 1][2];
if (zDiff > 0 && core.currentOrder[0].indexOf("Z") < 0) {
core.currentOrder[0] += "Z";
}
if (cDiff > 0 && core.currentOrder[0].indexOf("C") < 0) {
core.currentOrder[0] += "C";
}
if (tDiff > 0 && core.currentOrder[0].indexOf("T") < 0) {
core.currentOrder[0] += "T";
}
if (core.currentOrder[0].length() == 5) break;
}
if (core.currentOrder[0].indexOf("Z") < 0) core.currentOrder[0] += "Z";
if (core.currentOrder[0].indexOf("C") < 0) core.currentOrder[0] += "C";
if (core.currentOrder[0].indexOf("T") < 0) core.currentOrder[0] += "T";
}
/* @see BaseTiffReader#initMetadataStore() */
protected void initMetadataStore() {
super.initMetadataStore();
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
store.setImageName("", 0);
store.setImageCreationDate(
DataTools.convertDate(System.currentTimeMillis(), DataTools.UNIX), 0);
MetadataTools.populatePixels(store, this);
store.setDimensionsPhysicalSizeX(new Float(pixelSizeX), 0, 0);
store.setDimensionsPhysicalSizeY(new Float(pixelSizeY), 0, 0);
store.setDimensionsPhysicalSizeZ(new Float(pixelSizeZ), 0, 0);
store.setDimensionsTimeIncrement(new Float(pixelSizeT / 1000000.0), 0, 0);
}
// -- Helper methods --
private boolean isThisType(RandomAccessStream stream) throws IOException {
Hashtable ifd = TiffTools.getFirstIFD(stream);
String comment = TiffTools.getComment(ifd);
if (comment == null) return false;
return comment.indexOf("Improvision") != -1;
}
}
|
package cgeo.geocaching.maps;
import cgeo.geocaching.DirectionProvider;
import cgeo.geocaching.IGeoData;
import cgeo.geocaching.IWaypoint;
import cgeo.geocaching.LiveMapInfo;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.Settings;
import cgeo.geocaching.StoredList;
import cgeo.geocaching.cgCache;
import cgeo.geocaching.cgWaypoint;
import cgeo.geocaching.cgeoapplication;
import cgeo.geocaching.cgeocaches;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.gc.Login;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.Viewport;
import cgeo.geocaching.go4cache.Go4Cache;
import cgeo.geocaching.go4cache.Go4CacheUser;
import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapActivityImpl;
import cgeo.geocaching.maps.interfaces.MapControllerImpl;
import cgeo.geocaching.maps.interfaces.MapItemFactory;
import cgeo.geocaching.maps.interfaces.MapProvider;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.interfaces.MapViewImpl;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.GeoDirHandler;
import cgeo.geocaching.utils.LeastRecentlyUsedSet;
import cgeo.geocaching.utils.Log;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Class representing the Map in c:geo
*/
public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFactory {
/** max. number of caches displayed in the Live Map */
public static final int MAX_CACHES = 500;
/**Controls the behaviour of the map*/
public enum MapMode {
/** Live Map where caches are loaded from online */
LIVE_ONLINE,
/** Live Map where caches are loaded only from database */
LIVE_OFFLINE,
/** Map around some coordinates */
COORDS,
/** Map with a single cache (no reload on move) */
SINGLE,
/** Map with a list of caches (no reload on move) */
LIST
}
/** Handler Messages */
private static final int HIDE_PROGRESS = 0;
private static final int SHOW_PROGRESS = 1;
private static final int UPDATE_TITLE = 0;
private static final int INVALIDATE_MAP = 1;
private static final int UPDATE_PROGRESS = 0;
private static final int FINISHED_LOADING_DETAILS = 1;
//Menu
private static final String EXTRAS_GEOCODE = "geocode";
private static final String EXTRAS_COORDS = "coords";
private static final String EXTRAS_WPTTYPE = "wpttype";
private static final String EXTRAS_MAPSTATE = "mapstate";
private static final String EXTRAS_SEARCH = "search";
private static final String EXTRAS_MAP_MODE = "map_mode";
private static final int MENU_SELECT_MAPVIEW = 1;
private static final int MENU_MAP_LIVE = 2;
private static final int MENU_STORE_CACHES = 3;
private static final int MENU_TRAIL_MODE = 4;
private static final int SUBMENU_STRATEGY = 5;
private static final int MENU_STRATEGY_FASTEST = 51;
private static final int MENU_STRATEGY_FAST = 52;
private static final int MENU_STRATEGY_AUTO = 53;
private static final int MENU_STRATEGY_DETAILED = 74;
private static final int MENU_CIRCLE_MODE = 6;
private static final int MENU_AS_LIST = 7;
private static final String EXTRAS_MAP_TITLE = "mapTitle";
private static final String BUNDLE_MAP_SOURCE = "mapSource";
private static final String BUNDLE_MAP_STATE = "mapState";
private Resources res = null;
private MapItemFactory mapItemFactory = null;
private Activity activity = null;
private MapViewImpl mapView = null;
private cgeoapplication app = null;
final private GeoDirHandler geoDirUpdate = new UpdateLoc();
private SearchResult searchIntent = null;
private String geocodeIntent = null;
private Geopoint coordsIntent = null;
private WaypointType waypointTypeIntent = null;
private int[] mapStateIntent = null;
// status data
/** Last search result used for displaying header */
private SearchResult lastSearchResult = null;
private String[] tokens = null;
private boolean noMapTokenShowed = false;
// map status data
private boolean followMyLocation = false;
private Viewport viewport = null;
private Viewport viewportUsers = null;
private int zoom = -100;
// threads
private LoadTimer loadTimer = null;
private Go4CacheTimer go4CacheTimer = null;
private LoadDetails loadDetailsThread = null;
/** Time of last {@link LoadRunnable} run */
private volatile long loadThreadRun = 0L;
/** Time of last {@link Go4CacheRunnable} run */
private volatile long go4CacheThreadRun = 0L;
//Interthread communication flag
private volatile boolean downloaded = false;
// overlays
private CachesOverlay overlayCaches = null;
private OtherCachersOverlay overlayGo4Cache = null;
private ScaleOverlay overlayScale = null;
private PositionOverlay overlayPosition = null;
// data for overlays
private static final int[][] INSET_RELIABLE = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; // center, 33x40 / 45x51
private static final int[][] INSET_TYPE = { { 5, 8, 6, 10 }, { 4, 4, 5, 11 } }; // center, 22x22 / 36x36
private static final int[][] INSET_OWN = { { 21, 0, 0, 26 }, { 25, 0, 0, 35 } }; // top right, 12x12 / 16x16
private static final int[][] INSET_FOUND = { { 0, 0, 21, 28 }, { 0, 0, 25, 35 } }; // top left, 12x12 / 16x16
private static final int[][] INSET_USERMODIFIEDCOORDS = { { 21, 28, 0, 0 }, { 19, 25, 0, 0 } }; // bottom right, 12x12 / 26x26
private static final int[][] INSET_PERSONALNOTE = { { 0, 28, 21, 0 }, { 0, 25, 19, 0 } }; // bottom left, 12x12 / 26x26
private SparseArray<LayerDrawable> overlaysCache = new SparseArray<LayerDrawable>();
private int cachesCnt = 0;
/** List of caches in the viewport */
private LeastRecentlyUsedSet<cgCache> caches = null;
/** List of waypoints in the viewport */
private final LeastRecentlyUsedSet<cgWaypoint> waypoints = new LeastRecentlyUsedSet<cgWaypoint>(MAX_CACHES);
// storing for offline
private ProgressDialog waitDialog = null;
private int detailTotal = 0;
private int detailProgress = 0;
private long detailProgressTime = 0L;
// views
private ImageSwitcher myLocSwitch = null;
/**Controls the map behaviour*/
private MapMode mapMode = null;
// other things
// private boolean live = true; // live map (live, dead) or rest (displaying caches on map)
private boolean liveChanged = false; // previous state for loadTimer
private boolean centered = false; // if map is already centered
private boolean alreadyCentered = false; // -""- for setting my location
private static Set<String> dirtyCaches = null;
// Thread pooling
private static BlockingQueue<Runnable> displayQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor displayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, displayQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> downloadQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor downloadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, downloadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> loadQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor loadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, loadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> Go4CacheQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor Go4CacheExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, Go4CacheQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> go4CacheDisplayQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor go4CacheDisplayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, go4CacheDisplayQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
// handlers
/** Updates the titles */
final private Handler displayHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
final int what = msg.what;
switch (what) {
case UPDATE_TITLE:
// set title
final StringBuilder title = new StringBuilder();
if (mapMode == MapMode.LIVE_ONLINE) {
title.append(res.getString(R.string.map_live));
} else {
title.append(mapTitle);
}
countVisibleCaches();
if (caches != null && caches.size() > 0 && !mapTitle.contains("[")) {
title.append(" [").append(cachesCnt);
if (cachesCnt != caches.size()) {
title.append('/').append(caches.size());
}
title.append(']');
}
if (Settings.isDebug() && lastSearchResult != null && StringUtils.isNotBlank(lastSearchResult.getUrl())) {
title.append('[').append(lastSearchResult.getUrl()).append(']');
}
ActivityMixin.setTitle(activity, title.toString());
break;
case INVALIDATE_MAP:
mapView.repaintRequired(null);
break;
default:
break;
}
}
};
/** Updates the progress. */
final private Handler showProgressHandler = new Handler() {
private int counter = 0;
@Override
public void handleMessage(Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
ActivityMixin.showProgress(activity, false);
}
} else if (what == SHOW_PROGRESS) {
ActivityMixin.showProgress(activity, true);
counter++;
}
}
};
final private class LoadDetailsHandler extends CancellableHandler {
@Override
public void handleRegularMessage(Message msg) {
if (msg.what == UPDATE_PROGRESS) {
if (waitDialog != null) {
int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else if (secondsRemaining < 90) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + (secondsRemaining / 60) + " " + res.getString(R.string.caches_eta_min));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + (secondsRemaining / 60) + " " + res.getString(R.string.caches_eta_mins));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS) {
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog.setOnCancelListener(null);
}
geoDirUpdate.startDir();
}
}
@Override
public void handleCancel(final Object extra) {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
geoDirUpdate.startDir();
}
}
final private Handler noMapTokenHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (!noMapTokenShowed) {
ActivityMixin.showToast(activity, res.getString(R.string.map_token_err));
noMapTokenShowed = true;
}
}
};
/**
* calling activities can set the map title via extras
*/
private String mapTitle;
/* Current source id */
private int currentSourceId;
public CGeoMap(MapActivityImpl activity) {
super(activity);
}
protected void countVisibleCaches() {
final List<cgCache> protectedCaches = caches.getAsList();
int count = 0;
if (protectedCaches.size() > 0) {
final Viewport viewport = mapView.getViewport();
for (final cgCache cache : protectedCaches) {
if (cache != null && cache.getCoords() != null) {
if (viewport.contains(cache)) {
count++;
}
}
}
}
cachesCnt = count;
}
@Override
public void onSaveInstanceState(final Bundle outState) {
outState.putInt(BUNDLE_MAP_SOURCE, currentSourceId);
outState.putIntArray(BUNDLE_MAP_STATE, currentMapState());
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// class init
res = this.getResources();
activity = this.getActivity();
app = (cgeoapplication) activity.getApplication();
int countBubbleCnt = app.getAllStoredCachesCount(true, CacheType.ALL);
caches = new LeastRecentlyUsedSet<cgCache>(MAX_CACHES + countBubbleCnt);
final MapProvider mapProvider = Settings.getMapProvider();
mapItemFactory = mapProvider.getMapItemFactory();
// Get parameters from the intent
final Bundle extras = activity.getIntent().getExtras();
if (extras != null) {
mapMode = (MapMode) extras.get(EXTRAS_MAP_MODE);
searchIntent = (SearchResult) extras.getParcelable(EXTRAS_SEARCH);
geocodeIntent = extras.getString(EXTRAS_GEOCODE);
coordsIntent = (Geopoint) extras.getParcelable(EXTRAS_COORDS);
waypointTypeIntent = WaypointType.findById(extras.getString(EXTRAS_WPTTYPE));
mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE);
mapTitle = extras.getString(EXTRAS_MAP_TITLE);
}
else {
mapMode = Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE;
}
if (StringUtils.isBlank(mapTitle)) {
mapTitle = res.getString(R.string.map_map);
}
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
currentSourceId = savedInstanceState.getInt(BUNDLE_MAP_SOURCE, Settings.getMapSource());
mapStateIntent = savedInstanceState.getIntArray(BUNDLE_MAP_STATE);
} else {
currentSourceId = Settings.getMapSource();
}
// If recreating from an obsolete map source, we may need a restart
if (changeMapSource(Settings.getMapSource())) {
return;
}
// reset status
noMapTokenShowed = false;
ActivityMixin.keepScreenOn(activity, true);
// set layout
ActivityMixin.setTheme(activity);
activity.setContentView(mapProvider.getMapLayoutId());
ActivityMixin.setTitle(activity, res.getString(R.string.map_map));
// initialize map
mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId());
mapView.setMapSource();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mapView.preLoad();
mapView.setOnDragListener(this);
// initialize overlays
mapView.clearOverlays();
if (Settings.isPublicLoc() && overlayGo4Cache == null) {
overlayGo4Cache = mapView.createAddUsersOverlay(activity, getResources().getDrawable(R.drawable.user_location));
}
if (overlayCaches == null) {
overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker));
}
if (overlayPosition == null) {
overlayPosition = mapView.createAddPositionOverlay(activity);
}
if (overlayScale == null) {
overlayScale = mapView.createAddScaleOverlay(activity);
}
mapView.repaintRequired(null);
mapView.getMapController().setZoom(Settings.getMapZoom());
if (null == mapStateIntent) {
followMyLocation = mapMode == MapMode.LIVE_OFFLINE || mapMode == MapMode.LIVE_ONLINE;
} else {
followMyLocation = 1 == mapStateIntent[3];
if ((overlayCaches.getCircles() ? 1 : 0) != mapStateIntent[4]) {
overlayCaches.switchCircles();
}
}
if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) {
centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent);
}
// prepare my location button
myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position);
myLocSwitch.setFactory(this);
myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out);
myLocSwitch.setOnClickListener(new MyLocationListener());
switchMyLocationButton();
prepareFilterBar();
if (!app.isLiveMapHintShown() && !Settings.getHideLiveMapHint()) {
Intent hintIntent = new Intent(activity, LiveMapInfo.class);
activity.startActivity(hintIntent);
app.setLiveMapHintShown();
}
}
private void prepareFilterBar() {
// show the filter warning bar if the filter is set
if (Settings.getCacheType() != CacheType.ALL) {
String cacheType = Settings.getCacheType().getL10n();
((TextView) activity.findViewById(R.id.filter_text)).setText(cacheType);
activity.findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
} else {
activity.findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
@Override
public void onResume() {
super.onResume();
app.setAction(StringUtils.defaultIfBlank(geocodeIntent, null));
addGeoDirObservers();
if (!CollectionUtils.isEmpty(dirtyCaches)) {
for (String geocode : dirtyCaches) {
cgCache cache = app.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS);
// remove to update the cache
caches.remove(cache);
caches.add(cache);
}
dirtyCaches.clear();
// Update display
displayExecutor.execute(new DisplayRunnable(mapView.getViewport()));
}
startTimer();
}
private void addGeoDirObservers() {
geoDirUpdate.startGeoAndDir();
}
private void deleteGeoDirObservers() {
geoDirUpdate.stopGeoAndDir();
}
@Override
public void onPause() {
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
deleteGeoDirObservers();
savePrefs();
if (mapView != null) {
mapView.destroyDrawingCache();
}
overlaysCache.clear();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu submenu = menu.addSubMenu(1, MENU_SELECT_MAPVIEW, 0, res.getString(R.string.map_view_map)).setIcon(R.drawable.ic_menu_mapmode);
addMapViewMenuItems(submenu);
menu.add(0, MENU_MAP_LIVE, 0, res.getString(R.string.map_live_disable)).setIcon(R.drawable.ic_menu_refresh);
menu.add(0, MENU_STORE_CACHES, 0, res.getString(R.string.caches_store_offline)).setIcon(R.drawable.ic_menu_set_as).setEnabled(false);
menu.add(0, MENU_TRAIL_MODE, 0, res.getString(R.string.map_trail_hide)).setIcon(R.drawable.ic_menu_trail);
Strategy strategy = Settings.getLiveMapStrategy();
SubMenu subMenuStrategy = menu.addSubMenu(0, SUBMENU_STRATEGY, 0, res.getString(R.string.map_strategy)).setIcon(R.drawable.ic_menu_preferences);
subMenuStrategy.setHeaderTitle(res.getString(R.string.map_strategy_title));
subMenuStrategy.add(2, MENU_STRATEGY_FASTEST, 0, Strategy.FASTEST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FASTEST);
subMenuStrategy.add(2, MENU_STRATEGY_FAST, 0, Strategy.FAST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FAST);
subMenuStrategy.add(2, MENU_STRATEGY_AUTO, 0, Strategy.AUTO.getL10n()).setCheckable(true).setChecked(strategy == Strategy.AUTO);
subMenuStrategy.add(2, MENU_STRATEGY_DETAILED, 0, Strategy.DETAILED.getL10n()).setCheckable(true).setChecked(strategy == Strategy.DETAILED);
subMenuStrategy.setGroupCheckable(2, true, true);
menu.add(0, MENU_CIRCLE_MODE, 0, res.getString(R.string.map_circles_hide)).setIcon(R.drawable.ic_menu_circle);
menu.add(0, MENU_AS_LIST, 0, res.getString(R.string.map_as_list)).setIcon(R.drawable.ic_menu_agenda);
return true;
}
private static void addMapViewMenuItems(final Menu menu) {
MapProviderFactory.addMapviewMenuItems(menu, 1, Settings.getMapSource());
menu.setGroupCheckable(1, true, true);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
for (Integer mapSourceId : MapProviderFactory.getMapSources().keySet()) {
final MenuItem menuItem = menu.findItem(mapSourceId);
if (menuItem != null) {
final MapSource mapSource = MapProviderFactory.getMapSource(mapSourceId);
if (mapSource != null) {
menuItem.setEnabled(mapSource.isAvailable());
}
}
}
MenuItem item;
try {
item = menu.findItem(MENU_TRAIL_MODE); // show trail
if (Settings.isMapTrail()) {
item.setTitle(res.getString(R.string.map_trail_hide));
} else {
item.setTitle(res.getString(R.string.map_trail_show));
}
item = menu.findItem(MENU_MAP_LIVE); // live map
if (mapMode == MapMode.LIVE_ONLINE) {
item.setTitle(res.getString(R.string.map_live_disable));
} else {
item.setTitle(res.getString(R.string.map_live_enable));
}
final Set<String> geocodesInViewport = getGeocodesForCachesInViewport();
menu.findItem(MENU_STORE_CACHES).setEnabled(isLiveMode() && !isLoading() && CollectionUtils.isNotEmpty(geocodesInViewport) && app.hasUnsavedCaches(new SearchResult(geocodesInViewport)));
item = menu.findItem(MENU_CIRCLE_MODE); // show circles
if (overlayCaches != null && overlayCaches.getCircles()) {
item.setTitle(res.getString(R.string.map_circles_hide));
} else {
item.setTitle(res.getString(R.string.map_circles_show));
}
item = menu.findItem(MENU_AS_LIST);
item.setEnabled(isLiveMode() && !isLoading());
menu.findItem(SUBMENU_STRATEGY).setEnabled(isLiveMode());
} catch (Exception e) {
Log.e("cgeomap.onPrepareOptionsMenu: " + e.toString());
}
return true;
}
private boolean isLiveMode() {
return mapMode == MapMode.LIVE_OFFLINE || mapMode == MapMode.LIVE_ONLINE;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
switch (id) {
case MENU_TRAIL_MODE:
Settings.setMapTrail(!Settings.isMapTrail());
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_MAP_LIVE:
Settings.setLiveMap(!Settings.isLiveMap());
mapMode = Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE;
liveChanged = true;
lastSearchResult = null;
searchIntent = null;
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_STORE_CACHES:
if (!isLoading()) {
final Set<String> geocodesInViewport = getGeocodesForCachesInViewport();
final List<String> geocodes = new ArrayList<String>();
for (final String geocode : geocodesInViewport) {
if (!app.isOffline(geocode, null)) {
geocodes.add(geocode);
}
}
detailTotal = geocodes.size();
detailProgress = 0;
if (detailTotal == 0) {
ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing));
return true;
}
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler();
waitDialog = new ProgressDialog(activity);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage());
waitDialog.setMax(detailTotal);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
geoDirUpdate.startDir();
} catch (Exception e) {
Log.e("cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString());
}
}
});
float etaTime = detailTotal * 7.0f / 60.0f;
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else if (etaTime < 1.5) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + Math.round(etaTime) + " " + res.getString(R.string.caches_eta_min));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + Math.round(etaTime) + " " + res.getString(R.string.caches_eta_mins));
}
waitDialog.show();
detailProgressTime = System.currentTimeMillis();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes);
loadDetailsThread.start();
}
return true;
case MENU_CIRCLE_MODE:
if (overlayCaches == null) {
return false;
}
overlayCaches.switchCircles();
mapView.repaintRequired(overlayCaches);
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_AS_LIST: {
cgeocaches.startActivityMap(activity, new SearchResult(getGeocodesForCachesInViewport()));
return true;
}
case MENU_STRATEGY_FASTEST: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FASTEST);
return true;
}
case MENU_STRATEGY_FAST: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FAST);
return true;
}
case MENU_STRATEGY_AUTO: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.AUTO);
return true;
}
case MENU_STRATEGY_DETAILED: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.DETAILED);
return true;
}
default:
int mapSource = MapProviderFactory.getMapSourceFromMenuId(id);
if (MapProviderFactory.isValidSourceId(mapSource)) {
item.setChecked(true);
changeMapSource(mapSource);
return true;
}
}
return false;
}
/**
* @return a Set of geocodes corresponding to the caches that are shown on screen.
*/
private Set<String> getGeocodesForCachesInViewport() {
final Set<String> geocodes = new HashSet<String>();
final List<cgCache> cachesProtected = caches.getAsList();
final Viewport viewport = mapView.getViewport();
for (final cgCache cache : cachesProtected) {
if (viewport.contains(cache)) {
geocodes.add(cache.getGeocode());
}
}
return geocodes;
}
/**
* Restart the current activity if the map provider has changed, or change the map source if needed.
*
* @param mapSource
* the new map source, which can be the same as the current one
* @return true if a restart is needed, false otherwise
*/
private boolean changeMapSource(final int mapSource) {
// If the current or the requested map source is invalid, request the first available map source instead
// and restart the activity.
if (!MapProviderFactory.isValidSourceId(mapSource)) {
Log.e("CGeoMap.onCreate: invalid map source requested: " + mapSource);
currentSourceId = MapProviderFactory.getSourceIdFromOrdinal(0);
Settings.setMapSource(currentSourceId);
mapRestart();
return true;
}
final boolean restartRequired = !MapProviderFactory.isSameActivity(currentSourceId, mapSource);
Settings.setMapSource(mapSource);
currentSourceId = mapSource;
if (restartRequired) {
mapRestart();
} else if (mapView != null) {
mapView.setMapSource();
}
return restartRequired;
}
/**
* Restart the current activity with the default map source.
*/
private void mapRestart() {
// close old mapview
activity.finish();
// prepare information to restart a similar view
Intent mapIntent = new Intent(activity, Settings.getMapProvider().getMapClass());
mapIntent.putExtra(EXTRAS_SEARCH, searchIntent);
mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent);
if (coordsIntent != null) {
mapIntent.putExtra(EXTRAS_COORDS, coordsIntent);
}
mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null);
mapIntent.putExtra(EXTRAS_MAP_TITLE, mapTitle);
mapIntent.putExtra(EXTRAS_MAP_MODE, mapMode);
final int[] mapState = currentMapState();
if (mapState != null) {
mapIntent.putExtra(EXTRAS_MAPSTATE, mapState);
}
// start the new map
activity.startActivity(mapIntent);
}
/**
* Get the current map state from the map view if it exists or from the mapStateIntent field otherwise.
*
* @return the current map state as an array of int, or null if no map state is available
*/
private int[] currentMapState() {
if (mapView == null) {
return mapStateIntent;
}
final GeoPointImpl mapCenter = mapView.getMapViewCenter();
return new int[] {
mapCenter.getLatitudeE6(),
mapCenter.getLongitudeE6(),
mapView.getMapZoomLevel(),
followMyLocation ? 1 : 0,
overlayCaches.getCircles() ? 1 : 0
};
}
private void savePrefs() {
if (mapView == null) {
return;
}
Settings.setMapZoom(mapView.getMapZoomLevel());
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle(final IGeoData geo) {
if (followMyLocation) {
centerMap(geo.getCoords());
}
}
// class: update location
private class UpdateLoc extends GeoDirHandler {
@Override
protected void updateGeoData(final IGeoData geo) {
try {
boolean repaintRequired = false;
if (overlayPosition == null && mapView != null) {
overlayPosition = mapView.createAddPositionOverlay(activity);
}
if ((overlayPosition != null && geo.getLocation() != null)) {
overlayPosition.setCoordinates(geo.getLocation());
}
if (geo.getCoords() != null) {
if (followMyLocation) {
myLocationInMiddle(geo);
} else {
repaintRequired = true;
}
}
if (!Settings.isUseCompass() || geo.getSpeed() > 5) { // use GPS when speed is higher than 18 km/h
overlayPosition.setHeading(geo.getBearing());
repaintRequired = true;
}
if (repaintRequired && mapView != null) {
mapView.repaintRequired(overlayPosition);
}
} catch (Exception e) {
Log.w("Failed to update location.");
}
}
@Override
public void updateDirection(final float direction) {
if (overlayPosition != null && mapView != null && (app.currentGeo().getSpeed() <= 5)) { // use compass when speed is lower than 18 km/h
overlayPosition.setHeading(DirectionProvider.getDirectionNow(activity, direction));
mapView.repaintRequired(overlayPosition);
}
}
}
/**
* Starts the {@link LoadTimer} and {@link Go4CacheTimer}.
*/
public synchronized void startTimer() {
if (coordsIntent != null) {
// display just one point
(new DisplayPointThread()).start();
} else {
// start timer
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
loadTimer = new LoadTimer();
loadTimer.start();
}
if (Settings.isPublicLoc()) {
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
go4CacheTimer = new Go4CacheTimer();
go4CacheTimer.start();
}
}
/**
* loading timer Triggers every 250ms and checks for viewport change and starts a {@link LoadRunnable}.
*/
private class LoadTimer extends Thread {
public LoadTimer() {
super("Load Timer");
}
private volatile boolean stop = false;
public void stopIt() {
stop = true;
}
@Override
public void run() {
while (!stop) {
try {
sleep(250);
if (mapView != null) {
// get current viewport
final Viewport viewportNow = mapView.getViewport();
// Since zoomNow is used only for local comparison purposes,
// it is ok to use the Google Maps compatible zoom level of OSM Maps
final int zoomNow = mapView.getMapZoomLevel();
// check if map moved or zoomed
//TODO Portree Use Rectangle inside with bigger search window. That will stop reloading on every move
boolean moved = false;
if (liveChanged) {
moved = true;
} else if (mapMode == MapMode.LIVE_ONLINE && !downloaded) {
moved = true;
} else if (viewport == null) {
moved = true;
} else if (zoomNow != zoom) {
moved = true;
} else if (mapMoved(viewport, viewportNow) && (cachesCnt <= 0 || CollectionUtils.isEmpty(caches) || !viewport.includes(viewportNow))) {
moved = true;
}
// update title on any change
if (moved || zoomNow != zoom || !viewportNow.equals(viewport)) {
displayHandler.sendEmptyMessage(UPDATE_TITLE);
}
zoom = zoomNow;
// save new values
if (moved) {
liveChanged = false;
long currentTime = System.currentTimeMillis();
if (1000 < (currentTime - loadThreadRun)) {
viewport = viewportNow;
loadExecutor.execute(new LoadRunnable(viewport));
}
}
}
yield();
} catch (Exception e) {
Log.w("cgeomap.LoadTimer.run: " + e.toString());
}
}
}
public boolean isLoading() {
return loadExecutor.getActiveCount() > 0 ||
downloadExecutor.getActiveCount() > 0 ||
displayExecutor.getActiveCount() > 0;
}
}
/**
* Timer triggering every 250 ms to start the {@link Go4CacheRunnable} for displaying user.
*/
private class Go4CacheTimer extends Thread {
public Go4CacheTimer() {
super("Users Timer");
}
private volatile boolean stop = false;
public void stopIt() {
stop = true;
}
@Override
public void run() {
while (!stop) {
try {
sleep(250);
if (mapView != null) {
// get current viewport
final Viewport viewportNow = mapView.getViewport();
// check if map moved or zoomed
boolean moved = false;
long currentTime = System.currentTimeMillis();
if (60000 < (currentTime - go4CacheThreadRun)) {
moved = true;
} else if (viewportUsers == null) {
moved = true;
} else if (mapMoved(viewportUsers, viewportNow) && !viewportUsers.includes(viewportNow)) {
moved = true;
}
// save new values
if (moved && (1000 < (currentTime - go4CacheThreadRun))) {
viewportUsers = viewportNow;
Go4CacheExecutor.execute(new Go4CacheRunnable(viewportUsers));
}
}
yield();
} catch (Exception e) {
Log.w("cgeomap.LoadUsersTimer.run: " + e.toString());
}
}
}
}
/**
* Worker thread that loads caches and waypoints from the database and then spawns the {@link DownloadRunnable}.
* started by {@link LoadTimer}
*/
private class LoadRunnable extends DoRunnable {
public LoadRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
loadThreadRun = System.currentTimeMillis();
SearchResult searchResult;
// stage 1 - pull and render from the DB only for live map
if (mapMode == MapMode.LIVE_ONLINE) {
searchResult = new SearchResult(app.getCachedInViewport(viewport, Settings.getCacheType()));
} else if (mapMode == MapMode.LIVE_OFFLINE) {
searchResult = new SearchResult(app.getStoredInViewport(viewport, Settings.getCacheType()));
} else {
// map started from another activity
searchResult = new SearchResult(searchIntent);
if (geocodeIntent != null) {
searchResult.addGeocode(geocodeIntent);
}
}
downloaded = true;
Set<cgCache> cachesFromSearchResult = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_WAYPOINTS);
// to update the caches they have to be removed first
caches.removeAll(cachesFromSearchResult);
caches.addAll(cachesFromSearchResult);
if (isLiveMode()) {
final boolean excludeMine = Settings.isExcludeMyCaches();
final boolean excludeDisabled = Settings.isExcludeDisabledCaches();
final List<cgCache> tempList = caches.getAsList();
for (cgCache cache : tempList) {
if ((cache.isFound() && excludeMine) || (cache.isOwn() && excludeMine) || (cache.isDisabled() && excludeDisabled)) {
caches.remove(cache);
}
}
}
countVisibleCaches();
if (cachesCnt < Settings.getWayPointsThreshold() || geocodeIntent != null) {
waypoints.clear();
if (isLiveMode() || mapMode == MapMode.COORDS) {
//All visible waypoints
//FIXME apply type filter
waypoints.addAll(app.getWaypointsInViewport(viewport, Settings.isExcludeMyCaches(), Settings.isExcludeDisabledCaches()));
} else {
//All waypoints from the viewed caches
for (cgCache c : caches.getAsList()) {
waypoints.addAll(c.getWaypoints());
}
}
}
//render
displayExecutor.execute(new DisplayRunnable(viewport));
if (mapMode == MapMode.LIVE_ONLINE) {
downloadExecutor.execute(new DownloadRunnable(viewport));
}
lastSearchResult = searchResult;
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
}
/**
* Worker thread downloading caches from the internet.
* Started by {@link LoadRunnable}. Duplicate Code with {@link Go4CacheRunnable}
*/
private class DownloadRunnable extends DoRunnable {
public DownloadRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS); // show progress
int count = 0;
SearchResult searchResult;
do {
if (tokens == null) {
tokens = Login.getMapTokens();
if (noMapTokenHandler != null && tokens == null) {
noMapTokenHandler.sendEmptyMessage(0);
}
}
searchResult = ConnectorFactory.searchByViewport(viewport.resize(0.8), tokens);
if (searchResult != null) {
downloaded = true;
if (searchResult.getError() == StatusCode.NOT_LOGGED_IN) {
Login.login();
tokens = null;
} else {
break;
}
}
count++;
} while (count < 2);
if (searchResult != null) {
Set<cgCache> result = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
// to update the caches they have to be removed first
caches.removeAll(result);
caches.addAll(result);
lastSearchResult = searchResult;
}
//render
displayExecutor.execute(new DisplayRunnable(viewport));
} catch (ThreadDeath e) {
Log.d("DownloadThread stopped");
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
}
/**
* Thread to Display (down)loaded caches. Started by {@link LoadRunnable} and {@link DownloadRunnable}
*/
private class DisplayRunnable extends DoRunnable {
public DisplayRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
if (mapView == null || caches == null) {
throw new ThreadDeath();
}
// display caches
final List<cgCache> cachesToDisplay = caches.getAsList();
final List<cgWaypoint> waypointsToDisplay = new ArrayList<cgWaypoint>(waypoints);
final List<CachesOverlayItemImpl> itemsToDisplay = new ArrayList<CachesOverlayItemImpl>();
if (!cachesToDisplay.isEmpty()) {
// Only show waypoints for single view or setting
// when less than showWaypointsthreshold Caches shown
if (mapMode == MapMode.SINGLE || (cachesCnt < Settings.getWayPointsThreshold())) {
for (cgWaypoint waypoint : waypointsToDisplay) {
if (waypoint == null || waypoint.getCoords() == null) {
continue;
}
itemsToDisplay.add(getItem(waypoint, null, waypoint));
}
}
for (cgCache cache : cachesToDisplay) {
if (cache == null || cache.getCoords() == null) {
continue;
}
itemsToDisplay.add(getItem(cache, cache, null));
}
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
cachesCnt = cachesToDisplay.size();
} else {
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
}
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} catch (ThreadDeath e) {
Log.d("DisplayThread stopped");
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS);
}
}
}
/**
* Thread to load users from Go 4 Cache
*/
private class Go4CacheRunnable extends DoRunnable {
public Go4CacheRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
go4CacheThreadRun = System.currentTimeMillis();
List<Go4CacheUser> go4CacheUsers = Go4Cache.getGeocachersInViewport(Settings.getUsername(), viewport.resize(1.5));
go4CacheDisplayExecutor.execute(new Go4CacheDisplayRunnable(go4CacheUsers, viewport));
}
}
/**
* Thread to display users of Go 4 Cache started from {@link Go4CacheRunnable}
*/
private class Go4CacheDisplayRunnable extends DoRunnable {
private List<Go4CacheUser> users = null;
public Go4CacheDisplayRunnable(List<Go4CacheUser> usersIn, final Viewport viewport) {
super(viewport);
users = usersIn;
}
@Override
public void run() {
if (mapView == null || CollectionUtils.isEmpty(users)) {
return;
}
// display users
List<OtherCachersOverlayItemImpl> items = new ArrayList<OtherCachersOverlayItemImpl>();
int counter = 0;
OtherCachersOverlayItemImpl item;
for (Go4CacheUser userOne : users) {
if (userOne.getCoords() == null) {
continue;
}
item = mapItemFactory.getOtherCachersOverlayItemBase(activity, userOne);
items.add(item);
counter++;
if ((counter % 10) == 0) {
overlayGo4Cache.updateItems(items);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
}
}
overlayGo4Cache.updateItems(items);
}
}
/**
* Thread to display one point. Started on opening if in single mode.
*/
private class DisplayPointThread extends Thread {
@Override
public void run() {
if (mapView == null || caches == null) {
return;
}
if (coordsIntent != null) {
final cgWaypoint waypoint = new cgWaypoint("some place", waypointTypeIntent != null ? waypointTypeIntent : WaypointType.WAYPOINT, false);
waypoint.setCoords(coordsIntent);
final CachesOverlayItemImpl item = getItem(waypoint, null, waypoint);
overlayCaches.updateItems(item);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
cachesCnt = 1;
} else {
cachesCnt = 0;
}
displayHandler.sendEmptyMessage(UPDATE_TITLE);
}
}
private static abstract class DoRunnable implements Runnable {
final protected Viewport viewport;
public DoRunnable(final Viewport viewport) {
this.viewport = viewport;
}
@Override
public abstract void run();
}
/**
* get if map is loading something
*
* @return
*/
private synchronized boolean isLoading() {
if (loadTimer != null) {
return loadTimer.isLoading();
}
return false;
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
final private CancellableHandler handler;
final private List<String> geocodes;
private long last = 0L;
public LoadDetails(final CancellableHandler handler, final List<String> geocodes) {
this.handler = handler;
this.geocodes = geocodes;
}
public void stopIt() {
handler.cancel();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
deleteGeoDirObservers();
for (final String geocode : geocodes) {
try {
if (handler.isCancelled()) {
break;
}
if (!app.isOffline(geocode, null)) {
if ((System.currentTimeMillis() - last) < 1500) {
try {
int delay = 1000 + (int) (Math.random() * 1000.0) - (int) (System.currentTimeMillis() - last);
if (delay < 0) {
delay = 500;
}
sleep(delay);
} catch (Exception e) {
// nothing
}
}
if (handler.isCancelled()) {
Log.i("Stopped storing process.");
break;
}
cgCache.storeCache(null, geocode, StoredList.STANDARD_LIST_ID, false, handler);
}
} catch (Exception e) {
Log.e("cgeocaches.LoadDetails.run: " + e.toString());
} finally {
// one more cache over
detailProgress++;
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
// FIXME: what does this yield() do here?
yield();
last = System.currentTimeMillis();
}
// we're done
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
addGeoDirObservers();
}
}
private static boolean mapMoved(final Viewport referenceViewport, final Viewport newViewport) {
return Math.abs(newViewport.getLatitudeSpan() - referenceViewport.getLatitudeSpan()) > 50e-6 ||
Math.abs(newViewport.getLongitudeSpan() - referenceViewport.getLongitudeSpan()) > 50e-6 ||
Math.abs(newViewport.center.getLatitude() - referenceViewport.center.getLatitude()) > referenceViewport.getLatitudeSpan() / 4 ||
Math.abs(newViewport.center.getLongitude() - referenceViewport.center.getLongitude()) > referenceViewport.getLongitudeSpan() / 4;
}
// center map to desired location
private void centerMap(final Geopoint coords) {
if (coords == null) {
return;
}
if (mapView == null) {
return;
}
final MapControllerImpl mapController = mapView.getMapController();
final GeoPointImpl target = makeGeoPoint(coords);
if (alreadyCentered) {
mapController.animateTo(target);
} else {
mapController.setCenter(target);
}
alreadyCentered = true;
}
// move map to view results of searchIntent
private void centerMap(String geocodeCenter, final SearchResult searchCenter, final Geopoint coordsCenter, int[] mapState) {
final MapControllerImpl mapController = mapView.getMapController();
if (!centered && mapState != null) {
try {
mapController.setCenter(mapItemFactory.getGeoPointBase(new Geopoint(mapState[0] / 1.0e6, mapState[1] / 1.0e6)));
mapController.setZoom(mapState[2]);
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
} else if (!centered && (geocodeCenter != null || searchIntent != null)) {
try {
Viewport viewport = null;
if (geocodeCenter != null) {
viewport = app.getBounds(geocodeCenter);
} else if (searchCenter != null) {
viewport = app.getBounds(searchCenter.getGeocodes());
}
if (viewport == null) {
return;
}
mapController.setCenter(mapItemFactory.getGeoPointBase(viewport.center));
if (viewport.getLatitudeSpan() != 0 && viewport.getLongitudeSpan() != 0) {
mapController.zoomToSpan((int) (viewport.getLatitudeSpan() * 1e6), (int) (viewport.getLongitudeSpan() * 1e6));
}
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
} else if (!centered && coordsCenter != null) {
try {
mapController.setCenter(makeGeoPoint(coordsCenter));
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
}
}
// switch My Location button image
private void switchMyLocationButton() {
if (followMyLocation) {
myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on);
myLocationInMiddle(app.currentGeo());
} else {
myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off);
}
}
// set my location listener
private class MyLocationListener implements View.OnClickListener {
@Override
public void onClick(View view) {
followMyLocation = !followMyLocation;
switchMyLocationButton();
}
}
@Override
public void onDrag() {
if (followMyLocation) {
followMyLocation = false;
switchMyLocationButton();
}
}
// make geopoint
private GeoPointImpl makeGeoPoint(final Geopoint coords) {
return mapItemFactory.getGeoPointBase(coords);
}
// close activity and open homescreen
@Override
public void goHome(View view) {
ActivityMixin.goHome(activity);
}
// open manual entry
@Override
public void goManual(View view) {
ActivityMixin.goManual(activity, "c:geo-live-map");
}
@Override
public View makeView() {
ImageView imageView = new ImageView(activity);
imageView.setScaleType(ScaleType.CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return imageView;
}
private static Intent newIntent(final Context context) {
return new Intent(context, Settings.getMapProvider().getMapClass());
}
public static void startActivitySearch(final Activity fromActivity, final SearchResult search, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_SEARCH, search);
mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.LIST);
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityLiveMap(final Activity fromActivity) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_MAP_MODE, Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE);
fromActivity.startActivity(mapIntent);
}
public static void startActivityCoords(final Activity fromActivity, final Geopoint coords, final WaypointType type, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.COORDS);
mapIntent.putExtra(EXTRAS_COORDS, coords);
if (type != null) {
mapIntent.putExtra(EXTRAS_WPTTYPE, type.id);
}
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityGeoCode(final Activity fromActivity, final String geocode) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.SINGLE);
mapIntent.putExtra(EXTRAS_GEOCODE, geocode);
mapIntent.putExtra(EXTRAS_MAP_TITLE, geocode);
fromActivity.startActivity(mapIntent);
}
public static void markCacheAsDirty(final String geocode) {
if (dirtyCaches == null) {
dirtyCaches = new HashSet<String>();
}
dirtyCaches.add(geocode);
}
/**
* Returns a OverlayItem represented by an icon
*
* @param coord
* The coords
* @param cache
* Cache
* @param waypoint
* Waypoint. Mutally exclusive with cache
* @return
*/
private CachesOverlayItemImpl getItem(final IWaypoint coord, final cgCache cache, final cgWaypoint waypoint) {
if (cache != null) {
final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(coord, cache.getType());
final int hashcode = new HashCodeBuilder()
.append(cache.isReliableLatLon())
.append(cache.getType().id)
.append(cache.isDisabled() || cache.isArchived())
.append(cache.isOwn())
.append(cache.isFound())
.append(cache.hasUserModifiedCoords())
.append(cache.getPersonalNote())
.append(cache.isLogOffline())
.append(cache.getListId() > 0)
.toHashCode();
final LayerDrawable ldFromCache = overlaysCache.get(hashcode);
if (ldFromCache != null) {
item.setMarker(ldFromCache);
return item;
}
// Set initial capacities to the maximum of layers and insets to avoid dynamic reallocation
final ArrayList<Drawable> layers = new ArrayList<Drawable>(9);
final ArrayList<int[]> insets = new ArrayList<int[]>(8);
// background: disabled or not
final Drawable marker = getResources().getDrawable(cache.isDisabled() || cache.isArchived() ? R.drawable.marker_disabled : R.drawable.marker);
layers.add(marker);
final int resolution = marker.getIntrinsicWidth() > 40 ? 1 : 0;
// reliable or not
if (!cache.isReliableLatLon()) {
insets.add(INSET_RELIABLE[resolution]);
layers.add(getResources().getDrawable(R.drawable.marker_notreliable));
}
// cache type
layers.add(getResources().getDrawable(cache.getType().markerId));
insets.add(INSET_TYPE[resolution]);
// own
if (cache.isOwn()) {
layers.add(getResources().getDrawable(R.drawable.marker_own));
insets.add(INSET_OWN[resolution]);
// if not, checked if stored
} else if (cache.getListId() > 0) {
layers.add(getResources().getDrawable(R.drawable.marker_stored));
insets.add(INSET_OWN[resolution]);
}
// found
if (cache.isFound()) {
layers.add(getResources().getDrawable(R.drawable.marker_found));
insets.add(INSET_FOUND[resolution]);
// if not, perhaps logged offline
} else if (cache.isLogOffline()) {
layers.add(getResources().getDrawable(R.drawable.marker_found_offline));
insets.add(INSET_FOUND[resolution]);
}
// user modified coords
if (cache.hasUserModifiedCoords()) {
layers.add(getResources().getDrawable(R.drawable.marker_usermodifiedcoords));
insets.add(INSET_USERMODIFIEDCOORDS[resolution]);
}
// personal note
if (cache.getPersonalNote() != null) {
layers.add(getResources().getDrawable(R.drawable.marker_personalnote));
insets.add(INSET_PERSONALNOTE[resolution]);
}
final LayerDrawable ld = new LayerDrawable(layers.toArray(new Drawable[layers.size()]));
int index = 1;
for (final int[] inset : insets) {
ld.setLayerInset(index++, inset[0], inset[1], inset[2], inset[3]);
}
overlaysCache.put(hashcode, ld);
item.setMarker(ld);
return item;
}
if (waypoint != null) {
final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(coord, null);
Drawable[] layers = new Drawable[2];
layers[0] = getResources().getDrawable(R.drawable.marker);
layers[1] = getResources().getDrawable(waypoint.getWaypointType().markerId);
LayerDrawable ld = new LayerDrawable(layers);
if (layers[0].getIntrinsicWidth() > 40) {
ld.setLayerInset(1, 9, 12, 10, 13);
} else {
ld.setLayerInset(1, 9, 12, 8, 12);
}
item.setMarker(ld);
return item;
}
return null;
}
}
|
package mmsort;
import java.util.Comparator;
public class DpsSort implements ISortAlgorithm {
public static final int ALGORITHM_THRESHOLD = 20;
/**
* dpsSort
*
* Dual-pivot Stable Quicksort
*
* Dual-pibot Quicksort
*
* 3 way partition Quicksort
*
* @param array sort target /
* @param from index of first element /
* @param to index of last element (exclusive) / + 1
* @param workArray work array /
* @param depthRemainder The remaining number of times of the depth of the call /
* @param comparator comparator of array element /
*/
public static final <T> void dpsSort(final T[] array, final int from, final int to, final T[] workArray, final int depthRemainder, final Comparator<? super T> comparator)
{
final int range = to - from;
if (range < ALGORITHM_THRESHOLD) {
BinInsertionSort.binInsertionSort(array, from, to, comparator);
return;
}
// MergeSort
if (depthRemainder < 0) {
MatSort.matSort(array, from, to, comparator, workArray, (range + 9) / 10);
return;
}
//final int gap = range / 7;
final int gap = (range >> 3) + (range >> 6) + 1;
final int p3 = from + (range >> 1);
final int p2 = p3 - gap;
final int p1 = p2 - gap;
final int p4 = p3 + gap;
final int p5 = p4 + gap;
T v1 = array[p1];
T v2 = array[p2];
T v3 = array[p3];
T v4 = array[p4];
T v5 = array[p5];
if (comparator.compare(v1, v2) <= 0) {
if (comparator.compare(v2, v3) <= 0) {
// v1 <= v2 <= v3
} else if (comparator.compare(v1, v3) <= 0) {
// v1 <= v3 <= v2
final T temp = v2; v2 = v3; v3 = temp;
} else {
// v3 <= v1 <= v2
final T temp = v1; v1 = v3; v3 = v2; v2 = temp;
}
} else {
if (comparator.compare(v1, v3) <= 0) {
// v2 <= v1 <= v3
final T temp = v1; v1 = v2; v2 = temp;
} else if (comparator.compare(v2, v3) <= 0) {
// v2 <= v3 <= v1
final T temp = v1; v1 = v2; v2 = v3; v3 = temp;
} else {
// v3 <= v2 <= v1
final T temp = v1; v1 = v3; v3 = temp;
}
}
if (comparator.compare(v2, v4) <= 0) {
if (comparator.compare(v3, v4) <= 0) {
// v3 <= v4
} else {
// v2 <= v4 < v3;
final T temp = v4; v4 = v3; v3 = temp;
}
} else {
if (comparator.compare(v1, v4) <= 0) {
// v1 <= v4 < v2;
final T temp = v4; v4 = v3; v3 = v2; v2 = temp;
} else {
// v4 < v1 <= v2;
final T temp = v4; v4 = v3; v3 = v2; v2 = v1; v1 = temp;
}
}
// v2v4
if (comparator.compare(v3, v5) <= 0) {
// v3 <= v5
if (comparator.compare(v4, v5) <= 0) {
// v3 <= v4 <= v5
} else {
// v3 <= v5 < v4
///final T temp = v5; v5 = v4; v4 = temp;
v4 = v5;
}
} else {
// v5 < v3
if (comparator.compare(v2, v5) <= 0) {
// v2 <= v5 < v3
///final T temp = v5; v5 = v4; v4 = v3; v3 = temp;
v4 = v3;
} else {
// v5 < v2 <= v3
if (comparator.compare(v1, v5) <= 0) {
// v1 <= v5 < v2 <= v3
///final T temp = v5; v5 = v4; v4 = v3; v3 = v2; v2 = temp;
v4 = v3; v2 = v5;
} else {
// v5 < v1 <= v2 <= v3
///final T temp = v5; v5 = v4; v4 = v3; v3 = v2; v2 = v1; v1 = temp;
v4 = v3; v2 = v1;
}
}
}
if (comparator.compare(v2, v4) != 0) {
// v2 v4
// dual pivot quick sort
final T pivot1 = v2;
final T pivot2 = v4;
int idx1A = from; // value <= pivot1 (arrays)
int idx2W = 0; // pivot1 < value < pivot2(works)
int idx3W = range - 1; // pivot2 <= value (works)
for (int idx = from; idx < to; idx++) {
final T value = array[idx];
if (comparator.compare(value, pivot1) <= 0) {
array[idx1A++] = value;
} else if (comparator.compare(value, pivot2) >= 0) {
workArray[idx3W--] = value;
} else {
workArray[idx2W++] = value;
}
}
int idxTo = idx1A;
// works array
//for (int idx = 0; idx < idx2W; idx++) {
// array[idxTo++] = works[idx];
System.arraycopy(workArray, 0, array, idxTo, idx2W);
idxTo += idx2W;
// works array
for (int idx = range - 1; idx > idx3W; idx
array[idxTo++] = workArray[idx];
}
// CPU
dpsSort(array, idx1A + idx2W, to, workArray, depthRemainder - 1, comparator);
// CPU
dpsSort(array, idx1A, idx1A + idx2W, workArray, depthRemainder - 1, comparator);
dpsSort(array, from, idx1A, workArray, depthRemainder - 1, comparator);
} else {
// pivot1 pivot2
// 3 way partition
final T pivot = v2;
int idx1A = from; // value < pivot (array)
int idx2W = 0; // value == pivot (workArray)
int idx3W = range - 1; // pivot < value (workArray)
for (int idx = from; idx < to; idx++) {
final T value = array[idx];
final int compareVal = comparator.compare(value, pivot);
if (compareVal < 0) {
array[idx1A++] = value;
} else if (compareVal > 0) {
workArray[idx3W--] = value;
} else {
workArray[idx2W++] = value;
}
}
int idxTo = idx1A;
// works array
//for (int idx = 0; idx < idx2W; idx++) {
// array[idxTo++] = works[idx];
System.arraycopy(workArray, 0, array, idxTo, idx2W);
idxTo += idx2W;
// works array
for (int idx = range - 1; idx > idx3W; idx
array[idxTo++] = workArray[idx];
}
// CPU
dpsSort(array, idx1A + idx2W, to, workArray, depthRemainder - 1, comparator);
// CPU
dpsSort(array, from, idx1A, workArray, depthRemainder - 1, comparator);
}
}
public static final <T> void dpsSort(final T[] array, final int from, final int to, final Comparator<? super T> comparator)
{
final int range = to - from;
@SuppressWarnings("unchecked")
final T[] workArray = (T[])new Object[range];
// (log2(range))
// Dual-pivot quicksortlog3(/) * 2.2
// 1.22
final int depthRemainder = (int)(Math.log(range / ALGORITHM_THRESHOLD) / Math.log(3.0) * 2.2 * 1.2 + 2);
dpsSort(array, from, to, workArray, depthRemainder, comparator);
}
@Override
public <T> void sort(final T[] array, final int from, final int to, final Comparator<? super T> comparator)
{
dpsSort(array, from, to, comparator);
}
@Override
public boolean isStable()
{
return true;
}
@Override
public String getName()
{
return "dpsSort";
}
}
|
package cx2x.xcodeml.xnode;
import cx2x.xcodeml.helper.XelementHelper;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import java.util.List;
/**
* XcodeML AST node.
*
* @author clementval
*/
public class Xnode {
protected final Element _baseElement;
/**
* Constructs an Xnode object from an element in the AST.
* @param element Base element for the Xnode object.
*/
public Xnode(Element element){
_baseElement = element;
}
/**
* Constructs a new element in the AST.
* @param opcode Code of the new element.
* @param xcodeml Current XcodeML program unit in which the element is
* created.
*/
public Xnode(Xcode opcode, XcodeProgram xcodeml){
_baseElement = xcodeml.getDocument().createElement(opcode.code());
}
/**
* Get the element opcode.
* @return Opcode.
*/
public Xcode Opcode(){
return Xcode.valueOf(_baseElement.getTagName().toUpperCase());
}
/**
* Check whether the element has the corresponding attribute.
* @param attrCode Attribute code.
* @return True if the element has the corresponding attribute.
*/
public boolean hasAttribute(Xattr attrCode){
return _baseElement != null
&& _baseElement.hasAttribute(attrCode.toString());
}
/**
* Get the attribute's value.
* @param attrCode Attribute code.
* @return Attribute's value.
*/
public String getAttribute(Xattr attrCode){
if(_baseElement.hasAttribute(attrCode.toString())){
return _baseElement.getAttribute(attrCode.toString());
} else {
return null;
}
}
/**
* Get boolean value of an attribute.
* @param attrCode Attribute code.
* @return Attribute's value. False if attribute doesn't exist.
*/
public boolean getBooleanAttribute(Xattr attrCode) {
return _baseElement.hasAttribute(attrCode.toString()) &&
_baseElement.getAttribute(attrCode.toString()).equals(XelementName.TRUE);
}
/**
* Get the element's value.
* @return Element value.
*/
public String getValue(){
return _baseElement.getTextContent().trim();
}
/**
* Set attribute value.
* @param attrCode Attribute code.
* @param value Value of the attribute.
*/
public void setAttribute(Xattr attrCode, String value){
_baseElement.setAttribute(attrCode.toString(), value);
}
/**
* Get the list of child elements.
* @return List of children of the current element.
*/
public List<Xnode> getChildren(){
List<Xnode> nodes = new ArrayList<>();
NodeList children = _baseElement.getChildNodes();
for(int i = 0; i < children.getLength(); ++i){
Node child = children.item(i);
if(child.getNodeType() == Node.ELEMENT_NODE){
nodes.add(new Xnode((Element)child));
}
}
return nodes;
}
/**
* Check whether the current element has a body element.
* @return True if the element has a body. False otherwise.
*/
public boolean hasBody(){
switch (Opcode()){
case FDOSTATEMENT:
case FFUNCTIONDEFINITION:
return true;
}
return false;
}
/**
* Get the inner body element.
* @return The body element if found. Null otherwise.
*/
public Xnode getBody(){
return findNode(Xcode.BODY);
}
/**
* Find first child with the given opcode.
* @param opcode Code of the element to be found.
* @return The found element. Null if nothing found.
*/
public Xnode findNode(Xcode opcode){
List<Xnode> children = getChildren();
for(Xnode child : children){
if(child.Opcode() == opcode){
return child;
}
}
return null;
}
/**
* Find a specific element in the children of the current element.
* @param opcodes List of opcode to reach the element.
* @return The element if found. Null otherwise.
*/
public Xnode find(Xcode... opcodes){
Xnode tmp = this;
for(Xcode opcode : opcodes){
tmp = tmp.findNode(opcode);
if(tmp == null){
return null;
}
}
return tmp;
}
/**
* Get child at position.
* @param pos Position of the child.
* @return Child at the corresponding position.
*/
public Xnode getChild(int pos){
List<Xnode> children = getChildren();
if(pos < 0 || pos > children.size() - 1){
return null;
}
return children.get(pos);
}
/**
* Set the element value.
* @param value The element value.
*/
public void setValue(String value){
_baseElement.setTextContent(value);
}
/**
* Delete the stored root element and all its children.
*/
public void delete(){
XelementHelper.delete(_baseElement);
}
/**
* Get the base element.
* @return Element.
*/
public Element getElement(){
return _baseElement;
}
/**
* Create an identical copy of the element and its children.
* @return A node representing the root element of the clone.
*/
public Node cloneNode(){
return _baseElement.cloneNode(true);
}
/**
* Append an element ot the children of this element.
* @param node The element to append.
* @param clone If true, the element is cloned before being appened. If
* false, the element is directly appened.
*/
public void appendToChildren(Xnode node, boolean clone){
if(node != null){
if(clone){
_baseElement.appendChild(node.cloneNode());
} else {
_baseElement.appendChild(node.getElement());
}
}
}
/**
* Insert as first child.
* @param node Element to be inserted.
* @param clone Clone or not the element before insertion.
*/
public void insert(Xnode node, boolean clone){
if(node != null) {
NodeList children = _baseElement.getChildNodes();
Node toInsert = clone ? node.cloneNode() : node.getElement();
if(children.getLength() == 0){
_baseElement.appendChild(toInsert);
} else {
_baseElement.insertBefore(toInsert, children.item(0));
}
}
}
/**
* Set the file attribute of the element.
* @param value File path.
*/
public void setFile(String value){
setAttribute(Xattr.FILE, value);
}
/**
* Set the lineno attribute in the element.
* @param lineno Line number.
*/
public void setLine(int lineno){
setAttribute(Xattr.LINENO, String.valueOf(lineno));
}
/**
* Clone the current element with all its children.
* @return A copy of the current element.
*/
public Xnode cloneObject() {
Node clone = cloneNode();
return new Xnode((Element)clone);
}
/**
*
* @return
*/
public int getLineNo(){
if(_baseElement.hasAttribute(Xattr.LINENO.toString())){
return Integer.parseInt(_baseElement.getAttribute(Xattr.LINENO.toString()));
} else {
return 0;
}
}
/**
*
* @return
*/
public String getFile(){
return _baseElement.getAttribute(Xattr.FILE.toString());
}
}
|
package ca.teamTen.recitopia;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* A Recipe with a name, ingredients, instructions, photos
* and an author. Recipes can be published (stored on the server)
* or not (stored on the phone).
*
* Recipe instances are somewhat immutable.
*
* @see RecipeBook
*/
public class Recipe implements Serializable
{
/**
* Serializable version id.
*/
private static final long serialVersionUID = 1L;
private String recipeName;
private ArrayList<String> ingredients;
private String cookingInstruction;
private String author;
private transient boolean isPublished;
private ArrayList<Photo> photos;
/**
* simple constructor for use with GSon
* @param published
*/
public Recipe(boolean published) {
isPublished = published;
}
/**
* Create a new Recipe
* @param recipeName name of the recipe
* @param ingredients an array of ingredients
* @param instruction a string containing the instructions
* @param author the userid (email) of the author of this recipe
*/
public Recipe(String recipeName, ArrayList<String> ingredients, String instruction, String author) {
this.recipeName = recipeName;
if (ingredients != null) {
this.ingredients = new ArrayList<String>(ingredients);
} else {
this.ingredients = new ArrayList<String>();
}
this.cookingInstruction = instruction;
this.author = author;
this.photos = new ArrayList<Photo>();
}
/**
* Get the name/title of the recipe
* @return the name
*/
public String getRecipeName() {
return this.recipeName;
}
/**
* Get the recipe author's userid (email)
* @return the author
*/
public String showAuthor() {
return this.author;
}
/**
* Get the recipe ingredients
* @return the ingredients
*/
public ArrayList<String> showIngredients() {
return this.ingredients;
}
/**
* Get the recipe instructions
* @return instructions
*/
public String showCookingInstructions() {
return this.cookingInstruction;
}
/**
* Gets the photos associated with this recipe
* @return an array of photos associated with this recipe
*/
public Photo[] getPhotos() {
return (Photo[]) this.photos.toArray(new Photo[photos.size()]);
}
/**
* Adds a photo to the recipe.
* @param photo
*/
public void addPhotos(Photo photo) {
this.photos.add(photo);
}
/**
* Gets whether the recipe has been published
* @return true if the recipe is published
*/
public boolean publishRecipe() {
return false;
}
/**
* Checks for equality of all members.
*
* isPublished is not checked, as this is meta-data, not
* data.
*
* @return true if all members are equal
*/
public boolean equalData(Recipe other) {
if (other == null) {
return false;
}
Set<String> myIngredients = new HashSet<String>(ingredients);
for (String ingredient: other.ingredients) {
if (!myIngredients.contains(ingredient)) {
return false;
}
}
return recipeName.equals(other.recipeName)
&& cookingInstruction.equals(other.cookingInstruction)
&& author.equals(other.author)
;
// TODO: check photos?
}
/**
* toString() method converts a Recipe object into a string for sharing/display purposes
*/
public String toString() {
String ingredientsString = new String();
for(int i = 0; i < ingredients.size(); i++) {
if(i == (ingredients.size()-1))
ingredientsString = ingredientsString.concat(ingredients.get(i)).concat("\n");
else
ingredientsString = ingredientsString.concat(ingredients.get(i)).concat(", ");
}
return "Recipe Name: " + getRecipeName() + "\n" + "\n"
+ "Author: " + author + "\n" + "\n"
+ "Ingredients: " + ingredientsString + "\n" + "\n"
+ "Cooking Instructions: " + cookingInstruction;
}
}
|
//import uk.co.uwcs.choob.*;
import uk.co.uwcs.choob.modules.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import java.util.*;
//import java.security.*;
import java.util.regex.*;
public class UserTypeCheckResult
{
boolean hasChecked;
boolean isBot;
boolean isAway;
boolean isOperator;
boolean isRegistered;
boolean isSecure;
long timestamp;
}
public class UserTypeCheck
{
private Modules mods;
private IRCInterface irc;
private Map<String,UserTypeCheckResult> userChecks;
private int[] statsCalled;
private int[] statsWhoisd;
private int[] statsFailed;
private int statsIndex;
private int statsLastHour;
private final int STATS_COUNT = 24;
/* Time that the API will wait for data to arrive */
private final int USER_DATA_WAIT = 10000; // 10 seconds
/* If true, cached requests will block until the live request times out */
private final boolean USER_DATA_CACHE_BLOCK = true;
/* The time between checks for expired cache items. */
private final int USER_DATA_INTERVAL = 30000; // 30 seconds
/* the time for which an entry is cached. */
private final int USER_DATA_TIMEOUT = USER_DATA_INTERVAL * 10; // 5 minutes
/* Different flag types... */
private final int USER_TYPE_FLAG_BOT = 1;
private final int USER_TYPE_FLAG_AWAY = 2;
private final int USER_TYPE_FLAG_IRCOP = 3;
private final int USER_TYPE_FLAG_REGISTERED = 4;
private final int USER_TYPE_FLAG_SECURE = 5;
private final int USER_TYPE_FLAG__MIN = USER_TYPE_FLAG_BOT;
private final int USER_TYPE_FLAG__MAX = USER_TYPE_FLAG_SECURE;
/* Return values from the API "check" */
private final int USER_TYPE_RV_ERROR = -1;
private final int USER_TYPE_RV_NO = 0;
private final int USER_TYPE_RV_YES = 1;
private final Pattern SplitWhoisLine = Pattern.compile("^([^ ]+) ([^ ]+) (.*)$");
public UserTypeCheck(Modules mods, IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
userChecks = new HashMap<String,UserTypeCheckResult>();
statsIndex = 0;
statsLastHour = 0;
statsCalled = new int[STATS_COUNT];
statsWhoisd = new int[STATS_COUNT];
statsFailed = new int[STATS_COUNT];
mods.interval.callBack(null, 1);
}
public String[] info()
{
return new String[] {
"Plugin for getting and caching type info (is bot, is ircop, is registered, etc.), about a user",
"The Choob Team",
"choob@uwcs.co.uk",
"$Rev$$Date$"
};
}
/* This is never called. WTF? */
public void destroy(Modules mods)
{
// Notify all threads blocked on user queries. This allows anything
// that was asking about a user to continue (and fail) rather than be
// stuck for all eternity.
synchronized(userChecks)
{
Iterator<String> user = userChecks.keySet().iterator();
while(user.hasNext()) {
UserTypeCheckResult entry = userChecks.get(user.next());
//FIXME: synchronized?//
entry.notifyAll();
}
}
}
public synchronized void interval(Object parameter, Modules mods, IRCInterface irc)
{
synchronized(userChecks)
{
Iterator<String> user = userChecks.keySet().iterator();
String nick;
while(user.hasNext()) {
// We want to remove any items that have expired, but leave
// those still in progress.
nick = user.next();
UserTypeCheckResult entry = userChecks.get(nick);
if (entry.hasChecked && (System.currentTimeMillis() > entry.timestamp + USER_DATA_TIMEOUT)) {
System.out.println("UTC: Data for user <" + nick + "> has expired.");
userChecks.remove(nick);
// Restart iterator, otherwise it gets all touchy.
user = userChecks.keySet().iterator();
}
}
}
// Update stats.
int newHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) % 12;
if (statsLastHour != newHour) {
statsLastHour = newHour;
double totalC = 0;
double totalW = 0;
double totalF = 0;
for (int i = 0; i < STATS_COUNT; i++) {
totalC += statsCalled[i];
totalW += statsWhoisd[i];
totalF += statsFailed[i];
}
System.out.println("UTC: Average API usage : " + (totalC / STATS_COUNT) + "/hour");
System.out.println("UTC: Average WHOIS commands issued: " + (totalW / STATS_COUNT) + "/hour");
System.out.println("UTC: Average failed requests : " + (totalF / STATS_COUNT) + "/hour");
statsIndex++;
statsCalled[statsIndex] = 0;
statsWhoisd[statsIndex] = 0;
statsFailed[statsIndex] = 0;
}
mods.interval.callBack(null, USER_DATA_INTERVAL);
}
public String[] helpCommandCheck = {
"Displays some cached status information about a user.",
"[<nickname>]",
"<nickname> is an optional nick to check"
};
public void commandCheck(Message mes)
{
String nick = mods.util.getParamString(mes);
if (nick.length() == 0)
nick = mes.getNick();
int Bot = apiStatus(nick, "bot");
int Away = apiStatus(nick, "away");
int IRCop = apiStatus(nick, "ircop");
int Reg = apiStatus(nick, "registered");
int SSL = apiStatus(nick, "secure");
irc.sendContextReply(mes, "Status for " + nick +
": bot = " + mapRVToString(Bot) +
"; away = " + mapRVToString(Away) +
"; ircop = " + mapRVToString(IRCop) +
"; registered = " + mapRVToString(Reg) +
"; secure = " + mapRVToString(SSL) +
".");
}
/*
* Checks the status of the nickname and returns the status of the specified
* flag. This bblocks the caller if a client-server check is needed for this
* user (which is then cached). The block times out after 10 seconds, at
* which point the error value is returned (-1).
*
* @param nick The nickname to check the status of.
* @param flag The flag to check. May be one of: "bot" (user is marked as a bot),
* "away" (marked away), "ircop" (IRC operator/network service),
* "registered" (registered and identified with NickServ) or
* "secure" (using a secure [SSL] connection).
* @return 1 meaning the flag is true/set for the user, 0 if it is false/not
* set and -1 if an error occurs.
*/
public int apiStatus(String nick, String flag)
{
statsCalled[statsIndex]++;
String nickl = nick.toLowerCase();
String flagl = flag.toLowerCase();
if (flagl.equals("bot"))
return getStatus(nickl, USER_TYPE_FLAG_BOT);
if (flagl.equals("away"))
return getStatus(nickl, USER_TYPE_FLAG_AWAY);
if (flagl.equals("ircop"))
return getStatus(nickl, USER_TYPE_FLAG_IRCOP);
if (flagl.equals("registered"))
return getStatus(nickl, USER_TYPE_FLAG_REGISTERED);
if (flagl.equals("secure"))
return getStatus(nickl, USER_TYPE_FLAG_SECURE);
return USER_TYPE_RV_ERROR;
}
public void onServerResponse(ServerResponse ev)
{
// Check for a code we care about first. If we don't care about the
// code, we can bail right here. This saves on using the RegExp, and
// the |synchronized| stuff below.
int code = ev.getCode();
if ((code != 301) && (code != 307) && (code != 313)
&& (code != 318) && (code != 335) && (code != 671)) {
return;
}
Matcher sp = SplitWhoisLine.matcher(ev.getResponse());
if (!sp.matches())
return;
String nickl = sp.group(2).toLowerCase();
UserTypeCheckResult userData;
synchronized(userChecks) {
userData = userChecks.get(nickl);
}
if (userData == null) {
return;
}
synchronized(userData) {
if (code == 335) {
userData.isBot = true;
}
if (code == 301) {
userData.isAway = true;
}
if (code == 313) {
userData.isOperator = true;
}
if (code == 307) {
userData.isRegistered = true;
}
if (code == 671) {
userData.isSecure = true;
}
if (code == 318) {
userData.timestamp = System.currentTimeMillis();
userData.hasChecked = true;
System.out.println("UTC: Data for user <" + nickl +
">: bot(" + (new Boolean(userData.isBot)).toString() +
"); away(" + (new Boolean(userData.isAway)).toString() +
"); ircop(" + (new Boolean(userData.isOperator)).toString() +
"); reg(" + (new Boolean(userData.isRegistered)).toString() +
"); ssl(" + (new Boolean(userData.isSecure)).toString() +
").");
userData.notifyAll();
}
}
}
private int getStatus(String nick, int flag)
{
UserTypeCheckResult userData = getUserData(nick);
if (userData == null) {
return USER_TYPE_RV_ERROR;
}
switch(flag) {
case USER_TYPE_FLAG_BOT:
return mapBooleanToCheckRV(userData.isBot);
case USER_TYPE_FLAG_AWAY:
return mapBooleanToCheckRV(userData.isAway);
case USER_TYPE_FLAG_IRCOP:
return mapBooleanToCheckRV(userData.isOperator);
case USER_TYPE_FLAG_REGISTERED:
return mapBooleanToCheckRV(userData.isRegistered);
case USER_TYPE_FLAG_SECURE:
return mapBooleanToCheckRV(userData.isSecure);
}
return USER_TYPE_RV_ERROR;
}
private UserTypeCheckResult getUserData(String nick)
{
UserTypeCheckResult data;
synchronized(userChecks) {
data = userChecks.get(nick);
if (data != null) {
if (!USER_DATA_CACHE_BLOCK && !data.hasChecked) {
statsFailed[statsIndex]++;
System.out.println("UTC: Check (cached) for user <" + nick + "> has no data!");
return null;
}
synchronized(data) {
if (!data.hasChecked) {
statsFailed[statsIndex]++;
System.out.println("UTC: Check (cached) for user <" + nick + "> FAILED!");
return null;
}
return data;
}
}
// Create new data thing and send query off.
data = new UserTypeCheckResult();
data.hasChecked = false;
userChecks.put(nick, data);
}
statsWhoisd[statsIndex]++;
irc.sendRawLine("WHOIS " + nick);
synchronized(data) {
try {
data.wait(USER_DATA_WAIT);
} catch (InterruptedException e) {
// Do nothing, as data.hasChecked will be false anyway.
}
if (!data.hasChecked) {
statsFailed[statsIndex]++;
System.out.println("UTC: Check (live) for user <" + nick + "> FAILED!");
return null;
}
return data;
}
}
private int mapBooleanToCheckRV(boolean in)
{
if (in)
return USER_TYPE_RV_YES;
return USER_TYPE_RV_NO;
}
private String mapRVToString(int rv)
{
switch (rv) {
case USER_TYPE_RV_YES: return "yes";
case USER_TYPE_RV_NO: return "no";
default: return "error";
}
}
}
|
package gov.nih.nci.evs.browser.utils;
import java.util.*;
import java.sql.*;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.*;
import org.LexGrid.LexBIG.DataModel.Collections.*;
import org.LexGrid.LexBIG.DataModel.Core.*;
import org.LexGrid.LexBIG.Exceptions.*;
import org.LexGrid.LexBIG.Impl.*;
import org.LexGrid.LexBIG.LexBIGService.*;
import org.LexGrid.concepts.*;
import org.LexGrid.LexBIG.Utility.Iterators.*;
import org.LexGrid.codingSchemes.*;
import org.LexGrid.LexBIG.Utility.*;
import org.LexGrid.LexBIG.DataModel.Core.types.*;
import org.LexGrid.LexBIG.Extensions.Generic.*;
import org.LexGrid.naming.*;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.*;
import org.LexGrid.commonTypes.*;
import gov.nih.nci.evs.browser.properties.*;
import gov.nih.nci.evs.browser.common.*;
import org.apache.commons.codec.language.*;
import org.apache.log4j.*;
import org.LexGrid.relations.Relations;
import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension.Mapping.SearchContext;
import org.LexGrid.LexBIG.Extensions.Generic.*;
import org.LexGrid.LexBIG.Extensions.Generic.SupplementExtension;
import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension;
import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension.Direction;
import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension.MappingSortOption;
import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension.MappingSortOptionName;
import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension.QualifierSortOption;
import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension.Mapping;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption;
import static gov.nih.nci.evs.browser.common.Constants.*;
import gov.nih.nci.evs.browser.bean.*;
/**
* @author EVS Team
* @version 1.0
*
* Modification history Initial implementation kim.ong@ngc.com
*
*/
public class MappingSearchUtils {
private static Logger _logger = Logger.getLogger(SearchUtils.class);
public MappingSearchUtils() {
}
public static String getMappingRelationsContainerName(String scheme, String version) {
CodingSchemeVersionOrTag versionOrTag =
new CodingSchemeVersionOrTag();
if (version != null) {
versionOrTag.setVersion(version);
}
String relationsContainerName = null;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
if (cs == null) return null;
java.util.Enumeration<? extends Relations> relations = cs.enumerateRelations();
while (relations.hasMoreElements()) {
Relations relation = (Relations) relations.nextElement();
Boolean isMapping = relation.getIsMapping();
System.out.println("isMapping: " + isMapping);
if (isMapping != null && isMapping.equals(Boolean.TRUE)) {
relationsContainerName = relation.getContainerName();
break;
}
}
if (relationsContainerName == null) {
System.out.println("WARNING: Mapping container not found in " + scheme);
return null;
} else {
System.out.println("relationsContainerName " + relationsContainerName);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return relationsContainerName;
}
private CodedNodeSet.PropertyType[] getAllNonPresentationPropertyTypes() {
CodedNodeSet.PropertyType[] propertyTypes =
new CodedNodeSet.PropertyType[3];
propertyTypes[0] = PropertyType.COMMENT;
propertyTypes[1] = PropertyType.DEFINITION;
propertyTypes[2] = PropertyType.GENERIC;
return propertyTypes;
}
public ResolvedConceptReferencesIteratorWrapper searchByCode(
String scheme, String version, String matchText,
String matchAlgorithm, int maxToReturn) {
Vector schemes = new Vector();
schemes.add(scheme);
Vector versions = new Vector();
versions.add(version);
return searchByCode(scheme, version, matchText, matchAlgorithm, SearchContext.SOURCE_OR_TARGET_CODES, maxToReturn);
}
public ResolvedConceptReferencesIteratorWrapper searchByCode(
Vector schemes, Vector versions, String matchText,
String matchAlgorithm, int maxToReturn) {
return searchByCode(
schemes, versions, matchText,
matchAlgorithm, SearchContext.SOURCE_OR_TARGET_CODES, maxToReturn);
}
public ResolvedConceptReferencesIteratorWrapper searchByCode(
String scheme, String version, String matchText,
String matchAlgorithm, SearchContext searchContext, int maxToReturn) {
Vector schemes = new Vector();
schemes.add(scheme);
Vector versions = new Vector();
versions.add(version);
return searchByCode(schemes, versions, matchText, matchAlgorithm, searchContext, maxToReturn);
}
public ResolvedConceptReferencesIteratorWrapper searchByCode(
Vector schemes, Vector versions, String matchText,
String matchAlgorithm, SearchContext searchContext, int maxToReturn) {
System.out.println("============================== MappingSearchUtils searchByCode");
if (matchText == null || matchText.trim().length() == 0)
return null;
matchText = matchText.trim();
_logger.debug("searchByCode ... " + matchText);
if (matchAlgorithm.compareToIgnoreCase("contains") == 0)
{
matchAlgorithm = new SearchUtils().findBestContainsAlgorithm(matchText);
}
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
MappingExtension mappingExtension = null;
try {
mappingExtension = (MappingExtension)lbSvc.getGenericExtension("MappingExtension");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
ResolvedConceptReferencesIterator itr = null;
int lcv = 0;
String scheme = null;
String version = null;
int numberRemaining = -1;
while (itr == null && numberRemaining == -1 && lcv < schemes.size()) {
scheme = (String) schemes.elementAt(lcv);
version = (String) versions.elementAt(lcv);
System.out.println(scheme + " (version: " + version);
String containerName = getMappingRelationsContainerName(scheme, version);
System.out.println("\tcontainer name: " + containerName);
if (containerName != null) {
try {
Mapping mapping =
mappingExtension.getMapping(scheme, null, containerName);
if (mapping != null) {
ConceptReferenceList codeList = new ConceptReferenceList();
ConceptReference ref = new ConceptReference();
ref.setConceptCode(matchText);
codeList.addConceptReference(ref);
mapping = mapping.restrictToCodes(codeList, searchContext);
itr = mapping.resolveMapping();
if (itr != null) {
try {
numberRemaining = itr.numberRemaining();
System.out.println("\tsearchByCode matches: " + numberRemaining);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
lcv++;
}
if (itr != null) {
ResolvedConceptReferencesIteratorWrapper wrapper = new ResolvedConceptReferencesIteratorWrapper(itr);
wrapper.setCodingSchemeName(scheme);
wrapper.setCodingSchemeVersion(version);
return wrapper;
}
return null;
}
public ResolvedConceptReferencesIteratorWrapper searchByName(
String scheme, String version, String matchText,
String matchAlgorithm, int maxToReturn) {
Vector schemes = new Vector();
schemes.add(scheme);
Vector versions = new Vector();
versions.add(version);
return searchByName(schemes, versions, matchText, matchAlgorithm, maxToReturn);
}
public ResolvedConceptReferencesIteratorWrapper searchByName(
Vector schemes, Vector versions, String matchText,
String matchAlgorithm, int maxToReturn) {
if (matchText == null || matchText.trim().length() == 0)
return null;
matchText = matchText.trim();
_logger.debug("searchByName ... " + matchText);
if (matchAlgorithm.compareToIgnoreCase("contains") == 0)
{
matchAlgorithm = new SearchUtils().findBestContainsAlgorithm(matchText);
}
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
MappingExtension mappingExtension = null;
try {
mappingExtension = (MappingExtension)lbSvc.getGenericExtension("MappingExtension");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
ResolvedConceptReferencesIterator itr = null;
int lcv = 0;
String scheme = null;
String version = null;
int numberRemaining = -1;
while (itr == null && numberRemaining == -1 && lcv < schemes.size()) {
scheme = (String) schemes.elementAt(lcv);
version = (String) versions.elementAt(lcv);
String containerName = getMappingRelationsContainerName(scheme, version);
if (containerName != null) {
try {
Mapping mapping =
mappingExtension.getMapping(scheme, null, containerName);
if (mapping != null) {
mapping = mapping.restrictToMatchingDesignations(
matchText, SearchDesignationOption.ALL, matchAlgorithm, null, SearchContext.SOURCE_OR_TARGET_CODES
);
//Finally, resolve the Mapping.
itr = mapping.resolveMapping();
try {
numberRemaining = itr.numberRemaining();
System.out.println("Number of matches: " + numberRemaining);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
//return null;
}
}
lcv++;
}
if (itr != null) {
ResolvedConceptReferencesIteratorWrapper wrapper = new ResolvedConceptReferencesIteratorWrapper(itr);
wrapper.setCodingSchemeName(scheme);
wrapper.setCodingSchemeVersion(version);
return wrapper;
}
return null;
}
public ResolvedConceptReferencesIteratorWrapper searchByProperties(
String scheme, String version, String matchText,
String matchAlgorithm, int maxToReturn) {
System.out.println("searchByProperties scheme: " + scheme);
System.out.println("searchByProperties version: " + version);
Vector schemes = new Vector();
schemes.add(scheme);
Vector versions = new Vector();
versions.add(version);
return searchByProperties(schemes, versions, matchText, matchAlgorithm, maxToReturn);
}
public ResolvedConceptReferencesIteratorWrapper searchByProperties(
Vector schemes, Vector versions, String matchText,
String matchAlgorithm, int maxToReturn) {
if (matchText == null || matchText.trim().length() == 0)
return null;
matchText = matchText.trim();
_logger.debug("searchByName ... " + matchText);
if (matchAlgorithm.compareToIgnoreCase("contains") == 0)
{
matchAlgorithm = new SearchUtils().findBestContainsAlgorithm(matchText);
}
CodedNodeSet.PropertyType[] propertyTypes = null;
LocalNameList propertyNames = null;
LocalNameList sourceList = null;
propertyTypes = getAllNonPresentationPropertyTypes();
LocalNameList contextList = null;
NameAndValueList qualifierList = null;
String language = null;
// to be modified
SearchContext searchContext = SearchContext.SOURCE_OR_TARGET_CODES
;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
MappingExtension mappingExtension = null;
try {
mappingExtension = (MappingExtension)lbSvc.getGenericExtension("MappingExtension");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
ResolvedConceptReferencesIterator itr = null;
int lcv = 0;
String scheme = null;
String version = null;
System.out.println("schemes.size(): " + schemes.size() + " lcv: " + lcv);
int numberRemaining = -1;
while (itr == null && numberRemaining == -1 && lcv < schemes.size()) {
scheme = (String) schemes.elementAt(lcv);
version = (String) versions.elementAt(lcv);
String containerName = getMappingRelationsContainerName(scheme, version);
if (containerName != null) {
try {
Mapping mapping =
mappingExtension.getMapping(scheme, null, containerName);
if (mapping != null) {
mapping = mapping.restrictToMatchingProperties(
propertyNames,
propertyTypes,
sourceList,
contextList,
qualifierList,
matchAlgorithm,
language,
null,
searchContext);
//Finally, resolve the Mapping.
itr = mapping.resolveMapping();
try {
numberRemaining = itr.numberRemaining();
System.out.println("Number of matches: " + numberRemaining);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
//return null;
}
}
lcv++;
}
if (itr != null) {
ResolvedConceptReferencesIteratorWrapper wrapper = new ResolvedConceptReferencesIteratorWrapper(itr);
wrapper.setCodingSchemeName(scheme);
wrapper.setCodingSchemeVersion(version);
return wrapper;
}
return null;
}
public LocalNameList getSupportedAssociationNames(LexBIGService lbSvc, String scheme,
String version, String containerName) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
LocalNameList list = new LocalNameList();
try {
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
Relations[] relations = cs.getRelations();
for (int i = 0; i < relations.length; i++) {
Relations relation = relations[i];
_logger.debug("** getSupportedRoleNames containerName: "
+ relation.getContainerName());
if (relation.getContainerName().compareToIgnoreCase(containerName) == 0) {
org.LexGrid.relations.AssociationPredicate[] asso_array =
relation.getAssociationPredicate();
for (int j = 0; j < asso_array.length; j++) {
org.LexGrid.relations.AssociationPredicate association =
(org.LexGrid.relations.AssociationPredicate) asso_array[j];
// list.add(association.getAssociationName());
// KLO, 092209
//list.add(association.getForwardName());
list.addEntry(association.getAssociationName());
}
}
}
} catch (Exception ex) {
}
return list;
}
public ResolvedConceptReferencesIteratorWrapper searchByRelationships(
String scheme, String version, String matchText,
String matchAlgorithm, int maxToReturn) {
Vector schemes = new Vector();
schemes.add(scheme);
Vector versions = new Vector();
versions.add(version);
return searchByRelationships(schemes, versions, matchText, matchAlgorithm, maxToReturn);
}
public ResolvedConceptReferencesIteratorWrapper searchByRelationships(
Vector schemes, Vector versions, String matchText,
String matchAlgorithm, int maxToReturn) {
if (matchText == null || matchText.trim().length() == 0)
return null;
matchText = matchText.trim();
_logger.debug("searchByName ... " + matchText);
if (matchAlgorithm.compareToIgnoreCase("contains") == 0)
{
matchAlgorithm = new SearchUtils().findBestContainsAlgorithm(matchText);
}
SearchDesignationOption option = SearchDesignationOption.ALL;
String language = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
LocalNameList propertyNames = null;
LocalNameList sourceList = null;
propertyTypes = getAllNonPresentationPropertyTypes();
LocalNameList contextList = null;
NameAndValueList qualifierList = null;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
MappingExtension mappingExtension = null;
try {
mappingExtension = (MappingExtension)lbSvc.getGenericExtension("MappingExtension");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
ResolvedConceptReferencesIterator itr = null;
int lcv = 0;
String scheme = null;
String version = null;
System.out.println("schemes.size(): " + schemes.size() + " lcv: " + lcv);
int numberRemaining = -1;
while (itr == null && numberRemaining == -1 && lcv < schemes.size()) {
scheme = (String) schemes.elementAt(lcv);
version = (String) versions.elementAt(lcv);
String containerName = getMappingRelationsContainerName(scheme, version);
if (containerName != null) {
LocalNameList relationshipList = getSupportedAssociationNames(lbSvc, scheme, version, containerName);
try {
Mapping mapping =
mappingExtension.getMapping(scheme, null, containerName);
if (mapping != null) {
mapping = mapping.restrictToRelationship(
matchText,
option,
matchAlgorithm,
language,
relationshipList);
//Finally, resolve the Mapping.
itr = mapping.resolveMapping();
try {
numberRemaining = itr.numberRemaining();
System.out.println("Number of matches: " + numberRemaining);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
//return null;
}
}
lcv++;
}
if (itr != null) {
ResolvedConceptReferencesIteratorWrapper wrapper = new ResolvedConceptReferencesIteratorWrapper(itr);
wrapper.setCodingSchemeName(scheme);
wrapper.setCodingSchemeVersion(version);
return wrapper;
}
return null;
}
public static ResolvedConceptReferencesIterator getRestrictedMappingDataIterator(String scheme, String version,
List<MappingSortOption> sortOptionList, ResolvedConceptReferencesIterator searchResultsIterator) {
return getRestrictedMappingDataIterator(scheme, version,
sortOptionList, searchResultsIterator, SearchContext.SOURCE_OR_TARGET_CODES);
}
public static ResolvedConceptReferencesIterator getRestrictedMappingDataIterator(String scheme, String version,
List<MappingSortOption> sortOptionList, ResolvedConceptReferencesIterator searchResultsIterator, SearchContext context) {
System.out.println("(***********) getRestrictedMappingDataIterator ...");
if (searchResultsIterator == null) return null;
try {
int numRemaining = searchResultsIterator.numberRemaining();
System.out.println("(***********) searchResultsIterator passing number of matches: " + numRemaining);
} catch (Exception e) {
System.out.println("searchResultsIterator.numberRemaining() throws exception???");
return null;
}
CodingSchemeVersionOrTag versionOrTag =
new CodingSchemeVersionOrTag();
if (version != null) {
versionOrTag.setVersion(version);
}
String relationsContainerName = null;
LexBIGService distributed = RemoteServerUtil.createLexBIGService();
try {
CodingScheme cs = distributed.resolveCodingScheme(scheme, versionOrTag);
if (cs == null) return null;
java.util.Enumeration<? extends Relations> relations = cs.enumerateRelations();
while (relations.hasMoreElements()) {
Relations relation = (Relations) relations.nextElement();
Boolean isMapping = relation.getIsMapping();
System.out.println("isMapping: " + isMapping);
if (isMapping != null && isMapping.equals(Boolean.TRUE)) {
relationsContainerName = relation.getContainerName();
break;
}
}
if (relationsContainerName == null) {
System.out.println("WARNING: Mapping container not found in " + scheme);
return null;
} else {
System.out.println("relationsContainerName " + relationsContainerName);
}
MappingExtension mappingExtension = (MappingExtension)
distributed.getGenericExtension("MappingExtension");
Mapping mapping =
mappingExtension.getMapping(scheme, versionOrTag, relationsContainerName);
//ConceptReferenceList codeList (to be derived based on ResolvedConceptReferencesIterator searchResultsIterator)
ConceptReferenceList codeList = new ConceptReferenceList();
System.out.println("getRestrictedMappingDataIterator Step 5 while loop -- retrieving refs");
if (searchResultsIterator != null) {
int lcv = 0;
while(searchResultsIterator.hasNext()){
ResolvedConceptReference[] refs = searchResultsIterator.next(100).getResolvedConceptReference();
for(ResolvedConceptReference ref : refs){
lcv++;
System.out.println("(" + lcv + ") " + ref.getEntityDescription().getContent() + "(" + ref.getCode() + ")");
codeList.addConceptReference((ConceptReference) ref);
}
}
} else {
System.out.println("resolved_value_set.jsp ResolvedConceptReferencesIterator == NULL???");
}
mapping = mapping.restrictToCodes(codeList, context);
ResolvedConceptReferencesIterator itr = mapping.resolveMapping(sortOptionList);
return itr;
} catch (Exception ex) {
//ex.printStackTrace();
System.out.println("getRestrictedMappingDataIterator throws exceptions???");
}
return null;
}
public List getMappingRelationship(
String scheme, String version, String code, int direction) {
SearchContext searchContext = SearchContext.SOURCE_OR_TARGET_CODES;
if (direction == 1) searchContext = SearchContext.SOURCE_CODES;
else if (direction == -1) searchContext = SearchContext.TARGET_CODES;
ResolvedConceptReferencesIteratorWrapper wrapper = searchByCode(
scheme, version, code, "exactMatch", searchContext, -1);
if (wrapper == null) return null;
ResolvedConceptReferencesIterator iterator = wrapper.getIterator();
if (iterator == null) return null;
int numberRemaining = 0;
try {
numberRemaining = iterator.numberRemaining();
if (numberRemaining == 0) {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
MappingIteratorBean mappingIteratorBean = new MappingIteratorBean(
iterator,
numberRemaining, // number remaining
0, // istart
50, // iend,
numberRemaining, // size,
0, // pageNumber,
1); // numberPages
mappingIteratorBean.initialize(
iterator,
numberRemaining, // number remaining
0, // istart
50, // iend,
numberRemaining, // size,
0, // pageNumber,
1); // numberPages
return mappingIteratorBean.getData(0, numberRemaining); // implement getAll
}
/*
public static String TYPE_ROLE = "type_role";
public static String TYPE_ASSOCIATION = "type_association";
public static String TYPE_SUPERCONCEPT = "type_superconcept";
public static String TYPE_SUBCONCEPT = "type_subconcept";
public static String TYPE_INVERSE_ROLE = "type_inverse_role";
public static String TYPE_INVERSE_ASSOCIATION = "type_inverse_association";
*/
private String replaceAssociationNameByRela(AssociatedConcept ac,
String associationName) {
if (ac.getAssociationQualifiers() == null)
return associationName;
if (ac.getAssociationQualifiers().getNameAndValue() == null)
return associationName;
for (NameAndValue qual : ac.getAssociationQualifiers()
.getNameAndValue()) {
String qualifier_name = qual.getName();
String qualifier_value = qual.getContent();
if (qualifier_name.compareToIgnoreCase("rela") == 0) {
return qualifier_value; // replace associationName by Rela value
}
}
return associationName;
}
public HashMap getMappingRelationshipHashMap(String scheme, String version, String code) {
HashMap hmap = new HashMap();
HashMap map1 = getMappingRelationshipHashMap(scheme, version, code, 1);
ArrayList list = (ArrayList) map1.get(TYPE_ASSOCIATION);
if (list != null) {
hmap.put(TYPE_ASSOCIATION, list);
}
HashMap map2 = getMappingRelationshipHashMap(scheme, version, code, -1);
list = (ArrayList) map2.get(TYPE_INVERSE_ASSOCIATION);
if (list != null) {
hmap.put(TYPE_INVERSE_ASSOCIATION, list);
}
return hmap;
}
public HashMap getMappingRelationshipHashMap(
String scheme, String version, String code, int direction) {
SearchContext searchContext = SearchContext.SOURCE_OR_TARGET_CODES;
if (direction == 1) searchContext = SearchContext.SOURCE_CODES;
else if (direction == -1) searchContext = SearchContext.TARGET_CODES;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm =
new DataUtils().createLexBIGServiceConvenienceMethods(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferencesIteratorWrapper wrapper = searchByCode(
scheme, version, code, "exactMatch", searchContext, -1);
if (wrapper == null) return null;
ResolvedConceptReferencesIterator iterator = wrapper.getIterator();
if (iterator == null) return null;
HashMap hmap = new HashMap();
ArrayList list = new ArrayList();
try {
while (iterator.hasNext()) {
ResolvedConceptReference ref = (ResolvedConceptReference) iterator.next();
AssociationList asso_of = ref.getSourceOf();
if (asso_of != null) {
Association[] associations =
asso_of.getAssociation();
if (associations != null) {
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = null;
try {
associationName = lbscm
.getAssociationNameFromAssociationCode(
scheme, csvt, assoc
.getAssociationName());
} catch (Exception ex) {
associationName = assoc.getAssociationName();
}
AssociatedConcept[] acl =
assoc.getAssociatedConcepts()
.getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
EntityDescription ed =
ac.getEntityDescription();
String name = "No Description";
if (ed != null)
name = ed.getContent();
String pt = name;
if (associationName
.compareToIgnoreCase("equivalentClass") != 0
&& ac.getConceptCode().indexOf("@") == -1) {
String relaValue =
replaceAssociationNameByRela(
ac, associationName);
String s =
relaValue + "|" + pt + "|"
+ ac.getConceptCode() + "|"
+ ac.getCodingSchemeName();
if (direction == -1) {
s = relaValue + "|" + ref.getEntityDescription().getContent() + "|"
+ ref.getCode() + "|"
+ ref.getCodingSchemeName();
}
if (ac.getAssociationQualifiers() != null) {
String qualifiers = "";
for (NameAndValue qual : ac
.getAssociationQualifiers()
.getNameAndValue()) {
String qualifier_name = qual.getName();
String qualifier_value = qual.getContent();
qualifiers = qualifiers + (qualifier_name + ":" + qualifier_value) + "$";
}
s = s + "|" + qualifiers;
}
if (direction == -1) {
s = s + "|" + ref.getCodeNamespace();
} else {
s = s + "|" + ac.getCodeNamespace();
}
list.add(s);
}
}
}
}
}
}
if (list.size() > 0) {
Collections.sort(list);
}
if (direction == 1) {
hmap.put(TYPE_ASSOCIATION, list);
} else {
hmap.put(TYPE_INVERSE_ASSOCIATION, list);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return hmap;
}
}
|
package dr.app.beauti.generator;
import dr.app.beast.BeastVersion;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.enumTypes.ClockType;
import dr.app.beauti.enumTypes.FixRateType;
import dr.app.beauti.enumTypes.StartingTreeType;
import dr.app.beauti.enumTypes.TreePriorType;
import dr.app.beauti.options.*;
import dr.app.beauti.util.XMLWriter;
import dr.app.util.Arguments;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodel.substmodel.AbstractSubstitutionModel;
import dr.evomodelxml.speciation.MultiSpeciesCoalescentParser;
import dr.evomodelxml.speciation.SpeciationLikelihoodParser;
import dr.evoxml.*;
import dr.inferencexml.distribution.MixedDistributionLikelihoodParser;
import dr.inferencexml.model.CompoundLikelihoodParser;
import dr.inferencexml.model.CompoundParameterParser;
import dr.inferencexml.operators.SimpleOperatorScheduleParser;
import dr.util.Attribute;
import dr.util.Version;
import dr.xml.XMLParser;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class holds all the data for the current BEAUti Document
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Walter Xie
* @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $
*/
public class BeastGenerator extends Generator {
private final static Version version = new BeastVersion();
private final AlignmentGenerator alignmentGenerator;
private final TreePriorGenerator treePriorGenerator;
private final TreeLikelihoodGenerator treeLikelihoodGenerator;
private final SubstitutionModelGenerator substitutionModelGenerator;
private final InitialTreeGenerator initialTreeGenerator;
private final TreeModelGenerator treeModelGenerator;
private final BranchRatesModelGenerator branchRatesModelGenerator;
private final OperatorsGenerator operatorsGenerator;
private final ParameterPriorGenerator parameterPriorGenerator;
private final LogGenerator logGenerator;
private final GeneralTraitGenerator generalTraitGenerator;
private final STARBEASTGenerator starEASTGeneratorGenerator;
private final TMRCAStatisticsGenerator tmrcaStatisticsGenerator;
public BeastGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
alignmentGenerator = new AlignmentGenerator(options, components);
tmrcaStatisticsGenerator = new TMRCAStatisticsGenerator(options, components);
substitutionModelGenerator = new SubstitutionModelGenerator(options, components);
treePriorGenerator = new TreePriorGenerator(options, components);
treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components);
initialTreeGenerator = new InitialTreeGenerator(options, components);
treeModelGenerator = new TreeModelGenerator(options, components);
branchRatesModelGenerator = new BranchRatesModelGenerator(options, components);
operatorsGenerator = new OperatorsGenerator(options, components);
parameterPriorGenerator = new ParameterPriorGenerator(options, components);
logGenerator = new LogGenerator(options, components);
generalTraitGenerator = new GeneralTraitGenerator(options, components);
starEASTGeneratorGenerator = new STARBEASTGenerator(options, components);
}
public void checkOptions() throws IllegalArgumentException {
//++++++++++++++++ Taxon List ++++++++++++++++++
TaxonList taxonList = options.taxonList;
Set<String> ids = new HashSet<String>();
ids.add(TaxaParser.TAXA);
ids.add(AlignmentParser.ALIGNMENT);
if (taxonList != null) {
if (taxonList.getTaxonCount() < 2) {
throw new IllegalArgumentException("BEAST requires at least two taxa to run.");
}
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (ids.contains(taxon.getId())) {
throw new IllegalArgumentException("A taxon has the same id," + taxon.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxon.getId());
}
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
for (Taxa taxa : options.taxonSets) {
if (taxa.getTaxonCount() < 2) {
throw new IllegalArgumentException("Taxon set, " + taxa.getId() + ", should contain\n" +
"at least two taxa.");
}
if (ids.contains(taxa.getId())) {
throw new IllegalArgumentException("A taxon sets has the same id," + taxa.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxa.getId());
}
//++++++++++++++++ Tree Prior ++++++++++++++++++
// if (options.isShareSameTreePrior()) {
if (options.getPartitionTreeModels().size() > 1) { //TODO not allowed multi-prior yet
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePriorType.GMRF_SKYRIDE) {
throw new IllegalArgumentException("For GMRF, tree model/tree prior combination not implemented by BEAST yet" +
"\nIt is only available for single tree model partition for this release.");
}
}
}
//+++++++++++++++ Starting tree ++++++++++++++++
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
if (model.getStartingTreeType() == StartingTreeType.USER) {
if (model.getUserStartingTree() == null) {
throw new IllegalArgumentException("Please selected a starting tree in Trees panel");
}
}
}
//++++++++++++++++ Random local clock model validation ++++++++++++++++++
for (PartitionClockModel model : options.getPartitionNonTraitsClockModels()) {
// 1 random local clock CANNOT have different tree models
if (model.getClockType() == ClockType.RANDOM_LOCAL_CLOCK) { // || AUTOCORRELATED_LOGNORMAL
PartitionTreeModel treeModel = null;
for (PartitionData pd : model.getAllPartitionData()) { // only the PDs linked to this tree model
if (treeModel != null && treeModel != pd.getPartitionTreeModel()) {
throw new IllegalArgumentException("One random local clock CANNOT have different tree models !");
}
treeModel = pd.getPartitionTreeModel();
}
}
}
//++++++++++++++++ Tree Model ++++++++++++++++++
if (options.allowDifferentTaxa) {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
int numOfTaxa = -1;
for (PartitionData pd : model.getAllPartitionData()) {
if (pd.getAlignment() != null) {
if (numOfTaxa > 0) {
if (numOfTaxa != pd.getTaxaCount()) {
throw new IllegalArgumentException("Partitions with different taxa cannot share the same tree");
}
} else {
numOfTaxa = pd.getTaxaCount();
}
}
}
}
}
//++++++++++++++++ Species tree ++++++++++++++++++
if (options.useStarBEAST) {
// if (!(options.nodeHeightPrior == TreePriorType.SPECIES_BIRTH_DEATH || options.nodeHeightPrior == TreePriorType.SPECIES_YULE)) {
// //TODO: more species tree model
}
// add other tests and warnings here
// Speciation model with dated tips
// Sampling rates without dated tips or priors on rate or nodes
}
/**
* Generate a beast xml file from these beast options
*
* @param file File
* @throws java.io.IOException IOException
* @throws dr.app.util.Arguments.ArgumentException
* ArgumentException
*/
public void generateXML(File file) throws GeneratorException, IOException, Arguments.ArgumentException {
XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(file)));
writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
writer.writeComment("Generated by BEAUTi " + version.getVersionString(),
" by Alexei J. Drummond and Andrew Rambaut",
" Department of Computer Science, University of Auckland and",
" Institute of Evolutionary Biology, University of Edinburgh",
" http://beast.bio.ed.ac.uk/");
writer.writeOpenTag("beast");
writer.writeText("");
// this gives any added implementations of the 'Component' interface a
// chance to generate XML at this point in the BEAST file.
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
//++++++++++++++++ Taxon List ++++++++++++++++++
try {
writeTaxa(writer, options.taxonList);
if (options.allowDifferentTaxa) { // allow diff taxa for multi-gene
writer.writeText("");
writer.writeComment("List all taxons regarding each gene (file) for Multispecies Coalescent function");
// write all taxa in each gene tree regarding each data partition,
for (PartitionData partition : options.getNonTraitsDataList()) {
// do I need if (!alignments.contains(alignment)) {alignments.add(alignment);} ?
writeDifferentTaxaForMultiGene(partition, writer);
}
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Taxon list generation has failed");
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
List<Taxa> taxonSets = options.taxonSets;
try {
if (taxonSets != null && taxonSets.size() > 0) {
tmrcaStatisticsGenerator.writeTaxonSets(writer, taxonSets);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Taxon sets generation has failed");
}
//++++++++++++++++ Alignments ++++++++++++++++++
try {
alignmentGenerator.writeAlignments(writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Alignments generation has failed");
}
//++++++++++++++++ Pattern Lists ++++++++++++++++++
try {
if (!options.samplePriorOnly) {
for (PartitionData partition : options.getNonTraitsDataList()) { // Each PD has one TreeLikelihood
writePatternList(partition, writer);
writer.writeText("");
}
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Pattern lists generation has failed");
}
//++++++++++++++++ General Data of Traits ++++++++++++++++++
try {
for (TraitData trait : options.getTraitsList()) {
// if (trait.isSpecifiedTraitAnalysis(TraitData.TRAIT_LOCATIONS.toString())) { // locations
// writer.writeComment(TraitData.getPhylogeographicDescription());
if (!trait.isSpecifiedTraitAnalysis(TraitData.TRAIT_SPECIES)) {
generalTraitGenerator.writeGeneralDataType(trait, writer);
writer.writeText("");
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("General data of traits generation has failed");
}
//++++++++++++++++ Tree Prior Model ++++++++++++++++++
try {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeTreePriorModel(prior, writer);
writer.writeText("");
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Tree prior model generation has failed");
}
//++++++++++++++++ Starting Tree ++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
initialTreeGenerator.writeStartingTree(model, writer);
writer.writeText("");
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Starting tree generation has failed");
}
//++++++++++++++++ Tree Model +++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
treeModelGenerator.writeTreeModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Tree model generation has failed");
}
//++++++++++++++++ Tree Prior Likelihood ++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior = model.getPartitionTreePrior();
treePriorGenerator.writePriorLikelihood(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographic(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Tree prior likelihood generation has failed");
}
//++++++++++++++++ Branch Rates Model ++++++++++++++++++
try {
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeBranchRatesModel(model, writer);
writer.writeText("");
}
// write allClockRate for fix mean option in clock model panel
if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
writer.writeOpenTag(CompoundParameterParser.COMPOUND_PARAMETER, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "allClockRates")});
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeAllClockRateRefs(model, writer);
}
writer.writeCloseTag(CompoundParameterParser.COMPOUND_PARAMETER);
writer.writeText("");
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Branch rates model generation is failed");
}
//++++++++++++++++ Substitution Model & Site Model ++++++++++++++++++
try {
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSubstitutionSiteModel(model, writer);
substitutionModelGenerator.writeAllMus(model, writer); // allMus
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Substitution model or site model generation has failed");
}
//++++++++++++++++ Site Model ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// substitutionModelGenerator.writeSiteModel(model, writer); // site model
// substitutionModelGenerator.writeAllMus(model, writer); // allMus
// writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
//++++++++++++++++ Tree Likelihood ++++++++++++++++++
try {
for (PartitionData partition : options.getNonTraitsDataList()) { // Each PD has one TreeLikelihood
treeLikelihoodGenerator.writeTreeLikelihood(partition, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Tree likelihood generation has failed");
}
//++++++++++++++++ Ancestral Tree Likelihood ++++++++++++++++++
try {
for (TraitData trait : options.getTraitsList()) {
if (!trait.isSpecifiedTraitAnalysis(TraitData.TRAIT_SPECIES)) {
generalTraitGenerator.writeAncestralTreeLikelihood(trait, writer);
}
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Ancestral Tree likelihood generation has failed");
}
//++++++++++++++++ *BEAST ++++++++++++++++++
try {
if (options.useStarBEAST) { // species
writeStarBEAST(writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("*BEAST special part generation has failed");
}
try {
if (taxonSets != null && taxonSets.size() > 0) {
tmrcaStatisticsGenerator.writeTMRCAStatistics(writer);
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("TMRCA statistics generation has failed");
}
//++++++++++++++++ Operators ++++++++++++++++++
try {
List<Operator> operators = options.selectOperators();
operatorsGenerator.writeOperatorSchedule(operators, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Operators generation has failed");
}
//++++++++++++++++ MCMC ++++++++++++++++++
try {
// XMLWriter writer, List<PartitionSubstitutionModel> models,
writeMCMC(writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("MCMC or log generation is failed");
}
try {
writeTimerReport(writer);
writer.writeText("");
if (options.performTraceAnalysis) {
writeTraceAnalysis(writer);
}
if (options.generateCSV) {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer);
}
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("The last part of XML generation has failed");
}
writer.writeCloseTag("beast");
writer.flush();
writer.close();
}
/**
* Generate a taxa block from these beast options
*
* @param writer the writer
* @param taxonList the taxon list to write
* @throws dr.app.util.Arguments.ArgumentException
* ArgumentException
*/
private void writeTaxa(XMLWriter writer, TaxonList taxonList) throws Arguments.ArgumentException {
// -1 (single taxa), 0 (1st gene of multi-taxa)
writer.writeComment("The list of taxa analyse (can also include dates/ages).",
"ntax=" + taxonList.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)});
boolean hasAttr = options.hasDiscreteIntegerTraitsExcludeSpecies();
boolean firstDate = true;
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
boolean hasDate = false;
if (options.clockModelOptions.isTipCalibrated()) {
hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE);
}
writer.writeTag(TaxonParser.TAXON, new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, taxon.getId())},
!(hasDate || hasAttr)); // false if any of hasDate or hasAttr is true
if (hasDate) {
dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
if (firstDate) {
options.units = date.getUnits();
firstDate = false;
} else {
if (options.units != date.getUnits()) {
System.err.println("Error: Units in dates do not match.");
}
}
Attribute[] attributes = {
new Attribute.Default<Double>(DateParser.VALUE, date.getTimeValue()),
new Attribute.Default<String>(DateParser.DIRECTION, date.isBackwards() ? DateParser.BACKWARDS : DateParser.FORWARDS),
new Attribute.Default<String>(DateParser.UNITS, Units.Utils.getDefaultUnitName(options.units))
//new Attribute.Default("origin", date.getOrigin()+"")
};
writer.writeTag(dr.evolution.util.Date.DATE, attributes, true);
}
if (hasAttr) {
generalTraitGenerator.writeAttrTrait(taxon, writer);
}
if (hasDate || hasAttr) writer.writeCloseTag(TaxonParser.TAXON);
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer);
}
writer.writeCloseTag(TaxaParser.TAXA);
}
public void writeDifferentTaxaForMultiGene(PartitionData dataPartition, XMLWriter writer) {
String data = dataPartition.getName();
Alignment alignment = dataPartition.getAlignment();
writer.writeComment("gene name = " + data + ", ntax= " + alignment.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, data + "." + TaxaParser.TAXA)});
for (int i = 0; i < alignment.getTaxonCount(); i++) {
final Taxon taxon = alignment.getTaxon(i);
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* *BEAST block
*
* @param writer XMLWriter
*/
private void writeStarBEAST(XMLWriter writer) {
String traitName = TraitData.TRAIT_SPECIES;
writer.writeText("");
writer.writeComment(options.starBEASTOptions.getDescription());
writer.writeOpenTag(traitName, new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, traitName)});
//new Attribute.Default<String>("traitType", traitType)});
starEASTGeneratorGenerator.writeMultiSpecies(options.taxonList, writer);
writer.writeCloseTag(traitName);
starEASTGeneratorGenerator.writeSTARBEAST(writer);
}
/**
* Writes the pattern lists
*
* @param partition the partition data to write the pattern lists for
* @param writer the writer
*/
public void writePatternList(PartitionData partition, XMLWriter writer) {
writer.writeText("");
PartitionSubstitutionModel model = partition.getPartitionSubstitutionModel();
String codonHeteroPattern = model.getCodonHeteroPattern();
int partitionCount = model.getCodonPartitionCount();
if (model.getDataType() == Nucleotides.INSTANCE && codonHeteroPattern != null && partitionCount > 1) {
if (codonHeteroPattern.equals("112")) {
writer.writeComment("The unique patterns for codon positions 1 & 2");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(1) + partition.getPrefix() + SitePatternsParser.PATTERNS),
}
);
writePatternList(partition, 0, 3, writer);
writePatternList(partition, 1, 3, writer);
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
writer.writeComment("The unique patterns for codon positions 3");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(2) + partition.getPrefix() + SitePatternsParser.PATTERNS),
}
);
writePatternList(partition, 2, 3, writer);
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
} else {
// pattern is 123
// write pattern lists for all three codon positions
for (int i = 1; i <= 3; i++) {
writer.writeComment("The unique patterns for codon positions " + i);
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(i) + partition.getPrefix() + SitePatternsParser.PATTERNS),
}
);
writePatternList(partition, i - 1, 3, writer);
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
}
}
} else {
writePatternList(partition, 0, 1, writer);
}
}
/**
* Write a single pattern list
*
* @param partition the partition to write a pattern list for
* @param offset offset by
* @param every skip every
* @param writer the writer
*/
private void writePatternList(PartitionData partition, int offset, int every, XMLWriter writer) {
Alignment alignment = partition.getAlignment();
int from = partition.getFromSite();
int to = partition.getToSite();
int partEvery = partition.getEvery();
if (partEvery > 1 && every > 1) throw new IllegalArgumentException();
if (from < 1) from = 1;
every = Math.max(partEvery, every);
from += offset;
// this object is created solely to calculate the number of patterns in the alignment
SitePatterns patterns = new SitePatterns(alignment, from - 1, to - 1, every);
writer.writeComment("The unique patterns from " + from + " to " + (to > 0 ? to : "end") + ((every > 1) ? " every " + every : ""),
"npatterns=" + patterns.getPatternCount());
List<Attribute> attributes = new ArrayList<Attribute>();
// no codon, unique patterns site patterns
if (offset == 0 && every == 1)
attributes.add(new Attribute.Default<String>(XMLParser.ID, partition.getPrefix() + SitePatternsParser.PATTERNS));
attributes.add(new Attribute.Default<String>("from", "" + from));
if (to >= 0) attributes.add(new Attribute.Default<String>("to", "" + to));
if (every > 1) {
attributes.add(new Attribute.Default<String>("every", "" + every));
}
// generate <patterns>
writer.writeOpenTag(SitePatternsParser.PATTERNS, attributes);
writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
writer.writeCloseTag(SitePatternsParser.PATTERNS);
}
/**
* Write the timer report block.
*
* @param writer the writer
*/
public void writeTimerReport(XMLWriter writer) {
writer.writeOpenTag("report");
writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer"));
writer.writeIDref("mcmc", "mcmc");
writer.writeCloseTag("property");
writer.writeCloseTag("report");
}
/**
* Write the trace analysis block.
*
* @param writer the writer
*/
public void writeTraceAnalysis(XMLWriter writer) {
writer.writeTag(
"traceAnalysis",
new Attribute[]{
new Attribute.Default<String>("fileName", options.logFileName)
},
true
);
}
/**
* Write the MCMC block.
*
* @param writer XMLWriter
*/
public void writeMCMC(XMLWriter writer) {
writer.writeComment("Define MCMC");
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(new Attribute.Default<String>(XMLParser.ID, "mcmc"));
attributes.add(new Attribute.Default<Integer>("chainLength", options.chainLength));
attributes.add(new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false"));
if (options.operatorAnalysis) {
attributes.add(new Attribute.Default<String>("operatorAnalysis", options.operatorAnalysisFileName));
}
writer.writeOpenTag("mcmc", attributes);
if (options.hasData()) {
writer.writeOpenTag(CompoundLikelihoodParser.POSTERIOR, new Attribute.Default<String>(XMLParser.ID, "posterior"));
}
// write prior block
writer.writeOpenTag(CompoundLikelihoodParser.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior"));
if (options.useStarBEAST) { // species
// coalescent prior
writer.writeIDref(MultiSpeciesCoalescentParser.SPECIES_COALESCENT, TraitData.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePriorType.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihoodParser.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// prior on species tree
writer.writeIDref(SpeciationLikelihoodParser.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
}
parameterPriorGenerator.writeParameterPriors(writer);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior = model.getPartitionTreePrior();
treePriorGenerator.writePriorLikelihoodReference(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographicReference(prior, writer);
writer.writeText("");
}
for (PartitionSubstitutionModel model : options.getPartitionTraitsSubstitutionModels()) {
// e.g. <svsGeneralSubstitutionModel idref="locations.model" />
// if (!(model.getLocationSubstType() == LocationSubstModelType.SYM_SUBST && (!model.isActivateBSSVS()))) {
if (model.isActivateBSSVS()) {
writer.writeIDref(GeneralTraitGenerator.getLocationSubstModelTag(model), model.getPrefix() + AbstractSubstitutionModel.MODEL);
writer.writeText("");
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer);
writer.writeCloseTag(CompoundLikelihoodParser.PRIOR);
if (options.hasData()) {
// write likelihood block
writer.writeOpenTag(CompoundLikelihoodParser.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood"));
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
if (options.hasDiscreteIntegerTraitsExcludeSpecies()) {
generalTraitGenerator.writeAncestralTreeLikelihoodReferences(writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer);
writer.writeCloseTag(CompoundLikelihoodParser.LIKELIHOOD);
writer.writeCloseTag(CompoundLikelihoodParser.POSTERIOR);
}
writer.writeIDref(SimpleOperatorScheduleParser.OPERATOR_SCHEDULE, "operators");
// write log to screen
logGenerator.writeLogToScreen(writer, branchRatesModelGenerator, substitutionModelGenerator);
// write log to file
logGenerator.writeLogToFile(writer, treePriorGenerator, branchRatesModelGenerator,
substitutionModelGenerator, treeLikelihoodGenerator, generalTraitGenerator);
logGenerator.writeAdditionalLogToFile(writer, branchRatesModelGenerator, substitutionModelGenerator);
// write tree log to file
logGenerator.writeTreeLogToFile(writer);
writer.writeCloseTag("mcmc");
}
}
|
package dr.app.beauti.generator;
import dr.app.beast.BeastVersion;
import dr.app.beauti.util.XMLWriter;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.options.*;
import dr.app.beauti.options.Parameter;
import dr.app.beauti.priorsPanel.PriorType;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.StrictClockBranchRates;
import dr.evomodel.clock.ACLikelihood;
import dr.evomodel.coalescent.BayesianSkylineLikelihood;
import dr.evomodel.coalescent.CoalescentLikelihood;
import dr.evomodel.coalescent.GMRFFixedGridImportanceSampler;
import dr.evomodel.coalescent.GMRFSkyrideLikelihood;
import dr.evomodel.speciation.SpeciationLikelihood;
import dr.evomodel.speciation.SpeciesBindings;
import dr.evomodel.speciation.SpeciesTreeBMPrior;
import dr.evomodel.speciation.SpeciesTreeModel;
import dr.evomodel.speciation.TreePartitionCoalescent;
import dr.evomodel.tree.*;
import dr.evomodelxml.BirthDeathModelParser;
import dr.evomodelxml.DiscretizedBranchRatesParser;
import dr.evomodelxml.LoggerParser;
import dr.evomodelxml.TreeLoggerParser;
import dr.evomodelxml.TreeModelParser;
import dr.evomodelxml.YuleModelParser;
import dr.evoxml.*;
import dr.inference.distribution.DistributionLikelihood;
import dr.inference.distribution.ExponentialDistributionModel;
import dr.inference.distribution.ExponentialMarkovModel;
import dr.inference.distribution.MixedDistributionLikelihood;
import dr.inference.loggers.Columns;
import dr.inference.model.*;
import dr.inference.operators.SimpleOperatorSchedule;
import dr.util.Attribute;
import dr.util.Version;
import dr.xml.AttributeParser;
import dr.xml.XMLParser;
import java.io.Writer;
import java.util.*;
/**
* This class holds all the data for the current BEAUti Document
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $
*/
public class BeastGenerator extends Generator {
private final static Version version = new BeastVersion();
private final static String TREE_FILE_LOG = "treeFileLog";
private final static String SUB_TREE_FILE_LOG = "substTreeFileLog";
private final TreePriorGenerator treePriorGenerator;
private final TreeLikelihoodGenerator treeLikelihoodGenerator;
private final PartitionModelGenerator partitionModelGenerator;
private final InitialTreeGenerator initialTreeGenerator;
private final TreeModelGenerator treeModelGenerator;
private final BranchRatesModelGenerator branchRatesModelGenerator;
private final OperatorsGenerator operatorsGenerator;
private final MultiSpeciesCoalescentGenerator multiSpeciesCoalescentGenerator;
public BeastGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
partitionModelGenerator = new PartitionModelGenerator(options, components);
treePriorGenerator = new TreePriorGenerator(options, components);
treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components);
initialTreeGenerator = new InitialTreeGenerator(options, components);
treeModelGenerator = new TreeModelGenerator(options, components);
branchRatesModelGenerator = new BranchRatesModelGenerator(options, components);
operatorsGenerator = new OperatorsGenerator(options, components);
multiSpeciesCoalescentGenerator = new MultiSpeciesCoalescentGenerator (options, components);
}
public void checkOptions() throws IllegalArgumentException {
//++++++++++++++++ Taxon List ++++++++++++++++++
TaxonList taxonList = options.taxonList;
Set<String> ids = new HashSet<String>();
ids.add(TaxaParser.TAXA);
ids.add(AlignmentParser.ALIGNMENT);
if (taxonList != null) {
if (taxonList.getTaxonCount() < 2) {
throw new IllegalArgumentException("BEAST requires at least two taxa to run.");
}
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (ids.contains(taxon.getId())) {
throw new IllegalArgumentException("A taxon has the same id," + taxon.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxon.getId());
}
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
for (Taxa taxa : options.taxonSets) {
if (taxa.getTaxonCount() < 2) {
throw new IllegalArgumentException("Taxon set, " + taxa.getId() + ", should contain\n" +
"at least two taxa.");
}
if (ids.contains(taxa.getId())) {
throw new IllegalArgumentException("A taxon sets has the same id," + taxa.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxa.getId());
}
//++++++++++++++++ Species tree ++++++++++++++++++
if (options.isSpeciesAnalysis()) {
if (!(options.nodeHeightPrior == TreePrior.SPECIES_BIRTH_DEATH || options.nodeHeightPrior == TreePrior.SPECIES_YULE)) {
//TODO: more species tree model
throw new IllegalArgumentException("Species analysis requires to define species tree prior in Tree panel.");
}
}
// add other tests and warnings here
// Speciation model with dated tips
// Sampling rates without dated tips or priors on rate or nodes
}
/**
* Generate a beast xml file from these beast options
*
* @param w the writer
*/
public void generateXML(Writer w) {
XMLWriter writer = new XMLWriter(w);
writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
writer.writeComment("Generated by BEAUTi " + version.getVersionString());
writer.writeComment(" by Alexei J. Drummond and Andrew Rambaut");
writer.writeComment(" Department of Computer Science, University of Auckland and");
writer.writeComment(" Institute of Evolutionary Biology, University of Edinburgh");
writer.writeComment(" http://beast.bio.ed.ac.uk/");
writer.writeOpenTag("beast");
writer.writeText("");
// this gives any added implementations of the 'Component' interface a
// chance to generate XML at this point in the BEAST file.
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
writeTaxa(writer, options.taxonList);
List<Taxa> taxonSets = options.taxonSets;
if (taxonSets != null && taxonSets.size() > 0) {
writeTaxonSets(writer, taxonSets);
}
if ( options.isSpeciesAnalysis() ) { // species
writer.writeText("");
writer.writeComment("List all taxons regarding each gene (file) for Multispecies Coalescent function");
// write all taxa in each gene tree regarding each data partition,
for (DataPartition partition : options.dataPartitions) {
// do I need if (!alignments.contains(alignment)) {alignments.add(alignment);} ?
writeAllTaxaForMultiGene(partition, writer);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
List<Alignment> alignments = new ArrayList<Alignment>();
for (DataPartition partition : options.dataPartitions) {
Alignment alignment = partition.getAlignment();
if (!alignments.contains(alignment)) {
alignments.add(alignment);
}
}
if (!options.samplePriorOnly) {
int index = 1;
for (Alignment alignment : alignments) {
if (alignments.size() > 1) {
//if (!options.allowDifferentTaxa) {
alignment.setId(AlignmentParser.ALIGNMENT + index);
//} else { // e.g. alignment_gene1
// alignment.setId("alignment_" + mulitTaxaTagName + index);
} else {
alignment.setId(AlignmentParser.ALIGNMENT);
}
writeAlignment(alignment, writer);
index += 1;
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
for (PartitionModel model : options.getActivePartitionModels()) {
writePatternList(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
} else {
Alignment alignment = alignments.get(0);
alignment.setId(AlignmentParser.ALIGNMENT);
writeAlignment(alignment, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
}
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
treePriorGenerator.setGenePrefix(model.getName() + "."); // partitionName.constant
treePriorGenerator.writeTreePriorModel(writer);
}
} else { // no species
treePriorGenerator.setGenePrefix("");
treePriorGenerator.writeTreePriorModel(writer);
}
writer.writeText("");
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
initialTreeGenerator.setGenePrefix(model.getName() + "."); // partitionName.startingTree
initialTreeGenerator.writeStartingTree(writer);
}
} else { // no species
initialTreeGenerator.setGenePrefix("");
initialTreeGenerator.writeStartingTree(writer);
}
writer.writeText("");
// treeModelGenerator = new TreeModelGenerator(options);
if ( options.isSpeciesAnalysis() ) { // species
// generate gene trees regarding each data partition, if no species, only create 1 tree
for (PartitionModel model : options.getActivePartitionModels()) {
treeModelGenerator.setGenePrefix(model.getName() + "."); // partitionName.treeModel
treeModelGenerator.writeTreeModel(writer);
}
} else { // no species
treeModelGenerator.setGenePrefix("");
treeModelGenerator.writeTreeModel(writer);
}
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
treePriorGenerator.setGenePrefix(model.getName() + "."); // partitionName.treeModel
treePriorGenerator.writeTreePrior(writer);
}
} else { // no species
treePriorGenerator.setGenePrefix("");
treePriorGenerator.writeTreePrior(writer);
}
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
if (options.isSpeciesAnalysis()) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
branchRatesModelGenerator.setGenePrefix(model.getName() + ".");
//TODO: fixParameters
branchRatesModelGenerator.writeBranchRatesModel(writer);
}
} else { // no species
branchRatesModelGenerator.setGenePrefix("");
branchRatesModelGenerator.writeBranchRatesModel(writer);
}
writer.writeText("");
for (PartitionModel partitionModel : options.getActivePartitionModels()) {
partitionModelGenerator.writeSubstitutionModel(partitionModel, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
boolean writeMuParameters = options.getTotalActivePartitionModelCount() > 1;
for (PartitionModel model : options.getActivePartitionModels()) {
partitionModelGenerator.writeSiteModel(model, writeMuParameters, writer);
writer.writeText("");
}
if (writeMuParameters) {
writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "allMus")});
for (PartitionModel model : options.getActivePartitionModels()) {
partitionModelGenerator.writeMuParameterRefs(model, writer);
}
writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
for (PartitionModel model : options.getActivePartitionModels()) {
if ( options.isSpeciesAnalysis() ) { // species
treeLikelihoodGenerator.setGenePrefix(model.getName() + ".");
} else {
treeLikelihoodGenerator.setGenePrefix("");
}
//TODO: need merge genePrifx and prefix
treeLikelihoodGenerator.writeTreeLikelihood(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
// traits tag
if (options.selecetedTraits.size() > 0) {
for (String trait : options.selecetedTraits) {
TraitGuesser.TraitType traiType = options.traitTypes.get(trait);
writeTraits(writer, trait, traiType.toString(), options.taxonList);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
}
if (taxonSets != null && taxonSets.size() > 0) {
//TODO: need to suit for multi-gene-tree
writeTMRCAStatistics(writer);
}
List<Operator> operators = options.selectOperators();
operatorsGenerator.writeOperatorSchedule(operators, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
// XMLWriter writer, List<PartitionModel> models,
writeMCMC(options.getActivePartitionModels(), writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
writeTimerReport(writer);
writer.writeText("");
if (options.performTraceAnalysis) {
writeTraceAnalysis(writer);
}
if (options.generateCSV) {
treePriorGenerator.writeAnalysisToCSVfile(writer);
}
writer.writeCloseTag("beast");
writer.flush();
}
/**
* Generate a taxa block from these beast options
*
* @param writer the writer
* @param taxonList the taxon list to write
*/
private void writeTaxa(XMLWriter writer, TaxonList taxonList) {
// -1 (single taxa), 0 (1st gene of multi-taxa)
writer.writeComment("The list of taxa analyse (can also include dates/ages).");
writer.writeComment("ntax=" + taxonList.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)});
boolean firstDate = true;
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
boolean hasDate = false;
if (options.maximumTipHeight > 0.0) {
hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE);
}
writer.writeTag(TaxonParser.TAXON, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, taxon.getId())}, !hasDate);
if (hasDate) {
dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
if (firstDate) {
options.units = date.getUnits();
firstDate = false;
} else {
if (options.units != date.getUnits()) {
System.err.println("Error: Units in dates do not match.");
}
}
Attribute[] attributes = {
new Attribute.Default<Double>("value", date.getTimeValue()),
new Attribute.Default<String>("direction", date.isBackwards() ? "backwards" : "forwards"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
/*,
new Attribute.Default("origin", date.getOrigin()+"")*/
};
writer.writeTag(dr.evolution.util.Date.DATE, attributes, true);
writer.writeCloseTag(TaxonParser.TAXON);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer);
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate additional taxon sets
*
* @param writer the writer
* @param taxonSets a list of taxa to write
*/
private void writeTaxonSets(XMLWriter writer, List<Taxa> taxonSets) {
writer.writeText("");
for (Taxa taxa : taxonSets) {
writer.writeOpenTag(
TaxaParser.TAXA,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, taxa.getId())
}
);
for (int j = 0; j < taxa.getTaxonCount(); j++) {
writer.writeIDref(TaxonParser.TAXON, taxa.getTaxon(j).getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
}
/**
* Determine and return the datatype description for these beast options
* note that the datatype in XML may differ from the actual datatype
*
* @param alignment the alignment to get data type description of
* @return description
*/
private String getAlignmentDataTypeDescription(Alignment alignment) {
String description;
switch (alignment.getDataType().getType()) {
case DataType.TWO_STATES:
case DataType.COVARION:
// TODO make this work
throw new RuntimeException("TO DO!");
//switch (partition.getPartitionModel().binarySubstitutionModel) {
// case ModelOptions.BIN_COVARION:
// description = TwoStateCovarion.DESCRIPTION;
// break;
// default:
// description = alignment.getDataType().getDescription();
//break;
default:
description = alignment.getDataType().getDescription();
}
return description;
}
public void writeAllTaxaForMultiGene(DataPartition dataPartition, XMLWriter writer) {
String gene = dataPartition.getName();
Alignment alignment = dataPartition.getAlignment();
writer.writeComment("gene name = " + gene + ", ntax= " + alignment.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, gene + ".taxa")});
for (int i = 0; i < alignment.getTaxonCount(); i++) {
final Taxon taxon = alignment.getTaxon(i);
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate an alignment block from these beast options
*
* @param alignment the alignment to write
* @param writer the writer
*/
public void writeAlignment(Alignment alignment, XMLWriter writer) {
writer.writeText("");
writer.writeComment("The sequence alignment (each sequence refers to a taxon above).");
writer.writeComment("ntax=" + alignment.getTaxonCount() + " nchar=" + alignment.getSiteCount());
if (options.samplePriorOnly) {
writer.writeComment("Null sequences generated in order to sample from the prior only.");
}
writer.writeOpenTag(
AlignmentParser.ALIGNMENT,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, alignment.getId()),
new Attribute.Default<String>("dataType", getAlignmentDataTypeDescription(alignment))
}
);
for (int i = 0; i < alignment.getTaxonCount(); i++) {
Taxon taxon = alignment.getTaxon(i);
writer.writeOpenTag("sequence");
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
if (!options.samplePriorOnly) {
writer.writeText(alignment.getAlignedSequenceString(i));
} else {
writer.writeText("N");
}
writer.writeCloseTag("sequence");
}
writer.writeCloseTag(AlignmentParser.ALIGNMENT);
}
/**
* Generate traits block regarding specific trait name (currently only <species>) from options
* @param writer
* @param trait
* @param traitType
* @param taxonList
*/
private void writeTraits(XMLWriter writer, String trait, String traitType, TaxonList taxonList) {
writer.writeText("");
if (options.isSpeciesAnalysis()) { // species
writer.writeComment("Species definition: binds taxa, species and gene trees");
}
writer.writeComment("trait = " + trait + " trait_type = " + traitType);
writer.writeOpenTag(trait, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, trait)});
//new Attribute.Default<String>("traitType", traitType)});
// write sub-tags for species
if (options.isSpeciesAnalysis()) { // species
multiSpeciesCoalescentGenerator.writeMultiSpecies(taxonList, writer);
} // end write sub-tags for species
writer.writeCloseTag(trait);
if (options.isSpeciesAnalysis()) { // species
multiSpeciesCoalescentGenerator.writeMultiSpeciesCoalescent(writer);
}
}
/**
* Writes the pattern lists
*
* @param model the partition model to write the pattern lists for
* @param writer the writer
*/
public void writePatternList(PartitionModel model, XMLWriter writer) {
writer.writeText("");
String codonHeteroPattern = model.getCodonHeteroPattern();
int partitionCount = model.getCodonPartitionCount();
if (model.dataType == Nucleotides.INSTANCE && codonHeteroPattern != null && partitionCount > 1) {
if (codonHeteroPattern.equals("112")) {
writer.writeComment("The unique patterns for codon positions 1 & 2");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(1) + SitePatternsParser.PATTERNS),
}
);
for (DataPartition partition : options.dataPartitions) {
if (partition.getPartitionModel() == model) {
writePatternList(partition, 0, 3, writer);
writePatternList(partition, 1, 3, writer);
}
}
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
writer.writeComment("The unique patterns for codon positions 3");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(2) + SitePatternsParser.PATTERNS),
}
);
for (DataPartition partition : options.dataPartitions) {
if (partition.getPartitionModel() == model) {
writePatternList(partition, 2, 3, writer);
}
}
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
} else {
// pattern is 123
// write pattern lists for all three codon positions
for (int i = 1; i <= 3; i++) {
writer.writeComment("The unique patterns for codon positions " + i);
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(i) + SitePatternsParser.PATTERNS),
}
);
for (DataPartition partition : options.dataPartitions) {
if (partition.getPartitionModel() == model) {
writePatternList(partition, i - 1, 3, writer);
}
}
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
}
}
} else {
//partitionCount = 1;
writer.writeComment("The unique patterns site patterns");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix() + SitePatternsParser.PATTERNS),
}
);
for (DataPartition partition : options.dataPartitions) {
if (partition.getPartitionModel() == model) {
writePatternList(partition, 0, 1, writer);
}
}
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
}
}
/**
* Write a single pattern list
*
* @param partition the partition to write a pattern list for
* @param offset offset by
* @param every skip every
* @param writer the writer
*/
private void writePatternList(DataPartition partition, int offset, int every, XMLWriter writer) {
Alignment alignment = partition.getAlignment();
int from = partition.getFromSite();
int to = partition.getToSite();
int partEvery = partition.getEvery();
if (partEvery > 1 && every > 1) throw new IllegalArgumentException();
if (from < 1) from = 1;
every = Math.max(partEvery, every);
from += offset;
writer.writeComment("The unique patterns from " + from + " to " + (to > 0 ? to : "end") + ((every > 1) ? " every " + every : ""));
// this object is created solely to calculate the number of patterns in the alignment
SitePatterns patterns = new SitePatterns(alignment, from - 1, to - 1, every);
writer.writeComment("npatterns=" + patterns.getPatternCount());
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(new Attribute.Default<String>("from", "" + from));
if (to >= 0) attributes.add(new Attribute.Default<String>("to", "" + to));
if (every > 1) {
attributes.add(new Attribute.Default<String>("every", "" + every));
}
writer.writeOpenTag(SitePatternsParser.PATTERNS, attributes);
writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
writer.writeCloseTag(SitePatternsParser.PATTERNS);
}
/**
* Generate tmrca statistics
*
* @param writer the writer
*/
public void writeTMRCAStatistics(XMLWriter writer) {
writer.writeText("");
for (Taxa taxa : options.taxonSets) {
writer.writeOpenTag(
TMRCAStatistic.TMRCA_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "tmrca(" + taxa.getId() + ")"),
}
);
writer.writeOpenTag(TMRCAStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(TMRCAStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(TMRCAStatistic.TMRCA_STATISTIC);
if (options.taxonSetsMono.get(taxa)) {
writer.writeOpenTag(
MonophylyStatistic.MONOPHYLY_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "monophyly(" + taxa.getId() + ")"),
});
writer.writeOpenTag(MonophylyStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(MonophylyStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(MonophylyStatistic.MONOPHYLY_STATISTIC);
}
}
}
// /**
// * Write the operator schedule XML block.
// *
// * @param operators the list of operators
// * @param writer the writer
// */
// public void writeOperatorSchedule(List<Operator> operators, XMLWriter writer) {
// Attribute[] operatorAttributes;
//// switch (options.coolingSchedule) {
//// case SimpleOperatorSchedule.LOG_SCHEDULE:
// if (options.nodeHeightPrior == TreePrior.GMRF_SKYRIDE) {
// operatorAttributes = new Attribute[2];
// operatorAttributes[1] = new Attribute.Default<String>(SimpleOperatorSchedule.OPTIMIZATION_SCHEDULE, SimpleOperatorSchedule.LOG_STRING);
// } else {
//// break;
//// default:
// operatorAttributes = new Attribute[1];
// operatorAttributes[0] = new Attribute.Default<String>(XMLParser.ID, "operators");
// writer.writeOpenTag(
// SimpleOperatorSchedule.OPERATOR_SCHEDULE,
// operatorAttributes
//// new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "operators")}
// for (Operator operator : operators) {
// if (operator.weight > 0. && operator.inUse)
// writeOperator(operator, writer);
// writer.writeCloseTag(SimpleOperatorSchedule.OPERATOR_SCHEDULE);
// private void writeOperator(Operator operator, XMLWriter writer) {
// switch (operator.type) {
// case SCALE:
// writeScaleOperator(operator, writer);
// break;
// case RANDOM_WALK:
// writeRandomWalkOperator(operator, writer);
// case RANDOM_WALK_ABSORBING:
// writeRandomWalkOperator(operator, false, writer);
// break;
// case RANDOM_WALK_REFLECTING:
// writeRandomWalkOperator(operator, true, writer);
// break;
// case INTEGER_RANDOM_WALK:
// writeIntegerRandomWalkOperator(operator, writer);
// break;
// case UP_DOWN:
// writeUpDownOperator(operator, writer);
// break;
// case SCALE_ALL:
// writeScaleAllOperator(operator, writer);
// break;
// case SCALE_INDEPENDENTLY:
// writeScaleOperator(operator, writer, true);
// break;
// case CENTERED_SCALE:
// writeCenteredOperator(operator, writer);
// break;
// case DELTA_EXCHANGE:
// writeDeltaOperator(operator, writer);
// break;
// case INTEGER_DELTA_EXCHANGE:
// writeIntegerDeltaOperator(operator, writer);
// break;
// case SWAP:
// writeSwapOperator(operator, writer);
// break;
// case BITFLIP:
// writeBitFlipOperator(operator, writer);
// break;
// case TREE_BIT_MOVE:
// writeTreeBitMoveOperator(operator, writer);
// break;
// case UNIFORM:
// writeUniformOperator(operator, writer);
// break;
// case INTEGER_UNIFORM:
// writeIntegerUniformOperator(operator, writer);
// break;
// case SUBTREE_SLIDE:
// writeSubtreeSlideOperator(operator, writer);
// break;
// case NARROW_EXCHANGE:
// writeNarrowExchangeOperator(operator, writer);
// break;
// case WIDE_EXCHANGE:
// writeWideExchangeOperator(operator, writer);
// break;
// case WILSON_BALDING:
// writeWilsonBaldingOperator(operator, writer);
// break;
// case SAMPLE_NONACTIVE:
// writeSampleNonActiveOperator(operator, writer);
// break;
// case SCALE_WITH_INDICATORS:
// writeScaleWithIndicatorsOperator(operator, writer);
// break;
// case GMRF_GIBBS_OPERATOR:
// writeGMRFGibbsOperator(operator, writer);
// break;
// default:
// private Attribute getRef(String name) {
// return new Attribute.Default<String>(XMLParser.IDREF, name);
// private void writeParameterRefByName(XMLWriter writer, String name) {
// writer.writeTag(ParameterParser.PARAMETER, getRef(name), true);
// private void writeParameter1Ref(XMLWriter writer, Operator operator) {
// writeParameterRefByName(writer, operator.parameter1.getName());
// private void writeScaleOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// private void writeScaleOperator(Operator operator, XMLWriter writer, boolean indepedently) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("scaleAllIndependently", indepedently ? "true" : "false")
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// private void writeRandomWalkOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// "randomWalkOperator",
// new Attribute[]{
// new Attribute.Default<Double>("windowSize", operator.tuning),
// getWeightAttribute(operator.weight)
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkOperator");
// private void writeRandomWalkOperator(Operator operator, boolean reflecting, XMLWriter writer) {
// writer.writeOpenTag(
// "randomWalkOperator",
// new Attribute[]{
// new Attribute.Default<Double>("windowSize", operator.tuning),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("boundaryCondition",
// (reflecting ? "reflecting" : "absorbing"))
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkOperator");
// private void writeIntegerRandomWalkOperator(Operator operator, XMLWriter writer) {
// int windowSize = (int) Math.round(operator.tuning);
// if (windowSize < 1) windowSize = 1;
// writer.writeOpenTag(
// "randomWalkIntegerOperator",
// new Attribute[]{
// new Attribute.Default<Integer>("windowSize", windowSize),
// getWeightAttribute(operator.weight)
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkIntegerOperator");
// private void writeScaleAllOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// new Attribute.Default<String>("scaleAll", "true"),
// getWeightAttribute(operator.weight)
// if (operator.parameter2 == null) {
// writeParameter1Ref(writer, operator);
// } else {
// writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER);
// writeParameter1Ref(writer, operator);
// writer.writeIDref(ParameterParser.PARAMETER, operator.parameter2.getName());
// writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// private void writeUpDownOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(UpDownOperator.UP_DOWN_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// writer.writeOpenTag(UpDownOperator.UP);
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(UpDownOperator.UP);
// writer.writeOpenTag(UpDownOperator.DOWN);
// writer.writeIDref(ParameterParser.PARAMETER, operator.parameter2.getName());
// writer.writeCloseTag(UpDownOperator.DOWN);
// writer.writeCloseTag(UpDownOperator.UP_DOWN_OPERATOR);
// private void writeCenteredOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(CenteredScaleOperator.CENTERED_SCALE,
// new Attribute[]{
// new Attribute.Default<Double>(CenteredScaleOperator.SCALE_FACTOR, operator.tuning),
// getWeightAttribute(operator.weight)
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(CenteredScaleOperator.CENTERED_SCALE);
// private void writeDeltaOperator(Operator operator, XMLWriter writer) {
// if (operator.getName().equals("Relative rates")) {
// int[] parameterWeights = options.getPartitionWeights();
// if (parameterWeights != null && parameterWeights.length > 1) {
// String pw = "" + parameterWeights[0];
// for (int i = 1; i < parameterWeights.length; i++) {
// pw += " " + parameterWeights[i];
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<Double>(DeltaExchangeOperator.DELTA, operator.tuning),
// new Attribute.Default<String>(DeltaExchangeOperator.PARAMETER_WEIGHTS, pw),
// getWeightAttribute(operator.weight)
// } else {
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<Double>(DeltaExchangeOperator.DELTA, operator.tuning),
// getWeightAttribute(operator.weight)
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(DeltaExchangeOperator.DELTA_EXCHANGE);
// private void writeIntegerDeltaOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<String>(DeltaExchangeOperator.DELTA, Integer.toString((int) operator.tuning)),
// new Attribute.Default<String>("integer", "true"),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("autoOptimize", "false")
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(DeltaExchangeOperator.DELTA_EXCHANGE);
// private void writeSwapOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SwapOperator.SWAP_OPERATOR,
// new Attribute[]{
// new Attribute.Default<String>("size", Integer.toString((int) operator.tuning)),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("autoOptimize", "false")
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(SwapOperator.SWAP_OPERATOR);
// private void writeBitFlipOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(BitFlipOperator.BIT_FLIP_OPERATOR,
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(BitFlipOperator.BIT_FLIP_OPERATOR);
// private void writeTreeBitMoveOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(TreeBitMoveOperator.BIT_MOVE_OPERATOR,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(TreeBitMoveOperator.BIT_MOVE_OPERATOR);
// private void writeUniformOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag("uniformOperator",
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("uniformOperator");
// private void writeIntegerUniformOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag("uniformIntegerOperator",
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("uniformIntegerOperator");
// private void writeNarrowExchangeOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(ExchangeOperator.NARROW_EXCHANGE,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(ExchangeOperator.NARROW_EXCHANGE);
// private void writeWideExchangeOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(ExchangeOperator.WIDE_EXCHANGE,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(ExchangeOperator.WIDE_EXCHANGE);
// private void writeWilsonBaldingOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(WilsonBalding.WILSON_BALDING,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// // not supported anymore. probably never worked. (todo) get it out of GUI too
//// if (options.nodeHeightPrior == TreePrior.CONSTANT) {
//// treePriorGenerator.writeNodeHeightPriorModelRef(writer);
// writer.writeCloseTag(WilsonBalding.WILSON_BALDING);
// private void writeSampleNonActiveOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SampleNonActiveGibbsOperator.SAMPLE_NONACTIVE_GIBBS_OPERATOR,
// getWeightAttribute(operator.weight));
// writer.writeOpenTag(SampleNonActiveGibbsOperator.DISTRIBUTION);
// writeParameterRefByName(writer, operator.getName());
// writer.writeCloseTag(SampleNonActiveGibbsOperator.DISTRIBUTION);
// writer.writeOpenTag(SampleNonActiveGibbsOperator.DATA_PARAMETER);
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(SampleNonActiveGibbsOperator.DATA_PARAMETER);
// writer.writeOpenTag(SampleNonActiveGibbsOperator.INDICATOR_PARAMETER);
// writeParameterRefByName(writer, operator.parameter2.getName());
// writer.writeCloseTag(SampleNonActiveGibbsOperator.INDICATOR_PARAMETER);
// writer.writeCloseTag(SampleNonActiveGibbsOperator.SAMPLE_NONACTIVE_GIBBS_OPERATOR);
// private void writeGMRFGibbsOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// GMRFSkyrideBlockUpdateOperator.BLOCK_UPDATE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>(GMRFSkyrideBlockUpdateOperator.SCALE_FACTOR, operator.tuning),
// getWeightAttribute(operator.weight)
// writer.writeIDref(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD, "skyride");
// writer.writeCloseTag(GMRFSkyrideBlockUpdateOperator.BLOCK_UPDATE_OPERATOR);
// private void writeScaleWithIndicatorsOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// writeParameter1Ref(writer, operator);
// writer.writeOpenTag(ScaleOperator.INDICATORS, new Attribute.Default<String>(ScaleOperator.PICKONEPROB, "1.0"));
// writeParameterRefByName(writer, operator.parameter2.getName());
// writer.writeCloseTag(ScaleOperator.INDICATORS);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// private void writeSubtreeSlideOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SubtreeSlideOperator.SUBTREE_SLIDE,
// new Attribute[]{
// new Attribute.Default<Double>("size", operator.tuning),
// new Attribute.Default<String>("gaussian", "true"),
// getWeightAttribute(operator.weight)
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(SubtreeSlideOperator.SUBTREE_SLIDE);
// private Attribute getWeightAttribute(double weight) {
// if (weight == (int)weight) {
// return new Attribute.Default<Integer>("weight", (int)weight);
// } else {
// return new Attribute.Default<Double>("weight", weight);
/**
* Write the timer report block.
*
* @param writer the writer
*/
public void writeTimerReport(XMLWriter writer) {
writer.writeOpenTag("report");
writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer"));
writer.writeIDref("object", "mcmc");
writer.writeCloseTag("property");
writer.writeCloseTag("report");
}
/**
* Write the trace analysis block.
*
* @param writer the writer
*/
public void writeTraceAnalysis(XMLWriter writer) {
writer.writeTag(
"traceAnalysis",
new Attribute[]{
new Attribute.Default<String>("fileName", options.logFileName)
},
true
);
}
/**
* Write the MCMC block.
* @param models
* @param writer
*/
public void writeMCMC(List<PartitionModel> models, XMLWriter writer) {
writer.writeComment("Define MCMC");
writer.writeOpenTag(
"mcmc",
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "mcmc"),
new Attribute.Default<Integer>("chainLength", options.chainLength),
new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false")
});
if (options.hasData()) {
writer.writeOpenTag(CompoundLikelihood.POSTERIOR, new Attribute.Default<String>(XMLParser.ID, "posterior"));
}
// write prior block
writer.writeOpenTag(CompoundLikelihood.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior"));
if (options.isSpeciesAnalysis()) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, COALESCENT);
// prior on population sizes
if (options.nodeHeightPrior == TreePrior.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
} else {
writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
}
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
}
writeParameterPriors(writer);
switch (options.nodeHeightPrior) {
case YULE:
case BIRTH_DEATH:
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, "speciation");
break;
case SKYLINE:
writer.writeIDref(BayesianSkylineLikelihood.SKYLINE_LIKELIHOOD, "skyline");
writer.writeIDref(ExponentialMarkovModel.EXPONENTIAL_MARKOV_MODEL, "eml1");
break;
case GMRF_SKYRIDE:
writer.writeIDref(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD, "skyride");
break;
case LOGISTIC:
writer.writeIDref(BooleanLikelihood.BOOLEAN_LIKELIHOOD, "booleanLikelihood1");
break;
case SPECIES_YULE:
case SPECIES_BIRTH_DEATH:
// do not need
// for (PartitionModel model : models) {
// writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, model.getName() + "." + COALESCENT);
break;
default:
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, COALESCENT);
}
if (options.nodeHeightPrior == TreePrior.EXTENDED_SKYLINE) {
writer.writeOpenTag(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD);
writer.writeOpenTag(MixedDistributionLikelihood.DISTRIBUTION0);
writer.writeIDref(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL, "demographic.populationMeanDist");
writer.writeCloseTag(MixedDistributionLikelihood.DISTRIBUTION0);
writer.writeOpenTag(MixedDistributionLikelihood.DISTRIBUTION1);
writer.writeIDref(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL, "demographic.populationMeanDist");
writer.writeCloseTag(MixedDistributionLikelihood.DISTRIBUTION1);
writer.writeOpenTag(MixedDistributionLikelihood.DATA);
writer.writeIDref(ParameterParser.PARAMETER, "demographic.popSize");
writer.writeCloseTag(MixedDistributionLikelihood.DATA);
writer.writeOpenTag(MixedDistributionLikelihood.INDICATORS);
writer.writeIDref(ParameterParser.PARAMETER, "demographic.indicators");
writer.writeCloseTag(MixedDistributionLikelihood.INDICATORS);
writer.writeCloseTag(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer);
writer.writeCloseTag(CompoundLikelihood.PRIOR);
if (options.hasData()) {
// write likelihood block
writer.writeOpenTag(CompoundLikelihood.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood"));
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
if (options.clockType == ClockType.AUTOCORRELATED_LOGNORMAL) {
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, BranchRateModel.BRANCH_RATES);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer);
writer.writeCloseTag(CompoundLikelihood.LIKELIHOOD);
writer.writeCloseTag(CompoundLikelihood.POSTERIOR);
}
writer.writeIDref(SimpleOperatorSchedule.OPERATOR_SCHEDULE, "operators");
// write log to screen
writeLogToScreen(writer);
// write log to file
writeLogToFile(writer);
// write tree log to file
writeTreeLogToFile(models, writer);
writer.writeCloseTag("mcmc");
}
/**
* write log to screen
* @param writer
*/
private void writeLogToScreen(XMLWriter writer) {
writer.writeComment("write log to screen");
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "screenLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.echoEvery + "")
});
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Posterior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Prior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
writer.writeCloseTag(Columns.COLUMN);
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Likelihood"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
writer.writeCloseTag(Columns.COLUMN);
}
if ( options.isSpeciesAnalysis() ) { // species
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "PopMean"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.POP_MEAN);
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Root Height"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getName() + "." + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
} else { // no species
writer.writeIDref(ParameterParser.PARAMETER, TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
writer.writeCloseTag(Columns.COLUMN);
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Rate"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
if (options.clockType == ClockType.STRICT_CLOCK) {
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getName() + ".clock.rate");
}
} else { // no species
writer.writeIDref(ParameterParser.PARAMETER, "clock.rate");
}
} else {
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getName() + ".meanRate");
}
} else { // no species
writer.writeIDref(RateStatistic.RATE_STATISTIC, "meanRate");
}
}
writer.writeCloseTag(Columns.COLUMN);
if (options.clockType == ClockType.RANDOM_LOCAL_CLOCK) {
writeSumStatisticColumn(writer, "rateChanges", "Rate Changes");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_SCREEN_LOG, writer);
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SCREEN_LOG, writer);
}
/**
* write log to file
* @param writer
*/
private void writeLogToFile(XMLWriter writer) {
writer.writeComment("write log to file");
if (options.logFileName == null) {
options.logFileName = options.fileNameStem + ".log";
}
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "fileLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(LoggerParser.FILE_NAME, options.logFileName)
});
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
}
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
}
if ( options.isSpeciesAnalysis() ) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, COALESCENT);
// prior on population sizes
if (options.nodeHeightPrior == TreePrior.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
} else {
writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
}
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.POP_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, SpeciesTreeModel.SPECIES_TREE + "." + SPLIT_POPS);
if (options.nodeHeightPrior == TreePrior.SPECIES_BIRTH_DEATH) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME);
} else if (options.nodeHeightPrior == TreePrior.SPECIES_YULE) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE);
}
for (PartitionModel model : options.getActivePartitionModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getName() + "." + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
} else { // no species
writer.writeIDref(ParameterParser.PARAMETER, TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
if (options.clockType == ClockType.STRICT_CLOCK) {
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getName() + ".clock.rate");
}
} else { // no species
writer.writeIDref(ParameterParser.PARAMETER, "clock.rate");
}
} else {
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getName() + ".meanRate");
}
} else { // no species
writer.writeIDref(RateStatistic.RATE_STATISTIC, "meanRate");
}
}
for (Taxa taxa : options.taxonSets) {
writer.writeIDref("tmrcaStatistic", "tmrca(" + taxa.getId() + ")");
}
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
treePriorGenerator.setGenePrefix(model.getName() + "."); // partitionName.treeModel
treePriorGenerator.writeParameterLog(writer);
}
} else { // no species
treePriorGenerator.setGenePrefix("");
treePriorGenerator.writeParameterLog(writer);
}
for (PartitionModel model : options.getActivePartitionModels()) {
partitionModelGenerator.writeLog(writer, model);
}
if (hasCodonOrUserPartitions()) {
writer.writeIDref(ParameterParser.PARAMETER, "allMus");
}
switch (options.clockType) {
case STRICT_CLOCK:
break;
case UNCORRELATED_EXPONENTIAL:
writer.writeIDref(ParameterParser.PARAMETER, ClockType.UCED_MEAN);
writer.writeIDref(RateStatistic.RATE_STATISTIC, RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
break;
case UNCORRELATED_LOGNORMAL:
writer.writeIDref(ParameterParser.PARAMETER, ClockType.UCLD_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, ClockType.UCLD_STDEV);
writer.writeIDref(RateStatistic.RATE_STATISTIC, RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ParameterParser.PARAMETER, "treeModel.rootRate");
writer.writeIDref(ParameterParser.PARAMETER, "branchRates.var");
writer.writeIDref(RateStatistic.RATE_STATISTIC, RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
break;
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(RateStatistic.RATE_STATISTIC, RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
writer.writeIDref(SumStatistic.SUM_STATISTIC, "rateChanges");
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_PARAMETERS, writer);
if (options.hasData()) {
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_LIKELIHOODS, writer);
if ( options.isSpeciesAnalysis() ) { // species
for (PartitionModel model : options.getActivePartitionModels()) {
treePriorGenerator.setGenePrefix(model.getName() + "."); // partitionName.treeModel
treePriorGenerator.writeLikelihoodLog(writer);
}
} else { // no species
treePriorGenerator.setGenePrefix("");
treePriorGenerator.writeLikelihoodLog(writer);
}
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_FILE_LOG, writer);
}
/**
* write tree log to file
* @param models
* @param writer
*/
private void writeTreeLogToFile(List<PartitionModel> models, XMLWriter writer) {
writer.writeComment("write tree log to file");
if (options.isSpeciesAnalysis()) { // species
// species tree log
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, TraitGuesser.Traits.TRAIT_SPECIES + "." + TREE_FILE_LOG), // speciesTreeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + options.SPECIES_TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(SpeciesTreeModel.SPECIES_TREE, SP_TREE);
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
// gene tree log
for (PartitionModel model : models) {
String treeFileName;
if (options.substTreeLog) {
treeFileName = options.fileNameStem + "." + model.getName() + "(time)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME;
} else {
treeFileName = options.fileNameStem + "." + model.getName() + "." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME; // stem.partitionName.tree
}
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getName() + "." + TREE_FILE_LOG), // partionName.treeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, treeFileName),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(TreeModel.TREE_MODEL, model.getName() + "." + TreeModel.TREE_MODEL);
switch (options.clockType) {
case STRICT_CLOCK:
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getName() + "." + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getName() + "." + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
} // end For loop
} else { // no species
if (options.treeFileName == null) {
if (options.substTreeLog) {
options.treeFileName = options.fileNameStem + "(time)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME;
} else {
options.treeFileName = options.fileNameStem + "." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME;
}
}
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, TREE_FILE_LOG),
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.treeFileName),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
switch (options.clockType) {
case STRICT_CLOCK:
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
/*if (options.clockType != ClockType.STRICT_CLOCK) {
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, BranchRateModel.BRANCH_RATES);
}*/
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TREES_LOG, writer);
// if (mapTreeLog) {
// // write tree log to file
// if (mapTreeFileName == null) {
// mapTreeFileName = fileNameStem + ".MAP.tree";
// writer.writeOpenTag("logML",
// new Attribute[] {
// new Attribute.Default<String>(TreeLogger.FILE_NAME, mapTreeFileName)
// writer.writeOpenTag("ml");
// writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
// writer.writeCloseTag("ml");
// writer.writeOpenTag("column", new Attribute[] {
// new Attribute.Default<String>("label", "MAP tree")
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag("column");
// writer.writeCloseTag("logML");
if (options.substTreeLog) {
if (options.isSpeciesAnalysis()) { // species
//TODO: species sub tree
// species tree
// writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
// new Attribute[]{
// new Attribute.Default<String>(XMLParser.ID, options.TRAIT_SPECIES + "." + SUB_TREE_FILE_LOG),
// new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
// new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
// new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.TRAIT_SPECIES +
// "(subst)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME),
// new Attribute.Default<String>(TreeLoggerParser.BRANCH_LENGTHS, TreeLoggerParser.SUBSTITUTIONS)
// writer.writeIDref(TreeModel.TREE_MODEL, options.TRAIT_SPECIES + "." + TreeModel.TREE_MODEL);
// switch (options.clockType) {
// case STRICT_CLOCK:
// writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, options.TRAIT_SPECIES + "." + BranchRateModel.BRANCH_RATES);
// break;
// case UNCORRELATED_EXPONENTIAL:
// case UNCORRELATED_LOGNORMAL:
// case RANDOM_LOCAL_CLOCK:
// writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, options.TRAIT_SPECIES + "." + BranchRateModel.BRANCH_RATES);
// break;
// case AUTOCORRELATED_LOGNORMAL:
// writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, options.TRAIT_SPECIES + "." + BranchRateModel.BRANCH_RATES);
// break;
// default:
// writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
// gene tree
for (PartitionModel model : models) {
// write tree log to file
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getName() + "." + SUB_TREE_FILE_LOG),
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + model.getName() +
"(subst)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.BRANCH_LENGTHS, TreeLoggerParser.SUBSTITUTIONS)
});
writer.writeIDref(TreeModel.TREE_MODEL, model.getName() + "." + TreeModel.TREE_MODEL);
switch (options.clockType) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, model.getName() + "." + BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getName() + "." + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getName() + "." + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
} else { // no species
// write tree log to file
if (options.substTreeFileName == null) {
options.substTreeFileName = options.fileNameStem + "(subst)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME;
}
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, SUB_TREE_FILE_LOG),
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.substTreeFileName),
new Attribute.Default<String>(TreeLoggerParser.BRANCH_LENGTHS, TreeLoggerParser.SUBSTITUTIONS)
});
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
switch (options.clockType) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREES_LOG, writer);
}
/**
* Write the priors for each parameter
*
* @param writer the writer
*/
private void writeParameterPriors(XMLWriter writer) {
boolean first = true;
for( Map.Entry<Taxa, Boolean> taxaBooleanEntry : options.taxonSetsMono.entrySet() ) {
if( taxaBooleanEntry.getValue() ) {
if( first ) {
writer.writeOpenTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
first = false;
}
final String taxaRef = "monophyly(" + taxaBooleanEntry.getKey().getId() + ")";
writer.writeIDref(MonophylyStatistic.MONOPHYLY_STATISTIC, taxaRef);
}
}
if( !first ) {
writer.writeCloseTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
}
ArrayList<Parameter> parameters = options.selectParameters();
for( Parameter parameter : parameters ) {
if( parameter.priorType != PriorType.NONE ) {
if( parameter.priorType != PriorType.UNIFORM_PRIOR || parameter.isNodeHeight ) {
writeParameterPrior(parameter, writer);
}
}
}
}
/**
* Write the priors for each parameter
*
* @param parameter the parameter
* @param writer the writer
*/
private void writeParameterPrior(dr.app.beauti.options.Parameter parameter, XMLWriter writer) {
switch (parameter.priorType) {
case UNIFORM_PRIOR:
writer.writeOpenTag(DistributionLikelihood.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(DistributionLikelihood.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.UNIFORM_PRIOR);
break;
case EXPONENTIAL_PRIOR:
writer.writeOpenTag(DistributionLikelihood.EXPONENTIAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.MEAN, "" + parameter.exponentialMean),
new Attribute.Default<String>(DistributionLikelihood.OFFSET, "" + parameter.exponentialOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.EXPONENTIAL_PRIOR);
break;
case NORMAL_PRIOR:
writer.writeOpenTag(DistributionLikelihood.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(DistributionLikelihood.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.NORMAL_PRIOR);
break;
case LOGNORMAL_PRIOR:
writer.writeOpenTag(DistributionLikelihood.LOG_NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.MEAN, "" + parameter.logNormalMean),
new Attribute.Default<String>(DistributionLikelihood.STDEV, "" + parameter.logNormalStdev),
new Attribute.Default<String>(DistributionLikelihood.OFFSET, "" + parameter.logNormalOffset),
// this is to be implemented...
new Attribute.Default<String>(DistributionLikelihood.MEAN_IN_REAL_SPACE, "false")
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.LOG_NORMAL_PRIOR);
break;
case GAMMA_PRIOR:
writer.writeOpenTag(DistributionLikelihood.GAMMA_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.SHAPE, "" + parameter.gammaAlpha),
new Attribute.Default<String>(DistributionLikelihood.SCALE, "" + parameter.gammaBeta),
new Attribute.Default<String>(DistributionLikelihood.OFFSET, "" + parameter.gammaOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.GAMMA_PRIOR);
break;
case JEFFREYS_PRIOR:
writer.writeOpenTag(JeffreysPriorLikelihood.JEFFREYS_PRIOR);
writeParameterIdref(writer, parameter);
writer.writeCloseTag(JeffreysPriorLikelihood.JEFFREYS_PRIOR);
break;
case POISSON_PRIOR:
writer.writeOpenTag(DistributionLikelihood.POISSON_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.MEAN, "" + parameter.poissonMean),
new Attribute.Default<String>(DistributionLikelihood.OFFSET, "" + parameter.poissonOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.POISSON_PRIOR);
break;
case TRUNC_NORMAL_PRIOR:
writer.writeOpenTag(DistributionLikelihood.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(DistributionLikelihood.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.UNIFORM_PRIOR);
writer.writeOpenTag(DistributionLikelihood.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(DistributionLikelihood.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(DistributionLikelihood.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(DistributionLikelihood.NORMAL_PRIOR);
break;
default:
throw new IllegalArgumentException("Unknown priorType");
}
}
private void writeParameterIdref(XMLWriter writer, dr.app.beauti.options.Parameter parameter) {
if (parameter.isStatistic) {
writer.writeIDref("statistic", parameter.getName());
} else {
writer.writeIDref(ParameterParser.PARAMETER, parameter.getName());
}
}
/**
* @return true either if the options have more than one partition or any partition is
* broken into codon positions.
*/
private boolean hasCodonOrUserPartitions() {
final List<PartitionModel> models = options.getActivePartitionModels();
return (models.size() > 1 || models.get(0).getCodonPartitionCount() > 1);
}
}
|
package dr.app.vcs;
import dr.evolution.coalescent.CoalescentSimulator;
import dr.evolution.coalescent.PiecewiseLinearPopulation;
import dr.evolution.tree.Tree;
import dr.evolution.util.Date;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.Units;
import ml.options.Options;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* This program simulates a set of coalescent trees from an arbitrary variable population size history expressed as
* a piecewise-linear function.
* <p/>
* Usage:
* java -jar vcs.jar [options] <infile> <outfile>
* <p/>
* Options:
* <ul>
* <li> <b> -g <genTime> </b> sets the generation time to the given value. This is used to scale
* times in the input file into units of generations.
* The default value is 1.0
* <li> <b> -n <numSamples> </b> sets the number of samples to generate the trees from.
* The default value is 50
* <li> <b> -p <popScale> </b> sets the population size scale factor to the given value. This scale
* factor transforms the population sizes in the input file to
* effective population sizes. This is useful if the population size
* profiles are expressed, for example, as prevalences, so then scale
* factor would represent the effective numbers of hosts in the
* population of interest.
* The default value is 1.0
* <li> <b> -se <sampleEnd> </b> the time at which last taxa is sampled, in the time scale provided by the input
* file. If this differs from the time specified be -ss option then the
* samples will be evenly spaced between the two times.
* The default value is the last time if -f is set and the first time
* otherwise.
* <li> <b> -ss <sampleStart> </b> the time at which first taxa is sampled, in the time scale provided by the input
* file. If this differs from the time specified be -se option then the
* samples will be evenly spaced between the two times.
* The default value is the last time if -f is set and the first time
* otherwise.
* <li> <b> -f </b> specifies that the population size history proceeds forward in time.
* Otherwise the population size history is assumed to proceed into the past. <br>
* <li> <b> -reps <reps> </b> the number of replicate simulations that will be performed.
* Each replicate will be separated in the output file by a comment line that labels the replicate, e.g. #rep 0.
* </ul>
* <p/>
* <infile> a whitespace-delimited plain text file. The first column contains the time
* and should be ascending from zero. Subsequent columns contain the population size
* histories, for which a tree will be simulated for each.
* <p/>
* <outfile> the file to which the trees will be written in newick format.
*
* @author Alexei Drummond
*/
public class VariableCoalescentSimulator {
public static void main(String[] arg) throws IOException {
long startTime = System.currentTimeMillis();
Options options = new Options(arg, 0, 7);
options.getSet().addOption("g", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
options.getSet().addOption("n", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
options.getSet().addOption("p", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
options.getSet().addOption("se", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
options.getSet().addOption("ss", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
options.getSet().addOption("reps", Options.Separator.EQUALS, Options.Multiplicity.ZERO_OR_ONE);
options.getSet().addOption("f", Options.Multiplicity.ZERO_OR_ONE);
if (!options.check()) {
System.out.println(options.getCheckErrors());
System.out.println();
printUsage();
System.exit(1);
}
double generationTime = 1.0;
double popSizeScale = 1.0;
int n = 50;
double ss = -1;
double se = -1;
int reps = 1;
boolean timeForward = options.getSet().isSet("f");
if (options.getSet().isSet("g")) {
String g = options.getSet().getOption("g").getResultValue(0);
generationTime = Double.parseDouble(g);
System.out.println("generation time = " + g);
}
if (options.getSet().isSet("n")) {
String sampleSize = options.getSet().getOption("n").getResultValue(0);
n = Integer.parseInt(sampleSize);
System.out.println("sample size = " + n);
}
if (options.getSet().isSet("p")) {
String p = options.getSet().getOption("p").getResultValue(0);
popSizeScale = Double.parseDouble(p);
System.out.println("population size scale factor = " + p);
}
if (options.getSet().isSet("ss")) {
String sampleStart = options.getSet().getOption("ss").getResultValue(0);
ss = Double.parseDouble(sampleStart);
System.out.println("sample start time = " + ss);
}
if (options.getSet().isSet("se")) {
String sampleEnd = options.getSet().getOption("se").getResultValue(0);
se = Double.parseDouble(sampleEnd);
System.out.println("sample end time = " + se);
}
if (options.getSet().isSet("reps")) {
String replicates = options.getSet().getOption("reps").getResultValue(0);
reps = Integer.parseInt(replicates);
System.out.println("replicates = " + reps);
}
String filename = options.getSet().getData().get(0);
String outfile = options.getSet().getData().get(1);
// READ DEMOGRAPHIC FUNCTION
BufferedReader reader = new BufferedReader(new FileReader(filename));
List<Double> times = new ArrayList<Double>();
String line = reader.readLine();
String[] tokens = line.trim().split("[\t ]+");
if (tokens.length < 2) throw new RuntimeException();
List<Double>[] popSizes = new List[tokens.length - 1];
for (int i = 0; i < tokens.length - 1; i++) {
popSizes[i] = new ArrayList<Double>();
}
while (line != null) {
double time = Double.parseDouble(tokens[0]) / generationTime;
times.add(time);
for (int i = 1; i < tokens.length; i++) {
popSizes[i - 1].add(Double.parseDouble(tokens[i]));
}
line = reader.readLine();
if (line != null) {
tokens = line.trim().split("[\t ]+");
if (tokens.length != popSizes.length + 1) throw new RuntimeException();
}
}
reader.close();
// GENERATE SAMPLE
double lastTime = times.get(times.size() - 1);
if (ss == -1) {
ss = timeForward ? lastTime : times.get(0);
}
if (se == -1) {
se = timeForward ? lastTime : times.get(0);
}
double dt = (se - ss) / ((double) n - 1.0);
double time = ss;
Taxa taxa = new Taxa();
for (int i = 0; i < n; i++) {
double sampleTime;
if (timeForward) {
sampleTime = (lastTime - time) / generationTime;
} else sampleTime = time / generationTime;
Taxon taxon = new Taxon(i + "");
taxon.setAttribute(dr.evolution.util.Date.DATE, new Date(sampleTime, Units.Type.GENERATIONS, true));
taxa.addTaxon(taxon);
time += dt;
}
double minTheta = Double.MAX_VALUE;
double maxTheta = 0.0;
PrintWriter out = new PrintWriter(new FileWriter(outfile));
int popHistory = 0;
PiecewiseLinearPopulation[] demography = new PiecewiseLinearPopulation[popSizes.length];
for (List<Double> popSize : popSizes) {
double[] thetas = new double[popSize.size()];
double[] intervals = new double[times.size() - 1];
for (int i = intervals.length; i >= 0; i
int j = timeForward ? intervals.length - i : i - 1;
int k = timeForward ? i : intervals.length - i + 1;
if (i != 0) intervals[j] = times.get(k) - times.get(k - 1);
double theta = popSize.get(k) * popSizeScale;
thetas[j] = theta;
if (theta < minTheta) {
minTheta = theta;
}
if (theta > maxTheta) {
maxTheta = theta;
}
//System.out.println(t + "\t" + theta);
}
System.out.println("N" + popHistory + "(t) range = [" + minTheta + ", " + maxTheta + "]");
demography[popHistory] = new PiecewiseLinearPopulation(intervals, thetas, Units.Type.GENERATIONS);
popHistory += 1;
}
CoalescentSimulator simulator = new CoalescentSimulator();
for (int i = 0; i < reps; i++) {
out.println("#rep " + i);
for (int j = 0; j < demography.length; j++) {
Tree tree = simulator.simulateTree(taxa, demography[j]);
out.println(Tree.Utils.newick(tree));
//System.err.println(Tree.Utils.newick(tree));
}
}
out.flush();
out.close();
long stopTime = System.currentTimeMillis();
System.out.println("Took " + (stopTime - startTime) / 1000.0 + " seconds");
}
private static Taxa readSampleFile(String fileName, double generationTime) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
Taxa taxa = new Taxa();
int id = 0;
while (line != null) {
if (!line.startsWith("
String[] tokens = line.split("[\t ]+");
// sample times are in the same units as simulation
double sampleTime = Double.parseDouble(tokens[0]) / generationTime;
int count = Integer.parseInt(tokens[1]);
for (int i = 0; i < count; i++) {
Taxon taxon = new Taxon(id + "");
taxon.setAttribute(dr.evolution.util.Date.DATE, new Date(sampleTime, Units.Type.GENERATIONS, true));
taxa.addTaxon(taxon);
id += 1;
}
}
line = reader.readLine();
}
return taxa;
}
private static void printUsage() {
System.out.println(
"Usage: \n" +
" java -jar vcs.jar [options] <infile> <outfile>\n" +
" \n" +
"Options:\n" +
" -g <value> sets the generation time to the given value. This is used to scale\n" +
" times in the input file into units of generations. \n" +
" The default value is 1.0\n" +
" -n <int> sets the number of samples to generate the trees from. \n" +
" The default value is 50\n" +
" -p <value> sets the population size scale factor to the given value. This scale \n" +
" factor transforms the population sizes in the input file to\n" +
" effective population sizes. This is useful if the population size\n" +
" profiles are expressed, for example, as prevalences, so then scale\n" +
" factor would represent the effective numbers of hosts in the\n" +
" population of interest. \n" +
" The default value is 1.0\n" +
" -ss <value> the time at which first taxa is sampled, in the time scale provided by the input\n" +
" file. If this differs from the time specified be -ss option then the \n" +
" samples will be evenly spaced between the two times.\n" +
" The default value is the last time if -f is set and the first time\n" +
" otherwise.\n" +
" -se <value> the time at which last taxa is sampled, in the time scale provided by the input\n" +
" file. If this differs from the time specified be -se option then the \n" +
" samples will be evenly spaced between the two times.\n" +
" The default value is the last time if -f is set and the first time\n" +
" otherwise.\n" +
" -reps <reps> the number of replicate simulations that will be performed. \n" +
" Each replicate will be separated in the output file by a comment line that\n" +
" labels the replicate, e.g. #rep 0.\n" +
" -f specifies that the population size history proceeds forward in time.\n" +
" Otherwise the population size history is assumed to proceed into the past.\n" +
"\n" +
"<infile> A whitespace-delimited plain text file. The first column contains the time\n" +
" and should be ascending from zero. Subsequent columns contain the population size\n" +
" histories, for which a tree will be simulated for each.\n" +
"<outfile> The file to which the trees will be written in newick format.");
}
}
|
package dr.evolution.alignment;
import dr.evolution.datatype.DataType;
import dr.evolution.sequence.Sequence;
import dr.evolution.sequence.Sequences;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import java.util.Arrays;
import java.util.Map;
/**
* A simple alignment class that implements gaps by characters in the sequences.
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: SimpleAlignment.java,v 1.46 2005/06/21 16:25:15 beth Exp $
*/
public class SimpleAlignment extends Sequences implements Alignment, dr.util.XHTMLable {
// SimpleAlignment METHODS
/**
* parameterless constructor.
*/
public SimpleAlignment() {
}
/**
* Constructs a sub alignment based on the provided taxa.
*
* @param a
* @param taxa
*/
public SimpleAlignment(Alignment a, TaxonList taxa) {
for (int i = 0; i < taxa.getTaxonCount(); i++) {
Taxon taxon = taxa.getTaxon(i);
Sequence sequence = a.getSequence(a.getTaxonIndex(taxon));
addSequence(sequence);
}
}
/**
* Calculates the siteCount by finding the longest sequence.
*/
public void updateSiteCount() {
siteCount = 0;
int i, len, n = getSequenceCount();
for (i = 0; i < n; i++) {
len = getSequence(i).getLength();
if (len > siteCount)
siteCount = len;
}
siteCountKnown = true;
}
// Alignment IMPLEMENTATION
/**
* Sets the dataType of this alignment. This should be the same as
* the sequences.
*/
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
/**
* @return number of sites
*/
public int getSiteCount(DataType dataType) {
return getSiteCount();
}
/**
* sequence character at (sequence, site)
*/
public char getChar(int sequenceIndex, int siteIndex) {
return getSequence(sequenceIndex).getChar(siteIndex);
}
/**
* Returns string representation of single sequence in
* alignment with gap characters included.
*/
public String getAlignedSequenceString(int sequenceIndex) {
return getSequence(sequenceIndex).getSequenceString();
}
/**
* Returns string representation of single sequence in
* alignment with gap characters excluded.
*/
public String getUnalignedSequenceString(int sequenceIndex) {
StringBuffer unaligned = new StringBuffer();
for (int i = 0, n = getSiteCount(); i < n; i++) {
int state = getState(sequenceIndex, i);
if (!dataType.isGapState(state)) {
unaligned.append(dataType.getChar(state));
}
}
return unaligned.toString();
}
// Sequences METHODS
/**
* Add a sequence to the sequence list
*/
public void addSequence(Sequence sequence) {
if (dataType == null) {
if (sequence.getDataType() == null) {
dataType = sequence.guessDataType();
sequence.setDataType(dataType);
} else {
setDataType(sequence.getDataType());
}
} else if (sequence.getDataType() == null) {
sequence.setDataType(dataType);
} else if (dataType != sequence.getDataType()) {
throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
}
super.addSequence(sequence);
updateSiteCount();
}
/**
* Insert a sequence to the sequence list at position
*/
public void insertSequence(int position, Sequence sequence) {
if (dataType == null) {
if (sequence.getDataType() == null) {
dataType = sequence.guessDataType();
sequence.setDataType(dataType);
} else {
setDataType(sequence.getDataType());
}
} else if (sequence.getDataType() == null) {
sequence.setDataType(dataType);
} else if (dataType != sequence.getDataType()) {
throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
}
super.insertSequence(position, sequence);
}
// SiteList IMPLEMENTATION
/**
* @return number of sites
*/
public int getSiteCount() {
if (!siteCountKnown)
updateSiteCount();
return siteCount;
}
/**
* Gets the pattern of site as an array of state numbers (one per sequence)
*
* @return the site pattern at siteIndex
*/
public int[] getSitePattern(int siteIndex) {
Sequence seq;
int i, n = getSequenceCount();
int[] pattern = new int[n];
for (i = 0; i < n; i++) {
seq = getSequence(i);
if (siteIndex >= seq.getLength())
pattern[i] = dataType.getGapState();
else
pattern[i] = seq.getState(siteIndex);
}
return pattern;
}
/**
* Gets the pattern index at a particular site
*
* @return the patternIndex
*/
public int getPatternIndex(int siteIndex) {
return siteIndex;
}
/**
* @return the sequence state at (taxon, site)
*/
public int getState(int taxonIndex, int siteIndex) {
Sequence seq = getSequence(taxonIndex);
if (siteIndex >= seq.getLength()) {
return dataType.getGapState();
}
return seq.getState(siteIndex);
}
public void setState(int taxonIndex, int siteIndex, int state) {
Sequence seq = getSequence(taxonIndex);
if (siteIndex >= seq.getLength()) {
throw new IllegalArgumentException();
}
seq.setState(siteIndex, state);
}
// PatternList IMPLEMENTATION
/**
* @return number of patterns
*/
public int getPatternCount() {
return getSiteCount();
}
/**
* @return number of invariant sites
*/
public int getInvariantCount() {
int invariantSites = 0;
for(int i=0; i<getSiteCount(); i++) {
int[] pattern = getSitePattern(i);
if (Patterns.isInvariant(pattern)) {
invariantSites++;
}
}
return invariantSites;
}
public int getUniquePatternCount() {
Patterns patterns = new Patterns(this);
return patterns.getPatternCount();
}
public int getInformativeCount() {
Patterns patterns = new Patterns(this);
int informativeCount = 0;
for(int i = 0; i < patterns.getPatternCount(); i++) {
int[] pattern = patterns.getPattern(i);
if (isInformative(pattern)) {
informativeCount += patterns.getPatternWeight(i);
}
}
return informativeCount;
}
public int getSingletonCount() {
Patterns patterns = new Patterns(this);
int singletonCount = 0;
for(int i = 0; i < patterns.getPatternCount(); i++) {
int[] pattern = patterns.getPattern(i);
if (!Patterns.isInvariant(pattern) && !isInformative(pattern)) {
singletonCount += patterns.getPatternWeight(i);
}
}
return singletonCount;
}
private boolean isInformative(int[] pattern) {
int[] stateCounts = new int[getStateCount()];
for (int j = 0; j < pattern.length; j++) {
stateCounts[pattern[j]] ++;
}
boolean oneStateGreaterThanOne = false;
boolean secondStateGreaterThanOne = false;
for (int j = 0; j < stateCounts.length; j++) {
if (stateCounts[j] > 1) {
if (!oneStateGreaterThanOne) {
oneStateGreaterThanOne = true;
} else {
secondStateGreaterThanOne = true;
}
}
}
return secondStateGreaterThanOne;
}
/**
* @return number of states for this siteList
*/
public int getStateCount() {
return getDataType().getStateCount();
}
/**
* Gets the length of the pattern strings which will usually be the
* same as the number of taxa
*
* @return the length of patterns
*/
public int getPatternLength() {
return getSequenceCount();
}
/**
* Gets the pattern as an array of state numbers (one per sequence)
*
* @return the pattern at patternIndex
*/
public int[] getPattern(int patternIndex) {
return getSitePattern(patternIndex);
}
/**
* @return state at (taxonIndex, patternIndex)
*/
public int getPatternState(int taxonIndex, int patternIndex) {
return getState(taxonIndex, patternIndex);
}
/**
* Gets the weight of a site pattern (always 1.0)
*/
public double getPatternWeight(int patternIndex) {
return 1.0;
}
/**
* @return the array of pattern weights
*/
public double[] getPatternWeights() {
double[] weights = new double[siteCount];
for (int i = 0; i < siteCount; i++)
weights[i] = 1.0;
return weights;
}
/**
* @return the DataType of this siteList
*/
public DataType getDataType() {
return dataType;
}
/**
* @return the frequency of each state
*/
public double[] getStateFrequencies() {
return PatternList.Utils.empiricalStateFrequencies(this);
}
public String toString() {
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(6);
StringBuffer buffer = new StringBuffer();
buffer.append("Site count = ").append(getSiteCount()).append("\n");
buffer.append("Invariant sites = ").append(getInvariantCount()).append("\n\n");
buffer.append("Singleton sites = ").append(getSingletonCount()).append("\n\n");
buffer.append("Parsimony informative sites = ").append(getInformativeCount()).append("\n\n");
buffer.append("Unique site patters = ").append(getUniquePatternCount()).append("\n\n");
buffer.append("Invariant sites = ").append(getInvariantCount()).append("\n\n");
for (int i = 0; i < getSequenceCount(); i++) {
String name = formatter.formatToFieldWidth(getTaxonId(i), 10);
buffer.append(">" + name + "\n");
buffer.append(getAlignedSequenceString(i) + "\n");
}
return buffer.toString();
}
public String toXHTML() {
String xhtml = "<p><em>Alignment</em> data type = ";
xhtml += getDataType().getDescription();
xhtml += ", no. taxa = ";
xhtml += getTaxonCount();
xhtml += ", no. sites = ";
xhtml += getSiteCount();
xhtml += "</p>";
xhtml += "<pre>";
int length, maxLength = 0;
for (int i = 0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
if (length > maxLength)
maxLength = length;
}
for (int i = 0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
xhtml += getTaxonId(i);
for (int j = length; j <= maxLength; j++)
xhtml += " ";
xhtml += getAlignedSequenceString(i) + "\n";
}
xhtml += "</pre>";
return xhtml;
}
// INSTANCE VARIABLES
private DataType dataType = null;
private int siteCount = 0;
private boolean siteCountKnown = false;
}
|
package vn.edu.fpt.hsts.bizlogic.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import vn.edu.fpt.hsts.bizlogic.model.DoctorModel;
import vn.edu.fpt.hsts.bizlogic.model.FoodPrescriptionModel;
import vn.edu.fpt.hsts.bizlogic.model.MedicinePhaseModel;
import vn.edu.fpt.hsts.bizlogic.model.MedicinePrescriptionModel;
import vn.edu.fpt.hsts.bizlogic.model.PracticePrescriptionModel;
import vn.edu.fpt.hsts.bizlogic.model.PrescriptionModel;
import vn.edu.fpt.hsts.common.IConsts;
import vn.edu.fpt.hsts.common.expception.BizlogicException;
import vn.edu.fpt.hsts.common.util.DateUtils;
import vn.edu.fpt.hsts.common.util.StringUtils;
import vn.edu.fpt.hsts.persistence.IDbConsts;
import vn.edu.fpt.hsts.persistence.entity.Account;
import vn.edu.fpt.hsts.persistence.entity.Appointment;
import vn.edu.fpt.hsts.persistence.entity.Doctor;
import vn.edu.fpt.hsts.persistence.entity.Food;
import vn.edu.fpt.hsts.persistence.entity.FoodTreatment;
import vn.edu.fpt.hsts.persistence.entity.Illness;
import vn.edu.fpt.hsts.persistence.entity.MedicalRecord;
import vn.edu.fpt.hsts.persistence.entity.Medicine;
import vn.edu.fpt.hsts.persistence.entity.MedicinePhase;
import vn.edu.fpt.hsts.persistence.entity.MedicineTreatment;
import vn.edu.fpt.hsts.persistence.entity.Notify;
import vn.edu.fpt.hsts.persistence.entity.Phase;
import vn.edu.fpt.hsts.persistence.entity.Practice;
import vn.edu.fpt.hsts.persistence.entity.PracticeTreatment;
import vn.edu.fpt.hsts.persistence.entity.Treatment;
import vn.edu.fpt.hsts.persistence.repo.AppointmentRepo;
import vn.edu.fpt.hsts.persistence.repo.DoctorRepo;
import vn.edu.fpt.hsts.persistence.repo.FoodRepo;
import vn.edu.fpt.hsts.persistence.repo.FoodTreatmentRepo;
import vn.edu.fpt.hsts.persistence.repo.IllnessRepo;
import vn.edu.fpt.hsts.persistence.repo.MedicalRecordRepo;
import vn.edu.fpt.hsts.persistence.repo.MedicineRepo;
import vn.edu.fpt.hsts.persistence.repo.MedicineTreatmentRepo;
import vn.edu.fpt.hsts.persistence.repo.NotifyRepo;
import vn.edu.fpt.hsts.persistence.repo.PracticeRepo;
import vn.edu.fpt.hsts.persistence.repo.PracticeTreatmentRepo;
import vn.edu.fpt.hsts.persistence.repo.TreatmentRepo;
import javax.swing.*;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Service
public class DoctorService extends AbstractService {
private static final Logger LOGGER = LoggerFactory.getLogger(DoctorService.class);
/**
* The {@link DoctorRepo}.
*/
@Autowired
private DoctorRepo doctorRepo;
/**
* The {@link AppointmentRepo}.
*/
@Autowired
private AppointmentRepo appointmentRepo;
/**
* The {@link TreatmentRepo}.
*/
@Autowired
private TreatmentRepo treatmentRepo;
/**
* The {@link MedicineTreatmentRepo}.
*/
@Autowired
private MedicineTreatmentRepo medicineTreatmentRepo;
/**
* The {@link MedicineRepo}.
*/
@Autowired
private MedicineRepo medicineRepo;
/**
* The {@link MedicalRecordRepo}.
*/
@Autowired
private MedicalRecordRepo medicalRecordRepo;
/**
* The {@link IllnessRepo}.
*/
@Autowired
private IllnessRepo illnessRepo;
/**
* The {@link FoodRepo}.
*/
@Autowired
private FoodRepo foodRepo;
/**
* The {@link FoodTreatmentRepo}.
*/
@Autowired
private FoodTreatmentRepo foodTreatmentRepo;
/**
* The {@link PracticeTreatmentRepo}.
*/
@Autowired
private PracticeTreatmentRepo practiceTreatmentRepo;
/**
* The {@link PracticeRepo}.
*/
@Autowired
private PracticeRepo practiceRepo;
/**
* The {@link NotifyRepo}.
*/
@Autowired
private NotifyRepo notifyRepo;
/**
* The {@link IllnessService}.
*/
@Autowired
private IllnessService illnessService;
@Value("${hsts.default.treatment.long}")
private int treatmentLong;
public List<DoctorModel> findAll() {
LOGGER.info(IConsts.BEGIN_METHOD);
try {
final List<Doctor> doctors = doctorRepo.findAll();
if (null != doctors && !doctors.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Got {} records", doctors.size());
}
final List<DoctorModel> modelList = new ArrayList<DoctorModel>();
for (Doctor doctor: doctors) {
DoctorModel model = new DoctorModel();
model.fromEntity(doctor);
modelList.add(model);
}
return modelList;
}
return Collections.emptyList();
} finally {
LOGGER.info(IConsts.END_METHOD);
}
}
@Transactional(rollbackOn = BizlogicException.class)
public void makePrescription(final PrescriptionModel prescription,
final int appointmentId,
final String appointmentDate) throws BizlogicException {
LOGGER.info(IConsts.BEGIN_METHOD);
try {
LOGGER.info("prescription[{}], appointmentId[{}], appointmentDate[{}]", prescription, appointmentId, appointmentDate);
// Find appointment by id
final Appointment appointment = appointmentRepo.findOne(appointmentId);
if (null == appointment) {
LOGGER.error("Appointment with id[{}] is not found", appointmentId);
throw new BizlogicException("Appointment with id[{}] is not found", null, appointmentId);
}
appointment.setStatus(IDbConsts.IAppointmentStatus.FINISHED);
Date toDate = null;
final MedicalRecord medicalRecord = appointment.getMedicalRecord();
final String dianostic = prescription.getDiagnostic();
if (StringUtils.isNotEmpty(dianostic)) {
final Illness illness = illnessRepo.findOne(Integer.parseInt(dianostic));
medicalRecord.setIllness(illness);
}
medicalRecord.setStatus(IDbConsts.IMedicalRecordStatus.ON_TREATING);
if (StringUtils.isNotEmpty(appointmentDate)) {
toDate = DateUtils.parseDate(appointmentDate, DateUtils.DATE_PATTERN_3);
if (null == toDate) {
throw new BizlogicException("Wrong input date format: {}", null, appointmentDate);
}
// Create next appointment
Appointment nextAppointment = new Appointment();
nextAppointment.setStatus(IDbConsts.IAppointmentStatus.ENTRY);
nextAppointment.setMeetingDate(toDate);
nextAppointment.setMedicalRecord(appointment.getMedicalRecord());
appointmentRepo.save(nextAppointment);
// Set old appointment link to new appointment
appointment.setNextAppointment(nextAppointment);
// Create notify to patient
final Notify notify = new Notify();
notify.setSender(getCurrentAccount());
notify.setReceiver(medicalRecord.getPatient().getAccount());
notify.setType(IDbConsts.INotifyType.DOCTOR_PATIENT_APPOINTMENT);
notify.setStatus(IDbConsts.INotifyStatus.UNCOMPLETED);
final int patientId = medicalRecord.getPatient().getId();
notify.setMessage(String.valueOf(patientId));
notifyRepo.saveAndFlush(notify);
}
medicalRecordRepo.saveAndFlush(medicalRecord);
appointmentRepo.save(appointment);
// Set old treatment to DONE
final Treatment treatment = treatmentRepo.findLastTreatmenByAppointmentId(appointmentId);
if (null != treatment) {
treatment.setStatus(IDbConsts.ITreatmentStatus.FINISHED);
treatment.setToDate(new Date());
treatmentRepo.save(treatment);
}
if (null != prescription) {
// create new treatment
final Treatment newTreatment = new Treatment();
newTreatment.setStatus(IDbConsts.ITreatmentStatus.ON_TREATING);
newTreatment.setAppointment(appointment);
newTreatment.setFromDate(new Date());
//TODO
// newTreatment.setCaloriesBurnEveryday(Integer.parseInt(prescription.getKcalRequire()));
if (null != toDate) {
// Set toDate = appointmentDate
newTreatment.setToDate(toDate);
} else {
// Set todate to next 7 day, note that UI should be check
toDate = DateUtils.plusDateTime(new Date(), Calendar.DATE, treatmentLong);
newTreatment.setToDate(toDate);
}
treatmentRepo.save(newTreatment);
// TODO implement for medicine, food, practice and multiple row, validate data
// Medicine
final List<MedicinePrescriptionModel> mPresModels = prescription.getmPresModels();
if (null != mPresModels && !mPresModels.isEmpty()) {
for(MedicinePrescriptionModel medicineModel: mPresModels) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(medicineModel.toString());
}
Medicine medicine = medicineRepo.findOne(medicineModel.getM());
if (null == medicine) {
throw new BizlogicException("Medicine with id[{}] is not found", null, medicineModel.getM());
}
MedicineTreatment medicineTreatment = new MedicineTreatment();
medicineTreatment.setMedicine(medicine);
medicineTreatment.setNumberOfTime(medicineModel.getmTime());
//TODO
// medicineTreatment.setQuantitative(medicineModel.getmQuantity());
medicineTreatment.setAdvice(medicineModel.getmNote());
medicineTreatment.setTreatment(newTreatment);
medicineTreatmentRepo.save(medicineTreatment);
}
}
// Food
final List<FoodPrescriptionModel> fPresModels = prescription.getfPresModels();
if(null != fPresModels && !fPresModels.isEmpty()) {
for (FoodPrescriptionModel foodModel: fPresModels) {
Food food = foodRepo.findOne(foodModel.getF());
if (null == food) {
throw new BizlogicException("Food with id[{}] is not found", null, foodModel.getF());
}
FoodTreatment foodTreatment = new FoodTreatment();
foodTreatment.setFood(food);
foodTreatment.setTreatment(newTreatment);
foodTreatment.setNumberOfTime(foodModel.getfTime());
foodTreatment.setQuantitative(foodModel.getfQuantity());
foodTreatment.setAdvice(foodModel.getfNote());
foodTreatmentRepo.save(foodTreatment);
}
}
// Practice
final List<PracticePrescriptionModel> pPresModels = prescription.getpPresModels();
if (null != pPresModels && !pPresModels.isEmpty()) {
for(PracticePrescriptionModel practiceModel: pPresModels) {
final Practice practice = practiceRepo.findOne(practiceModel.getP());
if (null == practice) {
throw new BizlogicException("Practice with name[{}] is not found", null, practiceModel.getP());
}
PracticeTreatment practiceTreatment = new PracticeTreatment();
practiceTreatment.setTreatment(newTreatment);
practiceTreatment.setNumberOfTime(practiceModel.getpTime());
practiceTreatment.setPractice(practice);
practiceTreatment.setAdvice(practiceModel.getpNote());
practiceTreatment.setTimeDuration(practiceModel.getpIntensity());
practiceTreatmentRepo.save(practiceTreatment);
}
}
}
// Create notify to patient
final Notify notify = new Notify();
notify.setSender(getCurrentAccount());
notify.setReceiver(medicalRecord.getPatient().getAccount());
notify.setType(IDbConsts.INotifyType.DOCTOR_PATIENT_PRESCRIPTION);
notify.setStatus(IDbConsts.INotifyStatus.UNCOMPLETED);
final int patientId = medicalRecord.getPatient().getId();
notify.setMessage(String.valueOf(patientId));
notifyRepo.saveAndFlush(notify);
// flush all change to db
appointmentRepo.flush();
treatmentRepo.flush();
medicineTreatmentRepo.flush();
foodTreatmentRepo.flush();
practiceTreatmentRepo.flush();
} catch (BizlogicException e) {
throw e;
} catch (Exception e) {
throw new BizlogicException("Error while making new prescription: {}", null, e.getMessage());
}finally {
LOGGER.info(IConsts.END_METHOD);
}
}
public List<MedicinePhaseModel> getMedicines(final int appointmentId, final int diagnostic) throws BizlogicException {
LOGGER.info(IConsts.BEGIN_METHOD);
try {
// Find phase for diagnostic
final Phase phase = illnessService.getPhaseSugestion(appointmentId, diagnostic);
if(null == phase) {
return Collections.emptyList();
}
final List<MedicinePhase> medicinePhases = phase.getMedicinePhaseList();
if(null != medicinePhases && !medicinePhases.isEmpty()) {
if (LOGGER.isDebugEnabled()){
LOGGER.debug("Got {} records", medicinePhases.size());
}
final List<MedicinePhaseModel> listData = new ArrayList<MedicinePhaseModel>();
for (MedicinePhase medicinePhase: medicinePhases) {
MedicinePhaseModel model = new MedicinePhaseModel();
model.fromEntity(medicinePhase);
listData.add(model);
}
return listData;
}
return Collections.emptyList();
} finally {
LOGGER.info(IConsts.END_METHOD);
}
}
}
|
package org.voltdb.utils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.voltdb.CLIConfig;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.BatchTimeoutOverrideType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.NoConnectionsException;
import org.voltdb.client.ProcCallException;
import org.voltdb.parser.SQLParser;
import org.voltdb.parser.SQLParser.FileInfo;
import org.voltdb.parser.SQLParser.FileOption;
import org.voltdb.parser.SQLParser.ParseRecallResults;
import com.google_voltpatches.common.collect.ImmutableMap;
import jline.console.CursorBuffer;
import jline.console.KeyMap;
import jline.console.history.FileHistory;
public class SQLCommand
{
private static boolean m_stopOnError = true;
private static boolean m_debug = false;
private static boolean m_interactive;
private static boolean m_versionCheck = true;
private static boolean m_returningToPromptAfterError = false;
private static int m_exitCode = 0;
private static boolean m_hasBatchTimeout = true;
private static int m_batchTimeout = BatchTimeoutOverrideType.DEFAULT_TIMEOUT;
private static final String m_readme = "SQLCommandReadme.txt";
public static String getReadme() {
return m_readme;
}
private static List<String> RecallableSessionLines = new ArrayList<String>();
private static boolean m_testFrontEndOnly;
private static String m_testFrontEndResult;
private static String patchErrorMessageWithFile(String batchFileName, String message) {
Pattern errorMessageFilePrefix = Pattern.compile("\\[.*:([0-9]+)\\]");
Matcher matcher = errorMessageFilePrefix.matcher(message);
if (matcher.find()) {
// This won't work right if the filename contains a "$"...
message = matcher.replaceFirst("[" + batchFileName + ":$1]");
}
return message;
}
private static ClientResponse callProcedureHelper(String procName, Object... parameters)
throws NoConnectionsException, IOException, ProcCallException {
ClientResponse response = null;
if (m_hasBatchTimeout) {
response = m_client.callProcedureWithTimeout(m_batchTimeout, procName, parameters);
} else {
response = m_client.callProcedure(procName, parameters);
}
return response;
}
private static void executeDDLBatch(String batchFileName, String statements) {
try {
if ( ! m_interactive ) {
System.out.println();
System.out.println(statements);
}
if (! SQLParser.appearsToBeValidDDLBatch(statements)) {
throw new Exception("Error: This batch begins with a non-DDL statement. "
+ "Currently batching is only supported for DDL.");
}
if (m_testFrontEndOnly) {
m_testFrontEndResult += statements;
return;
}
ClientResponse response = m_client.callProcedure("@AdHoc", statements);
if (response.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Execution Error: " + response.getStatusString());
}
// Assert the current DDL AdHoc batch call behavior
assert(response.getResults().length == 1);
System.out.println("Batch command succeeded.");
loadStoredProcedures(Procedures, Classlist);
}
catch (ProcCallException ex) {
String fixedMessage = patchErrorMessageWithFile(batchFileName, ex.getMessage());
stopOrContinue(new Exception(fixedMessage));
}
catch (Exception ex) {
stopOrContinue(ex);
}
}
// The main loop for interactive mode.
public static void interactWithTheUser() throws Exception
{
final SQLConsoleReader interactiveReader =
new SQLConsoleReader(new FileInputStream(FileDescriptor.in), System.out);
interactiveReader.setBellEnabled(false);
FileHistory historyFile = null;
try {
// Maintain persistent history in ~/.sqlcmd_history.
historyFile = new FileHistory(new File(System.getProperty("user.home"), ".sqlcmd_history"));
interactiveReader.setHistory(historyFile);
// Make Ctrl-D (EOF) exit if on an empty line, otherwise delete the next character.
KeyMap keyMap = interactiveReader.getKeys();
keyMap.bind(new Character(KeyMap.CTRL_D).toString(), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CursorBuffer cursorBuffer = interactiveReader.getCursorBuffer();
if (cursorBuffer.length() == 0) {
System.exit(m_exitCode);
} else {
try {
interactiveReader.delete();
} catch (IOException e1) {
}
}
}
});
getInteractiveQueries(interactiveReader);
}
finally {
// Flush input history to a file.
if (historyFile != null) {
try {
historyFile.flush();
}
catch (IOException e) {
System.err.printf("* Unable to write history to \"%s\" *\n",
historyFile.getFile().getPath());
if (m_debug) {
e.printStackTrace();
}
}
}
// Clean up jline2 resources.
if (interactiveReader != null) {
interactiveReader.shutdown();
}
}
}
public static void getInteractiveQueries(SQLConsoleReader interactiveReader) throws Exception
{
// Reset the error state to avoid accidentally ignoring future FILE content
// after a file had runtime errors (ENG-7335).
m_returningToPromptAfterError = false;
final StringBuilder statement = new StringBuilder();
boolean isRecall = false;
while (true) {
String prompt = isRecall ? "" : ((RecallableSessionLines.size() + 1) + "> ");
isRecall = false;
String line = interactiveReader.readLine(prompt);
if (line == null) {
// This used to occur in an edge case when trying to pipe an
// empty file into stdin and ending up in interactive mode by
// mistake. That case works differently now, so this code path
// MAY be dead. If not, cut our losses by rigging a quick exit.
statement.setLength(0);
line = "EXIT;";
}
// Was there a line-ending semicolon typed at the prompt?
// This mostly matters for "non-directive" statements.
boolean executeImmediate = SQLParser.isSemiColonTerminated(line);
// When we are tracking the progress of a multi-line statement,
// avoid coincidentally recognizing mid-statement SQL content as sqlcmd
// "directives".
if (statement.length() == 0) {
if (line.trim().equals("") || SQLParser.isWholeLineComment(line)) {
// We don't strictly have to execute or append or recall
// a blank line or whole-line comment when no statement is in progress.
continue;
}
// EXIT command - exit immediately
if (SQLParser.isExitCommand(line)) {
return;
}
// RECALL command
ParseRecallResults recallParseResults = SQLParser.parseRecallStatement(line, RecallableSessionLines.size() - 1);
if (recallParseResults != null) {
if (recallParseResults.getError() == null) {
line = RecallableSessionLines.get(recallParseResults.getLine());
interactiveReader.putString(line);
interactiveReader.flush();
isRecall = true;
}
else {
System.out.println(recallParseResults.getError());
}
executeImmediate = false; // let user edit the recalled line.
continue;
}
// Queue up the line to the recall stack
//TODO: In the future, we may not want to have simple directives count as recallable
// lines, so this call would move down a ways.
RecallableSessionLines.add(line);
if (executesAsSimpleDirective(line)) {
executeImmediate = false; // return to prompt.
continue;
}
// If the line is a FILE command - execute the content of the file
FileInfo fileInfo = null;
try {
fileInfo = SQLParser.parseFileStatement(line);
}
catch (SQLParser.Exception e) {
stopOrContinue(e);
continue;
}
if (fileInfo != null) {
executeScriptFile(fileInfo, interactiveReader);
if (m_returningToPromptAfterError) {
// executeScriptFile stopped because of an error. Wipe the slate clean.
m_returningToPromptAfterError = false;
}
continue;
}
// else treat the input line as a regular database command
if (executeImmediate) {
executeStatements(line + "\n");
if (m_testFrontEndOnly) {
break; // test mode expects this early return before end of input.
}
continue;
}
}
else {
// With a multi-line statement pending,
// queue up the line continuation to the recall list.
//TODO: arguably, it would be more useful to append continuation
// lines to the last existing Lines entry to build each complete
// statement as a single recallable unit. Experiments indicated
// that joining the lines with a single space, while not as pretty
// as a newline for very long statements, behaved perfectly for
// line editing (cursor positioning).
RecallableSessionLines.add(line);
if (executeImmediate) {
statement.append(line + "\n");
executeStatements(statement.toString());
if (m_testFrontEndOnly) {
break; // test mode expects this early return before end of input.
}
statement.setLength(0);
continue;
}
}
// Collect lines ...
statement.append(line + "\n");
//TODO: Here's where we might append to a separate buffer that uses
// a single space rather than a newline as its separator to build up
// a recallable multi-line statement.
}
}
/// A stripped down variant of the processing in "interactWithTheUser" suitable for
/// applying to a command script. It skips all the interactive-only options.
/// It uses the same logic as the FILE directive but gets its input from stdin.
public static void executeNoninteractive() throws Exception
{
SQLCommandLineReader stdinReader = new LineReaderAdapter(new InputStreamReader(System.in));
FileInfo fileInfo = SQLParser.FileInfo.forSystemIn();
executeScriptFromReader(fileInfo, stdinReader);
}
/// Simple directives require only the input line and no other context from the input loop.
/// Return true if the line is a directive that has been completely handled here, so that the
/// input loop can proceed to the next line.
//TODO: There have been suggestions that some or all of these directives could be made
// available in non-interactive contexts. This function is available to enable that.
private static boolean executesAsSimpleDirective(String line) throws Exception {
// SHOW or LIST <blah> statement
String subcommand = SQLParser.parseShowStatementSubcommand(line);
if (subcommand != null) {
if (subcommand.equals("proc") || subcommand.equals("procedures")) {
execListProcedures();
}
else if (subcommand.equals("tables")) {
execListTables();
}
else if (subcommand.equals("classes")) {
execListClasses();
}
else if (subcommand.equals("config") || subcommand.equals("configuration")) {
execListConfigurations();
}
else {
String errorCase = (subcommand.equals("") || subcommand.equals(";")) ?
("Incomplete SHOW command.\n") :
("Invalid SHOW command completion: '" + subcommand + "'.\n");
System.out.println(errorCase +
"The valid SHOW command completions are proc, procedures, tables, or classes.");
}
// Consider it handled here, whether or not it was a good SHOW statement.
return true;
}
// HELP commands - ONLY in interactive mode, close batch and parse for execution
// Parser returns null if it isn't a HELP command. If no arguments are specified
// the returned string will be empty.
String helpSubcommand = SQLParser.parseHelpStatement(line);
if (helpSubcommand != null) {
// Ignore the arguments for now.
if (!helpSubcommand.isEmpty()) {
System.out.printf("Ignoring extra HELP argument(s): %s\n", helpSubcommand);
}
printHelp(System.out); // Print readme to the screen
return true;
}
String echoArgs = SQLParser.parseEchoStatement(line);
if (echoArgs != null) {
System.out.println(echoArgs);
return true;
}
String echoErrorArgs = SQLParser.parseEchoErrorStatement(line);
if (echoErrorArgs != null) {
System.err.println(echoErrorArgs);
return true;
}
// It wasn't a locally-interpreted directive.
return false;
}
private static void execListConfigurations() throws Exception {
VoltTable configData = m_client.callProcedure("@SystemCatalog", "CONFIG").getResults()[0];
if (configData.getRowCount() != 0) {
printConfig(configData);
}
}
private static void execListClasses() {
//TODO: since sqlcmd makes no intrinsic use of the Classlist, it would be more
// efficient to load the Classlist only "on demand" from here and to cache a
// complete formatted String result rather than the complex map representation.
// This would save churn on startup and on DDL update.
if (Classlist.isEmpty()) {
System.out.println();
System.out.println("
System.out.println();
}
List<String> list = new LinkedList<String>(Classlist.keySet());
Collections.sort(list);
int padding = 0;
for (String classname : list) {
padding = Math.max(padding, classname.length());
}
String format = " %1$-" + padding + "s";
String categoryHeader[] = new String[] {
"
"
"
for (int i = 0; i<3; i++) {
boolean firstInCategory = true;
for (String classname : list) {
List<Boolean> stuff = Classlist.get(classname);
// Print non-active procs first
if (i == 0 && !(stuff.get(0) && !stuff.get(1))) {
continue;
} else if (i == 1 && !(stuff.get(0) && stuff.get(1))) {
continue;
} else if (i == 2 && stuff.get(0)) {
continue;
}
if (firstInCategory) {
firstInCategory = false;
System.out.println();
System.out.println(categoryHeader[i]);
}
System.out.printf(format, classname);
System.out.println();
}
}
System.out.println();
}
private static void execListTables() throws Exception {
//TODO: since sqlcmd makes no intrinsic use of the tables list, it would be more
// efficient to load the list only "on demand" from here and to cache a
// complete formatted String result rather than the multiple lists.
// This would save churn on startup and on DDL update.
Tables tables = getTables();
printTables("User Tables", tables.tables);
printTables("User Views", tables.views);
printTables("User Export Streams", tables.exports);
System.out.println();
}
private static void execListProcedures() {
List<String> list = new LinkedList<String>(Procedures.keySet());
Collections.sort(list);
int padding = 0;
for (String procedure : list) {
if (padding < procedure.length()) {
padding = procedure.length();
}
}
padding++;
String format = "%1$-" + padding + "s";
boolean firstSysProc = true;
boolean firstUserProc = true;
for (String procedure : list) {
//TODO: it would be much easier over all to maintain sysprocs and user procs in
// in two separate maps.
if (procedure.startsWith("@")) {
if (firstSysProc) {
firstSysProc = false;
System.out.println("
}
}
else {
if (firstUserProc) {
firstUserProc = false;
System.out.println();
System.out.println("
}
}
for (List<String> parameterSet : Procedures.get(procedure).values()) {
System.out.printf(format, procedure);
String sep = "\t";
for (String paramType : parameterSet) {
System.out.print(sep + paramType);
sep = ", ";
}
System.out.println();
}
}
System.out.println();
}
private static void printConfig(VoltTable configData) {
System.out.println();
System.out.println(String.format("%-20s%-20s%-60s", "NAME", "VALUE", "DESCRIPTION"));
for (int i=0; i<100; i++) {
System.out.print('-');
}
System.out.println();
while (configData.advanceRow()) {
System.out.println(String.format("%-20s%-20s%-60s",
configData.getString(0), configData.getString(1), configData.getString(2)));
}
}
private static void printTables(final String name, final Collection<String> tables)
{
System.out.println();
System.out.println("
for (String table : tables) {
System.out.println(table);
}
System.out.println();
}
/** Adapt BufferedReader into a SQLCommandLineReader */
private static class LineReaderAdapter implements SQLCommandLineReader {
private final BufferedReader m_reader;
LineReaderAdapter(InputStreamReader reader) {
m_reader = new BufferedReader(reader);
}
@Override
public String readBatchLine() throws IOException {
return m_reader.readLine();
}
void close() {
try {
m_reader.close();
} catch (IOException e) { }
}
}
/**
* Reads a script file and executes its content.
* Note that the "script file" could be an inline batch,
* i.e., a "here document" that is coming from the same input stream
* as the "file" directive.
*
* @param fileInfo Info on the file directive being processed
* @param parentLineReader The current input stream, to be used for "here documents".
*/
static void executeScriptFile(FileInfo fileInfo, SQLCommandLineReader parentLineReader)
{
LineReaderAdapter adapter = null;
SQLCommandLineReader reader = null;
if ( ! m_interactive) {
System.out.println();
System.out.println(fileInfo.toString());
}
if (fileInfo.getOption() == FileOption.INLINEBATCH) {
// File command is a "here document" so pass in the current
// input stream.
reader = parentLineReader;
}
else {
try {
reader = adapter = new LineReaderAdapter(new FileReader(fileInfo.getFile()));
}
catch (FileNotFoundException e) {
System.err.println("Script file '" + fileInfo.getFile() + "' could not be found.");
stopOrContinue(e);
return; // continue to the next line after the FILE command
}
}
try {
executeScriptFromReader(fileInfo, reader);
}
catch (Exception x) {
stopOrContinue(x);
}
finally {
if (adapter != null) {
adapter.close();
}
}
}
/**
*
* @param fileInfo The FileInfo object describing the file command (or stdin)
* @param script The line reader object to read from
* @throws Exception
*/
private static void executeScriptFromReader(FileInfo fileInfo, SQLCommandLineReader reader)
throws Exception {
StringBuilder statement = new StringBuilder();
// non-interactive modes need to be more careful about discarding blank lines to
// keep from throwing off diagnostic line numbers. So "statement" may be non-empty even
// when a sql statement has not yet started (?)
boolean statementStarted = false;
StringBuilder batch = fileInfo.isBatch() ? new StringBuilder() : null;
String delimiter = (fileInfo.getOption() == FileOption.INLINEBATCH) ?
fileInfo.getDelimiter() : null;
while (true) {
String line = reader.readBatchLine();
if (delimiter != null) {
if (line == null) {
// We only print this nice message if the inline batch is
// being executed non-interactively. For an inline batch
// entered from the command line, SQLConsoleReader catches
// ctrl-D and exits the process before this code can execute,
// even if this code is in a "finally" block.
throw new Exception("ERROR: Failed to find delimiter \"" + delimiter +
"\" indicating end of inline batch. No batched statements were executed.");
}
if (delimiter.equals(line)) {
line = null;
}
}
if (line == null) {
// No more lines. Execute whatever we got.
if (statement.length() > 0) {
if (batch == null) {
String statementString = statement.toString();
// Trim here avoids a "missing statement" error from adhoc in an edge case
// like a blank line from stdin.
if ( ! statementString.trim().isEmpty()) {
//* enable to debug */if (m_debug) System.out.println("DEBUG QUERY:'" + statementString + "'");
executeStatements(statementString);
}
}
else {
// This means that batch did not end with a semicolon.
// Maybe it ended with a comment.
// For now, treat the final semicolon as optional and
// assume that we are not just adding a partial statement to the batch.
batch.append(statement);
executeDDLBatch(fileInfo.getFilePath(), batch.toString());
}
}
return;
}
if ( ! statementStarted) {
if (line.trim().equals("") || SQLParser.isWholeLineComment(line)) {
// We don't strictly have to include a blank line or whole-line
// comment at the start of a statement, but when we want to preserve line
// numbers (in a batch), we should at least append a newline.
// Whether to echo comments or blank lines from a batch is
// a grey area.
if (batch != null) {
statement.append(line).append("\n");
}
continue;
}
// Recursively process FILE commands, any failure will cause a recursive failure
FileInfo nestedFileInfo = SQLParser.parseFileStatement(fileInfo, line);
if (nestedFileInfo != null) {
// Guards must be added for FILE Batch containing batches.
if (batch != null) {
stopOrContinue(new RuntimeException(
"A FILE command is invalid in a batch."));
continue; // continue to the next line after the FILE command
}
// Execute the file content or fail to but only set m_returningToPromptAfterError
// if the intent is to cause a recursive failure, stopOrContinue decided to stop.
executeScriptFile(nestedFileInfo, reader);
if (m_returningToPromptAfterError) {
// The recursive readScriptFile stopped because of an error.
// Escape to the outermost readScriptFile caller so it can exit or
// return to the interactive prompt.
return;
}
// Continue after a bad nested file command by processing the next line
// in the current file.
continue;
}
// process other non-interactive directives
if (executesAsSimpleDirective(line)) {
continue;
}
// TODO: This would be a reasonable place to validate that the line
// starts with a SQL command keyword, exec/execute or one of the other
// known commands.
// According to the current parsing rules that allow multi-statement
// stacking on a line (as an undocumented feature),
// this work would also have to be repeated after each
// non-quoted non-commented statement-splitting semicolon.
// See executeStatements.
}
// Process normal @AdHoc commands which may be
// multi-line-statement continuations.
statement.append(line).append("\n");
// Check if the current statement ends here and now.
if (SQLParser.isSemiColonTerminated(line)) {
if (batch == null) {
String statementString = statement.toString();
// Trim here avoids a "missing statement" error from adhoc in an edge case
// like a blank line from stdin.
if ( ! statementString.trim().isEmpty()) {
//* enable to debug */ if (m_debug) System.out.println("DEBUG QUERY:'" + statementString + "'");
executeStatements(statementString);
}
statement.setLength(0);
}
statementStarted = false;
}
else {
// Disable directive processing until end of statement.
statementStarted = true;
}
}
}
private static long m_startTime;
// executeQueuedStatements is called instead of executeStatement because
// multiple semicolon-separated statements are allowed on a line and because
// using "line ends with semicolon" is not foolproof as a means of detecting
// the end of a statement. It could give a false negative for something as
// simple as an end-of-line comment.
private static void executeStatements(String statements)
{
List<String> parsedStatements = SQLParser.parseQuery(statements);
for (String statement: parsedStatements) {
executeStatement(statement);
}
}
private static void executeStatement(String statement)
{
if (m_testFrontEndOnly) {
m_testFrontEndResult += statement + ";\n";
return;
}
if ( !m_interactive && m_outputShowMetadata) {
System.out.println();
System.out.println(statement + ";");
}
try {
// EXEC <procedure> <params>...
m_startTime = System.nanoTime();
SQLParser.ExecuteCallResults execCallResults = SQLParser.parseExecuteCall(statement, Procedures);
if (execCallResults != null) {
Object[] objectParams = execCallResults.getParameterObjects();
if (execCallResults.procedure.equals("@UpdateApplicationCatalog")) {
File catfile = null;
if (objectParams[0] != null) {
catfile = new File((String)objectParams[0]);
}
File depfile = null;
if (objectParams[1] != null) {
depfile = new File((String)objectParams[1]);
}
printDdlResponse(m_client.updateApplicationCatalog(catfile, depfile));
// Need to update the stored procedures after a catalog change (could have added/removed SPs!). ENG-3726
loadStoredProcedures(Procedures, Classlist);
}
else if (execCallResults.procedure.equals("@UpdateClasses")) {
File jarfile = null;
if (objectParams[0] != null) {
jarfile = new File((String)objectParams[0]);
}
printDdlResponse(m_client.updateClasses(jarfile, (String)objectParams[1]));
// Need to reload the procedures and classes
loadStoredProcedures(Procedures, Classlist);
}
else {
// @SnapshotDelete needs array parameters.
if (execCallResults.procedure.equals("@SnapshotDelete")) {
objectParams[0] = new String[] { (String)objectParams[0] };
objectParams[1] = new String[] { (String)objectParams[1] };
}
printResponse(callProcedureHelper(execCallResults.procedure, objectParams));
}
return;
}
String explainStatement = SQLParser.parseExplainCall(statement);
if (explainStatement != null) {
// We've got a statement that starts with "explain", send the statement to
// @Explain (after parseExplainCall() strips "explain").
printResponse(m_client.callProcedure("@Explain", explainStatement));
return;
}
String explainProcName = SQLParser.parseExplainProcCall(statement);
if (explainProcName != null) {
// We've got a statement that starts with "explainproc", send the statement to
// @ExplainProc (now that parseExplainProcCall() has stripped out "explainproc").
printResponse(m_client.callProcedure("@ExplainProc", explainProcName));
return;
}
// LOAD CLASS <jar>?
String loadPath = SQLParser.parseLoadClasses(statement);
if (loadPath != null) {
File jarfile = new File(loadPath);
printDdlResponse(m_client.updateClasses(jarfile, null));
loadStoredProcedures(Procedures, Classlist);
return;
}
// REMOVE CLASS <class-selector>?
String classSelector = SQLParser.parseRemoveClasses(statement);
if (classSelector != null) {
printDdlResponse(m_client.updateClasses(null, classSelector));
loadStoredProcedures(Procedures, Classlist);
return;
}
// DDL statements get forwarded to @AdHoc,
// but get special post-processing.
if (SQLParser.queryIsDDL(statement)) {
// if the query is DDL, reload the stored procedures.
printDdlResponse(m_client.callProcedure("@AdHoc", statement));
loadStoredProcedures(Procedures, Classlist);
return;
}
// All other commands get forwarded to @AdHoc
printResponse(callProcedureHelper("@AdHoc", statement));
} catch (Exception exc) {
stopOrContinue(exc);
}
}
private static void stopOrContinue(Exception exc) {
System.err.println(exc.getMessage());
if (m_debug) {
exc.printStackTrace(System.err);
}
// Let the final exit code reflect any error(s) in the run.
// This is useful for debugging a script that may have multiple errors
// and multiple valid statements.
m_exitCode = -1;
if (m_stopOnError) {
if ( ! m_interactive ) {
System.exit(m_exitCode);
}
// Setting this member to drive a fast stack unwind from
// recursive readScriptFile requires explicit checks in that code,
// but still seems easier than a "throw" here from a catch block that
// would require additional exception handlers in the caller(s)
m_returningToPromptAfterError = true;
}
}
// Output generation
private static SQLCommandOutputFormatter m_outputFormatter = new SQLCommandOutputFormatterDefault();
private static boolean m_outputShowMetadata = true;
private static boolean isUpdateResult(VoltTable table)
{
return ((table.getColumnName(0).isEmpty() || table.getColumnName(0).equals("modified_tuples")) &&
table.getRowCount() == 1 && table.getColumnCount() == 1 && table.getColumnType(0) == VoltType.BIGINT);
}
private static void printResponse(ClientResponse response) throws Exception
{
if (response.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Execution Error: " + response.getStatusString());
}
long elapsedTime = System.nanoTime() - m_startTime;
for (VoltTable t : response.getResults()) {
long rowCount;
if (!isUpdateResult(t)) {
rowCount = t.getRowCount();
// Run it through the output formatter.
m_outputFormatter.printTable(System.out, t, m_outputShowMetadata);
//System.out.println("printable");
}
else {
rowCount = t.fetchRow(0).getLong(0);
}
if (m_outputShowMetadata) {
System.out.printf("(Returned %d rows in %.2fs)\n",
rowCount, elapsedTime / 1000000000.0);
}
}
}
private static void printDdlResponse(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Execution Error: " + response.getStatusString());
}
//TODO: In the future, if/when we change the prompt when waiting for the remainder of an unfinished command,
// successful DDL commands may just silently return to a normal prompt without this verbose feedback.
System.out.println("Command succeeded.");
}
// VoltDB connection support
private static Client m_client;
// Default visibility is for test purposes.
static Map<String,Map<Integer, List<String>>> Procedures =
Collections.synchronizedMap(new HashMap<String,Map<Integer, List<String>>>());
private static Map<String, List<Boolean>> Classlist =
Collections.synchronizedMap(new HashMap<String, List<Boolean>>());
private static void loadSystemProcedures()
{
Procedures.put("@Pause",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Quiesce",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Resume",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Shutdown",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@StopNode",
ImmutableMap.<Integer, List<String>>builder().put(1, Arrays.asList("int")).build());
Procedures.put("@SnapshotDelete",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build()
);
Procedures.put("@SnapshotRestore",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar"))
.put( 1, Arrays.asList("varchar")).build()
);
Procedures.put("@SnapshotSave",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>())
.put( 1, Arrays.asList("varchar"))
.put( 3, Arrays.asList("varchar", "varchar", "bit")).build());
Procedures.put("@SnapshotScan",
ImmutableMap.<Integer, List<String>>builder().put( 1,
Arrays.asList("varchar")).build());
Procedures.put("@Statistics",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("statisticscomponent", "bit")).build());
Procedures.put("@SystemCatalog",
ImmutableMap.<Integer, List<String>>builder().put( 1,Arrays.asList("metadataselector")).build());
Procedures.put("@SystemInformation",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("sysinfoselector")).build());
Procedures.put("@UpdateApplicationCatalog",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build());
Procedures.put("@UpdateClasses",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build());
Procedures.put("@UpdateLogging",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@Promote",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@SnapshotStatus",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Explain",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@ExplainProc",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@ValidatePartitioning",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("int", "varbinary")).build());
Procedures.put("@GetPartitionKeys",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@GC",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@ResetDR",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
}
private static Client getClient(ClientConfig config, String[] servers, int port) throws Exception
{
final Client client = ClientFactory.createClient(config);
// Only fail if we can't connect to any servers
boolean connectedAnyServer = false;
String connectionErrorMessages = "";
for (String server : servers) {
try {
client.createConnection(server.trim(), port);
connectedAnyServer = true;
}
catch (UnknownHostException e) {
connectionErrorMessages += "\n " + server.trim() + ":" + port + " - " + e.getMessage();
}
catch (IOException e) {
connectionErrorMessages += "\n " + server.trim() + ":" + port + " - " + e.getMessage();
}
}
if (!connectedAnyServer) {
throw new IOException("Unable to connect to VoltDB cluster" + connectionErrorMessages);
}
return client;
}
// General application support
private static void printUsage(String msg)
{
System.out.print(msg);
System.out.println("\n");
printUsage(-1);
}
private static void printUsage(int exitCode)
{
System.out.println(
"Usage: sqlcmd --help\n"
+ " or sqlcmd [--servers=comma_separated_server_list]\n"
+ " [--port=port_number]\n"
+ " [--user=user]\n"
+ " [--password=password]\n"
+ " [--kerberos=jaas_login_configuration_entry_key]\n"
+ " [--query=query]\n"
+ " [--output-format=(fixed|csv|tab)]\n"
+ " [--output-skip-metadata]\n"
+ " [--stop-on-error=(true|false)]\n"
+ " [--query-timeout=number_of_milliseconds]\n"
+ "\n"
+ "[--servers=comma_separated_server_list]\n"
+ " List of servers to connect to.\n"
+ " Default: localhost.\n"
+ "\n"
+ "[--port=port_number]\n"
+ " Client port to connect to on cluster nodes.\n"
+ " Default: 21212.\n"
+ "\n"
+ "[--user=user]\n"
+ " Name of the user for database login.\n"
+ " Default: (not defined - connection made without credentials).\n"
+ "\n"
+ "[--password=password]\n"
+ " Password of the user for database login.\n"
+ " Default: (not defined - connection made without credentials).\n"
+ "\n"
+ "[--kerberos=jaas_login_configuration_entry_key]\n"
+ " Enable kerberos authentication for user database login by specifying\n"
+ " the JAAS login configuration file entry name"
+ " Default: (not defined - connection made without credentials).\n"
+ "\n"
+ "[--query=query]\n"
+ " Execute a non-interactive query. Multiple query options are allowed.\n"
+ " Default: (runs the interactive shell when no query options are present).\n"
+ "\n"
+ "[--output-format=(fixed|csv|tab)]\n"
+ " Format of returned resultset data (Fixed-width, CSV or Tab-delimited).\n"
+ " Default: fixed.\n"
+ "\n"
+ "[--output-skip-metadata]\n"
+ " Removes metadata information such as column headers and row count from\n"
+ " produced output. Default: metadata output is enabled.\n"
+ "\n"
+ "[--stop-on-error=(true|false)]\n"
+ " Causes the utility to stop immediately or continue after detecting an error.\n"
+ " In interactive mode, a value of \"true\" discards any unprocessed input\n"
+ " and returns to the command prompt. Default: true.\n"
+ "\n"
+ "[--query-timeout=millisecond_number]\n"
+ " Read-only queries that take longer than this number of milliseconds will abort. Default: " + BatchTimeoutOverrideType.DEFAULT_TIMEOUT/1000.0 + " seconds.\n"
+ "\n"
);
System.exit(exitCode);
}
// printHelp() can print readme either to a file or to the screen
// depending on the argument passed in
// Default visibility is for test purposes.
static void printHelp(OutputStream prtStr)
{
try {
InputStream is = SQLCommand.class.getResourceAsStream(m_readme);
while (is.available() > 0) {
byte[] bytes = new byte[is.available()]; // Fix for ENG-3440
is.read(bytes, 0, bytes.length);
prtStr.write(bytes); // For JUnit test
}
}
catch (Exception x) {
System.err.println(x.getMessage());
System.exit(-1);
}
}
private static class Tables
{
TreeSet<String> tables = new TreeSet<String>();
TreeSet<String> exports = new TreeSet<String>();
TreeSet<String> views = new TreeSet<String>();
}
private static Tables getTables() throws Exception
{
Tables tables = new Tables();
VoltTable tableData = m_client.callProcedure("@SystemCatalog", "TABLES").getResults()[0];
while (tableData.advanceRow()) {
String tableName = tableData.getString("TABLE_NAME");
String tableType = tableData.getString("TABLE_TYPE");
if (tableType.equalsIgnoreCase("EXPORT")) {
tables.exports.add(tableName);
}
else if (tableType.equalsIgnoreCase("VIEW")) {
tables.views.add(tableName);
}
else {
tables.tables.add(tableName);
}
}
return tables;
}
private static void loadStoredProcedures(Map<String,Map<Integer, List<String>>> procedures,
Map<String, List<Boolean>> classlist)
{
VoltTable procs = null;
VoltTable params = null;
VoltTable classes = null;
try {
procs = m_client.callProcedure("@SystemCatalog", "PROCEDURES").getResults()[0];
params = m_client.callProcedure("@SystemCatalog", "PROCEDURECOLUMNS").getResults()[0];
classes = m_client.callProcedure("@SystemCatalog", "CLASSES").getResults()[0];
}
catch (NoConnectionsException e) {
e.printStackTrace();
return;
}
catch (IOException e) {
e.printStackTrace();
return;
}
catch (ProcCallException e) {
e.printStackTrace();
return;
}
Map<String, Integer> proc_param_counts = Collections.synchronizedMap(new HashMap<String, Integer>());
while (params.advanceRow()) {
String this_proc = params.getString("PROCEDURE_NAME");
Integer curr_val = proc_param_counts.get(this_proc);
if (curr_val == null) {
curr_val = 1;
}
else {
++curr_val;
}
proc_param_counts.put(this_proc, curr_val);
}
params.resetRowPosition();
Set<String> userProcs = new HashSet<String>();
while (procs.advanceRow()) {
String proc_name = procs.getString("PROCEDURE_NAME");
userProcs.add(proc_name);
Integer param_count = proc_param_counts.get(proc_name);
ArrayList<String> this_params = new ArrayList<String>();
// prepopulate it to make sure the size is right
if (param_count != null) {
for (int i = 0; i < param_count; i++) {
this_params.add(null);
}
}
else {
param_count = 0;
}
HashMap<Integer, List<String>> argLists = new HashMap<Integer, List<String>>();
argLists.put(param_count, this_params);
procedures.put(proc_name, argLists);
}
for (String proc_name : new ArrayList<String>(procedures.keySet())) {
if (!proc_name.startsWith("@") && !userProcs.contains(proc_name)) {
procedures.remove(proc_name);
}
}
classlist.clear();
while (classes.advanceRow()) {
String classname = classes.getString("CLASS_NAME");
boolean isProc = (classes.getLong("VOLT_PROCEDURE") == 1L);
boolean isActive = (classes.getLong("ACTIVE_PROC") == 1L);
if (!classlist.containsKey(classname)) {
List<Boolean> stuff = Collections.synchronizedList(new ArrayList<Boolean>());
stuff.add(isProc);
stuff.add(isActive);
classlist.put(classname, stuff);
}
}
// Retrieve the parameter types. Note we have to do some special checking
// for array types. ENG-3101
params.resetRowPosition();
while (params.advanceRow()) {
Map<Integer, List<String>> argLists = procedures.get(params.getString("PROCEDURE_NAME"));
assert(argLists.size() == 1);
List<String> this_params = argLists.values().iterator().next();
int idx = (int)params.getLong("ORDINAL_POSITION") - 1;
String param_type = params.getString("TYPE_NAME").toLowerCase();
// Detect if this parameter is supposed to be an array. It's kind of clunky, we have to
// look in the remarks column...
String param_remarks = params.getString("REMARKS");
if (null != param_remarks) {
param_type += (param_remarks.equalsIgnoreCase("ARRAY_PARAMETER") ? "_array" : "");
}
this_params.set(idx, param_type);
}
}
/// Parser unit test entry point
///TODO: it would be simpler if this testing entry point could just set up some mocking
/// of io and statement "execution" -- mocking with statement capture instead of actual execution
/// to better isolate the parser.
/// Then it could call a new simplified version of interactWithTheUser().
/// But the current parser tests expect to call a SQLCommand function that can return for
/// some progress checking before its input stream has been permanently terminated.
/// They would need to be able to check parser progress in one thread while
/// SQLCommand.interactWithTheUser() was awaiting further input on another thread
/// (or in its own process).
public static List<String> getParserTestQueries(InputStream inmocked, OutputStream outmocked)
{
testFrontEndOnly();
try {
SQLConsoleReader reader = new SQLConsoleReader(inmocked, outmocked);
getInteractiveQueries(reader);
return SQLParser.parseQuery(m_testFrontEndResult);
} catch (Exception ioe) {}
return null;
}
public static void testFrontEndOnly() {
m_testFrontEndOnly = true;
m_testFrontEndResult = "";
}
public static String getTestResult() { return m_testFrontEndResult; }
private static String extractArgInput(String arg) {
// the input arguments has "=" character when this function is called
String[] splitStrings = arg.split("=", 2);
if (splitStrings[1].isEmpty()) {
printUsage("Missing input value for " + splitStrings[0]);
}
return splitStrings[1];
}
// Application entry point
public static void main(String args[])
{
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
// Initialize parameter defaults
String serverList = "localhost";
int port = 21212;
String user = "";
String password = "";
String kerberos = "";
List<String> queries = null;
String ddlFile = "";
// Parse out parameters
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--servers=")) {
serverList = extractArgInput(arg);
}
else if (arg.startsWith("--port=")) {
port = Integer.valueOf(extractArgInput(arg));
}
else if (arg.startsWith("--user=")) {
user = extractArgInput(arg);
}
else if (arg.startsWith("--password=")) {
password = extractArgInput(arg);
}
else if (arg.startsWith("--kerberos=")) {
kerberos = extractArgInput(arg);
}
else if (arg.startsWith("--kerberos")) {
kerberos = "VoltDBClient";
}
else if (arg.startsWith("--query=")) {
List<String> argQueries = SQLParser.parseQuery(arg.substring(8));
if (!argQueries.isEmpty()) {
if (queries == null) {
queries = argQueries;
}
else {
queries.addAll(argQueries);
}
}
}
else if (arg.startsWith("--output-format=")) {
String formatName = extractArgInput(arg).toLowerCase();
if (formatName.equals("fixed")) {
m_outputFormatter = new SQLCommandOutputFormatterDefault();
}
else if (formatName.equals("csv")) {
m_outputFormatter = new SQLCommandOutputFormatterCSV();
}
else if (formatName.equals("tab")) {
m_outputFormatter = new SQLCommandOutputFormatterTabDelimited();
}
else {
printUsage("Invalid value for --output-format");
}
}
else if (arg.startsWith("--stop-on-error=")) {
String optionName = extractArgInput(arg).toLowerCase();
if (optionName.equals("true")) {
m_stopOnError = true;
}
else if (optionName.equals("false")) {
m_stopOnError = false;
}
else {
printUsage("Invalid value for --stop-on-error");
}
}
else if (arg.startsWith("--ddl-file=")) {
String ddlFilePath = extractArgInput(arg);
try {
ddlFile = new Scanner(new File(ddlFilePath)).useDelimiter("\\Z").next();
} catch (FileNotFoundException e) {
printUsage("DDL file not found at path:" + ddlFilePath);
}
}
else if (arg.startsWith("--query-timeout=")) {
m_hasBatchTimeout = true;
m_batchTimeout = Integer.valueOf(extractArgInput(arg));
}
// equals check starting here
else if (arg.equals("--output-skip-metadata")) {
m_outputShowMetadata = false;
}
else if (arg.equals("--debug")) {
m_debug = true;
}
else if (arg.equals("--help")) {
printHelp(System.out); // Print readme to the screen
System.out.println("\n\n");
printUsage(0);
}
else if (arg.equals("--no-version-check")) {
m_versionCheck = false; // Disable new version phone home check
}
else if ((arg.equals("--usage")) || (arg.equals("-?"))) {
printUsage(0);
}
else {
printUsage("Invalid Parameter: " + arg);
}
}
// Split server list
String[] servers = serverList.split(",");
// Phone home to see if there is a newer version of VoltDB
if (m_versionCheck) {
openURLAsync();
}
try
{
// If we need to prompt the user for a password, do so.
password = CLIConfig.readPasswordIfNeeded(user, password, "Enter password: ");
}
catch (IOException ex)
{
printUsage("Unable to read password: " + ex);
}
// Create connection
ClientConfig config = new ClientConfig(user, password);
config.setProcedureCallTimeout(0); // Set procedure all to infinite timeout, see ENG-2670
try {
// if specified enable kerberos
if (!kerberos.isEmpty()) {
config.enableKerberosAuthentication(kerberos);
}
m_client = getClient(config, servers, port);
} catch (Exception exc) {
System.err.println(exc.getMessage());
System.exit(-1);
}
try {
if (! ddlFile.equals("")) {
// fast DDL Loader mode
// System.out.println("fast DDL Loader mode with DDL input:\n" + ddlFile);
m_client.callProcedure("@AdHoc", ddlFile);
System.exit(m_exitCode);
}
// Load system procedures
loadSystemProcedures();
// Load user stored procs
loadStoredProcedures(Procedures, Classlist);
// Removed code to prevent Ctrl-C from exiting. The original code is visible
// in Git history hash 837df236c059b5b4362ffca7e7a5426fba1b7f20.
m_interactive = true;
if (queries != null && !queries.isEmpty()) {
// If queries are provided via command line options run them in
// non-interactive mode.
//TODO: Someday we should honor batching.
m_interactive = false;
for (String query : queries) {
executeStatement(query);
}
}
// This test for an interactive environment is mostly
// reliable. See stackoverflow.com/questions/1403772.
// It accurately detects when data is piped into the program
// but it fails to distinguish the case when data is ONLY piped
// OUT of the command -- that's a possible but very strange way
// to run an interactive session, so it's OK that we don't support
// it. Instead, in that edge case, we fall back to non-interactive
// mode but IN THAT MODE, we wait on and process user input as if
// from a slow pipe. Strange, but acceptable, and preferable to the
// check used here in the past (System.in.available() > 0)
// which would fail in the opposite direction, when a 0-length
// file was piped in, showing an interactive greeting and prompt
// before quitting.
if (System.console() == null && m_interactive) {
m_interactive = false;
executeNoninteractive();
}
if (m_interactive) {
// Print out welcome message
System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port);
interactWithTheUser();
}
}
catch (Exception x) {
stopOrContinue(x);
}
finally {
try { m_client.close(); } catch (Exception x) { }
}
// Processing may have been continued after one or more errors.
// Reflect them in the exit code.
// This might be a little unconventional for an interactive session,
// but it's also likely to be ignored in that case, so "no great harm done".
//* enable to debug */ System.err.println("Exiting with code " + m_exitCode);
System.exit(m_exitCode);
}
// The following two methods implement a "phone home" version check for VoltDB.
// Asynchronously ping VoltDB to see what the current released version is.
// If it is newer than the one running here, then notify the user in some manner TBD.
// Note that this processing should not impact utility use in any way. Ignore all
// errors.
private static void openURLAsync()
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
openURL();
}
});
// Set the daemon flag so that this won't hang the process if it runs into difficulty
t.setDaemon(true);
t.start();
}
private static void openURL()
{
URL url;
try {
// Read the response from VoltDB
String a="http://community.voltdb.com/versioncheck?app=sqlcmd&ver=" + org.voltdb.VoltDB.instance().getVersionString();
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while (br.readLine() != null) {
// At this time do nothing, just drain the stream.
// In the future we'll notify the user that a new version of VoltDB is available.
}
br.close();
} catch (Throwable e) {
// ignore any error
}
}
}
|
package dr.evomodel.operators;
import dr.evolution.tree.MutableTree;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeModel;
import dr.inference.operators.*;
import dr.math.MathUtils;
import dr.xml.*;
/**
* Implements branch exchange operations.
* There is a NARROW and WIDE variety.
* The narrow exchange is very similar to a rooted-tree
* nearest-neighbour interchange but with the restriction
* that node height must remain consistent.
*
* KNOWN BUGS: WIDE operator cannot be used on trees with 4 or less tips!
*/
public class ExchangeOperator extends SimpleMCMCOperator {
public static final String NARROW_EXCHANGE = "narrowExchange";
public static final String WIDE_EXCHANGE = "wideExchange";
public static final int NARROW = 0;
public static final int WIDE = 1;
private static final int MAX_TRIES = 10000;
private int mode = NARROW;
private TreeModel tree;
public ExchangeOperator(int mode, TreeModel tree, int weight) {
this.mode = mode;
this.tree = tree;
setWeight(weight);
}
public double doOperation() throws OperatorFailedException {
int tipCount = tree.getExternalNodeCount();
switch (mode) {
case NARROW: narrow(); break;
case WIDE: wide(); break;
}
if (tree.getExternalNodeCount() != tipCount) {
throw new RuntimeException("Lost some tips in " + ((mode == NARROW) ? "NARROW mode." : "WIDE mode."));
}
return 0.0;
}
/**
* WARNING: Assumes strictly bifurcating tree.
*/
public void narrow() throws OperatorFailedException {
final int nNodes = tree.getNodeCount();
final NodeRef root = tree.getRoot();
for(int tries = 0; tries < MAX_TRIES; ++tries) {
NodeRef i = tree.getNode(MathUtils.nextInt(nNodes));
while (root == i || tree.getParent(i) == root) {
i = tree.getNode(MathUtils.nextInt(nNodes));
}
final NodeRef iParent = tree.getParent(i);
final NodeRef iGrandParent = tree.getParent(iParent);
NodeRef iUncle = tree.getChild(iGrandParent, 0);
if (iUncle == iParent) {
iUncle = tree.getChild(iGrandParent, 1);
}
assert tree.getNodeHeight(i) < tree.getNodeHeight(iGrandParent);
if ( tree.getNodeHeight(iUncle) < tree.getNodeHeight(iParent) ) {
eupdate(i, iUncle, iParent, iGrandParent);
tree.pushTreeChangedEvent(iParent);
tree.pushTreeChangedEvent(iGrandParent);
return;
}
}
//System.out.println("tries = " + tries);
throw new OperatorFailedException("Couldn't find valid narrow move on this tree!!");
}
/**
* WARNING: Assumes strictly bifurcating tree.
*/
public void wide() throws OperatorFailedException {
final int nodeCount = tree.getNodeCount();
final NodeRef root = tree.getRoot();
// I don't know how to prove this but it seems that there are exactly k(k-1) permissable pairs for k+1
// contemporaneous tips, and since the total is 2k * (2k-1) / 2, so the average number of tries is 2.
// With serial data the average number of tries can be made arbitrarily high as tree becomes less balanced.
for(int tries = 0; tries < MAX_TRIES; ++tries) {
NodeRef i = tree.getNode(MathUtils.nextInt(nodeCount));
while (root == i) {
i = tree.getNode(MathUtils.nextInt(nodeCount));
}
NodeRef j = tree.getNode(MathUtils.nextInt(nodeCount));
while (j == i || j == root) {
j = tree.getNode(MathUtils.nextInt(nodeCount));
}
final NodeRef iP = tree.getParent(i);
final NodeRef jP = tree.getParent(j);
if ((iP != jP) && (i != jP) && (j != iP) &&
(tree.getNodeHeight(j) < tree.getNodeHeight(iP)) &&
(tree.getNodeHeight(i) < tree.getNodeHeight(jP))) {
eupdate(i, j, iP, jP);
//System.out.println("tries = " + tries+1);
return;
}
}
throw new OperatorFailedException("Couldn't find valid wide move on this tree!");
}
public int getMode() {
return mode;
}
public String getOperatorName() {
return ((mode == NARROW) ? "Narrow" : "Wide") + " Exchange";
}
/* exchange subtrees whose root are i and j */
private void eupdate(NodeRef i, NodeRef j, NodeRef iP, NodeRef jP) throws OperatorFailedException {
tree.beginTreeEdit();
tree.removeChild(iP, i);
tree.removeChild(jP, j);
tree.addChild(jP, i);
tree.addChild(iP, j);
try {
tree.endTreeEdit();
} catch(MutableTree.InvalidTreeException ite) {
throw new OperatorFailedException(ite.toString());
}
}
public double getMinimumAcceptanceLevel() { if (mode == NARROW) return 0.05; else return 0.01; }
public double getMinimumGoodAcceptanceLevel() { if (mode == NARROW) return 0.05; else return 0.01; }
public String getPerformanceSuggestion() {
if (MCMCOperator.Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) {
return "";
} else if (MCMCOperator.Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()){
return "";
} else {
return "";
}
}
public static XMLObjectParser NARROW_EXCHANGE_PARSER = new AbstractXMLObjectParser() {
public String getParserName() { return NARROW_EXCHANGE; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
TreeModel treeModel = (TreeModel)xo.getChild(TreeModel.class);
int weight = xo.getIntegerAttribute("weight");
return new ExchangeOperator(NARROW, treeModel, weight);
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mod.hrs.form;
import erp.mod.SModConsts;
import erp.mod.SModSysConsts;
import erp.mod.hrs.db.SDbAbsence;
import erp.mod.hrs.db.SDbAbsenceConsumption;
import erp.mod.hrs.db.SDbBenefitTable;
import erp.mod.hrs.db.SDbDeduction;
import erp.mod.hrs.db.SDbEarning;
import erp.mod.hrs.db.SDbEmployee;
import erp.mod.hrs.db.SDbLoan;
import erp.mod.hrs.db.SDbPayrollReceiptDeduction;
import erp.mod.hrs.db.SDbPayrollReceiptEarning;
import erp.mod.hrs.db.SHrsBenefit;
import erp.mod.hrs.db.SHrsBenefitParams;
import erp.mod.hrs.db.SHrsEmployeeDays;
import erp.mod.hrs.db.SHrsReceipt;
import erp.mod.hrs.db.SHrsReceiptDeduction;
import erp.mod.hrs.db.SHrsReceiptEarning;
import erp.mod.hrs.db.SHrsUtils;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import sa.lib.SLibConsts;
import sa.lib.SLibTimeUtils;
import sa.lib.SLibUtils;
import sa.lib.db.SDbConsts;
import sa.lib.db.SDbRegistry;
import sa.lib.grid.SGridColumnForm;
import sa.lib.grid.SGridConsts;
import sa.lib.grid.SGridPaneForm;
import sa.lib.grid.SGridPaneFormOwner;
import sa.lib.grid.SGridRow;
import sa.lib.gui.SGuiClient;
import sa.lib.gui.SGuiConsts;
import sa.lib.gui.SGuiParams;
import sa.lib.gui.SGuiUtils;
import sa.lib.gui.SGuiValidation;
import sa.lib.gui.bean.SBeanFieldKey;
import sa.lib.gui.bean.SBeanFieldText;
import sa.lib.gui.bean.SBeanFormDialog;
/**
*
* @author Juan Barajas, Sergio Flores
*/
public class SDialogPayrollReceipt extends SBeanFormDialog implements SGridPaneFormOwner, ActionListener, ItemListener, FocusListener, CellEditorListener {
private static final int COL_VAL = 2;
private static final int COL_AMT_UNT = 4;
public static final String LABEL_AUX_AMT = "Monto auxiliar";
public static final String LABEL_AUX_VAL = "Valor auxiliar";
protected SHrsReceipt moHrsReceipt;
protected SHrsBenefit moHrsBenefit;
/** Key: ID of earning. */
protected HashMap<Integer, SDbEarning> moEarnigsMap;
/** Key: ID of deduction. */
protected HashMap<Integer, SDbDeduction> moDeductionsMap;
protected SDbEarning moEarning;
protected SDbDeduction moDeduction;
protected String msOriginalEarningCode;
protected String msOriginalDeductionCode;
protected SGridPaneForm moGridReceiptEarnings;
protected SGridPaneForm moGridReceiptDeductions;
protected SGridPaneForm moGridAbsenceConsumptions;
protected boolean mbEditable;
/**
* Creates new form SDialogPayrollReceipt
* @param client
* @param title
*/
public SDialogPayrollReceipt(SGuiClient client, String title) {
setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.HRS_PAY_RCP, SLibConsts.UNDEFINED, title);
initComponents();
initComponentsCustom();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel12 = new javax.swing.JPanel();
jPanel15 = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jlName = new javax.swing.JLabel();
moTextName = new sa.lib.gui.bean.SBeanFieldText();
moTextNumber = new sa.lib.gui.bean.SBeanFieldText();
jPanel17 = new javax.swing.JPanel();
jlPaymentType = new javax.swing.JLabel();
moTextPaymentType = new sa.lib.gui.bean.SBeanFieldText();
jlDateBirth = new javax.swing.JLabel();
moTextDateBirth = new sa.lib.gui.bean.SBeanFieldText();
jlDepartament = new javax.swing.JLabel();
moTextDepartament = new sa.lib.gui.bean.SBeanFieldText();
jlSalaryType = new javax.swing.JLabel();
moTextSalaryType = new sa.lib.gui.bean.SBeanFieldText();
jlFiscalId = new javax.swing.JLabel();
moTextFiscalId = new sa.lib.gui.bean.SBeanFieldText();
jPanel29 = new javax.swing.JPanel();
jlSalary = new javax.swing.JLabel();
moDecSalary = new sa.lib.gui.bean.SBeanFieldDecimal();
jlDateBenefits = new javax.swing.JLabel();
moTextDateBenefits = new sa.lib.gui.bean.SBeanFieldText();
jlPosition = new javax.swing.JLabel();
moTextPosition = new sa.lib.gui.bean.SBeanFieldText();
jlEmployeeType = new javax.swing.JLabel();
moTextEmployeeType = new sa.lib.gui.bean.SBeanFieldText();
jlAlternativeId = new javax.swing.JLabel();
moTextAlternativeId = new sa.lib.gui.bean.SBeanFieldText();
jPanel18 = new javax.swing.JPanel();
jlWage = new javax.swing.JLabel();
moDecWage = new sa.lib.gui.bean.SBeanFieldDecimal();
jlDateLastHire = new javax.swing.JLabel();
moTextDateLastHire = new sa.lib.gui.bean.SBeanFieldText();
jlShift = new javax.swing.JLabel();
moTextShift = new sa.lib.gui.bean.SBeanFieldText();
jlWorkerType = new javax.swing.JLabel();
moTextWorkerType = new sa.lib.gui.bean.SBeanFieldText();
jlSocialSecurityNumber = new javax.swing.JLabel();
moTextSocialSecurityNumber = new sa.lib.gui.bean.SBeanFieldText();
jPanel19 = new javax.swing.JPanel();
jlSalarySscBase = new javax.swing.JLabel();
moDecSalarySscBase = new sa.lib.gui.bean.SBeanFieldDecimal();
jlDateLastDismissal_n = new javax.swing.JLabel();
moTextDateLastDismissal_n = new sa.lib.gui.bean.SBeanFieldText();
jlWorkingHoursDay = new javax.swing.JLabel();
moIntWorkingHoursDay = new sa.lib.gui.bean.SBeanFieldInteger();
jLabel1 = new javax.swing.JLabel();
jlRecruitmentSchemeType = new javax.swing.JLabel();
moTextRecruitmentSchemeType = new sa.lib.gui.bean.SBeanFieldText();
jPanel14 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jpEarnings = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
moTextEarningCode = new sa.lib.gui.bean.SBeanFieldText();
jbPickEarning = new javax.swing.JButton();
moTextEarningName = new sa.lib.gui.bean.SBeanFieldText();
jPanel28 = new javax.swing.JPanel();
jlEarningLoan_n1 = new javax.swing.JLabel();
moKeyEarningOtherPaymentType = new sa.lib.gui.bean.SBeanFieldKey();
jPanel2 = new javax.swing.JPanel();
jlEarningLoan_n = new javax.swing.JLabel();
moKeyEarningLoan_n = new sa.lib.gui.bean.SBeanFieldKey();
jPanel25 = new javax.swing.JPanel();
jlEarningValue = new javax.swing.JLabel();
moCompEarningValue = new sa.lib.gui.bean.SBeanCompoundField();
jLabel2 = new javax.swing.JLabel();
jlEarningAuxAmount1 = new javax.swing.JLabel();
moCurEarningAuxAmount1 = new sa.lib.gui.bean.SBeanCompoundFieldCurrency();
jlEarningAuxAmount1Hint = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
jbAddEarning = new javax.swing.JButton();
jPanel27 = new javax.swing.JPanel();
jlEarningAuxValue = new javax.swing.JLabel();
moCompEarningAuxValue = new sa.lib.gui.bean.SBeanCompoundField();
jlEarningAuxValueHint = new javax.swing.JLabel();
jlEarningAuxAmount2 = new javax.swing.JLabel();
moCurEarningAuxAmount2 = new sa.lib.gui.bean.SBeanCompoundFieldCurrency();
jlEarningAuxAmount2Hint = new javax.swing.JLabel();
jpDeductions = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
moTextDeductionCode = new sa.lib.gui.bean.SBeanFieldText();
jbPickDeduction = new javax.swing.JButton();
moTextDeductionName = new sa.lib.gui.bean.SBeanFieldText();
jPanel30 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jlDeductionLoan_n = new javax.swing.JLabel();
moKeyDeductionLoan_n = new sa.lib.gui.bean.SBeanFieldKey();
jPanel26 = new javax.swing.JPanel();
jlDeductionValue = new javax.swing.JLabel();
moCompDeductionValue = new sa.lib.gui.bean.SBeanCompoundField();
jPanel11 = new javax.swing.JPanel();
jbAddDeduction = new javax.swing.JButton();
jPanel21 = new javax.swing.JPanel();
jPanel20 = new javax.swing.JPanel();
jpAbsenceConsumption = new javax.swing.JPanel();
jPanel13 = new javax.swing.JPanel();
jPanel22 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jlEarningsTotal = new javax.swing.JLabel();
moCurEarningsTotal = new sa.lib.gui.bean.SBeanCompoundFieldCurrency();
jPanel23 = new javax.swing.JPanel();
jlDeductionsTotal = new javax.swing.JLabel();
moCurDeductionsTotal = new sa.lib.gui.bean.SBeanCompoundFieldCurrency();
jPanel24 = new javax.swing.JPanel();
jlNetTotal = new javax.swing.JLabel();
moCurNetTotal = new sa.lib.gui.bean.SBeanCompoundFieldCurrency();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Recibo de nómina");
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel12.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del empleado:"));
jPanel12.setLayout(new java.awt.BorderLayout());
jPanel15.setLayout(new java.awt.GridLayout(5, 1, 0, 5));
jPanel16.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlName.setText("Nombre:");
jlName.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel16.add(jlName);
moTextName.setEditable(false);
moTextName.setText("TEXT");
moTextName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
moTextName.setPreferredSize(new java.awt.Dimension(350, 23));
jPanel16.add(moTextName);
moTextNumber.setEditable(false);
moTextNumber.setText("TEXT");
moTextNumber.setToolTipText("Clave");
moTextNumber.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
moTextNumber.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel16.add(moTextNumber);
jPanel15.add(jPanel16);
jPanel17.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlPaymentType.setText("Período pago:");
jlPaymentType.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel17.add(jlPaymentType);
moTextPaymentType.setEditable(false);
moTextPaymentType.setText("TEXT");
moTextPaymentType.setPreferredSize(new java.awt.Dimension(85, 23));
jPanel17.add(moTextPaymentType);
jlDateBirth.setText("Nacimiento:");
jlDateBirth.setPreferredSize(new java.awt.Dimension(90, 23));
jPanel17.add(jlDateBirth);
moTextDateBirth.setEditable(false);
moTextDateBirth.setText("TEXT");
moTextDateBirth.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel17.add(moTextDateBirth);
jlDepartament.setText("Departamento:");
jlDepartament.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel17.add(jlDepartament);
moTextDepartament.setEditable(false);
moTextDepartament.setText("TEXT");
moTextDepartament.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel17.add(moTextDepartament);
jlSalaryType.setText("Tipo salario:");
jlSalaryType.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel17.add(jlSalaryType);
moTextSalaryType.setEditable(false);
moTextSalaryType.setText("TEXT");
jPanel17.add(moTextSalaryType);
jlFiscalId.setText("RFC:");
jlFiscalId.setPreferredSize(new java.awt.Dimension(40, 23));
jPanel17.add(jlFiscalId);
moTextFiscalId.setEditable(false);
moTextFiscalId.setText("XAXX010101000");
moTextFiscalId.setPreferredSize(new java.awt.Dimension(105, 23));
jPanel17.add(moTextFiscalId);
jPanel15.add(jPanel17);
jPanel29.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlSalary.setText("Salario diario:");
jlSalary.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel29.add(jlSalary);
moDecSalary.setEditable(false);
moDecSalary.setPreferredSize(new java.awt.Dimension(85, 23));
jPanel29.add(moDecSalary);
jlDateBenefits.setText("Inicio beneficios:");
jlDateBenefits.setPreferredSize(new java.awt.Dimension(90, 23));
jPanel29.add(jlDateBenefits);
moTextDateBenefits.setEditable(false);
moTextDateBenefits.setText("TEXT");
moTextDateBenefits.setToolTipText("");
moTextDateBenefits.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel29.add(moTextDateBenefits);
jlPosition.setText("Puesto:");
jlPosition.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel29.add(jlPosition);
moTextPosition.setEditable(false);
moTextPosition.setText("TEXT");
moTextPosition.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel29.add(moTextPosition);
jlEmployeeType.setText("Tipo empleado:");
jlEmployeeType.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel29.add(jlEmployeeType);
moTextEmployeeType.setEditable(false);
moTextEmployeeType.setText("TEXT");
jPanel29.add(moTextEmployeeType);
jlAlternativeId.setText("CURP:");
jlAlternativeId.setPreferredSize(new java.awt.Dimension(40, 23));
jPanel29.add(jlAlternativeId);
moTextAlternativeId.setEditable(false);
moTextAlternativeId.setText("XAXX010101XXXXXX00");
moTextAlternativeId.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel29.add(moTextAlternativeId);
jPanel15.add(jPanel29);
jPanel18.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlWage.setText("Sueldo mensual:");
jlWage.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel18.add(jlWage);
moDecWage.setEditable(false);
moDecWage.setText("0");
moDecWage.setPreferredSize(new java.awt.Dimension(85, 23));
jPanel18.add(moDecWage);
jlDateLastHire.setText("Última alta:");
jlDateLastHire.setPreferredSize(new java.awt.Dimension(90, 23));
jPanel18.add(jlDateLastHire);
moTextDateLastHire.setEditable(false);
moTextDateLastHire.setText("TEXT");
moTextDateLastHire.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel18.add(moTextDateLastHire);
jlShift.setText("Turno:");
jlShift.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel18.add(jlShift);
moTextShift.setEditable(false);
moTextShift.setText("TEXT");
moTextShift.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel18.add(moTextShift);
jlWorkerType.setText("Tipo obrero:");
jlWorkerType.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel18.add(jlWorkerType);
moTextWorkerType.setEditable(false);
moTextWorkerType.setText("TEXT");
jPanel18.add(moTextWorkerType);
jlSocialSecurityNumber.setText("NSS:");
jlSocialSecurityNumber.setPreferredSize(new java.awt.Dimension(40, 23));
jPanel18.add(jlSocialSecurityNumber);
moTextSocialSecurityNumber.setEditable(false);
moTextSocialSecurityNumber.setText("00000000000");
moTextSocialSecurityNumber.setPreferredSize(new java.awt.Dimension(85, 23));
jPanel18.add(moTextSocialSecurityNumber);
jPanel15.add(jPanel18);
jPanel19.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlSalarySscBase.setText("SBC:");
jlSalarySscBase.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel19.add(jlSalarySscBase);
moDecSalarySscBase.setEditable(false);
moDecSalarySscBase.setPreferredSize(new java.awt.Dimension(85, 23));
jPanel19.add(moDecSalarySscBase);
jlDateLastDismissal_n.setText("Última baja:");
jlDateLastDismissal_n.setPreferredSize(new java.awt.Dimension(90, 23));
jPanel19.add(jlDateLastDismissal_n);
moTextDateLastDismissal_n.setEditable(false);
moTextDateLastDismissal_n.setText("TEXT");
moTextDateLastDismissal_n.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel19.add(moTextDateLastDismissal_n);
jlWorkingHoursDay.setText("Horas jornada:");
jlWorkingHoursDay.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel19.add(jlWorkingHoursDay);
moIntWorkingHoursDay.setEditable(false);
moIntWorkingHoursDay.setPreferredSize(new java.awt.Dimension(50, 23));
jPanel19.add(moIntWorkingHoursDay);
jLabel1.setPreferredSize(new java.awt.Dimension(120, 23));
jPanel19.add(jLabel1);
jlRecruitmentSchemeType.setText("Régimen:");
jlRecruitmentSchemeType.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel19.add(jlRecruitmentSchemeType);
moTextRecruitmentSchemeType.setEditable(false);
moTextRecruitmentSchemeType.setText("TEXT");
moTextRecruitmentSchemeType.setPreferredSize(new java.awt.Dimension(275, 23));
jPanel19.add(moTextRecruitmentSchemeType);
jPanel15.add(jPanel19);
jPanel12.add(jPanel15, java.awt.BorderLayout.CENTER);
jPanel1.add(jPanel12, java.awt.BorderLayout.NORTH);
jPanel14.setLayout(new java.awt.BorderLayout());
jPanel4.setPreferredSize(new java.awt.Dimension(100, 325));
jPanel4.setLayout(new java.awt.BorderLayout());
jpEarnings.setBorder(javax.swing.BorderFactory.createTitledBorder("Percepciones:"));
jpEarnings.setLayout(new java.awt.BorderLayout());
jPanel6.setLayout(new java.awt.GridLayout(5, 1, 0, 5));
jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
moTextEarningCode.setText("TEXT");
moTextEarningCode.setToolTipText("Código percepción");
moTextEarningCode.setPreferredSize(new java.awt.Dimension(72, 23));
jPanel8.add(moTextEarningCode);
jbPickEarning.setText("...");
jbPickEarning.setToolTipText("Seleccionar percepción");
jbPickEarning.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel8.add(jbPickEarning);
moTextEarningName.setEditable(false);
moTextEarningName.setText("TEXT");
moTextEarningName.setToolTipText("Nombre percepción");
moTextEarningName.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel8.add(moTextEarningName);
jPanel6.add(jPanel8);
jPanel28.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlEarningLoan_n1.setText("Tipo otro pago:*");
jlEarningLoan_n1.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel28.add(jlEarningLoan_n1);
moKeyEarningOtherPaymentType.setToolTipText("Tipo otro pago");
moKeyEarningOtherPaymentType.setPreferredSize(new java.awt.Dimension(450, 23));
jPanel28.add(moKeyEarningOtherPaymentType);
jPanel6.add(jPanel28);
jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlEarningLoan_n.setText("Crédito/préstamo:*");
jlEarningLoan_n.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel2.add(jlEarningLoan_n);
moKeyEarningLoan_n.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel2.add(moKeyEarningLoan_n);
jPanel6.add(jPanel2);
jPanel25.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlEarningValue.setText("Cantidad/monto:");
jlEarningValue.setToolTipText("");
jlEarningValue.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel25.add(jlEarningValue);
moCompEarningValue.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel25.add(moCompEarningValue);
jLabel2.setPreferredSize(new java.awt.Dimension(15, 23));
jPanel25.add(jLabel2);
jlEarningAuxAmount1.setText("Monto auxiliar:");
jlEarningAuxAmount1.setToolTipText("");
jlEarningAuxAmount1.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel25.add(jlEarningAuxAmount1);
moCurEarningAuxAmount1.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel25.add(moCurEarningAuxAmount1);
jlEarningAuxAmount1Hint.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jlEarningAuxAmount1Hint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N
jlEarningAuxAmount1Hint.setToolTipText("Monto auxiliar");
jlEarningAuxAmount1Hint.setPreferredSize(new java.awt.Dimension(15, 23));
jPanel25.add(jlEarningAuxAmount1Hint);
jPanel6.add(jPanel25);
jPanel10.setLayout(new java.awt.BorderLayout());
jbAddEarning.setText("Agregar");
jbAddEarning.setMargin(new java.awt.Insets(2, 0, 2, 0));
jbAddEarning.setPreferredSize(new java.awt.Dimension(65, 23));
jPanel10.add(jbAddEarning, java.awt.BorderLayout.EAST);
jPanel27.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlEarningAuxValue.setText("Valor auxiliar:");
jlEarningAuxValue.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel27.add(jlEarningAuxValue);
moCompEarningAuxValue.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel27.add(moCompEarningAuxValue);
jlEarningAuxValueHint.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jlEarningAuxValueHint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N
jlEarningAuxValueHint.setToolTipText("Monto auxiliar");
jlEarningAuxValueHint.setPreferredSize(new java.awt.Dimension(15, 23));
jPanel27.add(jlEarningAuxValueHint);
jlEarningAuxAmount2.setText("Monto auxiliar:");
jlEarningAuxAmount2.setToolTipText("");
jlEarningAuxAmount2.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel27.add(jlEarningAuxAmount2);
moCurEarningAuxAmount2.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel27.add(moCurEarningAuxAmount2);
jlEarningAuxAmount2Hint.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jlEarningAuxAmount2Hint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N
jlEarningAuxAmount2Hint.setToolTipText("Monto auxiliar");
jlEarningAuxAmount2Hint.setPreferredSize(new java.awt.Dimension(15, 23));
jPanel27.add(jlEarningAuxAmount2Hint);
jPanel10.add(jPanel27, java.awt.BorderLayout.CENTER);
jPanel6.add(jPanel10);
jpEarnings.add(jPanel6, java.awt.BorderLayout.NORTH);
jPanel4.add(jpEarnings, java.awt.BorderLayout.CENTER);
jpDeductions.setBorder(javax.swing.BorderFactory.createTitledBorder("Deducciones:"));
jpDeductions.setPreferredSize(new java.awt.Dimension(425, 1));
jpDeductions.setLayout(new java.awt.BorderLayout());
jPanel7.setLayout(new java.awt.GridLayout(5, 1, 0, 5));
jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
moTextDeductionCode.setText("TEXT");
moTextDeductionCode.setToolTipText("Código deducción");
moTextDeductionCode.setPreferredSize(new java.awt.Dimension(72, 23));
jPanel9.add(moTextDeductionCode);
jbPickDeduction.setText("...");
jbPickDeduction.setToolTipText("Seleccionar deducción");
jbPickDeduction.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel9.add(jbPickDeduction);
moTextDeductionName.setEditable(false);
moTextDeductionName.setText("TEXT");
moTextDeductionName.setToolTipText("Nombre deducción");
moTextDeductionName.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel9.add(moTextDeductionName);
jPanel7.add(jPanel9);
jPanel30.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jPanel7.add(jPanel30);
jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlDeductionLoan_n.setText("Crédito/préstamo:*");
jlDeductionLoan_n.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel3.add(jlDeductionLoan_n);
moKeyDeductionLoan_n.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel3.add(moKeyDeductionLoan_n);
jPanel7.add(jPanel3);
jPanel26.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0));
jlDeductionValue.setText("Cantidad/monto:");
jlDeductionValue.setToolTipText("");
jlDeductionValue.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel26.add(jlDeductionValue);
moCompDeductionValue.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel26.add(moCompDeductionValue);
jPanel7.add(jPanel26);
jPanel11.setLayout(new java.awt.BorderLayout());
jbAddDeduction.setText("Agregar");
jbAddDeduction.setMargin(new java.awt.Insets(2, 0, 2, 0));
jbAddDeduction.setPreferredSize(new java.awt.Dimension(65, 23));
jPanel11.add(jbAddDeduction, java.awt.BorderLayout.EAST);
jPanel21.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jPanel11.add(jPanel21, java.awt.BorderLayout.CENTER);
jPanel7.add(jPanel11);
jpDeductions.add(jPanel7, java.awt.BorderLayout.NORTH);
jPanel4.add(jpDeductions, java.awt.BorderLayout.EAST);
jPanel14.add(jPanel4, java.awt.BorderLayout.NORTH);
jPanel20.setLayout(new java.awt.BorderLayout());
jpAbsenceConsumption.setBorder(javax.swing.BorderFactory.createTitledBorder("Consumo incidencias:"));
jpAbsenceConsumption.setLayout(new java.awt.BorderLayout());
jPanel20.add(jpAbsenceConsumption, java.awt.BorderLayout.CENTER);
jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder("Totales:"));
jPanel13.setLayout(new java.awt.BorderLayout());
jPanel22.setLayout(new java.awt.GridLayout(3, 1, 0, 5));
jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.TRAILING, 5, 0));
jlEarningsTotal.setText("Total percepciones:");
jlEarningsTotal.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel5.add(jlEarningsTotal);
moCurEarningsTotal.setEditable(false);
jPanel5.add(moCurEarningsTotal);
jPanel22.add(jPanel5);
jPanel23.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.TRAILING, 5, 0));
jlDeductionsTotal.setText("Total deducciones:");
jlDeductionsTotal.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel23.add(jlDeductionsTotal);
moCurDeductionsTotal.setEditable(false);
jPanel23.add(moCurDeductionsTotal);
jPanel22.add(jPanel23);
jPanel24.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.TRAILING, 5, 0));
jlNetTotal.setText("Total neto:");
jlNetTotal.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel24.add(jlNetTotal);
moCurNetTotal.setEditable(false);
jPanel24.add(moCurNetTotal);
jPanel22.add(jPanel24);
jPanel13.add(jPanel22, java.awt.BorderLayout.SOUTH);
jPanel20.add(jPanel13, java.awt.BorderLayout.EAST);
jPanel14.add(jPanel20, java.awt.BorderLayout.CENTER);
jPanel1.add(jPanel14, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel22;
private javax.swing.JPanel jPanel23;
private javax.swing.JPanel jPanel24;
private javax.swing.JPanel jPanel25;
private javax.swing.JPanel jPanel26;
private javax.swing.JPanel jPanel27;
private javax.swing.JPanel jPanel28;
private javax.swing.JPanel jPanel29;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel30;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JButton jbAddDeduction;
private javax.swing.JButton jbAddEarning;
private javax.swing.JButton jbPickDeduction;
private javax.swing.JButton jbPickEarning;
private javax.swing.JLabel jlAlternativeId;
private javax.swing.JLabel jlDateBenefits;
private javax.swing.JLabel jlDateBirth;
private javax.swing.JLabel jlDateLastDismissal_n;
private javax.swing.JLabel jlDateLastHire;
private javax.swing.JLabel jlDeductionLoan_n;
private javax.swing.JLabel jlDeductionValue;
private javax.swing.JLabel jlDeductionsTotal;
private javax.swing.JLabel jlDepartament;
private javax.swing.JLabel jlEarningAuxAmount1;
private javax.swing.JLabel jlEarningAuxAmount1Hint;
private javax.swing.JLabel jlEarningAuxAmount2;
private javax.swing.JLabel jlEarningAuxAmount2Hint;
private javax.swing.JLabel jlEarningAuxValue;
private javax.swing.JLabel jlEarningAuxValueHint;
private javax.swing.JLabel jlEarningLoan_n;
private javax.swing.JLabel jlEarningLoan_n1;
private javax.swing.JLabel jlEarningValue;
private javax.swing.JLabel jlEarningsTotal;
private javax.swing.JLabel jlEmployeeType;
private javax.swing.JLabel jlFiscalId;
private javax.swing.JLabel jlName;
private javax.swing.JLabel jlNetTotal;
private javax.swing.JLabel jlPaymentType;
private javax.swing.JLabel jlPosition;
private javax.swing.JLabel jlRecruitmentSchemeType;
private javax.swing.JLabel jlSalary;
private javax.swing.JLabel jlSalarySscBase;
private javax.swing.JLabel jlSalaryType;
private javax.swing.JLabel jlShift;
private javax.swing.JLabel jlSocialSecurityNumber;
private javax.swing.JLabel jlWage;
private javax.swing.JLabel jlWorkerType;
private javax.swing.JLabel jlWorkingHoursDay;
private javax.swing.JPanel jpAbsenceConsumption;
private javax.swing.JPanel jpDeductions;
private javax.swing.JPanel jpEarnings;
private sa.lib.gui.bean.SBeanCompoundField moCompDeductionValue;
private sa.lib.gui.bean.SBeanCompoundField moCompEarningAuxValue;
private sa.lib.gui.bean.SBeanCompoundField moCompEarningValue;
private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurDeductionsTotal;
private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurEarningAuxAmount1;
private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurEarningAuxAmount2;
private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurEarningsTotal;
private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurNetTotal;
private sa.lib.gui.bean.SBeanFieldDecimal moDecSalary;
private sa.lib.gui.bean.SBeanFieldDecimal moDecSalarySscBase;
private sa.lib.gui.bean.SBeanFieldDecimal moDecWage;
private sa.lib.gui.bean.SBeanFieldInteger moIntWorkingHoursDay;
private sa.lib.gui.bean.SBeanFieldKey moKeyDeductionLoan_n;
private sa.lib.gui.bean.SBeanFieldKey moKeyEarningLoan_n;
private sa.lib.gui.bean.SBeanFieldKey moKeyEarningOtherPaymentType;
private sa.lib.gui.bean.SBeanFieldText moTextAlternativeId;
private sa.lib.gui.bean.SBeanFieldText moTextDateBenefits;
private sa.lib.gui.bean.SBeanFieldText moTextDateBirth;
private sa.lib.gui.bean.SBeanFieldText moTextDateLastDismissal_n;
private sa.lib.gui.bean.SBeanFieldText moTextDateLastHire;
private sa.lib.gui.bean.SBeanFieldText moTextDeductionCode;
private sa.lib.gui.bean.SBeanFieldText moTextDeductionName;
private sa.lib.gui.bean.SBeanFieldText moTextDepartament;
private sa.lib.gui.bean.SBeanFieldText moTextEarningCode;
private sa.lib.gui.bean.SBeanFieldText moTextEarningName;
private sa.lib.gui.bean.SBeanFieldText moTextEmployeeType;
private sa.lib.gui.bean.SBeanFieldText moTextFiscalId;
private sa.lib.gui.bean.SBeanFieldText moTextName;
private sa.lib.gui.bean.SBeanFieldText moTextNumber;
private sa.lib.gui.bean.SBeanFieldText moTextPaymentType;
private sa.lib.gui.bean.SBeanFieldText moTextPosition;
private sa.lib.gui.bean.SBeanFieldText moTextRecruitmentSchemeType;
private sa.lib.gui.bean.SBeanFieldText moTextSalaryType;
private sa.lib.gui.bean.SBeanFieldText moTextShift;
private sa.lib.gui.bean.SBeanFieldText moTextSocialSecurityNumber;
private sa.lib.gui.bean.SBeanFieldText moTextWorkerType;
// End of variables declaration//GEN-END:variables
private void initComponentsCustom() {
SGuiUtils.setWindowBounds(this, 1024, 672); // aspect ratio: 0.65625 instead of standard 0.625
jbSave.setText("Aceptar");
moTextName.setTextSettings(SGuiUtils.getLabelName(jlName), 202);
moTextNumber.setTextSettings(SGuiUtils.getLabelName(jlName), 10);
moTextPaymentType.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moDecSalary.setDecimalSettings(SGuiUtils.getLabelName(jlSalary), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moDecWage.setDecimalSettings(SGuiUtils.getLabelName(jlWage), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moDecSalarySscBase.setDecimalSettings(SGuiUtils.getLabelName(jlSalarySscBase), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moTextDateBirth.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moTextDateBenefits.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moTextDateLastHire.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moTextDateLastDismissal_n.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moTextDepartament.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moTextPosition.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moTextShift.setTextSettings(SGuiUtils.getLabelName(jlName), 50);
moIntWorkingHoursDay.setIntegerSettings(SGuiUtils.getLabelName(jlName), SGuiConsts.GUI_TYPE_INT, false);
moTextSalaryType.setTextSettings(SGuiUtils.getLabelName(jlName), 100);
moTextEmployeeType.setTextSettings(SGuiUtils.getLabelName(jlName), 100);
moTextWorkerType.setTextSettings(SGuiUtils.getLabelName(jlName), 100);
moTextRecruitmentSchemeType.setTextSettings(SGuiUtils.getLabelName(jlName), 100);
moTextFiscalId.setTextSettings(SGuiUtils.getLabelName(jlName), 25);
moTextAlternativeId.setTextSettings(SGuiUtils.getLabelName(jlName), 25);
moTextSocialSecurityNumber.setTextSettings(SGuiUtils.getLabelName(jlName), 25);
moTextEarningCode.setTextSettings(SGuiUtils.getLabelName(moTextEarningCode.getToolTipText()), 10, 0);
moTextEarningCode.setFieldButton(jbPickEarning);
moTextEarningName.setTextSettings(SGuiUtils.getLabelName(moTextEarningName.getToolTipText()), 100, 0);
moKeyEarningOtherPaymentType.setKeySettings(miClient, SGuiUtils.getLabelName(moKeyEarningOtherPaymentType.getToolTipText()), true);
moKeyEarningLoan_n.setKeySettings(miClient, SGuiUtils.getLabelName(jlEarningLoan_n), true);
moCompEarningValue.setCompoundFieldSettings(miClient);
moCompEarningValue.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningValue), SGuiConsts.GUI_TYPE_DEC_QTY, false); // yes!, is NOT mandatory!
moCompEarningAuxValue.setCompoundFieldSettings(miClient);
moCompEarningAuxValue.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningAuxValue), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moCurEarningAuxAmount1.setCompoundFieldSettings(miClient);
moCurEarningAuxAmount1.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningAuxAmount1), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moCurEarningAuxAmount2.setCompoundFieldSettings(miClient);
moCurEarningAuxAmount2.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningAuxAmount2), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moTextDeductionCode.setTextSettings(SGuiUtils.getLabelName(moTextDeductionCode.getToolTipText()), 10, 0);
moTextDeductionCode.setFieldButton(jbPickDeduction);
moTextDeductionName.setTextSettings(SGuiUtils.getLabelName(moTextDeductionName.getToolTipText()), 100, 0);
moKeyDeductionLoan_n.setKeySettings(miClient, SGuiUtils.getLabelName(jlDeductionLoan_n), true);
moCompDeductionValue.setCompoundFieldSettings(miClient);
moCompDeductionValue.getField().setDecimalSettings(SGuiUtils.getLabelName(jlDeductionValue), SGuiConsts.GUI_TYPE_DEC_QTY, false); // yes!, is NOT mandatory!
moCurEarningsTotal.setCompoundFieldSettings(miClient);
moCurEarningsTotal.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningsTotal), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moCurDeductionsTotal.setCompoundFieldSettings(miClient);
moCurDeductionsTotal.getField().setDecimalSettings(SGuiUtils.getLabelName(jlDeductionsTotal), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moCurNetTotal.setCompoundFieldSettings(miClient);
moCurNetTotal.getField().setDecimalSettings(SGuiUtils.getLabelName(jlNetTotal), SGuiConsts.GUI_TYPE_DEC_AMT, false);
moFields.addField(moTextEarningCode);
moFields.addField(moTextEarningName);
moFields.addField(moKeyEarningOtherPaymentType);
moFields.addField(moKeyEarningLoan_n);
moFields.addField(moCompEarningValue.getField());
moFields.addField(moCompEarningAuxValue.getField());
moFields.addField(moCurEarningAuxAmount1.getField());
moFields.addField(moCurEarningAuxAmount2.getField());
moFields.addField(moTextDeductionCode);
moFields.addField(moTextDeductionName);
moFields.addField(moKeyDeductionLoan_n);
moFields.addField(moCompDeductionValue.getField());
moFields.setFormButton(jbSave);
// prevent from sending focus to next field when key 'enter' pressed:
moTextEarningCode.setNextField(null);
moTextDeductionCode.setNextField(null);
resetFieldsEarning();
resetFieldsDeduction();
mbEditable = true;
setEnableFields(mbEditable);
moGridReceiptEarnings = new SGridPaneForm(miClient, SModConsts.HRSX_PAY_REC_EAR, SLibConsts.UNDEFINED, "Percepciones") {
@Override
public void initGrid() {
setRowButtonsEnabled(false, true, true);
}
@Override
public ArrayList<SGridColumnForm> createGridColumns() {
SGridColumnForm columnForm;
ArrayList<SGridColumnForm> gridColumnsForm = new ArrayList<>();
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_INT_1B, "
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_S, "Percepción", 125));
columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Cantidad", 55);
columnForm.setEditable(mbEditable);
gridColumnsForm.add(columnForm);
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_UNT, "Unidad", 45));
columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto unitario $", 80);
columnForm.setEditable(mbEditable);
gridColumnsForm.add(columnForm);
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto $", 80));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Cantidad ajustada", 55));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_UNT, "Unidad", 45));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Parte exenta $", 80));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Parte gravada $", 80));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_M, "Crédito/préstamo"));
return gridColumnsForm;
}
@Override
public void actionRowEdit() {
if (jbRowEdit.isEnabled()) {
try {
SHrsReceiptEarning hrsReceiptEarning = (SHrsReceiptEarning) moGridReceiptEarnings.getSelectedGridRow();
SDialogPayrollEarning dlgPayrollEarning = new SDialogPayrollEarning(miClient, hrsReceiptEarning.clone(), "Percepción");
dlgPayrollEarning.setVisible(true);
if (dlgPayrollEarning.getFormResult() == SGuiConsts.FORM_RESULT_OK) {
refreshReceiptMovements();
}
}
catch (Exception e) {
SLibUtils.printException(this, e);
}
}
}
@Override
public void actionRowDelete() {
if (jbRowDelete.isEnabled()) {
if (jtTable.getSelectedRowCount() != 1) {
miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW);
}
else {
int moveId = 0;
boolean remove = false;
SHrsReceiptEarning hrsReceiptEarning = (SHrsReceiptEarning) moGridReceiptEarnings.getSelectedGridRow();
if (hrsReceiptEarning.getPayrollReceiptEarning().isSystem()) {
miClient.showMsgBoxInformation(SDbConsts.MSG_REG_ + hrsReceiptEarning.getEarning().getName() + SDbConsts.MSG_REG_IS_SYSTEM + "\n" +
"Se debe eliminar mediante la eliminación del consumo de incidencia respectivo.");
}
else {
for (SHrsReceiptEarning hrsReceiptEarningToRemove : moHrsReceipt.getHrsReceiptEarnings()) {
if (SLibUtils.compareKeys(hrsReceiptEarningToRemove.getRowPrimaryKey(), hrsReceiptEarning.getRowPrimaryKey())) {
remove = true;
moveId = hrsReceiptEarningToRemove.getPayrollReceiptEarning().getPkMoveId();
break;
}
}
if (remove) {
moHrsReceipt.removeHrsReceiptEarning(moveId);
refreshReceiptMovements();
}
}
}
}
}
};
moGridReceiptEarnings.setForm(null);
moGridReceiptEarnings.setPaneFormOwner(this);
jpEarnings.add(moGridReceiptEarnings, BorderLayout.CENTER);
moGridReceiptDeductions = new SGridPaneForm(miClient, SModConsts.HRSX_PAY_REC_DED, SLibConsts.UNDEFINED, "Deducciones") {
@Override
public void initGrid() {
setRowButtonsEnabled(false, false, true);
}
@Override
public ArrayList<SGridColumnForm> createGridColumns() {
SGridColumnForm columnForm;
ArrayList<SGridColumnForm> gridColumnsForm = new ArrayList<>();
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_INT_1B, "
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_S, "Deducción", 125));
columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Cantidad", 55);
columnForm.setEditable(mbEditable);
gridColumnsForm.add(columnForm);
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_UNT, "Unidad", 45));
columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto unitario $", 80);
columnForm.setEditable(mbEditable);
gridColumnsForm.add(columnForm);
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto $", 80));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_M, "Crédito/préstamo"));
moGridReceiptDeductions.getTable().getDefaultEditor(Double.class).addCellEditorListener(SDialogPayrollReceipt.this);
return gridColumnsForm;
}
@Override
public void actionRowDelete() {
if (jbRowDelete.isEnabled()) {
if (jtTable.getSelectedRowCount() != 1) {
miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW);
}
else {
int moveId = 0;
boolean remove = false;
SHrsReceiptDeduction hrsReceiptDeduction = (SHrsReceiptDeduction) moGridReceiptDeductions.getSelectedGridRow();
for (SHrsReceiptDeduction hrsReceiptDeductionToRemove : moHrsReceipt.getHrsReceiptDeductions()) {
if (SLibUtils.compareKeys(hrsReceiptDeductionToRemove.getRowPrimaryKey(), hrsReceiptDeduction.getRowPrimaryKey())) {
remove = true;
moveId = hrsReceiptDeductionToRemove.getPayrollReceiptDeduction().getPkMoveId();
break;
}
}
if (remove) {
moHrsReceipt.removeHrsReceiptDeduction(moveId);
refreshReceiptMovements();
}
}
}
}
};
moGridReceiptDeductions.setForm(null);
moGridReceiptDeductions.setPaneFormOwner(this);
jpDeductions.add(moGridReceiptDeductions, BorderLayout.CENTER);
moGridAbsenceConsumptions = new SGridPaneForm(miClient, SModConsts.HRS_ABS_CNS, SLibConsts.UNDEFINED, "Consumo incidencias") {
@Override
public void initGrid() {
setRowButtonsEnabled(true, false, true);
}
@Override
public ArrayList<SGridColumnForm> createGridColumns() {
ArrayList<SGridColumnForm> gridColumnsForm = new ArrayList<>();
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Clase incidencia"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Tipo incidencia"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CAT, "Folio"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Inicial incidencia"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Final incidencia"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Días efectivos incidencia"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Inicial consumo"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Final consumo"));
gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Días efectivos consumo"));
return gridColumnsForm;
}
@Override
public void actionRowNew() {
SDialogPayrollReceiptAbsence dlgAbsence = new SDialogPayrollReceiptAbsence(miClient, "Consumo de incidencias");
dlgAbsence.setValue(SModConsts.HRS_PAY_RCP, moHrsReceipt);
dlgAbsence.setFormVisible(true);
if (dlgAbsence.getFormResult() == SGuiConsts.FORM_RESULT_OK) {
populateAbsenceConsumption();
refreshReceiptMovements();
}
}
@Override
public void actionRowDelete() {
if (jbRowDelete.isEnabled()) {
try {
if (jtTable.getSelectedRowCount() == 0) {
miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROWS);
}
else if (miClient.showMsgBoxConfirm(SGridConsts.MSG_CONFIRM_REG_DEL) == JOptionPane.YES_OPTION) {
SGridRow[] gridRows = getSelectedGridRows();
for (int i = 0; i < gridRows.length; i++) {
SGridRow gridRow = gridRows[i];
SDbAbsenceConsumption absenceConsumption = (SDbAbsenceConsumption) gridRow;
moHrsReceipt.updateHrsReceiptEarningAbsence(absenceConsumption, false);
moModel.getGridRows().remove(moModel.getGridRows().indexOf(gridRow));
populateAbsenceConsumption();
refreshReceiptMovements();
}
}
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
}
}
};
moGridAbsenceConsumptions.setForm(null);
moGridAbsenceConsumptions.setPaneFormOwner(null);
jpAbsenceConsumption.add(moGridAbsenceConsumptions, BorderLayout.CENTER);
reloadCatalogues();
addAllListeners();
}
private void renderEmployee() {
SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee();
moTextName.setValue(employee.getXtaEmployeeName());
moTextNumber.setValue(employee.getNumber());
moTextFiscalId.setValue(employee.getXtaEmployeeRfc());
moTextAlternativeId.setValue(employee.getXtaEmployeeCurp());
moTextSocialSecurityNumber.setValue(employee.getSocialSecurityNumber());
moTextPaymentType.setValue(miClient.getSession().readField(SModConsts.HRSS_TP_PAY, new int[] { employee.getFkPaymentTypeId() }, SDbRegistry.FIELD_NAME));
moDecSalary.setValue(employee.getSalary());
moDecWage.setValue(employee.getWage());
moDecSalarySscBase.setValue(employee.getSalarySscBase());
moTextDateBirth.setValue(SLibUtils.DateFormatDate.format(employee.getDateBirth()));
moTextDateBenefits.setValue(SLibUtils.DateFormatDate.format(employee.getDateBenefits()));
moTextDateLastHire.setValue(SLibUtils.DateFormatDate.format(employee.getDateLastHire()));
moTextDateLastDismissal_n.setValue(employee.getDateLastDismissal_n() != null ? SLibUtils.DateFormatDate.format(employee.getDateLastDismissal_n()) : "");
moTextSalaryType.setValue(miClient.getSession().readField(SModConsts.HRSS_TP_SAL, new int[] { employee.getFkSalaryTypeId() }, SDbRegistry.FIELD_NAME));
moTextEmployeeType.setValue(miClient.getSession().readField(SModConsts.HRSU_TP_EMP, new int[] { employee.getFkEmployeeTypeId() }, SDbRegistry.FIELD_NAME));
moTextWorkerType.setValue(miClient.getSession().readField(SModConsts.HRSU_TP_WRK, new int[] { employee.getFkWorkerTypeId() }, SDbRegistry.FIELD_NAME));
moTextDepartament.setValue(miClient.getSession().readField(SModConsts.HRSU_DEP, new int[] { employee.getFkDepartmentId() }, SDbRegistry.FIELD_NAME));
moTextPosition.setValue(miClient.getSession().readField(SModConsts.HRSU_POS, new int[] { employee.getFkPositionId() }, SDbRegistry.FIELD_NAME));
moTextShift.setValue(miClient.getSession().readField(SModConsts.HRSU_SHT, new int[] { employee.getFkShiftId() }, SDbRegistry.FIELD_NAME));
moTextRecruitmentSchemeType.setValue(miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId()}, SDbRegistry.FIELD_NAME));
moIntWorkingHoursDay.setValue(employee.getWorkingHoursDay());
}
private SDbPayrollReceiptEarning createPayrollReceipEarning(SHrsReceipt hrsReceipt, SHrsEmployeeDays hrsEmployeeDays) {
double unitsAlleged;
double amountUnitAlleged;
int[] loanKey = moKeyEarningLoan_n.getSelectedIndex() <= 0 ? new int[] { 0, 0 } : moKeyEarningLoan_n.getValue();
if (moHrsBenefit == null) {
if (moEarning.isBasedOnUnits()) {
unitsAlleged = moCompEarningValue.getField().getValue();
amountUnitAlleged = 0;
}
else {
unitsAlleged = 1;
amountUnitAlleged = moCompEarningValue.getField().getValue();
}
}
else {
if (moEarning.isBasedOnUnits()) {
unitsAlleged = moHrsBenefit.getValuePayedReceipt();
amountUnitAlleged = 0;
}
else {
unitsAlleged = 1;
amountUnitAlleged = moHrsBenefit.getAmountPayedReceipt();
}
}
SDbPayrollReceiptEarning earning = hrsReceipt.getHrsPayroll().createPayrollReceiptEarning(
hrsReceipt, moEarning, hrsEmployeeDays, moHrsBenefit,
unitsAlleged, amountUnitAlleged, false,
loanKey[0], loanKey[1], moGridReceiptEarnings.getTable().getRowCount() + 1);
// consider specialized inputs:
earning.setFkOtherPaymentTypeId(moKeyEarningOtherPaymentType.getValue()[0]);
earning.setAuxiliarValue(!moCompEarningAuxValue.isEnabled() ? 0 : moCompEarningAuxValue.getField().getValue());
earning.setAuxiliarAmount1(!moCurEarningAuxAmount1.isEnabled() ? 0 : moCurEarningAuxAmount1.getField().getValue());
earning.setAuxiliarAmount2(!moCurEarningAuxAmount2.isEnabled() ? 0 : moCurEarningAuxAmount2.getField().getValue());
return earning;
}
private SDbPayrollReceiptDeduction createPayrollReceipDeduction(SHrsReceipt hrsReceipt) {
double unitsAlleged;
double amountUnitAlleged;
int[] loanKey = moKeyDeductionLoan_n.getSelectedIndex() <= 0 ? new int[] { 0, 0 } : moKeyDeductionLoan_n.getValue();
if (moDeduction.isBasedOnUnits()) {
unitsAlleged = moCompDeductionValue.getField().getValue();
amountUnitAlleged = 0;
}
else {
unitsAlleged = 1;
amountUnitAlleged = moCompDeductionValue.getField().getValue();
}
SDbPayrollReceiptDeduction deduction = hrsReceipt.getHrsPayroll().createPayrollReceiptDeduction(
hrsReceipt, moDeduction,
unitsAlleged, amountUnitAlleged, false,
loanKey[0], loanKey[1], moGridReceiptDeductions.getTable().getRowCount() + 1);
return deduction;
}
private void createBenefit(final SDbEarning earning) throws Exception {
int benefitType = 0;
Date dateCutOff = null;
SDbBenefitTable benefitTable = null;
SDbBenefitTable benefitTableAux = null;
SHrsBenefitParams benefitParams = null;
benefitTable = SHrsUtils.getBenefitTableByEarning(miClient.getSession(),
earning.getPkEarningId(),
moHrsReceipt.getHrsPayroll().getPayroll().getFkPaymentTypeId(),
moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd());
benefitType = benefitTable.getFkBenefitTypeId();
if (benefitType == SLibConsts.UNDEFINED) {
throw new Exception("No se encontró ninguna prestación para el tipo de prestación definido en la percepción '" + earning.getName() + "'.");
}
else if (earning.getFkBenefitTypeId() != benefitType) {
throw new Exception("El tipo de prestación de la percepción '" + earning.getName() + "', es diferente al tipo de prestación de la prestación '" + benefitTable.getName() + "'.");
}
// check if benefit is vacation bonus:
if (benefitType == SModSysConsts.HRSS_TP_BEN_VAC_BON) {
int tableAuxId = SHrsUtils.getRecentBenefitTable(miClient.getSession(),
SModSysConsts.HRSS_TP_BEN_VAC,
moHrsReceipt.getHrsPayroll().getPayroll().getFkPaymentTypeId(),
moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd());
benefitTableAux = moHrsReceipt.getHrsPayroll().getBenefitTable(tableAuxId);
if (benefitTableAux == null) {
throw new Exception("No se encontró ninguna tabla para la prestación 'Vacaciones' que es requerida para el pago de la prestación 'Prima Vacacional'.");
}
}
if (!moHrsReceipt.getHrsEmployee().getEmployee().isActive()) {
dateCutOff = moHrsReceipt.getHrsEmployee().getEmployee().getDateLastDismissal_n();
if (benefitType != SModSysConsts.HRSS_TP_BEN_ANN_BON && !SLibTimeUtils.isBelongingToPeriod(dateCutOff, moHrsReceipt.getHrsPayroll().getPayroll().getDateStart(), moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd())) {
dateCutOff = moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd();
}
}
else if (benefitType == SModSysConsts.HRSS_TP_BEN_ANN_BON) {
dateCutOff = SLibTimeUtils.getEndOfYear(moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd());
}
else {
dateCutOff = moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd();
}
// Create benefit params:
benefitParams = new SHrsBenefitParams(earning, benefitTable, benefitTableAux, moHrsReceipt, dateCutOff);
SDialogPayrollBenefit dlgBenefit = new SDialogPayrollBenefit(miClient, benefitType, "Agregar prestación");
dlgBenefit.setValue(SGuiConsts.PARAM_ROWS, benefitParams);
dlgBenefit.setVisible(true);
if (dlgBenefit.getFormResult() == SGuiConsts.FORM_RESULT_OK) {
moHrsBenefit = (SHrsBenefit) dlgBenefit.getValue(SGuiConsts.PARAM_ROWS);
if (moEarning.isBasedOnUnits()) {
moCompEarningValue.getField().setValue(moHrsBenefit.getValuePayedReceipt());
}
else {
moCompEarningValue.getField().setValue(moHrsBenefit.getAmountPayedReceipt());
}
actionAddEarning();
}
}
private void computeTotal() {
double earningTotal = 0;
double deductionTotal = 0;
for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) {
earningTotal += hrsReceiptEarning.getPayrollReceiptEarning().getAmount_r();
}
for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) {
deductionTotal += hrsReceiptDeduction.getPayrollReceiptDeduction().getAmount_r();
}
moCurEarningsTotal.getField().setValue(earningTotal);
moCurDeductionsTotal.getField().setValue(deductionTotal);
moCurNetTotal.getField().setValue(earningTotal - deductionTotal);
}
private void setEnableFields(boolean enable) {
moTextEarningCode.setEnabled(enable);
jbPickEarning.setEnabled(enable);
moCompEarningValue.setEditable(enable);
jbAddEarning.setEnabled(enable);
moKeyEarningLoan_n.setEnabled(enable && moKeyEarningLoan_n.getItemCount() > 0);
if (!enable) {
moKeyEarningOtherPaymentType.setEnabled(false);
jlEarningAuxValue.setEnabled(false);
moCompEarningAuxValue.setEnabled(false);
jlEarningAuxAmount1.setEnabled(false);
jlEarningAuxAmount1Hint.setEnabled(false);
moCurEarningAuxAmount1.setEnabled(false);
jlEarningAuxAmount2.setEnabled(false);
jlEarningAuxAmount2Hint.setEnabled(false);
moCurEarningAuxAmount2.setEnabled(false);
}
moTextDeductionCode.setEnabled(enable);
jbPickDeduction.setEnabled(enable);
moCompDeductionValue.setEditable(enable);
jbAddDeduction.setEnabled(enable);
moKeyDeductionLoan_n.setEnabled(enable && moKeyDeductionLoan_n.getItemCount() > 0);
jbSave.setEnabled(enable);
}
private void resetFieldsEarningAux() {
jlEarningAuxValue.setText(LABEL_AUX_VAL + ":");
jlEarningAuxValue.setEnabled(false);
jlEarningAuxValueHint.setToolTipText(null);
jlEarningAuxValueHint.setEnabled(false);
moCompEarningAuxValue.setEnabled(false);
moCompEarningAuxValue.getField().setMandatory(false);
moCompEarningAuxValue.setCompoundText("");
moCompEarningAuxValue.getField().setDecimalFormat(SLibUtils.DecimalFormatInteger);
moCompEarningAuxValue.getField().setMinDouble(0);
moCompEarningAuxValue.getField().setMaxDouble(Double.MAX_VALUE);
moCompEarningAuxValue.getField().resetField();
jlEarningAuxAmount1.setText(LABEL_AUX_AMT + ":");
jlEarningAuxAmount1.setEnabled(false);
jlEarningAuxAmount1Hint.setToolTipText(null);
jlEarningAuxAmount1Hint.setEnabled(false);
moCurEarningAuxAmount1.setEnabled(false);
moCurEarningAuxAmount1.getField().setMandatory(false);
moCurEarningAuxAmount1.getField().resetField();
jlEarningAuxAmount2.setText(LABEL_AUX_AMT + ":");
jlEarningAuxAmount2.setEnabled(false);
jlEarningAuxAmount2Hint.setToolTipText(null);
jlEarningAuxAmount2Hint.setEnabled(false);
moCurEarningAuxAmount2.setEnabled(false);
moCurEarningAuxAmount2.getField().setMandatory(false);
moCurEarningAuxAmount2.getField().resetField();
}
private void resetFieldsEarning() {
moEarning = null;
msOriginalEarningCode = "";
moTextEarningCode.resetField();
moTextEarningName.resetField();
moCompEarningValue.getField().resetField();
moCompEarningValue.setCompoundText("");
moKeyEarningLoan_n.setEnabled(false);
moKeyEarningLoan_n.removeAllItems();
// resetting of specialized fields related to other payments:
moKeyEarningOtherPaymentType.setEnabled(false);
moKeyEarningOtherPaymentType.removeItemListener(this); // prevent from triggering unwished item-state-changed event
moKeyEarningOtherPaymentType.resetField(); // will not trigger an item-state-changed event
itemStateChangedKeyEarningOtherPayment(); // force triggering an item-state-changed event
moKeyEarningOtherPaymentType.addItemListener(this);
}
private void resetFieldsDeduction() {
moDeduction = null;
msOriginalDeductionCode = "";
moTextDeductionCode.resetField();
moTextDeductionName.resetField();
moCompDeductionValue.getField().resetField();
moCompDeductionValue.setCompoundText("");
moKeyDeductionLoan_n.setEnabled(false);
moKeyDeductionLoan_n.removeAllItems();
}
private void prepareFocusFieldsEarning() {
moCompEarningValue.getField().setNextButton(null);
moCompEarningAuxValue.getField().setNextButton(null);
moCurEarningAuxAmount1.getField().setNextButton(null);
moCurEarningAuxAmount2.getField().setNextButton(null);
if (moCurEarningAuxAmount2.isEnabled()) { // field rarely used; preferable disabling it when not used
moCurEarningAuxAmount2.getField().setNextButton(jbAddEarning);
}
else if (moCurEarningAuxAmount1.isEnabled()) { // field rarely used; preferable disabling it when not used
moCurEarningAuxAmount1.getField().setNextButton(jbAddEarning);
}
else if (moCompEarningAuxValue.isEnabled()) { // field rarely used; preferable disabling it when not used
moCompEarningAuxValue.getField().setNextButton(jbAddEarning);
}
else {
moCompEarningValue.getField().setNextButton(jbAddEarning);
}
}
private void prepareFocusFieldsDeduction() {
moCompDeductionValue.getField().setNextButton(jbAddDeduction);
}
private void addHrsReceiptEarning() {
if (moEarning != null) {
SHrsEmployeeDays hrsEmployeeDays = moHrsReceipt.getHrsEmployee().createEmployeeDays();
SHrsReceiptEarning hrsReceiptEarning = new SHrsReceiptEarning();
hrsReceiptEarning.setHrsReceipt(moHrsReceipt);
hrsReceiptEarning.setEarning(moEarning);
hrsReceiptEarning.setPayrollReceiptEarning(createPayrollReceipEarning(moHrsReceipt, hrsEmployeeDays));
try {
if (moKeyEarningLoan_n.isEnabled() && moKeyEarningLoan_n.getSelectedIndex() > 0) {
SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyEarningLoan_n.getValue()[1]);
hrsReceiptEarning.getPayrollReceiptEarning().setUserEdited(true);
hrsReceiptEarning.getPayrollReceiptEarning().setFkLoanEmployeeId_n(moKeyEarningLoan_n.getValue()[0]);
hrsReceiptEarning.getPayrollReceiptEarning().setFkLoanLoanId_n(moKeyEarningLoan_n.getValue()[1]);
hrsReceiptEarning.getPayrollReceiptEarning().setFkLoanTypeId_n(loan.getFkLoanTypeId());
}
moHrsReceipt.addHrsReceiptEarning(hrsReceiptEarning);
populateEarnings();
populateDeductions();
}
catch (Exception e) {
SLibUtils.printException(this, e);
}
}
}
private void addHrsReceiptDeduction() {
if (moDeduction != null) {
SHrsReceiptDeduction hrsReceiptDeduction = new SHrsReceiptDeduction();
hrsReceiptDeduction.setHrsReceipt(moHrsReceipt);
hrsReceiptDeduction.setDeduction(moDeduction);
hrsReceiptDeduction.setPayrollReceiptDeduction(createPayrollReceipDeduction(moHrsReceipt));
try {
if (moKeyDeductionLoan_n.isEnabled() && moKeyDeductionLoan_n.getSelectedIndex() > 0) {
SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyDeductionLoan_n.getValue()[1]);
hrsReceiptDeduction.getPayrollReceiptDeduction().setUserEdited(true);
hrsReceiptDeduction.getPayrollReceiptDeduction().setFkLoanEmployeeId_n(moKeyDeductionLoan_n.getValue()[0]);
hrsReceiptDeduction.getPayrollReceiptDeduction().setFkLoanLoanId_n(moKeyDeductionLoan_n.getValue()[1]);
hrsReceiptDeduction.getPayrollReceiptDeduction().setFkLoanTypeId_n(loan.getFkLoanTypeId());
}
moHrsReceipt.addHrsReceiptDeduction(hrsReceiptDeduction);
populateDeductions();
}
catch (Exception e) {
SLibUtils.printException(this, e);
}
}
}
private void refreshReceiptMovements() {
populateEarnings();
populateDeductions();
}
private void populateEarnings() {
Vector<SGridRow> rows = new Vector<>();
moGridReceiptEarnings.setRowButtonsEnabled(false, mbEditable, mbEditable);
for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) {
SHrsReceiptEarning hrsReceiptEarningNew = new SHrsReceiptEarning();
hrsReceiptEarningNew.setHrsReceipt(moHrsReceipt);
hrsReceiptEarningNew.setEarning(hrsReceiptEarning.getEarning());
hrsReceiptEarningNew.setPayrollReceiptEarning(hrsReceiptEarning.getPayrollReceiptEarning());
rows.add(hrsReceiptEarningNew);
}
moGridReceiptEarnings.populateGrid(rows);
moGridReceiptEarnings.getTable().getDefaultEditor(Double.class).addCellEditorListener(this);
computeTotal();
}
private void populateDeductions() {
Vector<SGridRow> rows = new Vector<>();
moGridReceiptDeductions.setRowButtonsEnabled(false, false, mbEditable);
for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) {
SHrsReceiptDeduction hrsReceiptDeductionNew = new SHrsReceiptDeduction();
hrsReceiptDeductionNew.setHrsReceipt(moHrsReceipt);
hrsReceiptDeductionNew.setDeduction(hrsReceiptDeduction.getDeduction());
hrsReceiptDeductionNew.setPayrollReceiptDeduction(hrsReceiptDeduction.getPayrollReceiptDeduction());
rows.add(hrsReceiptDeductionNew);
}
moGridReceiptDeductions.populateGrid(rows);
moGridReceiptDeductions.getTable().getDefaultEditor(Double.class).addCellEditorListener(this);
computeTotal();
}
private void populateAbsenceConsumption() {
Vector<SGridRow> rows = new Vector<>();
moGridAbsenceConsumptions.setRowButtonsEnabled(mbEditable, false, mbEditable);
for (SDbAbsenceConsumption absenceConsumption : moHrsReceipt.getAbsenceConsumptions()) {
SDbAbsence absence = (SDbAbsence) miClient.getSession().readRegistry(SModConsts.HRS_ABS, new int[] { absenceConsumption.getPkEmployeeId(), absenceConsumption.getPkAbsenceId() });
absenceConsumption.setAuxNumber(absence.getNumber());
absenceConsumption.setAuxDateStart(absence.getDateStart());
absenceConsumption.setAuxDateEnd(absence.getDateEnd());
absenceConsumption.setAuxEffectiveDays(absence.getEffectiveDays());
rows.add(absenceConsumption);
}
moGridAbsenceConsumptions.populateGrid(rows);
moGridAbsenceConsumptions.setSelectedGridRow(0);
}
private void updateReceipt() {
for (SGridRow row : moGridReceiptEarnings.getModel().getGridRows()) {
SHrsReceiptEarning hrsReceiptEarningRow = (SHrsReceiptEarning) row;
for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) {
if (SLibUtils.compareKeys(hrsReceiptEarning.getRowPrimaryKey(), hrsReceiptEarningRow.getRowPrimaryKey())) {
if (!hrsReceiptEarning.getPayrollReceiptEarning().isAutomatic() && hrsReceiptEarningRow.getPayrollReceiptEarning().getUnits() == 0) {
moHrsReceipt.removeHrsReceiptEarning(hrsReceiptEarning.getPayrollReceiptEarning().getPkMoveId());
break;
}
}
}
}
for (SGridRow row : moGridReceiptDeductions.getModel().getGridRows()) {
SHrsReceiptDeduction hrsReceiptDeductionRow = (SHrsReceiptDeduction) row;
for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) {
if (SLibUtils.compareKeys(hrsReceiptDeduction.getRowPrimaryKey(), hrsReceiptDeductionRow.getRowPrimaryKey())) {
if (!hrsReceiptDeduction.getPayrollReceiptDeduction().isAutomatic() && hrsReceiptDeductionRow.getPayrollReceiptDeduction().getAmountUnitary() == 0) {
moHrsReceipt.removeHrsReceiptDeduction(hrsReceiptDeduction.getPayrollReceiptDeduction().getPkMoveId());
break;
}
}
}
}
}
private void actionLoadEarning(final boolean focusEventRaised, final boolean actionEventRaised) {
try {
if (moTextEarningCode.getValue().isEmpty()) {
if (focusEventRaised || actionEventRaised) {
resetFieldsEarning();
}
if (actionEventRaised) {
moCompEarningValue.getField().getComponent().requestFocusInWindow();
}
}
else if (moEarning == null || !moEarning.getCode().equals(moTextEarningCode.getValue())) {
// identify earning:
moEarning = null;
msOriginalEarningCode = moTextEarningCode.getValue();
for (SDbEarning earning : moEarnigsMap.values()) {
if (earning.getCode().equals(moTextEarningCode.getValue())) {
moEarning = earning;
break;
}
}
// process earning, if any:
if (moEarning == null) {
String code = moTextEarningCode.getValue();
miClient.showMsgBoxWarning("No se encontró ninguna percepción con el código '" + code + "'.");
resetFieldsEarning();
moTextEarningCode.setValue(code);
moTextEarningCode.requestFocusInWindow();
}
else if (moEarning.isAbsence()) {
miClient.showMsgBoxWarning("No se puede agregar la percepción '" + moEarning.getName() + " (" + moEarning.getCode() + ")' de forma directa, se debe agregar mediante una incidencia.");
moTextEarningCode.requestFocusInWindow();
}
else {
moTextEarningName.setValue(moEarning.getName());
moCompEarningValue.setCompoundText(moHrsReceipt.getHrsPayroll().getEarningComputationTypesMap().get(moEarning.getFkEarningComputationTypeId()));
moCompEarningValue.getField().setEditable(moEarning.areUnitsModifiable() || !moEarning.isBasedOnUnits());
// enable/disable specialized fields:
if (moEarning.isLoan()) {
miClient.getSession().populateCatalogue(moKeyEarningLoan_n, SModConsts.HRS_LOAN, SLibConsts.UNDEFINED, new SGuiParams(new int[] { moHrsReceipt.getHrsEmployee().getEmployee().getPkEmployeeId(), moEarning.getFkLoanTypeId()}));
moKeyEarningLoan_n.setEnabled(true);
}
else {
moKeyEarningLoan_n.setEnabled(false);
moKeyEarningLoan_n.removeAllItems();
}
// resetting of specialized fields related to other payments:
moKeyEarningOtherPaymentType.setEnabled(moEarning.getFkOtherPaymentTypeId() == SModSysConsts.HRSS_TP_OTH_PAY_OTH);
moKeyEarningOtherPaymentType.removeItemListener(this); // prevent from triggering unwished item-state-changed event
moKeyEarningOtherPaymentType.setValue(new int[] { moEarning.getFkOtherPaymentTypeId() }); // will not trigger an item-state-changed event
itemStateChangedKeyEarningOtherPayment(); // force triggering an item-state-changed event
moKeyEarningOtherPaymentType.addItemListener(this);
prepareFocusFieldsEarning();
// set focus on next editable field:
if (moKeyEarningOtherPaymentType.isEnabled()) {
moKeyEarningOtherPaymentType.requestFocusInWindow();
}
else if (moKeyEarningLoan_n.isEnabled()) {
moKeyEarningLoan_n.requestFocusInWindow();
}
else if (moCompEarningValue.getField().isEditable()) {
moCompEarningValue.getField().getComponent().requestFocusInWindow();
}
else {
jbAddEarning.requestFocusInWindow();
}
// create benefit, if it is necessary:
moHrsBenefit = null;
if (moEarning.isBenefit()) {
createBenefit(moEarning);
}
}
}
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
}
private void actionLoadDeduction(boolean focusEventRaised, final boolean actionEventRaised) {
try {
if (moTextDeductionCode.getValue().isEmpty()) {
if (focusEventRaised || actionEventRaised) {
resetFieldsDeduction();
}
if (actionEventRaised) {
moCompDeductionValue.getField().getComponent().requestFocusInWindow();
}
}
else if (moDeduction == null || !moDeduction.getCode().equals(moTextDeductionCode.getValue())) {
// identify deduction:
moDeduction = null;
msOriginalDeductionCode = moTextDeductionCode.getValue();
for (SDbDeduction deduction : moDeductionsMap.values()) {
if (deduction.getCode().equals(moTextDeductionCode.getValue())) {
moDeduction = deduction;
break;
}
}
// process deduction, if any:
if (moDeduction == null) {
String code = moTextDeductionCode.getValue();
miClient.showMsgBoxWarning("No se encontró ninguna deducción con el código '" + code + "'.");
resetFieldsDeduction();
moTextDeductionCode.setValue(code);
moTextDeductionCode.requestFocusInWindow();
}
else if (moDeduction.isAbsence()) {
miClient.showMsgBoxWarning("No se puede agregar la deducción '" + moDeduction.getName() + " (" + moDeduction.getCode() + ")' de forma directa, se debe agregar mediante una incidencia.");
moTextDeductionCode.requestFocusInWindow();
}
else {
moTextDeductionName.setValue(moDeduction.getName());
moCompDeductionValue.setCompoundText(moHrsReceipt.getHrsPayroll().getDeductionComputationTypesMap().get(moDeduction.getFkDeductionComputationTypeId()));
moCompDeductionValue.getField().setEditable(moDeduction.areUnitsModifiable() || !moDeduction.isBasedOnUnits());
// enable/disable specialized fields:
if (moDeduction.isLoan()) {
miClient.getSession().populateCatalogue(moKeyDeductionLoan_n, SModConsts.HRS_LOAN, SLibConsts.UNDEFINED, new SGuiParams(new int[] { moHrsReceipt.getHrsEmployee().getEmployee().getPkEmployeeId(), moDeduction.getFkLoanTypeId()}));
moKeyDeductionLoan_n.setEnabled(true);
}
else {
moKeyDeductionLoan_n.setEnabled(false);
moKeyDeductionLoan_n.removeAllItems();
}
prepareFocusFieldsDeduction();
// set focus on next editable field:
if (moKeyDeductionLoan_n.isEnabled()) {
moKeyDeductionLoan_n.requestFocusInWindow();
}
else if (moCompDeductionValue.getField().isEditable()) {
moCompDeductionValue.getField().getComponent().requestFocusInWindow();
}
else {
jbAddEarning.requestFocusInWindow();
}
}
}
}
catch (Exception e) {
SLibUtils.printException(this, e);
}
}
private void actionPickEarning() {
miClient.getSession().showOptionPicker(SModConsts.HRS_EAR, SLibConsts.UNDEFINED, null, moTextEarningCode);
if (!moTextEarningCode.getValue().isEmpty()) {
actionLoadEarning(false, false);
}
}
private void actionPickDeduction() {
miClient.getSession().showOptionPicker(SModConsts.HRS_DED, SLibConsts.UNDEFINED, null, moTextDeductionCode);
if (!moTextDeductionCode.getValue().isEmpty()) {
actionLoadDeduction(false, false);
}
}
private void actionAddEarning() {
try {
if (moEarning == null) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(moTextEarningCode.getToolTipText()) + "'.");
moTextEarningCode.requestFocusInWindow();
}
else {
SGuiValidation validation = moFields.validateFields();
if (SGuiUtils.computeValidation(miClient, validation)) {
// special-case validations:
if (moCompEarningValue.getField().getValue() == 0 &&
miClient.showMsgBoxConfirm(SGuiConsts.MSG_CNF_FIELD_VAL_ + "'" + moCompEarningValue.getField().getFieldName() + "'" + SGuiConsts.MSG_CNF_FIELD_VAL_UNDEF) != JOptionPane.YES_OPTION) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + moCompEarningValue.getField().getFieldName() + "'. ");
moCompEarningValue.getField().getComponent().requestFocusInWindow();
return;
}
if (moKeyEarningOtherPaymentType.isEnabled() && moKeyEarningOtherPaymentType.getValue()[0] == SModSysConsts.HRSS_TP_OTH_PAY_NON) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_DIF + "'" + SGuiUtils.getLabelName(moKeyEarningOtherPaymentType.getToolTipText()) + "'. ");
moKeyEarningOtherPaymentType.requestFocusInWindow();
return;
}
if (moEarning.isLoan()) {
if (moKeyEarningLoan_n.getSelectedIndex() <= 0) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(jlEarningLoan_n.getText()) + "'. ");
moKeyEarningLoan_n.requestFocusInWindow();
return;
}
}
if (moEarning.isBenefit() && moHrsBenefit == null) {
miClient.showMsgBoxWarning("Se debe capturar la cantidad o monto de la prestación '" + moEarning.getName() + "'.");
moTextEarningCode.requestFocusInWindow();
return;
}
// validate assimilated employees:
SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee(); // convenience variable
if (employee.isAssimilable() && moEarning.getFkEarningTypeId() != SModSysConsts.HRSS_TP_EAR_ASS_INC) {
// this message is duplicated as is in method validateForm(), please synchronize any change!
miClient.showMsgBoxWarning(employee.getXtaEmployeeName() + ", "
+ "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n"
+ "no puede tener percepciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_EAR, new int[] { SModSysConsts.HRSS_TP_EAR_ASS_INC }, SDbRegistry.FIELD_NAME) + "'.");
moTextEarningCode.requestFocusInWindow();
return;
}
// confirm multiple earnings of the same type:
for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) {
if (hrsReceiptEarning.getEarning().getPkEarningId() == moEarning.getPkEarningId() && !moEarning.isLoan() &&
miClient.showMsgBoxConfirm("La percepción '" + moEarning.getName() + "' ya existe en el recibo.\n"
+ "¿Está seguro que desea agregarla otra vez?") != JOptionPane.YES_OPTION) {
moTextEarningCode.requestFocusInWindow();
return;
}
}
// add earning:
addHrsReceiptEarning();
resetFieldsEarning();
moTextEarningCode.requestFocusInWindow();
}
}
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
}
private void actionAddDeduction() {
try {
if (moDeduction == null) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(moTextDeductionCode.getToolTipText()) + "'.");
moTextDeductionCode.requestFocusInWindow();
}
else {
SGuiValidation validation = moFields.validateFields();
if (SGuiUtils.computeValidation(miClient, validation)) {
// special-case validations:
if (moCompDeductionValue.getField().getValue() == 0 &&
miClient.showMsgBoxConfirm(SGuiConsts.MSG_CNF_FIELD_VAL_ + "'" + moCompDeductionValue.getField().getFieldName() + "'" + SGuiConsts.MSG_CNF_FIELD_VAL_UNDEF) != JOptionPane.YES_OPTION) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + moCompDeductionValue.getField().getFieldName() + "'. ");
moCompDeductionValue.getField().getComponent().requestFocusInWindow();
return;
}
if (moDeduction.isLoan()) {
if (moKeyDeductionLoan_n.getSelectedIndex() <= 0) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(jlDeductionLoan_n.getText()) + "'. ");
moKeyDeductionLoan_n.requestFocusInWindow();
return;
}
else {
SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyDeductionLoan_n.getValue()[1]);
if (loan.isPlainLoan()) {
double loanBalance = SHrsUtils.getLoanBalance(loan, moHrsReceipt, null, null);
if (loanBalance <= 0) {
miClient.showMsgBoxWarning("El préstamo '" + loan.composeLoanDescription() + "' " + (loanBalance == 0 ? "está saldado" : "tiene un saldo negativo de $" + SLibUtils.getDecimalFormatAmount().format(loanBalance)) + ".");
moCompDeductionValue.getField().getComponent().requestFocusInWindow();
return;
}
else if (moCompDeductionValue.getField().getValue() > loanBalance) {
miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_VAL_ + "'" + SGuiUtils.getLabelName(jlDeductionValue.getText()) + "'" + SGuiConsts.ERR_MSG_FIELD_VAL_LESS_EQUAL + "$" + SLibUtils.getDecimalFormatAmount().format(loanBalance) + ".");
moCompDeductionValue.getField().getComponent().requestFocusInWindow();
return;
}
}
}
}
// validate assimilated employees:
SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee(); // convenience variable
if (employee.isAssimilable() && moDeduction.getFkDeductionTypeId() != SModSysConsts.HRSS_TP_DED_TAX) {
// this message is duplicated as is in method validateForm(), please synchronize any change!
miClient.showMsgBoxWarning(employee.getXtaEmployeeName() + ", "
+ "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n"
+ "no puede tener deducciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_DED, new int[] { SModSysConsts.HRSS_TP_DED_TAX }, SDbRegistry.FIELD_NAME) + "'.");
moTextDeductionCode.requestFocusInWindow();
return;
}
// confirm multiple deductions of the same type:
for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) {
if (hrsReceiptDeduction.getDeduction().getPkDeductionId() == moDeduction.getPkDeductionId() && !moDeduction.isLoan() &&
miClient.showMsgBoxConfirm("La deducción '" + moDeduction.getName() + "' ya existe en el recibo.\n"
+ "¿Está seguro que desea agregarla otra vez?") != JOptionPane.YES_OPTION) {
moTextDeductionCode.requestFocusInWindow();
return;
}
}
// add deduction:
addHrsReceiptDeduction();
resetFieldsDeduction();
moTextDeductionCode.requestFocusInWindow();
}
}
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
}
private void itemStateChangedEarningLoan_n() {
if (moKeyEarningLoan_n.getSelectedIndex() <= 0) {
moCompEarningValue.getField().resetField();
}
}
private void itemStateChangedDeductionLoan_n() {
if (moKeyDeductionLoan_n.getSelectedIndex() <= 0) {
moCompDeductionValue.getField().resetField();
}
else {
try {
SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyDeductionLoan_n.getValue()[1]);
moCompDeductionValue.getField().setValue(SHrsUtils.computeLoanAmount(loan, moHrsReceipt, null, null));
}
catch (Exception e) {
SLibUtils.printException(this, e);
}
}
}
private void itemStateChangedKeyEarningOtherPayment() {
resetFieldsEarningAux();
if (moKeyEarningOtherPaymentType.getSelectedIndex() > 0) {
switch (moKeyEarningOtherPaymentType.getValue()[0]) {
case SModSysConsts.HRSS_TP_OTH_PAY_TAX_SUB:
jlEarningAuxAmount1.setText(SDbEarning.TAX_SUB_LABEL + ":");
jlEarningAuxAmount1.setEnabled(true);
jlEarningAuxAmount1Hint.setToolTipText(SDbEarning.TAX_SUB_HINT);
jlEarningAuxAmount1Hint.setEnabled(true);
moCurEarningAuxAmount1.setEnabled(true);
moCurEarningAuxAmount1.getField().setMandatory(false); // non-mandatory!
break;
case SModSysConsts.HRSS_TP_OTH_PAY_TAX_BAL:
int year = SLibTimeUtils.digestYear(moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd())[0];
jlEarningAuxValue.setText(SDbEarning.OTH_TAX_BAL_LABEL_YEAR + ":*");
jlEarningAuxValue.setEnabled(true);
jlEarningAuxValueHint.setToolTipText(SDbEarning.OTH_TAX_BAL_HINT_YEAR);
jlEarningAuxValueHint.setEnabled(true);
moCompEarningAuxValue.setEnabled(true);
moCompEarningAuxValue.getField().setMandatory(true); // mandatory!
moCompEarningAuxValue.setCompoundText("");
moCompEarningAuxValue.getField().setDecimalFormat(SLibUtils.DecimalFormatCalendarYear);
moCompEarningAuxValue.getField().setMinDouble(year - 1);
moCompEarningAuxValue.getField().setMaxDouble(year);
moCompEarningAuxValue.getField().setValue((double) year);
jlEarningAuxAmount1.setText(SDbEarning.OTH_TAX_BAL_LABEL_BAL + ":*");
jlEarningAuxAmount1.setEnabled(true);
jlEarningAuxAmount1Hint.setToolTipText(SDbEarning.OTH_TAX_BAL_HINT_BAL);
jlEarningAuxAmount1Hint.setEnabled(true);
moCurEarningAuxAmount1.setEnabled(true);
moCurEarningAuxAmount1.getField().setMandatory(true); // mandatory!
jlEarningAuxAmount2.setText(SDbEarning.OTH_TAX_BAL_LABEL_REM_BAL + ":");
jlEarningAuxAmount2.setEnabled(true);
jlEarningAuxAmount2Hint.setToolTipText(SDbEarning.OTH_TAX_BAL_HINT_REM_BAL);
jlEarningAuxAmount2Hint.setEnabled(true);
moCurEarningAuxAmount2.setEnabled(true);
moCurEarningAuxAmount2.getField().setMandatory(false); // non-mandatory!
break;
default:
}
}
prepareFocusFieldsEarning();
}
private void processCellEditionEarning() {
boolean refresh = false;
SHrsReceiptEarning hrsReceiptEarning = (SHrsReceiptEarning) moGridReceiptEarnings.getSelectedGridRow();
if (hrsReceiptEarning != null) {
switch (moGridReceiptEarnings.getTable().getSelectedColumn()) {
case COL_VAL:
if (hrsReceiptEarning.isEditableValueAlleged()) {
refresh = true;
}
else {
miClient.showMsgBoxWarning("No se puede modificar la 'Cantidad' de la percepción '" + hrsReceiptEarning.getEarning().getName() + "'.");
}
break;
case COL_AMT_UNT:
if (hrsReceiptEarning.isEditableAmountUnitary(hrsReceiptEarning.getAmountBeingEdited())) {
refresh = true;
}
else {
miClient.showMsgBoxWarning("No se puede modificar el 'Monto unitario' de la percepción '" + hrsReceiptEarning.getEarning().getName() + "'."
+ (!hrsReceiptEarning.getEarning().isBenefit() ? "" : "El monto capturado no puede ser menor que " + SLibUtils.getDecimalFormatAmount().format(hrsReceiptEarning.getAmountOriginal()) + "."));
}
break;
default:
}
}
if (refresh) {
try {
moHrsReceipt.computeReceipt();
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
int row = moGridReceiptEarnings.getTable().getSelectedRow();
refreshReceiptMovements();
moGridReceiptEarnings.setSelectedGridRow(row);
}
}
private void processCellEditionDeduction() {
boolean refresh = false;
SHrsReceiptDeduction hrsReceiptDeduction = (SHrsReceiptDeduction) moGridReceiptDeductions.getSelectedGridRow();
if (hrsReceiptDeduction != null) {
switch (moGridReceiptDeductions.getTable().getSelectedColumn()) {
case COL_VAL:
if (hrsReceiptDeduction.isEditableValueAlleged()) {
refresh = true;
}
else {
miClient.showMsgBoxWarning("No se puede modificar la 'Cantidad' de la deducción '" + hrsReceiptDeduction.getDeduction().getName() + "'.");
}
break;
case COL_AMT_UNT:
if (hrsReceiptDeduction.isEditableAmountUnitary(hrsReceiptDeduction.getAmountBeingEdited())) {
refresh = true;
}
else {
miClient.showMsgBoxWarning("No se puede modificar el 'Monto unitario' de la deducción '" + hrsReceiptDeduction.getDeduction().getName() + "'."
+ (!hrsReceiptDeduction.getDeduction().isBenefit() ? "" : "El monto capturado no puede ser menor que " + SLibUtils.getDecimalFormatAmount().format(hrsReceiptDeduction.getAmountOriginal()) + "."));
}
break;
default:
}
}
if (refresh) {
try {
moHrsReceipt.computeReceipt();
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
int row = moGridReceiptDeductions.getTable().getSelectedRow();
refreshReceiptMovements();
moGridReceiptDeductions.setSelectedGridRow(row);
}
}
@Override
public void addAllListeners() {
jbPickEarning.addActionListener(this);
jbAddEarning.addActionListener(this);
jbPickDeduction.addActionListener(this);
jbAddDeduction.addActionListener(this);
moTextEarningCode.addActionListener(this);
moTextDeductionCode.addActionListener(this);
moKeyEarningLoan_n.addItemListener(this);
moKeyDeductionLoan_n.addItemListener(this);
moKeyEarningOtherPaymentType.addItemListener(this);
moTextEarningCode.addFocusListener(this);
moTextDeductionCode.addFocusListener(this);
}
@Override
public void removeAllListeners() {
jbPickEarning.removeActionListener(this);
jbAddEarning.removeActionListener(this);
jbPickDeduction.removeActionListener(this);
jbAddDeduction.removeActionListener(this);
moTextEarningCode.removeActionListener(this);
moTextDeductionCode.removeActionListener(this);
moKeyEarningLoan_n.removeItemListener(this);
moKeyDeductionLoan_n.removeItemListener(this);
moKeyEarningOtherPaymentType.removeItemListener(this);
moTextEarningCode.removeFocusListener(this);
moTextDeductionCode.removeFocusListener(this);
}
@Override
public void reloadCatalogues() {
miClient.getSession().populateCatalogue(moKeyEarningOtherPaymentType, SModConsts.HRSS_TP_OTH_PAY, 0, null);
}
@Override
public void setRegistry(SDbRegistry registry) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public SDbRegistry getRegistry() throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public SGuiValidation validateForm() {
SGuiValidation validation = moFields.validateFields();
if (moHrsReceipt.getHrsPayroll().getPayroll().isPayrollNormal()) {
double daysWorked = 0;
for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) {
if (hrsReceiptEarning.getEarning().isDaysWorked() && !hrsReceiptEarning.getEarning().isAbsence()) {
daysWorked += hrsReceiptEarning.getPayrollReceiptEarning().getUnitsAlleged();
}
}
double daysAbsence = 0;
for (SDbAbsenceConsumption absenceConsumption : moHrsReceipt.getAbsenceConsumptions()) {
daysAbsence += absenceConsumption.getEffectiveDays();
}
SHrsEmployeeDays hrsEmployeeDays = moHrsReceipt.getHrsEmployee().createEmployeeDays();
double maxWorkingDays = hrsEmployeeDays.getWorkingDays();
double daysCovered = daysWorked + daysAbsence;
double daysDiff = maxWorkingDays - daysCovered;
if (Math.abs(daysDiff) > 0.0001) {
String msg = "¡ADVERTENCIA!\n"
+ "Los días laborables del empleado (" + maxWorkingDays + " " + (maxWorkingDays == 1 ? "día" : "días") + ") no son consistentes con\n"
+ "los días a pagar (" + daysWorked + " " + (daysWorked == 1 ? "día" : "días") + ")"
+ (daysAbsence == 0 ? "" : " más los días de incidencias (" + daysAbsence + " " + (daysAbsence == 1 ? "día" : "días") + ")" + "; esto es: "
+ maxWorkingDays + " " + (maxWorkingDays == 1 ? "día" : "días") + " vs. " + daysCovered + " " + (daysCovered == 1 ? "día" : "días")) + ".\n"
+ "¡SE PAGARÁ " + Math.abs(daysDiff) + " " + (Math.abs(daysDiff) == 1 ? "DÍA" : "DÍAS") + " DE " + (daysDiff > 0 ? "MENOS" : "MÁS") + " AL EMPLEADO!";
if (miClient.showMsgBoxConfirm(msg + "\n" + SGuiConsts.MSG_CNF_CONT) == JOptionPane.NO_OPTION) {
validation.setMessage("Ajustarse a los días laborables del empleado (" + maxWorkingDays + " " + (maxWorkingDays == 1 ? "día" : "días") + ").");
validation.setComponent(moTextEarningCode);
}
}
}
SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee(); // convenience variable
if (employee.isAssimilable()) {
for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) {
if (hrsReceiptEarning.getEarning().getFkEarningTypeId() != SModSysConsts.HRSS_TP_EAR_ASS_INC) {
// this message is duplicated as is in method actionAddEarning(), please synchronize any change!
validation.setMessage(employee.getXtaEmployeeName() + ", "
+ "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n"
+ "no puede tener percepciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_EAR, new int[] { SModSysConsts.HRSS_TP_EAR_ASS_INC }, SDbRegistry.FIELD_NAME) + "'.");
validation.setComponent(moTextEarningCode);
break;
}
}
if (validation.isValid()) {
for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) {
if (hrsReceiptDeduction.getDeduction().getFkDeductionTypeId() != SModSysConsts.HRSS_TP_DED_TAX) {
// this message is duplicated as is in method actionAddDeduction(), please synchronize any change!
validation.setMessage(employee.getXtaEmployeeName() + ", "
+ "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n"
+ "no puede tener deducciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_DED, new int[] { SModSysConsts.HRSS_TP_DED_TAX }, SDbRegistry.FIELD_NAME) + "'.");
validation.setComponent(moTextEarningCode);
break;
}
}
}
}
return validation;
}
@Override
@SuppressWarnings("unchecked")
public void setValue(final int type, final Object value) {
switch (type) {
case SGuiConsts.PARAM_REQ_PAY:
mbEditable = (boolean) value;
setEnableFields(mbEditable);
break;
case SModConsts.HRS_PAY_RCP:
moHrsReceipt = (SHrsReceipt) value;
renderEmployee();
refreshReceiptMovements();
populateAbsenceConsumption();
break;
case SModConsts.HRS_EAR:
moEarnigsMap = new HashMap<>();
for (SDbEarning earning : (ArrayList<SDbEarning>) value) {
moEarnigsMap.put(earning.getPkEarningId(), earning);
}
break;
case SModConsts.HRS_DED:
moDeductionsMap = new HashMap<>();
for (SDbDeduction deduction : (ArrayList<SDbDeduction>) value) {
moDeductionsMap.put(deduction.getPkDeductionId(), deduction);
}
break;
default:
}
}
@Override
public Object getValue(final int type) {
Object value = null;
switch (type) {
case SModConsts.HRS_PAY_RCP:
updateReceipt();
value = moHrsReceipt;
break;
default:
break;
}
return value;
}
@Override
public void actionSave() {
try {
if (!mbEditable) {
mnFormResult = SGuiConsts.FORM_RESULT_CANCEL;
dispose();
}
else {
updateReceipt();
super.actionSave();
}
}
catch (Exception e) {
SLibUtils.showException(this, e);
}
}
@Override
public void notifyRowNew(int gridType, int gridSubtype, int row, SGridRow gridRow) {
computeTotal();
}
@Override
public void notifyRowEdit(int gridType, int gridSubtype, int row, SGridRow gridRow) {
computeTotal();
}
@Override
public void notifyRowDelete(int gridType, int gridSubtype, int row, SGridRow gridRow) {
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
JButton button = (JButton) e.getSource();
if (button == jbPickEarning) {
actionPickEarning();
}
else if (button == jbAddEarning) {
actionAddEarning();
}
else if (button == jbPickDeduction) {
actionPickDeduction();
}
else if (button == jbAddDeduction) {
actionAddDeduction();
}
}
else if (e.getSource() instanceof SBeanFieldText) {
SBeanFieldText field = (SBeanFieldText) e.getSource();
if (field == moTextEarningCode) {
actionLoadEarning(false, true);
}
else if (field == moTextDeductionCode) {
actionLoadDeduction(false, true);
}
}
}
@Override
public void focusGained(FocusEvent e) {
if (e.getSource() instanceof SBeanFieldText) {
SBeanFieldText field = (SBeanFieldText) e.getSource();
if (field == moTextEarningCode) {
msOriginalEarningCode = moTextEarningCode.getValue();
}
else if (field == moTextDeductionCode) {
msOriginalDeductionCode = moTextDeductionCode.getValue();
}
}
}
@Override
public void focusLost(FocusEvent e) {
if (e.getSource() instanceof SBeanFieldText) {
SBeanFieldText field = (SBeanFieldText) e.getSource();
if (field == moTextEarningCode) {
if (!msOriginalEarningCode.equals(moTextEarningCode.getValue())) {
actionLoadEarning(true, false);
}
}
else if (field == moTextDeductionCode) {
if (!msOriginalDeductionCode.equals(moTextDeductionCode.getValue())) {
actionLoadDeduction(true, false);
}
}
}
}
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getSource() instanceof SBeanFieldKey && e.getStateChange() == ItemEvent.SELECTED) {
SBeanFieldKey field = (SBeanFieldKey) e.getSource();
if (field == moKeyEarningLoan_n) {
itemStateChangedEarningLoan_n();
}
else if (field == moKeyDeductionLoan_n) {
itemStateChangedDeductionLoan_n();
}
else if (field == moKeyEarningOtherPaymentType) {
itemStateChangedKeyEarningOtherPayment();
}
}
}
@Override
public void editingStopped(ChangeEvent e) {
if (moGridReceiptEarnings.getTable().getDefaultEditor(Double.class).equals(e.getSource())) {
processCellEditionEarning();
}
else if (moGridReceiptDeductions.getTable().getDefaultEditor(Double.class).equals(e.getSource())) {
processCellEditionDeduction();
}
}
@Override
public void editingCanceled(ChangeEvent e) {
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mtrn.form;
import erp.data.SDataConstants;
import erp.data.SDataConstantsSys;
import erp.data.SDataUtilities;
import erp.lib.SLibConstants;
import erp.lib.SLibUtilities;
import erp.lib.form.SFormComponentItem;
import erp.lib.form.SFormField;
import erp.lib.form.SFormUtilities;
import erp.lib.form.SFormValidation;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Map;
import java.util.Vector;
import javax.swing.AbstractAction;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
/**
*
* @author Alfonso Flores
*/
public class SDialogRepDpsWithBalance extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener {
private int mnFormType;
private int mnFormResult;
private int mnFormStatus;
private boolean mbFirstTime;
private boolean mbResetingForm;
private java.util.Vector<erp.lib.form.SFormField> mvFields;
private erp.client.SClientInterface miClient;
private erp.lib.form.SFormField moFieldDate;
private erp.lib.form.SFormField moFieldCompanyBranch;
private erp.lib.form.SFormField moFieldBizArea;
private erp.lib.form.SFormField moFieldBizPartner;
private erp.lib.form.SFormField moFieldAgent;
private erp.lib.form.SFormField moFieldRoute;
private boolean mbParamIsSupplier;
/** Creates new form SDialogRepDpsWithBalance */
public SDialogRepDpsWithBalance(erp.client.SClientInterface client) {
super(client.getFrame(), true);
miClient = client;
initComponents();
initComponentsExtra();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jlDate = new javax.swing.JLabel();
jftDate = new javax.swing.JFormattedTextField();
jbDate = new javax.swing.JButton();
jPanel6 = new javax.swing.JPanel();
jlCompanyBranch = new javax.swing.JLabel();
jcbCompanyBranch = new javax.swing.JComboBox<SFormComponentItem>();
jPanel5 = new javax.swing.JPanel();
jlBizArea = new javax.swing.JLabel();
jcbBizArea = new javax.swing.JComboBox<SFormComponentItem>();
jPanel7 = new javax.swing.JPanel();
jlBizPartner = new javax.swing.JLabel();
jcbBizPartner = new javax.swing.JComboBox<SFormComponentItem>();
jPanel8 = new javax.swing.JPanel();
jlAgent = new javax.swing.JLabel();
jcbAgent = new javax.swing.JComboBox<SFormComponentItem>();
jPanel9 = new javax.swing.JPanel();
jlRoute = new javax.swing.JLabel();
jcbRoute = new javax.swing.JComboBox<SFormComponentItem>();
jPanel11 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jrbByLocalCurrency = new javax.swing.JRadioButton();
jrbByDpsCurrency = new javax.swing.JRadioButton();
jPanel1 = new javax.swing.JPanel();
jbPrint = new javax.swing.JButton();
jbExit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Reporte de facturas con saldo de clientes");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuración del reporte:"));
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros del reporte:"));
jPanel3.setLayout(new java.awt.GridLayout(6, 1, 5, 5));
jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlDate.setText("Fecha corte: *");
jlDate.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel4.add(jlDate);
jftDate.setText("dd/mm/yyyyy");
jftDate.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel4.add(jftDate);
jbDate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_day.gif"))); // NOI18N
jbDate.setToolTipText("Seleccionar fecha");
jbDate.setFocusable(false);
jbDate.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel4.add(jbDate);
jPanel3.add(jPanel4);
jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlCompanyBranch.setText("Sucursal empresa:");
jlCompanyBranch.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel6.add(jlCompanyBranch);
jcbCompanyBranch.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbCompanyBranch.setPreferredSize(new java.awt.Dimension(266, 23));
jPanel6.add(jcbCompanyBranch);
jPanel3.add(jPanel6);
jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlBizArea.setText("Área negocios:");
jlBizArea.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel5.add(jlBizArea);
jcbBizArea.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbBizArea.setPreferredSize(new java.awt.Dimension(266, 23));
jPanel5.add(jcbBizArea);
jPanel3.add(jPanel5);
jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlBizPartner.setText("<Asoc. negocios>:");
jlBizPartner.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel7.add(jlBizPartner);
jcbBizPartner.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbBizPartner.setPreferredSize(new java.awt.Dimension(266, 23));
jPanel7.add(jcbBizPartner);
jPanel3.add(jPanel7);
jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlAgent.setText("Agente:");
jlAgent.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel8.add(jlAgent);
jcbAgent.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbAgent.setPreferredSize(new java.awt.Dimension(266, 23));
jPanel8.add(jcbAgent);
jPanel3.add(jPanel8);
jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlRoute.setText("Ruta:");
jlRoute.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel9.add(jlRoute);
jcbRoute.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbRoute.setPreferredSize(new java.awt.Dimension(266, 23));
jPanel9.add(jcbRoute);
jPanel3.add(jPanel9);
jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH);
jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Moneda del reporte:"));
jPanel11.setLayout(new java.awt.BorderLayout());
jPanel10.setLayout(new java.awt.GridLayout(2, 1, 0, 5));
buttonGroup1.add(jrbByLocalCurrency);
jrbByLocalCurrency.setText("Moneda local");
jPanel10.add(jrbByLocalCurrency);
buttonGroup1.add(jrbByDpsCurrency);
jrbByDpsCurrency.setText("Moneda del documento");
jPanel10.add(jrbByDpsCurrency);
jPanel11.add(jPanel10, java.awt.BorderLayout.NORTH);
jPanel2.add(jPanel11, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
jPanel1.setPreferredSize(new java.awt.Dimension(392, 33));
jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
jbPrint.setText("Imprimir");
jbPrint.setToolTipText("[Ctrl + Enter]");
jbPrint.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel1.add(jbPrint);
jbExit.setText("Cerrar");
jbExit.setToolTipText("[Escape]");
jbExit.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel1.add(jbExit);
getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
setSize(new java.awt.Dimension(576, 389));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
windowActivated();
}//GEN-LAST:event_formWindowActivated
private void initComponentsExtra() {
mvFields = new Vector<SFormField>();
moFieldDate = new SFormField(miClient, SLibConstants.DATA_TYPE_DATE, true, jftDate, jlDate);
moFieldDate.setPickerButton(jbDate);
moFieldCompanyBranch = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbCompanyBranch, jlCompanyBranch);
moFieldBizArea = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbBizArea, jlBizArea);
moFieldBizPartner = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbBizPartner, jlBizPartner);
moFieldAgent = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbAgent, jlAgent);
moFieldRoute = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbRoute, jlRoute);
mvFields.add(moFieldDate);
mvFields.add(moFieldCompanyBranch);
mvFields.add(moFieldBizArea);
mvFields.add(moFieldBizPartner);
mvFields.add(moFieldAgent);
mvFields.add(moFieldRoute);
jbPrint.addActionListener(this);
jbExit.addActionListener(this);
jbDate.addActionListener(this);
AbstractAction actionOk = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) { actionPrint(); }
};
SFormUtilities.putActionMap(getRootPane(), actionOk, "print", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);
AbstractAction action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) { actionClose(); }
};
SFormUtilities.putActionMap(getRootPane(), action, "exit", KeyEvent.VK_ESCAPE, 0);
setModalityType(ModalityType.MODELESS);
}
private void windowActivated() {
if (mbFirstTime) {
mbFirstTime = false;
if (mbParamIsSupplier) {
setTitle("Reporte de facturas con saldo de proveedores");
jlBizPartner.setText("Proveedor:");
}
else {
setTitle("Reporte de facturas con saldo de clientes");
jlBizPartner.setText("Cliente:");
}
jftDate.requestFocus();
}
}
private void actionPrint() {
Cursor cursor = getCursor();
SFormValidation validation = formValidate();
Map<String, Object> map = null;
JasperPrint jasperPrint = null;
JasperViewer jasperViewer = null;
if (validation.getIsError()) {
if (validation.getComponent() != null) {
validation.getComponent().requestFocus();
}
if (validation.getMessage().length() > 0) {
miClient.showMsgBoxWarning(validation.getMessage());
}
}
else {
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
map = miClient.createReportParams();
map.put("tDate", moFieldDate.getDate());
map.put("sBizArea", moFieldBizArea.getKeyAsIntArray()[0] == 0 ? "(TODAS)" : jcbBizArea.getSelectedItem().toString());
map.put("sCompanyBranch", moFieldCompanyBranch.getKeyAsIntArray()[0] == 0 ? "(TODAS)" : jcbCompanyBranch.getSelectedItem().toString());
map.put("sSalesAgent", moFieldAgent.getKeyAsIntArray()[0] == 0 ? "(TODOS)" : jcbAgent.getSelectedItem().toString());
map.put("sSalesRoute", moFieldRoute.getKeyAsIntArray()[0] == 0 ? "(TODAS)" : jcbRoute.getSelectedItem().toString());
map.put("nFidCtRef", mbParamIsSupplier ? SDataConstantsSys.BPSS_CT_BP_SUP : SDataConstantsSys.BPSS_CT_BP_CUS);
map.put("nFidCtDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[0] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[0]);
map.put("nFidClDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[1] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[1]);
map.put("nFidTpDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[2] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[2]);
map.put("sSqlWhereBizArea", moFieldBizArea.getKeyAsIntArray()[0] == 0 ? "" : " AND b.fid_ba = " + moFieldBizArea.getKeyAsIntArray()[0]);
map.put("sSqlWhereCompanyBranch", moFieldCompanyBranch.getKeyAsIntArray()[0] == 0 ? "" : " AND r.fid_cob = " + moFieldCompanyBranch.getKeyAsIntArray()[0]);
map.put("sSqlWhereBizPartner", moFieldBizPartner.getKeyAsIntArray()[0] == 0 ? "" : " AND re.fid_bp_nr = " + moFieldBizPartner.getKeyAsIntArray()[0]);
map.put("sSqlWhereSalesAgent", moFieldAgent.getKeyAsIntArray()[0] == 0 ? "" : " AND d.fid_sal_agt_n = " + moFieldAgent.getKeyAsIntArray()[0]);
map.put("sSqlWhereSalesRoute", moFieldRoute.getKeyAsIntArray()[0] == 0 ? "" : " AND rou.fid_sal_route = " + moFieldRoute.getKeyAsIntArray()[0]);
map.put("sTitle", mbParamIsSupplier ? " DE PROVEEDORES" : " DE CLIENTES");
map.put("sLocalCurrency", miClient.getSessionXXX().getParamsErp().getDbmsDataCurrency().getCurrency());
map.put("sBizPartner", moFieldBizPartner.getKeyAsIntArray()[0] == 0 ? "(TODOS)" : jcbBizPartner.getSelectedItem().toString());
map.put("nFidStDps", SDataConstantsSys.TRNS_ST_DPS_EMITED);
map.put("nFidStDpsVal", SDataConstantsSys.TRNS_ST_DPS_VAL_EFF);
map.put("nFidAccSysCat", mbParamIsSupplier ? SDataConstantsSys.FINS_TP_SYS_MOV_BPS_SUP[0] : SDataConstantsSys.FINS_TP_SYS_MOV_BPS_CUS[0]);
map.put("nFidAccSysTp", mbParamIsSupplier ? SDataConstantsSys.FINS_TP_SYS_MOV_BPS_SUP[1] : SDataConstantsSys.FINS_TP_SYS_MOV_BPS_CUS[1]);
map.put("sMark", mbParamIsSupplier ? "" : SDataConstantsSys.TXT_UNSIGNED);
jasperPrint = SDataUtilities.fillReport(miClient, jrbByDpsCurrency.isSelected() ? SDataConstantsSys.REP_TRN_DPS_UNP_CY : SDataConstantsSys.REP_TRN_DPS_UNP, map);
jasperViewer = new JasperViewer(jasperPrint, false);
jasperViewer.setTitle("Reporte de facturas con saldo " + (mbParamIsSupplier ? "de proveedores" : "de clientes"));
jasperViewer.setVisible(true);
}
catch(Exception e) {
SLibUtilities.renderException(this, e);
}
finally {
setCursor(cursor);
}
}
}
private void actionClose() {
mnFormResult = SLibConstants.FORM_RESULT_CANCEL;
setVisible(false);
}
private void actionDate() {
miClient.getGuiDatePickerXXX().formReset();
miClient.getGuiDatePickerXXX().setDate(moFieldDate.getDate());
miClient.getGuiDatePickerXXX().setVisible(true);
if (miClient.getGuiDatePickerXXX().getFormResult() == SLibConstants.FORM_RESULT_OK) {
moFieldDate.setFieldValue(miClient.getGuiDatePickerXXX().getGuiDate());
jftDate.requestFocus();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JButton jbDate;
private javax.swing.JButton jbExit;
private javax.swing.JButton jbPrint;
private javax.swing.JComboBox<SFormComponentItem> jcbAgent;
private javax.swing.JComboBox<SFormComponentItem> jcbBizArea;
private javax.swing.JComboBox<SFormComponentItem> jcbBizPartner;
private javax.swing.JComboBox<SFormComponentItem> jcbCompanyBranch;
private javax.swing.JComboBox<SFormComponentItem> jcbRoute;
private javax.swing.JFormattedTextField jftDate;
private javax.swing.JLabel jlAgent;
private javax.swing.JLabel jlBizArea;
private javax.swing.JLabel jlBizPartner;
private javax.swing.JLabel jlCompanyBranch;
private javax.swing.JLabel jlDate;
private javax.swing.JLabel jlRoute;
private javax.swing.JRadioButton jrbByDpsCurrency;
private javax.swing.JRadioButton jrbByLocalCurrency;
// End of variables declaration//GEN-END:variables
@Override
public void formClearRegistry() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void formReset() {
mnFormResult = SLibConstants.UNDEFINED;
mnFormStatus = SLibConstants.UNDEFINED;
mbFirstTime = true;
for (int i = 0; i < mvFields.size(); i++) {
((erp.lib.form.SFormField) mvFields.get(i)).resetField();
}
moFieldDate.setFieldValue(miClient.getSessionXXX().getWorkingDate());
jrbByLocalCurrency.setSelected(true);
}
@Override
public void formRefreshCatalogues() {
SFormUtilities.populateComboBox(miClient, jcbBizArea, SDataConstants.BPSU_BA);
SFormUtilities.populateComboBox(miClient, jcbCompanyBranch, SDataConstants.BPSU_BPB, new int[] { miClient.getSessionXXX().getCurrentCompany().getPkCompanyId() });
SFormUtilities.populateComboBox(miClient, jcbBizPartner, mbParamIsSupplier ? SDataConstants.BPSX_BP_SUP : SDataConstants.BPSX_BP_CUS);
SFormUtilities.populateComboBox(miClient, jcbAgent, SDataConstants.BPSX_BP_ATT_SAL_AGT);
SFormUtilities.populateComboBox(miClient, jcbRoute, SDataConstants.MKTU_SAL_ROUTE);
}
@Override
public erp.lib.form.SFormValidation formValidate() {
SFormValidation validation = new SFormValidation();
for (int i = 0; i < mvFields.size(); i++) {
if (!((erp.lib.form.SFormField) mvFields.get(i)).validateField()) {
validation.setIsError(true);
validation.setComponent(((erp.lib.form.SFormField) mvFields.get(i)).getComponent());
break;
}
}
return validation;
}
@Override
public void setFormStatus(int status) {
mnFormStatus = status;
}
@Override
public void setFormVisible(boolean visible) {
setVisible(visible);
}
@Override
public int getFormStatus() {
return mnFormStatus;
}
@Override
public int getFormResult() {
return mnFormResult;
}
@Override
public void setRegistry(erp.lib.data.SDataRegistry registry) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public erp.lib.data.SDataRegistry getRegistry() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setValue(int type, java.lang.Object value) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public java.lang.Object getValue(int type) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public javax.swing.JLabel getTimeoutLabel() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
if (e.getSource() instanceof javax.swing.JButton) {
javax.swing.JButton button = (javax.swing.JButton) e.getSource();
if (button == jbPrint) {
actionPrint();
}
else if (button == jbExit) {
actionClose();
}
else if (button == jbDate) {
actionDate();
}
}
}
public void setParamIsSupplier(boolean b) { mbParamIsSupplier = b; }
}
|
package okapi;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.ext.dropwizard.DropwizardMetricsOptions;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(VertxUnitRunner.class)
public class MetricsTest {
private Vertx vertx;
private Async async;
private HttpClient httpClient;
private int port;
private ConsoleReporter reporter1;
private GraphiteReporter reporter2;
public MetricsTest() {
}
@Before
public void setUp(TestContext context) {
port = Integer.parseInt(System.getProperty("port", "9130"));
String graphiteHost = System.getProperty("graphiteHost");
final String registryName = "okapi";
MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);
// Note the setEnabled (true or false)
DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions().
setEnabled(false).setRegistryName(registryName);
vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(metricsOpt));
reporter1 = ConsoleReporter.forRegistry(registry).build();
reporter1.start(1, TimeUnit.SECONDS);
if (graphiteHost != null) {
Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, 2003));
reporter2 = GraphiteReporter.forRegistry(registry)
.prefixedWith("okapiserver")
.build(graphite);
reporter2.start(1, TimeUnit.MILLISECONDS);
}
DeploymentOptions opt = new DeploymentOptions();
vertx.deployVerticle(MainVerticle.class.getName(),
opt, context.asyncAssertSuccess());
httpClient = vertx.createHttpClient();
}
@After
public void tearDown(TestContext context) {
vertx.close(context.asyncAssertSuccess());
if (reporter1 != null) {
reporter1.report();
reporter1.stop();
}
if (reporter2 != null) {
reporter2.report();
reporter2.stop();
}
}
@Test
public void test1(TestContext context) {
async = context.async();
checkHealth(context);
}
public void checkHealth(TestContext context) {
httpClient.get(port, "localhost", "/_/health", response -> {
response.handler(body -> {
context.assertEquals(200, response.statusCode());
});
response.endHandler(x -> {
done(context);
});
}).end();
}
public void done(TestContext context) {
async.complete();
}
}
|
//@snippet-start cma_main_migrator
package org.objectweb.proactive.examples.userguide.cmagent.migration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PADeployment;
import org.objectweb.proactive.api.PALifeCycle;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.ActiveObjectCreationException;
public class Main {
private static VirtualNode deploy(String descriptor) {
ProActiveDescriptor pad;
VirtualNode vn;
try {
//create object representation of the deployment file
pad = PADeployment.getProactiveDescriptor(descriptor);
//active all Virtual Nodes
pad.activateMappings();
//get the first Node available in the first Virtual Node
//specified in the descriptor file
vn = pad.getVirtualNodes()[0];
return vn;
} catch (NodeException nodeExcep) {
System.err.println(nodeExcep.getMessage());
} catch (ProActiveException proExcep) {
System.err.println(proExcep.getMessage());
}
return null;
}
public static void main(String args[]) {
try {
BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(System.in));
VirtualNode vn = deploy(args[0]);
String currentState = new String();
//@snippet-start cma_migrator_ao
//create the active oject
CMAgentMigrator ao = (CMAgentMigrator) PAActiveObject.newActive(CMAgentMigrator.class.getName(),
new Object[] {}, vn.getNode());
//@snippet-end cma_migrator_ao
// int input = 0;
int k = 1;
int choice;
while (k != 0) {
//display the menu with the available nodes
k = 1;
for (Node node : vn.getNodes()) {
System.out.println(k + ". Statistics for node :" + node.getNodeInformation().getURL());
k++;
}
System.out.println("0. Exit");
//select a node
do {
System.out.print("Choose a node :> ");
try {
// Read am option from keyboard
choice = Integer.parseInt(inputBuffer.readLine().trim());
} catch (NumberFormatException noExcep) {
choice = -1;
}
} while (!(choice >= 1 && choice < k || choice == 0));
if (choice == 0)
break;
//display information for the selected node
ao.migrateTo(vn.getNodes()[choice - 1]); //migrate
currentState = ao.getCurrentState().toString(); //get the state
System.out.println("\n" + currentState);
System.out.println("Calculating the statistics took " +
ao.getLastRequestServeTime().longValue() + "ms \n");
}
//stopping all the objects and JVMS
PAActiveObject.terminateActiveObject(ao, false);
vn.killAll(true);
PALifeCycle.exitSuccess();
} catch (NodeException nodeExcep) {
System.err.println(nodeExcep.getMessage());
} catch (ActiveObjectCreationException aoExcep) {
System.err.println(aoExcep.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
}
//@snippet-end cma_main_migrator
|
// This code is developed as part of the Java CoG Kit project
// This message may not be removed or altered.
package org.globus.cog.karajan.scheduler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.impl.common.StatusEvent;
import org.globus.cog.abstraction.interfaces.Service;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.StatusListener;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.abstraction.interfaces.TaskHandler;
import org.globus.cog.karajan.util.BoundContact;
import org.globus.cog.karajan.util.Contact;
import org.globus.cog.karajan.util.ContactSet;
import org.globus.cog.karajan.util.Queue;
import org.globus.cog.karajan.util.TaskHandlerWrapper;
import org.globus.cog.karajan.util.TypeUtil;
public abstract class AbstractScheduler extends Thread implements Scheduler {
private static final Logger logger = Logger.getLogger(AbstractScheduler.class);
public static final int THROTTLE_OFF = 100000000;
private List taskHandlers;
private final Map handlerMap;
private int maxSimultaneousJobs;
private final Queue jobs;
private final Map listeners;
private ContactSet grid;
private final Map properties;
private final Map constraints;
private List taskTransformers, failureHandlers;
private ResourceConstraintChecker constraintChecker;
public AbstractScheduler() {
super("Scheduler");
jobs = new Queue();
listeners = new HashMap();
handlerMap = new HashMap();
grid = new ContactSet();
maxSimultaneousJobs = 16384;
properties = new HashMap();
constraints = new HashMap();
taskTransformers = new LinkedList();
failureHandlers = new LinkedList();
// We always have the local file provider
TaskHandlerWrapper local = new TaskHandlerWrapper();
local.setProvider("local");
local.setType(TaskHandler.FILE_OPERATION);
this.addTaskHandler(local);
}
public final void addTaskHandler(TaskHandlerWrapper taskHandler) {
if (taskHandlers == null) {
taskHandlers = new LinkedList();
}
taskHandlers.add(taskHandler);
Integer type = new Integer(taskHandler.getType());
Map ht = (Map) handlerMap.get(type);
if (ht == null) {
ht = new HashMap();
handlerMap.put(type, ht);
}
ht.put(taskHandler.getProvider(), taskHandler);
}
public List getTaskHandlers() {
return taskHandlers;
}
public void setTaskHandlers(List taskHandlers) {
this.taskHandlers = taskHandlers;
}
public TaskHandlerWrapper getTaskHadlerWrapper(int index) {
return (TaskHandlerWrapper) getTaskHandlers().get(index);
}
public Collection getTaskHandlerWrappers(int type) {
Integer itype = new Integer(type);
if (handlerMap.containsKey(itype)) {
return ((Map) handlerMap.get(itype)).values();
}
else {
return new LinkedList();
}
}
public TaskHandlerWrapper getTaskHandlerWrapper(int type, String provider) {
Integer itype = new Integer(type);
if (handlerMap.containsKey(itype)) {
return (TaskHandlerWrapper) ((Map) handlerMap.get(itype)).get(provider);
}
return null;
}
public void setResources(ContactSet grid) {
if (logger.isInfoEnabled()) {
logger.info("Setting resources to: " + grid);
}
this.grid = grid;
}
public ContactSet getResources() {
return grid;
}
public void addJobStatusListener(StatusListener l, Task task) {
List jobListeners;
synchronized (listeners) {
if (listeners.containsKey(task)) {
jobListeners = (List) listeners.get(task);
}
else {
jobListeners = new ArrayList();
listeners.put(task, jobListeners);
}
jobListeners.add(l);
}
}
public void removeJobStatusListener(StatusListener l, Task task) {
synchronized (listeners) {
if (listeners.containsKey(task)) {
List jobListeners = (List) listeners.get(task);
jobListeners.remove(l);
if (jobListeners.size() == 0) {
listeners.remove(task);
}
}
}
}
public void fireJobStatusChangeEvent(StatusEvent e) {
List jobListeners = null;
synchronized (listeners) {
if (listeners.containsKey(e.getSource())) {
jobListeners = new ArrayList((List) listeners.get(e.getSource()));
}
}
if (jobListeners != null) {
Iterator i = jobListeners.iterator();
while (i.hasNext()) {
((StatusListener) i.next()).statusChanged(e);
}
}
}
public void fireJobStatusChangeEvent(Task source, Status status) {
StatusEvent jsce = new StatusEvent(source, status);
fireJobStatusChangeEvent(jsce);
}
public int getMaxSimultaneousJobs() {
return maxSimultaneousJobs;
}
public void setMaxSimultaneousJobs(int i) {
maxSimultaneousJobs = i;
}
public Queue getJobQueue() {
return jobs;
}
public void setProperty(String name, Object value) {
if (name.equalsIgnoreCase("maxSimultaneousJobs")) {
logger.debug("Scheduler: setting maxSimultaneousJobs to " + value);
setMaxSimultaneousJobs(throttleValue(value));
}
else {
throw new IllegalArgumentException("Unsupported property: " + name
+ ". Supported properties are: " + Arrays.asList(this.getPropertyNames()));
}
}
protected int throttleValue(Object value) {
if ("off".equalsIgnoreCase(value.toString())) {
return THROTTLE_OFF;
}
else {
return TypeUtil.toInt(value);
}
}
protected float floatThrottleValue(Object value) {
if ("off".equalsIgnoreCase(value.toString())) {
return THROTTLE_OFF;
}
else {
return (float) TypeUtil.toDouble(value);
}
}
public Object getProperty(String name) {
return properties.get(name);
}
public static final String[] propertyNames = new String[] { "maxSimultaneousJobs" };
public String[] getPropertyNames() {
return propertyNames;
}
public static String[] combineNames(String[] first, String[] last) {
String[] combined = new String[first.length + last.length];
System.arraycopy(first, 0, combined, 0, first.length);
System.arraycopy(last, 0, combined, first.length, last.length);
return combined;
}
public void setConstraints(Task task, Object constraint) {
synchronized (constraints) {
constraints.put(task, constraint);
}
}
public Object getConstraints(Task task) {
synchronized (constraints) {
return constraints.get(task);
}
}
protected void removeConstraints(Task task) {
synchronized (constraints) {
constraints.remove(task);
}
}
public void addTaskTransformer(TaskTransformer taskTransformer) {
this.taskTransformers.add(taskTransformer);
}
public List getTaskTransformers() {
return taskTransformers;
}
protected void applyTaskTransformers(Task t, Contact[] contacts, Service[] services) {
List transformers = getTaskTransformers();
Iterator i = transformers.iterator();
while (i.hasNext()) {
((TaskTransformer) i.next()).transformTask(t, contacts, services);
}
}
protected boolean runFailureHandlers(Task t) {
Iterator i = failureHandlers.iterator();
while (i.hasNext()) {
FailureHandler fh = (FailureHandler) i.next();
if (fh.handleFailure(t, this)) {
return true;
}
}
return false;
}
public void addFailureHandler(FailureHandler handler) {
failureHandlers.add(handler);
}
public ResourceConstraintChecker getConstraintChecker() {
return constraintChecker;
}
public void setConstraintChecker(ResourceConstraintChecker constraintChecker) {
this.constraintChecker = constraintChecker;
}
protected boolean checkConstraints(BoundContact resource, TaskConstraints tc) {
if (constraintChecker == null) {
return true;
}
else {
return constraintChecker.checkConstraints(resource, tc);
}
}
protected List checkConstraints(List resources, TaskConstraints tc) {
if (constraintChecker == null) {
return resources;
}
else {
return constraintChecker.checkConstraints(resources, tc);
}
}
}
|
package dr.evomodel.treedatalikelihood.discrete;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.treedatalikelihood.BeagleDataLikelihoodDelegate;
import dr.evomodel.treedatalikelihood.TreeDataLikelihood;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.loggers.Loggable;
import dr.inference.model.Parameter;
import dr.math.MultivariateFunction;
import dr.math.NumericalDerivative;
import dr.xml.Reportable;
import java.util.Arrays;
import static dr.math.MachineAccuracy.SQRT_EPSILON;
/**
* @author Marc A. Suchard
* @author Xiang Ji
*/
public class NodeHeightGradientForDiscreteTrait extends DiscreteTraitBranchRateGradient
implements GradientWrtParameterProvider, Reportable, Loggable {
private final double[] nodeHeights;
private final TreeModel treeModel;
public NodeHeightGradientForDiscreteTrait(String traitName,
TreeDataLikelihood treeDataLikelihood,
BeagleDataLikelihoodDelegate likelihoodDelegate,
Parameter rateParameter) {
super(traitName, treeDataLikelihood, likelihoodDelegate, rateParameter, false);
if (!(treeDataLikelihood.getTree() instanceof TreeModel)) {
throw new IllegalArgumentException("Must provide a TreeModel");
}
this.treeModel = (TreeModel) treeDataLikelihood.getTree();
this.nodeHeights = new double[tree.getInternalNodeCount()];
}
@Override
public Parameter getParameter() {
return treeModel.createNodeHeightsParameter(true, true, false);
}
@Override
public double[] getGradientLogDensity() {
double[] result = new double[tree.getInternalNodeCount()];
Arrays.fill(result, 0.0);
//Do single call to traitProvider with node == null (get full tree)
double[] gradient = (double[]) treeTraitProvider.getTrait(tree, null);
for (int i = 0; i < tree.getInternalNodeCount(); ++i) {
final NodeRef internalNode = tree.getInternalNode(i);
if (!tree.isRoot(internalNode)) {
final int internalNodeNumber = internalNode.getNumber();
result[i] -= gradient[internalNodeNumber] * branchRateModel.getBranchRate(tree, internalNode);
}
for (int j = 0; j < tree.getChildCount(internalNode); ++j){
NodeRef childNode = tree.getChild(internalNode, j);
final int childNodeNumber = childNode.getNumber();
result[i] += gradient[childNodeNumber] * branchRateModel.getBranchRate(tree, childNode);
}
}
return result;
}
private double[] getNodeHeights() {
for (int i = 0; i < tree.getInternalNodeCount(); ++i){
NodeRef internalNode = tree.getInternalNode(i);
nodeHeights[i] = tree.getNodeHeight(internalNode);
}
return nodeHeights;
}
private MultivariateFunction numeric1 = new MultivariateFunction() {
@Override
public double evaluate(double[] argument) {
for (int i = 0; i < argument.length; ++i) {
NodeRef internalNode = tree.getInternalNode(i);
treeModel.setNodeHeight(internalNode, argument[i]);
}
treeDataLikelihood.makeDirty();
return treeDataLikelihood.getLogLikelihood();
}
@Override
public int getNumArguments() {
return tree.getInternalNodeCount();
}
@Override
public double getLowerBound(int n) {
return 0;
}
@Override
public double getUpperBound(int n) {
return Double.POSITIVE_INFINITY;
}
};
@Override
public String getReport() {
treeDataLikelihood.makeDirty();
double[] savedValues = getNodeHeights();
double[] testGradient = null;
boolean largeEnoughValues = valuesAreSufficientlyLarge(getNodeHeights());
if (DEBUG && largeEnoughValues) {
testGradient = NumericalDerivative.gradient(numeric1, getNodeHeights());
}
for (int i = 0; i < savedValues.length; ++i) {
NodeRef internalNode = tree.getInternalNode(i);
treeModel.setNodeHeight(internalNode, savedValues[i]);
}
StringBuilder sb = new StringBuilder();
sb.append("Peeling: ").append(new dr.math.matrixAlgebra.Vector(getGradientLogDensity()));
sb.append("\n");
if (testGradient != null && largeEnoughValues) {
sb.append("numeric: ").append(new dr.math.matrixAlgebra.Vector(testGradient));
} else {
sb.append("mumeric: too close to 0");
}
sb.append("\n");
treeDataLikelihood.makeDirty();
return sb.toString();
}
private static final boolean DEBUG = true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.