answer
stringlengths 17
10.2M
|
|---|
package burlap.behavior.singleagent;
import burlap.oomdp.core.AbstractGroundedAction;
import burlap.oomdp.core.State;
/**
* This class is used to store Q-values.
* @author James MacGlashan
*
*/
public class QValue {
/**
* The state with which this Q-value is associated.
*/
public State s;
/**
* The action with which this Q-value is associated
*/
public AbstractGroundedAction a;
/**
* The numeric Q-value
*/
public double q;
/**
* Creates a Q-value for the given state an action pair with the specified q-value
* @param s the state
* @param a the action
* @param q the initial Q-value
*/
public QValue(State s, AbstractGroundedAction a, double q){
this.s = s;
this.a = a;
this.q = q;
}
/**
* Initialializes this Q-value by copying the information from another Q-value.
* @param src the source Q-value from which to copy.
*/
public QValue(QValue src){
this.s = src.s.copy();
this.a = src.a.copy();
this.q = src.q;
}
}
|
package com.joy.app.utils;
import android.content.Context;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.joy.app.JoyApplication;
import com.joy.app.utils.map.MapUtil;
import java.util.List;
/**
* @author litong
* @Description
* @: joy-android
* @: 16/1/8/11:24
* @: LocationUtil
*/
public class LocationUtil implements AMapLocationListener {
private boolean MockEnable = true;
private boolean WifiActive = true;
private boolean NeedAddress = true;
private AMapLocationClient locationClient;
private AMapLocationClientOption locationOption;
private Context mContext;
public LocationUtil(Context mContext) {
this.mContext = mContext;
}
/**
*
* @param mockEnable
*/
public void setMockEnable(boolean mockEnable) {
MockEnable = mockEnable;
}
/**
* WIFI
* @param wifiActive
*/
public void setWifiActive(boolean wifiActive) {
WifiActive = wifiActive;
}
/**
*
* @param needAddress
*/
public void setNeedAddress(boolean needAddress) {
NeedAddress = needAddress;
}
public void resetClientOption(boolean OnceLocation){
if (locationOption == null){
locationOption = new AMapLocationClientOption();
}
locationOption.setNeedAddress(NeedAddress);
//,false
locationOption.setOnceLocation(OnceLocation);
//WIFI
locationOption.setWifiActiveScan(WifiActive);
//,false
locationOption.setMockEnable(MockEnable);
}
public AMapLocationClient getLocationClient() {
if (locationClient == null){
locationClient = new AMapLocationClient(mContext);
if (locationOption == null){
resetClientOption(false);
}
locationClient.setLocationOption(locationOption);
}
return locationClient;
}
public void gettAccuracyLocation(AMapLocationListener listener, long Interval) {
resetClientOption(false);
locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//,,2000ms
locationOption.setInterval(Interval);
getLocationClient().setLocationListener(listener);
}
public void gettBatterySavingLocation(AMapLocationListener listener, long Interval) {
resetClientOption(false);
locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//,,2000ms
locationOption.setInterval(Interval);
getLocationClient().setLocationListener(listener);
}
public void getOnceLocation(AMapLocationListener listener) {
resetClientOption(true);
locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
getLocationClient().setLocationListener(listener);
getLocationClient().startLocation();
}
public void getOnceLocation() {
getOnceLocation(this);
}
public void getLastLocation(AMapLocationListener listener){
if (getLocationClient().getLastKnownLocation() != null){
listener.onLocationChanged(getLocationClient().getLastKnownLocation());
}else{
getOnceLocation(listener);
}
}
public AMapLocation getLastKnownLocation(){
return getLocationClient().getLastKnownLocation();
}
public void startLocation(){
if (locationClient != null) {
locationClient.startLocation();
}
}
public void stopLocation(){
if (locationClient != null && locationClient.isStarted()) {
locationClient.stopLocation();
}
}
public void removeListener(AMapLocationListener listener){
stopLocation();
locationClient.unRegisterLocationListener(listener);
}
public void onDestroy() {
if (locationClient != null) {
locationClient.onDestroy();
locationClient = null;
}
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
MapUtil.showLocationInfor(aMapLocation);
removeListener(this);
}
}
|
package com.mindorks.test;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.mindorks.butterknifelite.ButterKnifeLite;
import com.mindorks.butterknifelite.annotations.BindView;
import com.mindorks.butterknifelite.annotations.OnClick;
import com.mindorks.placeholderview.ExpandablePlaceHolderView;
import com.mindorks.test.expandable.ChildItem;
import com.mindorks.test.expandable.ParentItem;
public class TestActivity extends AppCompatActivity {
ParentItem parentItem;
@BindView(R.id.toolbar)
private Toolbar mToolbar;
@BindView(R.id.expandableView)
private ExpandablePlaceHolderView mExpandableView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnifeLite.bind(this);
parentItem = new ParentItem(this.getApplicationContext());
mExpandableView
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(parentItem)
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ParentItem(this.getApplicationContext()))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView))
.addView(new ChildItem(mExpandableView));
}
// @OnClick(R.id.collapse)
// void onCollapse() {
// try {
// mExpandableView.collapse(0);
// }catch (Resources.NotFoundException e){
// e.printStackTrace();
// @OnClick(R.id.expand)
// void onExpand() {
// try {
// mExpandableView.expand(0);
// }catch (Resources.NotFoundException e){
// e.printStackTrace();
@OnClick(R.id.collapse)
void onCollapse() {
try {
mExpandableView.collapse(parentItem);
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
@OnClick(R.id.expand)
void onExpand() {
try {
mExpandableView.expand(parentItem);
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
}
|
package org.fossasia.db;
import android.content.Context;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.fossasia.api.FossasiaUrls;
import org.fossasia.model.FossasiaEvent;
import org.fossasia.model.Speaker;
import org.fossasia.model.Sponsor;
import org.fossasia.model.Venue;
import org.fossasia.utils.StringUtils;
import org.fossasia.utils.VolleySingleton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class JsonToDatabase {
private final static String TAG = "JSON_TO_DATABASE";
private Context context;
private boolean tracks;
private ArrayList<String> queries;
private JsonToDatabaseCallback mCallback;
private int count;
public JsonToDatabase(Context context) {
count = 0;
this.context = context;
queries = new ArrayList<String>();
tracks = false;
}
public void setOnJsonToDatabaseCallback(JsonToDatabaseCallback callback) {
this.mCallback = callback;
}
public void startDataDownload() {
fetchTracks(FossasiaUrls.TRACKS_URL);
startTrackUrlFetch(FossasiaUrls.VERSION_TRACK_URL);
SponsorUrl(FossasiaUrls.SPONSOR_URL);
}
private void SponsorUrl(final String sponsorUrl) {
RequestQueue queue = VolleySingleton.getReqQueue(context);
//Request string reponse from the url
StringRequest stringRequest = new StringRequest(sponsorUrl, new Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray jsonArray1 = removePaddingFromString(response);
String name;
String img;
String url;
Sponsor temp;
for (int i=0;i<jsonArray1.length();i++){
try{
name = jsonArray1.getJSONObject(i).getJSONArray("c").getJSONObject(0).getString("v");
img = jsonArray1.getJSONObject(i).getJSONArray("c").getJSONObject(1).getString("v");
url = jsonArray1.getJSONObject(i).getJSONArray("c").getJSONObject(2).getString("v");
temp = new Sponsor((i+1),name,img,url);
String ab = temp.generatesql();
queries.add(ab);
// Log.d(TAG,ab);
}
catch ( JSONException e){
// Log.e(TAG, "JSON error: " + e.getMessage() + "\nResponse: " + response);
}
}
}
}
, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Log.d(TAG, "VOLLEY ERROR :" + error.getMessage());
}
}
);
queue.add(stringRequest);
}
private void startTrackUrlFetch(String url) {
RequestQueue queue = VolleySingleton.getReqQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(url, new Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray jsonArray = removePaddingFromString(response);
//Log.d(TAG, jsonArray.toString());
String name;
String url;
String venue;
String address;
String howToReach;
String link;
String room;
String mapLocation;
String version;
String forceTrack;
Venue temp;
for (int i = 0; i < jsonArray.length(); i++) {
try {
name = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(0)
.getString("v");
url = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(1)
.getString("f");
venue = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(2)
.getString("v");
room = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(3)
.getString("v");
link = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(4)
.getString("v");
address = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(6)
.getString("v");
howToReach = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(7)
.getString("v");
version = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(8)
.getString("v");
mapLocation = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(5)
.getString("v");
String query = "INSERT INTO %s VALUES (%d, '%s', '%s', '%s');";
query = String.format(query, DatabaseHelper.TABLE_NAME_TRACK_VENUE, i, name, venue, mapLocation);
queries.add(query);
temp = new Venue(name, venue, mapLocation, room, link, address, howToReach);
//Generate query
queries.add(temp.generateSql());
// Log.d(TAG, name);
fetchData(FossasiaUrls.PART_URL + url, venue, name, (i + 50) * 100);
} catch (JSONException e) {
// Log.e(TAG, "JSON Error: " + e.getMessage() + "\nResponse" + response);
}
}
count
checkStatus();
}
}
, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
count
checkStatus();
}
}
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
count++;
}
private void fetchData(String url, final String venue, final String forceTrack, final int id) {
final RequestQueue queue = VolleySingleton.getReqQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(url, new Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray jsonArray = removePaddingFromString(response);
// Log.d(TAG, jsonArray.toString());
String firstName;
String lastName;
String time;
String date;
String organization;
String email;
String blog;
String twitter;
String typeOfProposal;
String topicName;
String field;
String day;
String proposalAbstract;
String description;
String url;
String fullName;
String linkedIn;
String moderator;
for (int i = 0; i < jsonArray.length(); i++) {
try {
firstName = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.FIRST_NAME)
.getString("v");
lastName = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.LAST_NAME)
.getString("v");
time = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.TIME)
.getString("f");
date = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.DATE)
.getString("v");
organization = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.ORGANIZATION)
.getString("v");
email = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.EMAIL)
.getString("v");
blog = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.BLOG)
.getString("v");
twitter = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.TWITTER)
.getString("v");
typeOfProposal = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.TYPE_OF_PROPOSAL)
.getString("v");
topicName = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.TOPIC_NAME)
.getString("v");
field = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.TRACK)
.getString("v");
proposalAbstract = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.ABSTRACT)
.getString("v");
description = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.DESCRIPTION)
.getString("v");
url = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.URL)
.getString("v");
linkedIn = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.LINKEDIN)
.getString("v");
moderator = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(Constants.MODERATOR)
.getString("v");
String logData = "First Name: %s\nLast Name: %s\nDate: %s\nTime: %s\nOrganization: %s\nEmail: %s\nBlog: %s\nTwitter: %s\nType Of Proposal: %s\nTopic Name:%s\nTrack: %s\nAbstarct: %s\nDescription: %s\nURL: %s";
// logData = String.format(logData, firstName, lastName, date, time, organization, email, blog, twitter, typeOfProposal, topicName, field, proposalAbstract, description, url);
// Log.d(TAG, logData);
int id2 = id + i;
if (date.equals("") || firstName.equals("") || time.equals("") || topicName.equals("")) {
continue;
}
String[] dayDate = date.split(" ");
day = dayDate[0];
date = dayDate[1] + " " + dayDate[2];
FossasiaEvent temp = new FossasiaEvent(id2, topicName, field, date, day, time, proposalAbstract, description, venue, forceTrack, moderator);
fullName = firstName + " " + lastName;
Speaker tempSpeaker = new Speaker(id2, fullName, "", linkedIn, twitter, organization, url, 0);
queries.add(tempSpeaker.generateSqlQuery());
queries.add(temp.generateSqlQuery());
String query = "INSERT INTO %s VALUES ('%s', %d, '%s');";
query = String.format(query, DatabaseHelper.TABLE_NAME_SPEAKER_EVENT_RELATION, fullName, id2, StringUtils.replaceUnicode(topicName));
// Log.d(TAG, query);
queries.add(query);
} catch (JSONException e) {
// Log.e(TAG, "JSON Error: " + e.getMessage() + "\nResponse" + response);
}
}
count
checkStatus();
}
}
, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
count
checkStatus();
}
}
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
count++;
}
private void fetchTracks(String url) {
RequestQueue queue = VolleySingleton.getReqQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(url, new Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray jsonArray = removePaddingFromString(response);
// Log.d(TAG, jsonArray.toString());
String trackName;
String trackInformation;
for (int i = 0; i < jsonArray.length(); i++) {
try {
trackName = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(0)
.getString("v");
trackInformation = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(1)
.getString("v");
String query = "INSERT INTO %s VALUES (%d, '%s', '%s');";
query = String.format(query, DatabaseHelper.TABLE_NAME_TRACK, i, StringUtils.replaceUnicode(trackName), StringUtils.replaceUnicode(trackInformation));
// Log.d(TAG, query);
queries.add(query);
} catch (JSONException e) {
// Log.e(TAG, "JSON Error: " + e.getMessage() + "\nResponse" + response);
}
}
tracks = true;
checkStatus();
}
}
, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tracks = true;
checkStatus();
}
}
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private void fetchSpeakerEventRelation(String url) {
RequestQueue queue = VolleySingleton.getReqQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(url, new Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray jsonArray = removePaddingFromString(response);
// Log.d(TAG, jsonArray.toString());
String speaker;
String event;
for (int i = 0; i < jsonArray.length(); i++) {
try {
speaker = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(0)
.getString("v");
event = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(1)
.getString("v");
String query = "INSERT INTO %s VALUES ('%s', '%s');";
query = String.format(query, DatabaseHelper.TABLE_NAME_SPEAKER_EVENT_RELATION, speaker, event);
// Log.d(TAG, query);
queries.add(query);
} catch (JSONException e) {
// Log.e(TAG, "JSON Error: " + e.getMessage() + "\nResponse" + response);
}
}
// speakerEventRelation = true;
checkStatus();
}
}
, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// speakerEventRelation = true;
checkStatus();
}
}
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private void fetchKeySpeakers(String url) {
RequestQueue queue = VolleySingleton.getReqQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(url, new Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray jsonArray = removePaddingFromString(response);
// Log.d(TAG, jsonArray.toString());
String name;
String designation;
String profilePicUrl;
String information;
String twitterHandle;
String linkedInUrl;
int isKeySpeaker;
for (int i = 0; i < jsonArray.length(); i++) {
try {
name = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(0)
.getString("v");
designation = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(1)
.getString("v");
information = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(2)
.getString("v");
twitterHandle = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(3)
.getString("v");
linkedInUrl = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(4)
.getString("v");
profilePicUrl = jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(5)
.getString("v");
isKeySpeaker = (int) jsonArray.getJSONObject(i).getJSONArray("c").getJSONObject(6)
.getLong("v");
Speaker temp = new Speaker(i + 1, name, information, linkedInUrl, twitterHandle, designation, profilePicUrl, isKeySpeaker);
// Log.d(TAG, temp.generateSqlQuery());
queries.add(temp.generateSqlQuery());
} catch (JSONException e) {
// Log.e(TAG, "JSON Error: " + e.getMessage() + "\nResponse: " + response);
}
}
// keySpeakerLoaded = true;
checkStatus();
}
}
, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// keySpeakerLoaded = true;
checkStatus();
}
}
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private void checkStatus() {
if (tracks && count == 0) {
DatabaseManager dbManager = DatabaseManager.getInstance();
//Temporary clearing database for testing only
dbManager.clearDatabase();
dbManager.performInsertQueries(queries);
//Implement callbacks
if (mCallback != null) {
mCallback.onDataLoaded();
}
}
}
private JSONArray removePaddingFromString(String response) {
Log.d(TAG,"BEFORE: " + response);
response = response.replaceAll("\"v\":null", "\"v\":\"\"");
response = response.replaceAll("null", "{\"v\": \"\"}");
response = response.substring(response.indexOf("(") + 1, response.length() - 2);
Log.d(TAG,"AFTER :::::::" + response);
try {
JSONObject jObj = new JSONObject(response);
jObj = jObj.getJSONObject("table");
JSONArray jArray = jObj.getJSONArray("rows");
// Log.d(TAG, jArray.toString());
return jArray;
} catch (JSONException e) {
// Log.e(TAG, "JSON Error: " + e.getMessage() + "\nResponse" + response);
}
return null;
}
public static interface JsonToDatabaseCallback {
public void onDataLoaded();
}
}
|
package io.github.eb4j;
import java.io.File;
import java.nio.charset.Charset;
import io.github.eb4j.io.EBFile;
import io.github.eb4j.io.BookInputStream;
import io.github.eb4j.util.ByteUtil;
/**
*
*
* @author Hisaya FUKUMOTO
*/
public class Book {
/** (EB/EBG/EBXA/EBXA-C/S-EBXA) */
public static final int DISC_EB = 0;
/** EPWING */
public static final int DISC_EPWING = 1;
/** ISO 8859-1 */
public static final int CHARCODE_ISO8859_1 = 1;
/** JIS X 0208 */
public static final int CHARCODE_JISX0208 = 2;
/** JIS X 0208/GB 2312 */
public static final int CHARCODE_JISX0208_GB2312 = 3;
/** CATALOG(S) */
static final int[] SIZE_CATALOG = {40, 164};
static final int[] SIZE_TITLE = {30, 80};
static final int SIZE_DIRNAME = 8;
private static final String[] MISLEADED = {
// SONY DataDiskMan (DD-DR1) accessories.
"%;%s%A%e%j!\\%S%8%M%9!\\%/%i%&%s",
// Shin Eiwa Waei Chujiten (earliest edition)
"8&5f<R!!?71QOBCf<-E5",
// EB Kagakugijutsu Yougo Daijiten (YRRS-048)
"#E#B2J3X5;=QMQ8lBg<-E5",
// Nichi-Ei-Futsu Jiten (YRRS-059)
"#E#N#G!?#J#A#N!J!\\#F#R#E!K",
// Japanese-English-Spanish Jiten (YRRS-060)
"#E#N#G!?#J#A#N!J!\\#S#P#A!K",
// Panasonic KX-EBP2 accessories.
"%W%m%7!<%I1QOB!&OB1Q<-E5"
};
private String _bookPath = null;
private int _bookType = -1;
private int _charCode = -1;
/** EPWING */
private int _version = -1;
private SubBook[] _sub = null;
/**
*
*
* @param bookPath
* @exception EBException
*/
public Book(final String bookPath) throws EBException {
this(bookPath, null);
}
/**
*
*
* @param bookDir
* @exception EBException
*/
public Book(final File bookDir) throws EBException {
this(bookDir, null);
}
/**
*
*
* @param bookPath
* @param appendixPath
* @exception EBException
*/
@SuppressWarnings("checkstyle:avoidinlineconditionals")
public Book(final String bookPath, final String appendixPath) throws EBException {
this(new File(bookPath),
appendixPath == null ? null : new File(appendixPath));
}
/**
*
*
* @param bookDir
* @param appendixDir
* @exception EBException
*/
public Book(final File bookDir, final File appendixDir) throws EBException {
super();
_bookPath = bookDir.getPath();
if (!bookDir.isDirectory()) {
throw new EBException(EBException.DIR_NOT_FOUND, _bookPath);
}
if (!bookDir.canRead()) {
throw new EBException(EBException.CANT_READ_DIR, _bookPath);
}
_loadLanguage(bookDir);
_loadCatalog(bookDir);
if (appendixDir != null) {
Appendix appendix = new Appendix(appendixDir);
SubAppendix[] sa = appendix.getSubAppendixes();
int len = sa.length;
if (len > _sub.length) {
len = _sub.length;
}
for (int i=0; i<len; i++) {
_sub[i].setAppendix(sa[i]);
}
}
}
/**
*
*
* @return
*/
public String getPath() {
return _bookPath;
}
/**
*
*
* @return
* @see Book#DISC_EB
* @see Book#DISC_EPWING
*/
public int getBookType() {
return _bookType;
}
/**
*
*
* @return
* @see Book#CHARCODE_ISO8859_1
* @see Book#CHARCODE_JISX0208
* @see Book#CHARCODE_JISX0208_GB2312
*/
public int getCharCode() {
return _charCode;
}
/**
*
*
* @param charCode
* @see Book#CHARCODE_ISO8859_1
* @see Book#CHARCODE_JISX0208
* @see Book#CHARCODE_JISX0208_GB2312
*/
public void setCharCode(final int charCode) {
_charCode = charCode;
}
/**
*
*
* @return
*/
public int getSubBookCount() {
int ret = 0;
if (_sub != null) {
ret = _sub.length;
}
return ret;
}
/**
*
*
* @return
*/
public SubBook[] getSubBooks() {
if (_sub == null) {
return new SubBook[0];
}
int len = _sub.length;
SubBook[] list = new SubBook[len];
System.arraycopy(_sub, 0, list, 0, len);
return list;
}
/**
*
*
* @param index
* @return (null)
*/
public SubBook getSubBook(final int index) {
if (index < 0 || index >= _sub.length) {
return null;
}
return _sub[index];
}
/**
* EPWING
*
* @return EPWING
*/
public int getVersion() {
return _version;
}
/**
* CATALOG(S)
*
* @param dir
* @exception EBException CATALOG(S)
*/
private void _loadCatalog(final File dir) throws EBException {
EBFile file = null;
try {
file = new EBFile(dir, "catalog", EBFile.FORMAT_PLAIN);
_bookType = DISC_EB;
} catch (EBException e) {
switch (e.getErrorCode()) {
case EBException.FILE_NOT_FOUND:
file = new EBFile(dir, "catalogs", EBFile.FORMAT_PLAIN);
_bookType = DISC_EPWING;
break;
default:
throw e;
}
}
switch (_bookType) {
case DISC_EB:
_loadCatalogEB(file);
break;
default:
_loadCatalogEPWING(file);
break;
}
}
/**
* CATALOG
*
* @param file CATALOG
* @exception EBException CATALOG
*/
private void _loadCatalogEB(final EBFile file) throws EBException {
BookInputStream bis = file.getInputStream();
try {
byte[] b = new byte[16];
bis.readFully(b, 0, b.length);
int subCount = ByteUtil.getInt2(b, 0);
if (subCount <= 0) {
throw new EBException(EBException.UNEXP_FILE, file.getPath());
}
_sub = new SubBook[subCount];
b = new byte[SIZE_CATALOG[DISC_EB]];
for (int i=0; i<subCount; i++) {
bis.readFully(b, 0, b.length);
int off = 2;
String title = null;
if (_charCode == CHARCODE_ISO8859_1) {
title = new String(b, off, SIZE_TITLE[DISC_EB], Charset.forName("ISO8859-1"))
.trim();
for (int j=0; j<MISLEADED.length; j++) {
if (title.equals(MISLEADED[j])) {
_charCode = CHARCODE_JISX0208;
byte[] tmp = title.getBytes(Charset.forName("ISO8859-1"));
title = ByteUtil.jisx0208ToString(tmp, 0, tmp.length);
break;
}
}
} else {
title = ByteUtil.jisx0208ToString(b, off,
SIZE_TITLE[DISC_EB]);
}
off += SIZE_TITLE[DISC_EB];
String name = new String(b, off, SIZE_DIRNAME, Charset.forName("ASCII")).trim();
String[] fname = new String[3];
int[] format = new int[3];
fname[0] = "start";
format[0] = EBFile.FORMAT_PLAIN;
_sub[i] = new SubBook(this, title, name, 1,
fname, format, null, null);
}
} finally {
bis.close();
}
}
/**
* CATALOGS
*
* @param file CATALOGS
* @exception EBException CATALOGS
*/
private void _loadCatalogEPWING(final EBFile file) throws EBException {
BookInputStream bis = file.getInputStream();
try {
byte[] b = new byte[16];
bis.readFully(b, 0, b.length);
int subCount = ByteUtil.getInt2(b, 0);
if (subCount <= 0) {
throw new EBException(EBException.UNEXP_FILE, file.getPath());
}
// EPWING
_version = ByteUtil.getInt2(b, 2);
_sub = new SubBook[subCount];
b = new byte[SIZE_CATALOG[DISC_EPWING]];
for (int i=0; i<subCount; i++) {
bis.seek(16 + i * b.length);
bis.readFully(b, 0, b.length);
int off = 2;
String title = null;
if (_charCode == CHARCODE_ISO8859_1) {
title = new String(b, off, SIZE_TITLE[DISC_EPWING], Charset
.forName("ISO8859-1")).trim();
for (int j=0; j<MISLEADED.length; j++) {
if (title.equals(MISLEADED[j])) {
_charCode = CHARCODE_JISX0208;
byte[] tmp = title.getBytes(Charset.forName("ISO8859-1"));
title = ByteUtil.jisx0208ToString(tmp, 0, tmp.length);
break;
}
}
} else {
title = ByteUtil.jisx0208ToString(b, off,
SIZE_TITLE[DISC_EPWING]);
}
off += SIZE_TITLE[DISC_EPWING];
String name = new String(b, off, SIZE_DIRNAME, Charset.forName("ASCII")).trim();
off += SIZE_DIRNAME;
int index = ByteUtil.getInt2(b, off+4);
off += 6;
String[] narrow = new String[4];
String[] wide = new String[4];
off += 4;
for (int j=0; j<4; j++) {
if (b[off] != '\0' && (b[off]&0xff) < 0x80) {
wide[j] = new String(b, off, SIZE_DIRNAME, Charset.forName("ASCII")).trim();
}
if (b[off+32] != '\0' && (b[off+32]&0xff) < 0x80) {
narrow[j] = new String(b, off+32, SIZE_DIRNAME, Charset.forName("ASCII"))
.trim();
}
off += SIZE_DIRNAME;
}
String[] fname = new String[3];
int[] format = new int[3];
fname[0] = "honmon";
format[0] = EBFile.FORMAT_PLAIN;
if (_version != 1) {
bis.seek(16 + (subCount + i) * b.length);
bis.readFully(b, 0, b.length);
if ((b[4] & 0xff) != 0) {
fname[0] = new String(b, 4, SIZE_DIRNAME, Charset.forName("ASCII")).trim();
format[0] = b[55] & 0xff;
int dataType = ByteUtil.getInt2(b, 41);
if ((dataType & 0x03) == 0x02) {
fname[1] = new String(b, 44, SIZE_DIRNAME, Charset.forName("ASCII"))
.trim();
format[1] = b[54] & 0xff;
} else if (((dataType>>>8) & 0x03) == 0x02) {
fname[1] = new String(b, 56, SIZE_DIRNAME, Charset.forName("ASCII"))
.trim();
format[1] = b[53] & 0xff;
}
if ((dataType & 0x03) == 0x01) {
fname[2] = new String(b, 44, SIZE_DIRNAME, Charset.forName("ASCII"))
.trim();
format[2] = b[54] & 0xff;
} else if (((dataType>>>8) & 0x03) == 0x01) {
fname[2] = new String(b, 56, SIZE_DIRNAME, Charset.forName("ASCII"))
.trim();
format[2] = b[53] & 0xff;
}
for (int j=0; j<3; j++) {
switch (format[j]) {
case 0x00:
format[j] = EBFile.FORMAT_PLAIN;
break;
case 0x11:
format[j] = EBFile.FORMAT_EPWING;
break;
case 0x12:
format[j] = EBFile.FORMAT_EPWING6;
break;
default:
throw new EBException(EBException.UNEXP_FILE, file.getPath());
}
}
}
}
_sub[i] = new SubBook(this, title, name, index,
fname, format, narrow, wide);
}
} finally {
bis.close();
}
}
/**
* LANGUAGE
*
* @param dir
* @exception EBException LANGUAGE
*/
private void _loadLanguage(final File dir) throws EBException {
_charCode = CHARCODE_JISX0208;
EBFile file = null;
try {
file = new EBFile(dir, "language", EBFile.FORMAT_PLAIN);
} catch (EBException e) {
}
if (file == null) {
return;
}
BookInputStream bis = file.getInputStream();
try {
byte[] b = new byte[16];
if (bis.read(b, 0, b.length) != b.length) {
return;
}
_charCode = ByteUtil.getInt2(b, 0);
} finally {
if (bis != null) {
bis.close();
}
}
}
}
// end of Book.java
|
package de.tobject.findbugs.io;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.annotation.Nonnull;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import de.tobject.findbugs.FindbugsPlugin;
/**
* Input/output helper methods.
*
* @author David Hovemeyer
*/
public abstract class IO {
/**
* Write the contents of a file in the Eclipse workspace.
*
* @param file
* the file to write to
* @param output
* the FileOutput object responsible for generating the data
* @param monitor
* a progress monitor (or null if none)
* @throws CoreException
*/
public static void writeFile(IFile file, final FileOutput output, IProgressMonitor monitor) throws CoreException {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
output.writeFile(bos);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
if (!file.exists()) {
mkdirs(file, monitor);
file.create(bis, true, monitor);
} else {
file.setContents(bis, true, false, monitor);
}
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
}
}
/**
* Recursively creates all folders needed, up to the project. Project must
* already exist.
*
* @param resource
* non null
* @param monitor
* non null
* @throws CoreException
*/
private static void mkdirs(@Nonnull IResource resource, IProgressMonitor monitor) throws CoreException {
IContainer container = resource.getParent();
if (container.getType() == IResource.FOLDER && !container.exists()) {
if(!container.getParent().exists()) {
mkdirs(container, monitor);
}
((IFolder) container).create(true, true, monitor);
}
}
/**
* Write the contents of a java.io.File
*
* @param file
* the file to write to
* @param output
* the FileOutput object responsible for generating the data
*/
public static void writeFile(final File file, final FileOutput output, final IProgressMonitor monitor) throws CoreException {
try (FileOutputStream fout = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(fout)) {
if (monitor != null) {
monitor.subTask("writing data to " + file.getName());
}
output.writeFile(bout);
bout.flush();
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
}
}
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore
}
}
}
}
|
package ch.usi.dag.disl.weaver;
import java.util.LinkedList;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Frame;
import org.objectweb.asm.tree.analysis.SourceValue;
import ch.usi.dag.disl.coderep.Code;
import ch.usi.dag.disl.dynamiccontext.DynamicContext;
import ch.usi.dag.disl.exception.DiSLFatalException;
import ch.usi.dag.disl.exception.DynamicInfoException;
import ch.usi.dag.disl.processor.generator.PIResolver;
import ch.usi.dag.disl.processor.generator.ProcInstance;
import ch.usi.dag.disl.processor.generator.ProcMethodInstance;
import ch.usi.dag.disl.processorcontext.ArgumentContext;
import ch.usi.dag.disl.processorcontext.ArgumentProcessorContext;
import ch.usi.dag.disl.processorcontext.ArgumentProcessorMode;
import ch.usi.dag.disl.snippet.Shadow;
import ch.usi.dag.disl.snippet.Snippet;
import ch.usi.dag.disl.snippet.SnippetCode;
import ch.usi.dag.disl.staticcontext.generator.SCGenerator;
import ch.usi.dag.disl.util.AsmHelper;
import ch.usi.dag.disl.util.stack.StackUtil;
import ch.usi.dag.disl.weaver.pe.MaxCalculator;
import ch.usi.dag.disl.weaver.pe.PartialEvaluator;
public class WeavingCode {
final static String PROP_PE = "disl.parteval";
private WeavingInfo info;
private MethodNode method;
private SnippetCode code;
private InsnList iList;
private AbstractInsnNode[] iArray;
private Snippet snippet;
private Shadow shadow;
private int index;
private int maxLocals;
public WeavingCode(WeavingInfo weavingInfo, MethodNode method,
SnippetCode src, Snippet snippet, Shadow shadow, int index) {
this.info = weavingInfo;
this.method = method;
this.code = src.clone();
this.snippet = snippet;
this.shadow = shadow;
this.index = index;
this.iList = code.getInstructions();
this.iArray = iList.toArray();
maxLocals = MaxCalculator
.getMaxLocal(iList, method.desc, method.access);
}
// Search for an instruction sequence that match the pattern
// of fetching static information.
public void fixStaticInfo(SCGenerator staticInfoHolder) {
for (AbstractInsnNode instr : iList.toArray()) {
AbstractInsnNode previous = instr.getPrevious();
// Static information are represented by a static function call with
// a null as its parameter.
if (instr.getOpcode() != Opcodes.INVOKEVIRTUAL || previous == null
|| previous.getOpcode() != Opcodes.ALOAD) {
continue;
}
MethodInsnNode invocation = (MethodInsnNode) instr;
if (staticInfoHolder.contains(shadow, invocation.owner,
invocation.name)) {
Object const_var = staticInfoHolder.get(shadow,
invocation.owner, invocation.name);
if (const_var != null) {
// Insert a ldc instruction
code.getInstructions().insert(instr,
AsmHelper.loadConst(const_var));
} else {
// push null onto the stack
code.getInstructions().insert(instr,
new InsnNode(Opcodes.ACONST_NULL));
}
// remove the pseudo instructions
iList.remove(previous);
iList.remove(instr);
}
}
}
public void fixClassInfo() {
for (AbstractInsnNode instr : iList.toArray()) {
AbstractInsnNode previous = instr.getPrevious();
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE
|| previous == null || previous.getOpcode() != Opcodes.LDC) {
continue;
}
LdcInsnNode ldc = (LdcInsnNode) previous;
MethodInsnNode invocation = (MethodInsnNode) instr;
if (!(ldc.cst instanceof String)) {
continue;
}
// User should guarantee that internal name of a class is passed to
// the ClassContext.
Type clazz = Type.getObjectType(ldc.cst.toString());
iList.insert(instr, new LdcInsnNode(clazz));
iList.remove(ldc.getPrevious());
iList.remove(ldc);
iList.remove(invocation);
}
}
private void preFixDynamicInfoCheck() throws DynamicInfoException {
for (AbstractInsnNode instr : iList.toArray()) {
// it is invocation...
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE) {
continue;
}
MethodInsnNode invoke = (MethodInsnNode) instr;
// ... of dynamic context
if (!invoke.owner
.equals(Type.getInternalName(DynamicContext.class))) {
continue;
}
if (invoke.name.equals("getThis")) {
continue;
}
AbstractInsnNode secondOperand = instr.getPrevious();
AbstractInsnNode firstOperand = secondOperand.getPrevious();
// first operand test
switch (firstOperand.getOpcode()) {
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.BIPUSH:
break;
default:
throw new DynamicInfoException("In snippet "
+ snippet.getOriginClassName() + "."
+ snippet.getOriginMethodName()
+ " - pass the first (pos)"
+ " argument of a dynamic context method direcltly."
+ " ex: getStackValue(1, int.class)");
}
// second operand test
if (AsmHelper.getClassType(secondOperand) == null) {
throw new DynamicInfoException("In snippet "
+ snippet.getOriginClassName() + "."
+ snippet.getOriginMethodName()
+ " - pass the second (type)"
+ " argument of a dynamic context method direcltly."
+ " ex: getStackValue(1, int.class)");
}
}
}
private static List<String> primitiveTypes;
static {
primitiveTypes = new LinkedList<String>();
primitiveTypes.add("java/lang/Boolean");
primitiveTypes.add("java/lang/Byte");
primitiveTypes.add("java/lang/Character");
primitiveTypes.add("java/lang/Double");
primitiveTypes.add("java/lang/Float");
primitiveTypes.add("java/lang/Integer");
primitiveTypes.add("java/lang/Long");
}
// Search for an instruction sequence that stands for a request for dynamic
// information, and replace them with a load instruction.
// NOTE that if the user requests for the stack value, some store
// instructions will be inserted to the target method, and new local slot
// will be used for storing this.
public void fixDynamicInfo() throws DynamicInfoException {
preFixDynamicInfoCheck();
Frame<BasicValue> basicframe = info.getBasicFrame(index);
Frame<SourceValue> sourceframe = info.getSourceFrame(index);
for (AbstractInsnNode instr : iList.toArray()) {
// pseudo function call
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE) {
continue;
}
MethodInsnNode invoke = (MethodInsnNode) instr;
if (!invoke.owner
.equals(Type.getInternalName(DynamicContext.class))) {
continue;
}
AbstractInsnNode prev = instr.getPrevious();
if (invoke.name.equals("getThis")) {
if ((method.access & Opcodes.ACC_STATIC) != 0) {
iList.insert(instr, new InsnNode(Opcodes.ACONST_NULL));
} else {
iList.insert(instr, new VarInsnNode(Opcodes.ALOAD, 0));
}
iList.remove(invoke);
iList.remove(prev);
continue;
}
AbstractInsnNode next = instr.getNext();
// parsing:
// aload dynamic_info
// iconst
// ldc class
// invoke (current instruction)
// [checkcast]
// [invoke]
int operand = AsmHelper.getIConstOperand(prev.getPrevious());
Type t = AsmHelper.getClassType(prev);
if (invoke.name.equals("getStackValue")) {
if (basicframe == null) {
// TODO warn user that weaving location is unreachable.
iList.insert(instr, AsmHelper.loadNull(t));
if (!AsmHelper.isReferenceType(t)) {
iList.insert(instr, AsmHelper.boxValueOnStack(t));
}
} else {
int sopcode = t.getOpcode(Opcodes.ISTORE);
int lopcode = t.getOpcode(Opcodes.ILOAD);
// index should be less than the stack height
if (operand >= basicframe.getStackSize() || operand < 0) {
throw new DiSLFatalException("Illegal access of index "
+ operand + " on a stack with "
+ basicframe.getStackSize() + " operands");
}
// Type checking
Type targetType = StackUtil.getStackByIndex(basicframe,
operand).getType();
if (t.getSort() != targetType.getSort()) {
throw new DiSLFatalException("Unwanted type \""
+ targetType + "\", while user needs \"" + t
+ "\"");
}
// store the stack value without changing the semantic
int size = StackUtil.dupStack(sourceframe, method, operand,
sopcode, method.maxLocals);
// load the stack value
// box value if applicable
if (!AsmHelper.isReferenceType(t)) {
iList.insert(instr, AsmHelper.boxValueOnStack(t));
}
iList.insert(instr, new VarInsnNode(lopcode, method.maxLocals));
method.maxLocals += size;
}
}
// TRICK: the following two situation will generate a VarInsnNode
// with a negative local slot. And it will be updated in
// method fixLocalIndex
else if (invoke.name.equals("getMethodArgumentValue")) {
if (basicframe == null) {
// TODO warn user that weaving location is unreachable.
basicframe = info.getRetFrame();
}
int slot = AsmHelper.getInternalParamIndex(method, operand);
// index should be less than the size of local variables
if (slot >= basicframe.getLocals() || slot < 0) {
throw new DiSLFatalException("Illegal access of index "
+ slot + " while the size of local variable is "
+ basicframe.getLocals());
}
// Type checking
Type targetType = basicframe.getLocal(slot).getType();
if (t.getSort() != targetType.getSort()) {
throw new DiSLFatalException("Unwanted type \""
+ targetType + "\", while user needs \"" + t + "\"");
}
// box value if applicable
// boxing is removed by partial evaluator if not needed
if(! AsmHelper.isReferenceType(t)) {
iList.insert(instr, AsmHelper.boxValueOnStack(t));
}
iList.insert(instr, new VarInsnNode(t.getOpcode(Opcodes.ILOAD),
slot));
} else if (invoke.name.equals("getLocalVariableValue")) {
if (basicframe == null) {
// TODO warn user that weaving location is unreachable.
basicframe = info.getRetFrame();
}
// index should be less than the size of local variables
if (operand >= basicframe.getLocals() || operand < 0) {
throw new DiSLFatalException("Illegal access of index "
+ operand + " while the size of local variable is "
+ basicframe.getLocals());
}
// Type checking
Type targetType = basicframe.getLocal(operand).getType();
if (t.getSort() != targetType.getSort()) {
throw new DiSLFatalException("Unwanted type \""
+ targetType + "\", while user needs \"" + t + "\"");
}
// box value if applicable
// boxing is removed by partial evaluator if not needed
if(! AsmHelper.isReferenceType(t)) {
iList.insert(instr, AsmHelper.boxValueOnStack(t));
}
iList.insert(instr, new VarInsnNode(t.getOpcode(Opcodes.ILOAD),
operand));
}
// remove aload, iconst, ldc
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
// remove invoke
iList.remove(instr);
// remove checkcast
if (next.getOpcode() == Opcodes.CHECKCAST) {
iList.remove(next);
}
}
for (AbstractInsnNode instr : iList.toArray()) {
AbstractInsnNode prev = instr.getPrevious();
if (prev == null || (prev.getOpcode() != Opcodes.INVOKESTATIC)
|| (instr.getOpcode() != Opcodes.INVOKEVIRTUAL)) {
continue;
}
MethodInsnNode valueOf = (MethodInsnNode) prev;
MethodInsnNode toValue = (MethodInsnNode) instr;
if (!(primitiveTypes.contains(valueOf.owner)
&& valueOf.owner.equals(toValue.owner)
&& valueOf.name.equals("valueOf")
&& toValue.name.endsWith("Value"))) {
continue;
}
if (!Type.getArgumentTypes(valueOf.desc)[0].equals(Type
.getReturnType(toValue.desc))) {
continue;
}
iList.remove(prev);
iList.remove(instr);
}
}
// Fix the stack operand index of each stack-based instruction
// according to the maximum number of locals in the target method node.
// NOTE that the field maxLocals of the method node will be automatically
// updated.
public void fixLocalIndex() {
method.maxLocals = fixLocalIndex(iList, method.maxLocals);
}
private int fixLocalIndex(InsnList src, int offset) {
int max = offset;
for (AbstractInsnNode instr : src.toArray()) {
if (instr instanceof VarInsnNode) {
VarInsnNode varInstr = (VarInsnNode) instr;
varInstr.var += offset;
switch (varInstr.getOpcode()) {
case Opcodes.LLOAD:
case Opcodes.DLOAD:
case Opcodes.LSTORE:
case Opcodes.DSTORE:
max = Math.max(varInstr.var + 2, max);
break;
default:
max = Math.max(varInstr.var + 1, max);
break;
}
} else if (instr instanceof IincInsnNode) {
IincInsnNode iinc = (IincInsnNode) instr;
iinc.var += offset;
max = Math.max(iinc.var + 1, max);
}
}
return max;
}
private void fixArgumentContext(InsnList instructions, int position,
int totalCount, Type type) {
for (AbstractInsnNode instr : instructions.toArray()) {
AbstractInsnNode previous = instr.getPrevious();
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE
|| previous == null
|| previous.getOpcode() != Opcodes.ALOAD) {
continue;
}
MethodInsnNode invoke = (MethodInsnNode) instr;
if (!invoke.owner.equals(Type
.getInternalName(ArgumentContext.class))) {
continue;
}
if (invoke.name.equals("getPosition")) {
instructions.insert(instr, AsmHelper.loadConst(position));
} else if (invoke.name.equals("getTotalCount")) {
instructions.insert(instr, AsmHelper.loadConst(totalCount));
} else if (invoke.name.equals("getTypeDescriptor")) {
instructions
.insert(instr, AsmHelper.loadConst(type.toString()));
}
// remove the pseudo instructions
instructions.remove(previous);
instructions.remove(instr);
}
}
// combine processors into an instruction list
// NOTE that these processors are for the current method
private InsnList procInMethod(ProcInstance processor) {
InsnList ilist = new InsnList();
for (ProcMethodInstance processorMethod : processor.getMethods()) {
Code code = processorMethod.getCode().clone();
InsnList instructions = code.getInstructions();
int position = processorMethod.getArgPos();
int totalCount = processorMethod.getArgsCount();
Type type = processorMethod.getArgType().getASMType();
fixArgumentContext(instructions, position, totalCount, type);
AbstractInsnNode start = instructions.getFirst();
VarInsnNode target = new VarInsnNode(
type.getOpcode(Opcodes.ISTORE), 0);
instructions.insertBefore(start, target);
maxLocals = Math.max(fixLocalIndex(instructions, maxLocals),
maxLocals + type.getSize());
instructions.insertBefore(
target,
new VarInsnNode(type.getOpcode(Opcodes.ILOAD), AsmHelper
.getInternalParamIndex(method,
processorMethod.getArgPos())
- method.maxLocals));
ilist.add(instructions);
method.tryCatchBlocks.addAll(code.getTryCatchBlocks());
}
return ilist;
}
// combine processors into an instruction list
// NOTE that these processors are for the callee
private InsnList procBeforeInvoke(ProcInstance processor, int index) {
Frame<SourceValue> frame = info.getSourceFrame(index);
InsnList ilist = new InsnList();
for (ProcMethodInstance processorMethod : processor.getMethods()) {
Code code = processorMethod.getCode().clone();
InsnList instructions = code.getInstructions();
int position = processorMethod.getArgPos();
int totalCount = processorMethod.getArgsCount();
Type type = processorMethod.getArgType().getASMType();
fixArgumentContext(instructions, position, totalCount, type);
SourceValue source = StackUtil.getStackByIndex(frame, totalCount
- 1 - position);
int sopcode = type.getOpcode(Opcodes.ISTORE);
for (AbstractInsnNode itr : source.insns) {
method.instructions.insert(itr, new VarInsnNode(sopcode,
// TRICK: the value has to be set properly because
// method code will be not adjusted by fixLocalIndex
method.maxLocals + maxLocals));
method.instructions.insert(itr, new InsnNode(
type.getSize() == 2 ? Opcodes.DUP2 : Opcodes.DUP));
}
maxLocals = Math.max(fixLocalIndex(instructions, maxLocals),
maxLocals + type.getSize());
ilist.add(instructions);
method.tryCatchBlocks.addAll(code.getTryCatchBlocks());
}
return ilist;
}
// replace processor-applying pseudo invocation with processors
public void fixProcessor(PIResolver piResolver) {
for (int i : code.getInvokedProcessors().keySet()) {
AbstractInsnNode instr = iArray[i];
ProcInstance processor = piResolver.get(shadow, i);
if (processor != null) {
if (processor.getProcApplyType() == ArgumentProcessorMode.METHOD_ARGS) {
iList.insert(instr, procInMethod(processor));
} else {
iList.insert(instr, procBeforeInvoke(processor, index));
}
}
// remove pseudo invocation
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
iList.remove(instr);
}
}
private InsnList createGetArgsCode(String methodDescriptor) {
InsnList insnList = new InsnList();
Type[] argTypes = Type.getArgumentTypes(methodDescriptor);
// array creation code (length is the length of arguments)
insnList.add(AsmHelper.loadConst(argTypes.length));
insnList.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object"));
int argIndex = 0;
for (int i = 0; i < argTypes.length; ++i) {
// ** add new array store **
// duplicate array object
insnList.add(new InsnNode(Opcodes.DUP));
// add index into the array where to store the value
insnList.add(AsmHelper.loadConst(i));
Type argType = argTypes[i];
// load "object" that will be stored
int loadOpcode = argType.getOpcode(Opcodes.ILOAD);
insnList.add(new VarInsnNode(loadOpcode, argIndex));
// box non-reference type
if (! AsmHelper.isReferenceType(argType)) {
insnList.add(AsmHelper.boxValueOnStack(argType));
}
// store the value into the array on particular index
insnList.add(new InsnNode(Opcodes.AASTORE));
// shift argument index according to argument size
argIndex += argType.getSize();
}
return insnList;
}
public void fixProcessorInfo() {
for (AbstractInsnNode instr : iList.toArray()) {
// it is invocation...
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE) {
continue;
}
MethodInsnNode invoke = (MethodInsnNode) instr;
// ... of ArgumentProcessorContext
if (!invoke.owner.equals(Type
.getInternalName(ArgumentProcessorContext.class))) {
continue;
}
AbstractInsnNode prev = instr.getPrevious();
if (prev.getOpcode() != Opcodes.GETSTATIC) {
throw new DiSLFatalException("Unknown processor mode");
}
ArgumentProcessorMode procApplyType = ArgumentProcessorMode
.valueOf(((FieldInsnNode) prev).name);
if (invoke.name.equals("getArgs")) {
InsnList args = null;
if (procApplyType == ArgumentProcessorMode.METHOD_ARGS) {
args = createGetArgsCode(method.desc);
fixLocalIndex(args,
((method.access & Opcodes.ACC_STATIC) != 0 ? 0 : 1)
- method.maxLocals);
} else {
AbstractInsnNode callee = AsmHelper.skipVirualInsns(
shadow.getRegionStart(), true);
if (!(callee instanceof MethodInsnNode)) {
throw new DiSLFatalException("Unexpected instruction");
}
String desc = ((MethodInsnNode) callee).desc;
Type[] argTypes = Type.getArgumentTypes(desc);
Frame<SourceValue> frame = info.getSourceFrame(callee);
if (frame == null) {
throw new DiSLFatalException("Unknown target");
}
int argIndex = 0;
for (int i = 0; i < argTypes.length; i++) {
SourceValue source = StackUtil.getStackByIndex(frame,
argTypes.length - 1 - i);
Type type = argTypes[i];
int sopcode = type.getOpcode(Opcodes.ISTORE);
for (AbstractInsnNode itr : source.insns) {
method.instructions.insert(itr, new VarInsnNode(sopcode,
// TRICK: the value has to be set properly because
// method code will be not adjusted by fixLocalIndex
method.maxLocals + maxLocals + argIndex));
method.instructions.insert(itr,
new InsnNode(type.getSize() == 2 ? Opcodes.DUP2
: Opcodes.DUP));
}
argIndex += type.getSize();
}
args = createGetArgsCode(desc);
maxLocals = Math.max(fixLocalIndex(args, maxLocals),
maxLocals + argIndex);
}
iList.insert(instr, args);
} else if (invoke.name.equals("getReceiver")) {
if (procApplyType == ArgumentProcessorMode.METHOD_ARGS) {
if ((method.access & Opcodes.ACC_STATIC) != 0) {
iList.insert(instr, new InsnNode(Opcodes.ACONST_NULL));
} else {
iList.insert(instr, new VarInsnNode(Opcodes.ALOAD,
-method.maxLocals));
}
} else {
AbstractInsnNode callee = AsmHelper.skipVirualInsns(
shadow.getRegionStart(), true);
if (!(callee instanceof MethodInsnNode)) {
throw new DiSLFatalException("Unexpected instruction");
}
Frame<SourceValue> frame = info.getSourceFrame(callee);
if (frame == null) {
throw new DiSLFatalException("Unknown target");
}
if (callee.getOpcode() == Opcodes.INVOKESTATIC) {
iList.insert(instr, new InsnNode(Opcodes.ACONST_NULL));
} else {
String desc = ((MethodInsnNode) callee).desc;
SourceValue source = StackUtil.getStackByIndex(frame,
Type.getArgumentTypes(desc).length);
for (AbstractInsnNode itr : source.insns) {
method.instructions.insert(itr, new VarInsnNode(
Opcodes.ASTORE,
// TRICK: the value has to be set properly because
// method code will be not adjusted by fixLocalIndex
method.maxLocals + maxLocals));
method.instructions.insert(itr, new InsnNode(
Opcodes.DUP));
}
iList.insert(instr, new VarInsnNode(Opcodes.ALOAD,
maxLocals));
maxLocals++;
}
}
}
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
iList.remove(instr);
}
}
public InsnList getiList() {
return iList;
}
public List<TryCatchBlockNode> getTCBs() {
return code.getTryCatchBlocks();
}
public void transform(SCGenerator staticInfoHolder, PIResolver piResolver)
throws DynamicInfoException {
fixProcessor(piResolver);
fixProcessorInfo();
fixStaticInfo(staticInfoHolder);
fixClassInfo();
fixLocalIndex();
optimize();
fixDynamicInfo();
}
public void optimize() {
String prop_pe = System.getProperty(PROP_PE);
if ((prop_pe == null) || (prop_pe.length() < 2)
|| (prop_pe.charAt(0) != 'o' && prop_pe.charAt(0) != 'O')) {
return;
}
char option = prop_pe.charAt(1);
if (option >= '1' && option <= '3') {
for (int i = 0; i < (option - '0'); i++) {
PartialEvaluator.evaluate(iList, code.getTryCatchBlocks(),
method.desc, method.access);
}
} else if (option == 'x') {
while (PartialEvaluator.evaluate(iList, code.getTryCatchBlocks(),
method.desc, method.access))
;
}
}
}
|
package ch.usi.dag.disl.weaver;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Frame;
import org.objectweb.asm.tree.analysis.SourceValue;
import ch.usi.dag.disl.coderep.Code;
import ch.usi.dag.disl.dynamiccontext.DynamicContext;
import ch.usi.dag.disl.exception.DiSLFatalException;
import ch.usi.dag.disl.exception.DynamicInfoException;
import ch.usi.dag.disl.processor.generator.PIResolver;
import ch.usi.dag.disl.processor.generator.ProcInstance;
import ch.usi.dag.disl.processor.generator.ProcMethodInstance;
import ch.usi.dag.disl.processorcontext.ArgumentContext;
import ch.usi.dag.disl.processorcontext.ProcessorMode;
import ch.usi.dag.disl.snippet.Shadow;
import ch.usi.dag.disl.snippet.Snippet;
import ch.usi.dag.disl.snippet.SnippetCode;
import ch.usi.dag.disl.staticcontext.generator.SCGenerator;
import ch.usi.dag.disl.util.AsmHelper;
import ch.usi.dag.disl.util.stack.StackUtil;
import ch.usi.dag.disl.weaver.pe.MaxCalculator;
import ch.usi.dag.disl.weaver.pe.PartialEvaluator;
public class WeavingCode {
final static String PROP_PE = "disl.parteval";
private WeavingInfo info;
private MethodNode method;
private SnippetCode code;
private InsnList iList;
private AbstractInsnNode[] iArray;
private Snippet snippet;
private Shadow region;
private int index;
private int maxLocals;
public WeavingCode(WeavingInfo weavingInfo, SnippetCode src,
MethodNode method, Snippet snippet, Shadow region, int index) {
info = weavingInfo;
code = src.clone();
iList = code.getInstructions();
iArray = iList.toArray();
this.method = method;
this.snippet = snippet;
this.region = region;
this.index = index;
maxLocals = MaxCalculator
.getMaxLocal(iList, method.desc, method.access);
}
// Search for an instruction sequence that match the pattern
// of fetching static information.
public void fixStaticInfo(SCGenerator staticInfoHolder) {
for (AbstractInsnNode instr : iList.toArray()) {
AbstractInsnNode previous = instr.getPrevious();
// Static information are represented by a static function call with
// a null as its parameter.
if (instr.getOpcode() != Opcodes.INVOKEVIRTUAL || previous == null
|| previous.getOpcode() != Opcodes.ALOAD) {
continue;
}
MethodInsnNode invocation = (MethodInsnNode) instr;
if (staticInfoHolder.contains(region, invocation.owner,
invocation.name)) {
Object const_var = staticInfoHolder.get(region,
invocation.owner, invocation.name);
if (const_var != null) {
// Insert a ldc instruction
code.getInstructions().insert(instr,
AsmHelper.loadConst(const_var));
} else {
// push null onto the stack
code.getInstructions().insert(instr,
new InsnNode(Opcodes.ACONST_NULL));
}
// remove the pseudo instructions
iList.remove(previous);
iList.remove(instr);
}
}
}
private void preFixDynamicInfoCheck() throws DynamicInfoException {
for (AbstractInsnNode instr : iList.toArray()) {
// it is invocation...
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE) {
continue;
}
MethodInsnNode invoke = (MethodInsnNode) instr;
// ... of dynamic context
if (!invoke.owner
.equals(Type.getInternalName(DynamicContext.class))) {
continue;
}
if (invoke.name.equals("thisValue")) {
continue;
}
AbstractInsnNode secondOperand = instr.getPrevious();
AbstractInsnNode firstOperand = secondOperand.getPrevious();
// first operand test
switch (firstOperand.getOpcode()) {
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.BIPUSH:
break;
default:
throw new DynamicInfoException("In snippet "
+ snippet.getOriginClassName() + "."
+ snippet.getOriginMethodName()
+ " - pass the first (pos)"
+ " argument of a dynamic context method direcltly."
+ " ex: stackValue(1, int.class)");
}
// second operand test
if (AsmHelper.getClassType(secondOperand) == null) {
throw new DynamicInfoException("In snippet "
+ snippet.getOriginClassName() + "."
+ snippet.getOriginMethodName()
+ " - pass the second (type)"
+ " argument of a dynamic context method direcltly."
+ " ex: stackValue(1, int.class)");
}
}
}
// Search for an instruction sequence that stands for a request for dynamic
// information, and replace them with a load instruction.
// NOTE that if the user requests for the stack value, some store
// instructions will be inserted to the target method, and new local slot
// will be used for storing this.
public void fixDynamicInfo() throws DynamicInfoException {
preFixDynamicInfoCheck();
int max = AsmHelper.calcMaxLocal(iList);
Frame<BasicValue> basicframe = info.getBasicFrame(index);
Frame<SourceValue> sourceframe = info.getSourceFrame(index);
for (AbstractInsnNode instr : iList.toArray()) {
// pseudo function call
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE) {
continue;
}
MethodInsnNode invoke = (MethodInsnNode) instr;
if (!invoke.owner
.equals(Type.getInternalName(DynamicContext.class))) {
continue;
}
AbstractInsnNode prev = instr.getPrevious();
if (invoke.name.equals("thisValue")) {
if ((method.access & Opcodes.ACC_STATIC) == 0) {
iList.insert(instr, new VarInsnNode(Opcodes.ALOAD,
-method.maxLocals));
} else {
iList.insert(instr, new InsnNode(Opcodes.ACONST_NULL));
}
iList.remove(invoke);
iList.remove(prev);
continue;
}
AbstractInsnNode next = instr.getNext();
// parsing:
// aload dynamic_info
// iconst
// ldc class
// invoke (current instruction)
// [checkcast]
// [invoke]
int operand = AsmHelper.getIConstOperand(prev.getPrevious());
Type t = AsmHelper.getClassType(prev);
if (invoke.name.equals("stackValue")) {
int sopcode = t.getOpcode(Opcodes.ISTORE);
int lopcode = t.getOpcode(Opcodes.ILOAD);
// index should be less than the stack height
if (operand >= basicframe.getStackSize() || operand < 0) {
throw new DiSLFatalException("Illegal access of index "
+ operand + " on a stack with "
+ basicframe.getStackSize() + " operands");
}
// Type checking
Type targetType = StackUtil
.getStackByIndex(basicframe, operand).getType();
if (t.getSort() != targetType.getSort()) {
throw new DiSLFatalException("Unwanted type \""
+ targetType + "\", while user needs \"" + t + "\"");
}
// store the stack value without changing the semantic
int size = StackUtil.dupStack(sourceframe, method, operand,
sopcode, method.maxLocals + max);
// load the stack value
iList.insert(instr, new VarInsnNode(lopcode, max));
max += size;
}
// TRICK: the following two situation will generate a VarInsnNode
// with a negative local slot. And it will be updated in
// method fixLocalIndex
else if (invoke.name.equals("methodArgumentValue")) {
int slot = AsmHelper.getInternalParamIndex(method, operand);
// index should be less than the size of local variables
if (slot >= basicframe.getLocals() || slot < 0) {
throw new DiSLFatalException("Illegal access of index "
+ slot + " while the size of local variable is "
+ basicframe.getLocals());
}
// Type checking
Type targetType = basicframe.getLocal(slot).getType();
if (t.getSort() != targetType.getSort()) {
throw new DiSLFatalException("Unwanted type \""
+ targetType + "\", while user needs \"" + t + "\"");
}
iList.insert(instr, new VarInsnNode(t.getOpcode(Opcodes.ILOAD),
slot - method.maxLocals));
} else if (invoke.name.equals("localVariableValue")) {
// index should be less than the size of local variables
if (operand >= basicframe.getLocals() || operand < 0) {
throw new DiSLFatalException("Illegal access of index "
+ operand + " while the size of local variable is "
+ basicframe.getLocals());
}
// Type checking
Type targetType = basicframe.getLocal(operand).getType();
if (t.getSort() != targetType.getSort()) {
throw new DiSLFatalException("Unwanted type \""
+ targetType + "\", while user needs \"" + t + "\"");
}
iList.insert(instr, new VarInsnNode(t.getOpcode(Opcodes.ILOAD),
operand - method.maxLocals));
}
// remove aload, iconst, ldc
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
// remove invoke
iList.remove(instr);
// remove checkcast, invoke
if (next.getOpcode() == Opcodes.CHECKCAST) {
if (next.getNext().getOpcode() == Opcodes.INVOKEVIRTUAL) {
iList.remove(next.getNext());
}
iList.remove(next);
}
}
}
// Fix the stack operand index of each stack-based instruction
// according to the maximum number of locals in the target method node.
// NOTE that the field maxLocals of the method node will be automatically
// updated.
public void fixLocalIndex() {
method.maxLocals = fixLocalIndex(iList, method.maxLocals);
}
private int fixLocalIndex(InsnList src, int offset) {
int max = offset;
for (AbstractInsnNode instr : src.toArray()) {
if (instr instanceof VarInsnNode) {
VarInsnNode varInstr = (VarInsnNode) instr;
varInstr.var += offset;
switch (varInstr.getOpcode()) {
case Opcodes.LLOAD:
case Opcodes.DLOAD:
case Opcodes.LSTORE:
case Opcodes.DSTORE:
max = Math.max(varInstr.var + 2, max);
break;
default:
max = Math.max(varInstr.var + 1, max);
break;
}
} else if (instr instanceof IincInsnNode) {
IincInsnNode iinc = (IincInsnNode) instr;
iinc.var += offset;
max = Math.max(iinc.var + 1, max);
}
}
return max;
}
private void fixArgumentContext(InsnList instructions, int position,
int totalCount, Type type) {
for (AbstractInsnNode instr : instructions.toArray()) {
AbstractInsnNode previous = instr.getPrevious();
if (instr.getOpcode() != Opcodes.INVOKEINTERFACE
|| previous == null
|| previous.getOpcode() != Opcodes.ALOAD) {
continue;
}
MethodInsnNode invoke = (MethodInsnNode) instr;
if (!invoke.owner.equals(Type
.getInternalName(ArgumentContext.class))) {
continue;
}
if (invoke.name.equals("position")) {
instructions.insert(instr, AsmHelper.loadConst(position));
} else if (invoke.name.equals("totalCount")) {
instructions.insert(instr, AsmHelper.loadConst(totalCount));
} else if (invoke.name.equals("typeDescriptor")) {
instructions
.insert(instr, AsmHelper.loadConst(type.toString()));
}
// remove the pseudo instructions
instructions.remove(previous);
instructions.remove(instr);
}
}
// combine processors into an instruction list
// NOTE that these processors are for the current method
private InsnList procInMethod(ProcInstance processor) {
InsnList ilist = new InsnList();
for (ProcMethodInstance processorMethod : processor.getMethods()) {
Code code = processorMethod.getCode().clone();
InsnList instructions = code.getInstructions();
int position = processorMethod.getArgPos();
int totalCount = processorMethod.getArgsCount();
Type type = processorMethod.getArgType().getASMType();
fixArgumentContext(instructions, position, totalCount, type);
AbstractInsnNode start = instructions.getFirst();
VarInsnNode target = new VarInsnNode(
type.getOpcode(Opcodes.ISTORE), 0);
instructions.insertBefore(start, target);
maxLocals = fixLocalIndex(instructions, maxLocals);
instructions.insertBefore(
target,
new VarInsnNode(type.getOpcode(Opcodes.ILOAD), AsmHelper
.getInternalParamIndex(method,
processorMethod.getArgPos())
- method.maxLocals));
ilist.add(instructions);
method.tryCatchBlocks.addAll(code.getTryCatchBlocks());
}
return ilist;
}
// combine processors into an instruction list
// NOTE that these processors are for the callee
private InsnList procBeforeInvoke(ProcInstance processor, int index) {
Frame<SourceValue> frame = info.getSourceFrame(index);
InsnList ilist = new InsnList();
for (ProcMethodInstance processorMethod : processor.getMethods()) {
Code code = processorMethod.getCode().clone();
InsnList instructions = code.getInstructions();
int position = processorMethod.getArgPos();
int totalCount = processorMethod.getArgsCount();
Type type = processorMethod.getArgType().getASMType();
fixArgumentContext(instructions, position, totalCount, type);
SourceValue source = StackUtil.getStackByIndex(frame, totalCount
- 1 - position);
int sopcode = type.getOpcode(Opcodes.ISTORE);
for (AbstractInsnNode itr : source.insns) {
method.instructions.insert(itr, new VarInsnNode(sopcode,
// TRICK: the value has to be set properly because
// method code will be not adjusted by fixLocalIndex
method.maxLocals + maxLocals));
method.instructions.insert(itr, new InsnNode(
type.getSize() == 2 ? Opcodes.DUP2 : Opcodes.DUP));
}
maxLocals = fixLocalIndex(instructions, maxLocals);
ilist.add(instructions);
method.tryCatchBlocks.addAll(code.getTryCatchBlocks());
}
return ilist;
}
// replace processor-applying pseudo invocation with processors
public void fixProcessor(PIResolver piResolver) {
for (int i : code.getInvokedProcessors().keySet()) {
AbstractInsnNode instr = iArray[i];
ProcInstance processor = piResolver.get(region, i);
if (processor != null) {
if (processor.getProcApplyType() == ProcessorMode.CALLSITE_ARGS) {
iList.insert(instr, procBeforeInvoke(processor, index));
} else {
iList.insert(instr, procInMethod(processor));
}
}
// remove pseudo invocation
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
iList.remove(instr.getPrevious());
iList.remove(instr);
}
}
public InsnList getiList() {
return iList;
}
public List<TryCatchBlockNode> getTCBs() {
return code.getTryCatchBlocks();
}
public void transform(SCGenerator staticInfoHolder, PIResolver piResolver)
throws DynamicInfoException {
fixProcessor(piResolver);
fixStaticInfo(staticInfoHolder);
fixDynamicInfo();
fixLocalIndex();
optimize();
}
public void optimize() {
String prop_pe = System.getProperty(PROP_PE);
if ((prop_pe == null) || (prop_pe.length() < 2)
|| (prop_pe.charAt(0) != 'o' && prop_pe.charAt(0) != 'O')) {
return;
}
char option = prop_pe.charAt(1);
if (option >= '1' && option <= '3') {
for (int i = 0; i < (option - '0'); i++) {
PartialEvaluator.evaluate(iList, code.getTryCatchBlocks(),
method.desc, method.access);
}
} else if (option == 'x') {
while (PartialEvaluator.evaluate(iList, code.getTryCatchBlocks(),
method.desc, method.access))
;
}
}
}
|
package ftc8390.vv;
import android.graphics.Bitmap;
import com.qualcomm.robotcore.hardware.HardwareMap;
public class BeaconColorDetector {
public void init(HardwareMap hardwareMap) {
}
static public int red(int pixel) {
return (pixel >> 16) & 0xff;
}
static public int green(int pixel) {
return (pixel >> 8) & 0xff;
}
static public int blue(int pixel) {
return pixel & 0xff;
}
public boolean blueIsOnLeft(Bitmap rgbImage)
{
int leftXStart = (int)((double)rgbImage.getWidth() * 0.1);
int rightXStart = (int)((double)rgbImage.getWidth() * 0.6);
int leftXEnd = (int)((double)rgbImage.getWidth() * 0.4);
int rightXEnd = (int)((double)rgbImage.getWidth() * 0.9);
int yStart = (int)((double)rgbImage.getHeight() * 0.3);
int yEnd = (int)((double)rgbImage.getHeight() * 0.8);
int rightRedValue = 0;
int rightBlueValue = 0;
int leftRedValue = 0;
int leftBlueValue = 0;
for (int x = leftXStart; x < leftXEnd; x++) {
for (int y = yStart; y < yEnd; y++) {
int pixel = rgbImage.getPixel(x, y);
leftRedValue += red(pixel);
leftBlueValue += blue(pixel);
}
}
for (int x = rightXStart; x < rightXEnd; x++) {
for (int y = yStart; y < yEnd; y++) {
int pixel = rgbImage.getPixel(x, y);
rightRedValue += red(pixel);
rightBlueValue += blue(pixel);
}
}
if (leftRedValue - leftBlueValue > rightRedValue - rightBlueValue)
return false;
else
return true;
}
}
|
package jcavern;
import jcavern.ui.*;
import jcavern.thing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.Hashtable;
import java.awt.event.*;
import java.applet.*;
/**
* JCavernApplet is the launcher for the java version of cavern and glen.
*
* @author Bill Walker
* @version $Id$
*/
public class JCavernApplet extends Applet
{
/** * The official PLATO orange color, more or less. */
public static final Color CavernOrange = new Color(0xFF, 0x66, 0x00);
/** * Names of image files containing pictures of monsters. */
public static final String MonsterImageNames[] = {
"crab", "snail", "jubjub", "blob", "hoplite", "guy", "monster", "trex",
"demon", "wraith", "rajah", "grump", "larry", "eyeball", "ugly", "darklord", "chavin",
"wahoo", "gobbler", "scary", "jackolantern", "hippo", "alien", "forkman", "snake" };
/** * Names of image files containing pictures of non-monsters. */
public static final String OtherImageNames[] = {
"player", "chest", "tree", "tree2", "castle", "splat" };
/** * A table of messages */
private Hashtable mImages;
/** * A MediaTracker to make sure the images get loaded. */
private MediaTracker mTracker;
/**
* Displays the home card.
*
* @param inPlayer the Player currently in use
* @exception JCavernInternalError trouble displaying the card
*/
public void displayHomeCard(Player inPlayer) throws JCavernInternalError
{
IndexCard anIndex = new IndexCard(this, inPlayer);
anIndex.show();
}
/**
* Creates game world, player, viewers.
*/
public JCavernApplet()
{
mImages = new Hashtable();
//gApplet = this;
mTracker = new MediaTracker(this);
}
/**
* Retrieves a board image.
*
* @param aName the name of the image to retrieve
* @return a non-null Image
* @exception JCavernInternalError the image could not be retrieved
*/
public Image getBoardImage(String aName) throws JCavernInternalError
{
if (! mImages.containsKey(aName))
{
throw new JCavernInternalError("no such image " + aName + " in dictionary " + mImages);
}
return (Image) mImages.get(aName);
}
/**
* Installs KeyListener for keyboard commands.
*/
public void start()
{
}
/**
* Returns information about the applet.
*
* @return a non-null String
*/
public String getAppletInfo()
{
return "JCavern 0.0, Bill Walker";
}
/**
* Loads data files from the web server.
* These include monster prototypes, treasure prototypes, monster images, and other images.
*
* @exception JCavernInternalError could not load data
*/
private void loadDataFromServer() throws JCavernInternalError
{
try
{
MonsterFactory.loadPrototypes(new URL(getDocumentBase(), "bin/monster.dat"));
Treasure.loadPrototypes(new URL(getDocumentBase(), "bin/treasure.dat"));
}
catch(MalformedURLException mue)
{
System.out.println("JCaverApplet.init " + mue);
throw new JCavernInternalError("Can't load monster and treasure data");
}
loadArrayOfImages(MonsterImageNames);
loadArrayOfImages(OtherImageNames);
}
/**
* Loads an array of images.
*
* @param imageNames an array of non-null Strings containing the names of image files.
* @exception JCavernInternalError could not load data
*/
private void loadArrayOfImages(String[] imageNames) throws JCavernInternalError
{
for (int index = 0; index < imageNames.length; index++)
{
try
{
URL imageURL = new URL(getDocumentBase(), "bin/images/" + imageNames[index] + ".gif");
Image image = getImage(imageURL);
mTracker.addImage(image, 1);
mTracker.waitForID(1);
if (mTracker.isErrorID(index))
{
throw new JCavernInternalError("Can't load image " + mTracker.getErrorsID(index));
}
//System.out.println("name " + imageNames[index] + " image = " + image);
mImages.put(new String(imageNames[index]), image);
}
catch(InterruptedException ie)
{
System.out.println("JCaverApplet.init interrupted exception " + ie);
throw new JCavernInternalError("Can't load monster images");
}
catch(MalformedURLException mue)
{
System.out.println("JCaverApplet.init " + mue);
throw new JCavernInternalError("Can't load monster images");
}
}
}
/**
* Initialize the applet
*/
public void init()
{
try
{
loadDataFromServer();
IndexCard anIndex = new IndexCard(this, null);
anIndex.show();
}
catch (JCavernInternalError jcie)
{
System.out.println("Can't initialize applet!");
}
}
}
|
package railo.runtime.type.util;
import java.lang.reflect.Field;
import java.util.HashSet;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
public class KeyConstants {
public static final Key _A=KeyImpl._const("A");
public static final Key _AAA=KeyImpl._const("AAA");
public static final Key _ABC=KeyImpl._const("ABC");
public static final Key _ACCESS=KeyImpl._const("ACCESS");
public static final Key _ACTION=KeyImpl._const("ACTION");
public static final Key _AGE=KeyImpl._const("AGE");
public static final Key _ALIAS=KeyImpl._const("ALIAS");
public static final Key _APPMANAGER=KeyImpl._const("APPMANAGER");
public static final Key _APPSERVER=KeyImpl._const("APPSERVER");
public static final Key _ARG1=KeyImpl._const("ARG1");
public static final Key _ARGS=KeyImpl._const("ARGS");
public static final Key _ARR=KeyImpl._const("ARR");
public static final Key _AS=KeyImpl._const("AS");
public static final Key _ASTERISK=KeyImpl._const("ASTERISK");
public static final Key _ATTRIBUTES=KeyImpl._const("ATTRIBUTES");
public static final Key _Accept=KeyImpl._const("Accept");
public static final Key _Assertions=KeyImpl._const("Assertions");
public static final Key _Author=KeyImpl._const("Author");
public static final Key _B=KeyImpl._const("B");
public static final Key _BBB=KeyImpl._const("BBB");
public static final Key _BUFFER=KeyImpl._const("BUFFER");
public static final Key _C=KeyImpl._const("C");
public static final Key _CACHENAME=KeyImpl._const("CACHENAME");
public static final Key _CALL=KeyImpl._const("CALL");
public static final Key _CALLER=KeyImpl._const("CALLER");
public static final Key _caller=KeyImpl._const("caller");
public static final Key _CALLSUPER=KeyImpl._const("CALLSUPER");
public static final Key _CCC=KeyImpl._const("CCC");
public static final Key _CFCATCH=KeyImpl._const("CFCATCH");
public static final Key _CFID=KeyImpl._const("CFID");
public static final Key _CFTOKEN=KeyImpl._const("CFTOKEN");
public static final Key _CF_CLIENT_=KeyImpl._const("CF_CLIENT_");
public static final Key _CHILD=KeyImpl._const("CHILD");
public static final Key _CLASS=KeyImpl._const("CLASS");
public static final Key _CLASSNAME=KeyImpl._const("CLASSNAME");
public static final Key _CODE_CACHE=KeyImpl._const("CODE_CACHE");
public static final Key _COLDFUSION=KeyImpl._const("COLDFUSION");
public static final Key _COLLECTION=KeyImpl._const("COLLECTION");
public static final Key _COLUMN=KeyImpl._const("COLUMN");
public static final Key _COLUMNS=KeyImpl._const("COLUMNS");
public static final Key _COMMENTS=KeyImpl._const("COMMENTS");
public static final Key _CONDITION=KeyImpl._const("CONDITION");
public static final Key _CONFIGURE=KeyImpl._const("CONFIGURE");
public static final Key _CONFIGXML=KeyImpl._const("CONFIGXML");
public static final Key _CONTENT=KeyImpl._const("CONTENT");
public static final Key _CONTEXT=KeyImpl._const("CONTEXT");
public static final Key _CONTROLLER=KeyImpl._const("CONTROLLER");
public static final Key _COUNT=KeyImpl._const("COUNT");
public static final Key _COUNTER=KeyImpl._const("COUNTER");
public static final Key _CS=KeyImpl._const("CS");
public static final Key _Cause=KeyImpl._const("Cause");
public static final Key _CircuitXML=KeyImpl._const("CircuitXML");
public static final Key _Commenting=KeyImpl._const("Commenting");
public static final Key _Connection=KeyImpl._const("Connection");
public static final Key _Cookie=KeyImpl._const("Cookie");
public static final Key _Created=KeyImpl._const("Created");
public static final Key _D=KeyImpl._const("D");
public static final Key _D1=KeyImpl._const("D1");
public static final Key _DATA=KeyImpl._const("DATA");
public static final Key _DATASOURCE=KeyImpl._const("DATASOURCE");
public static final Key _DATATYPE=KeyImpl._const("DATATYPE");
public static final Key _DETAIL=KeyImpl._const("DETAIL");
public static final Key _DIR=KeyImpl._const("DIR");
public static final Key _DIRECTORY=KeyImpl._const("DIRECTORY");
public static final Key _DOC=KeyImpl._const("DOC");
public static final Key _DataSource=KeyImpl._const("DataSource");
public static final Key _Datasource=KeyImpl._const("Datasource");
public static final Key _Date=KeyImpl._const("Date");
public static final Key _E=KeyImpl._const("E");
public static final Key _ENABLE21=KeyImpl._const("ENABLE21");
public static final Key _ENABLE31=KeyImpl._const("ENABLE31");
public static final Key _EVENT=KeyImpl._const("EVENT");
public static final Key _EVENTNAME=KeyImpl._const("EVENTNAME");
public static final Key _EXE=KeyImpl._const("EXE");
public static final Key _EXECUTE=KeyImpl._const("EXECUTE");
public static final Key _Elements=KeyImpl._const("Elements");
public static final Key _Encryption=KeyImpl._const("Encryption");
public static final Key _EventName=KeyImpl._const("EventName");
public static final Key _Expires=KeyImpl._const("Expires");
public static final Key _expires=KeyImpl._const("expires");
public static final Key _F=KeyImpl._const("F");
public static final Key _FATYPE=KeyImpl._const("FATYPE");
public static final Key _FB_=KeyImpl._const("FB_");
public static final Key _FIELD=KeyImpl._const("FIELD");
public static final Key _FILENAME=KeyImpl._const("FILENAME");
public static final Key _FILE=KeyImpl._const("FILE");
public static final Key _FILES=KeyImpl._const("FILES");
public static final Key _FROM=KeyImpl._const("FROM");
public static final Key _FUSEBOX=KeyImpl._const("FUSEBOX");
public static final Key _FUSEQ=KeyImpl._const("FUSEQ");
public static final Key _FilePath=KeyImpl._const("FilePath");
public static final Key _GET=KeyImpl._const("GET");
public static final Key _GETLOG=KeyImpl._const("GETLOG");
public static final Key _GETPARENT=KeyImpl._const("GETPARENT");
public static final Key _Globals=KeyImpl._const("Globals");
public static final Key _HASENDTAG=KeyImpl._const("HASENDTAG");
public static final Key _HASNULL=KeyImpl._const("HASNULL");
public static final Key _Host=KeyImpl._const("Host");
public static final Key _I=KeyImpl._const("I");
public static final Key _ID=KeyImpl._const("ID");
public static final Key _INCLUDES=KeyImpl._const("INCLUDES");
public static final Key _INIT=KeyImpl._const("INIT");
public static final Key _INSTANCE=KeyImpl._const("INSTANCE");
public static final Key _ISDONE=KeyImpl._const("ISDONE");
public static final Key _ISFALSE=KeyImpl._const("ISFALSE");
public static final Key _ITEM=KeyImpl._const("ITEM");
public static final Key _ITERATOR=KeyImpl._const("ITERATOR");
public static final Key _Invokes=KeyImpl._const("Invokes");
public static final Key _J=KeyImpl._const("J");
public static final Key _JAVALOADER=KeyImpl._const("JAVALOADER");
public static final Key _JOIN=KeyImpl._const("JOIN");
public static final Key _KEY=KeyImpl._const("KEY");
public static final Key _Keywords=KeyImpl._const("Keywords");
public static final Key _LABEL=KeyImpl._const("LABEL");
public static final Key _LEFT=KeyImpl._const("LEFT");
public static final Key _LEFT_TYPE=KeyImpl._const("LEFT_TYPE");
public static final Key _LEN=KeyImpl._const("LEN");
public static final Key _LINE=KeyImpl._const("LINE");
public static final Key _LOG=KeyImpl._const("LOG");
public static final Key _LOGFACTORY=KeyImpl._const("LOGFACTORY");
public static final Key _LOGID=KeyImpl._const("LOGID");
public static final Key _Language=KeyImpl._const("Language");
public static final Key _Layout=KeyImpl._const("Layout");
public static final Key _Legend=KeyImpl._const("Legend");
public static final Key _LogInAs=KeyImpl._const("LogInAs");
public static final Key _MANYTOMANY=KeyImpl._const("MANYTOMANY");
public static final Key _MANYTOONE=KeyImpl._const("MANYTOONE");
public static final Key _MEMENTO=KeyImpl._const("MEMENTO");
public static final Key _MESSAGE=KeyImpl._const("MESSAGE");
public static final Key _METHOD=KeyImpl._const("METHOD");
public static final Key _MODULENAME=KeyImpl._const("MODULENAME");
public static final Key _MYFUSEBOX=KeyImpl._const("MYFUSEBOX");
public static final Key _Message=KeyImpl._const("Message");
public static final Key _ModDate=KeyImpl._const("ModDate");
public static final Key _Modified=KeyImpl._const("Modified");
public static final Key _NAME=KeyImpl._const("NAME");
public static final Key _Name=KeyImpl._const("Name");
public static final Key _OBJECT=KeyImpl._const("OBJECT");
public static final Key _ONETOMANY=KeyImpl._const("ONETOMANY");
public static final Key _ORDER=KeyImpl._const("ORDER");
public static final Key _ORGLOCALE=KeyImpl._const("ORGLOCALE");
public static final Key _OUTER=KeyImpl._const("OUTER");
public static final Key _OUTPUT=KeyImpl._const("OUTPUT");
public static final Key _OVERRIDE=KeyImpl._const("OVERRIDE");
public static final Key _OfficeMap=KeyImpl._const("OfficeMap");
public static final Key _PARAMETERS=KeyImpl._const("PARAMETERS");
public static final Key _PATH=KeyImpl._const("PATH");
public static final Key _PETER=KeyImpl._const("PETER");
public static final Key _PREFIX=KeyImpl._const("PREFIX");
public static final Key _PRIMARYKEY=KeyImpl._const("PRIMARYKEY");
public static final Key _PROCESSES=KeyImpl._const("PROCESSES");
public static final Key _PROPERTY=KeyImpl._const("PROPERTY");
public static final Key _PageLayout=KeyImpl._const("PageLayout");
public static final Key _Pragma=KeyImpl._const("Pragma");
public static final Key _Printing=KeyImpl._const("Printing");
public static final Key _Producer=KeyImpl._const("Producer");
public static final Key _Properties=KeyImpl._const("Properties");
public static final Key _Q=KeyImpl._const("Q");
public static final Key _QRY=KeyImpl._const("QRY");
public static final Key _QUERY=KeyImpl._const("QUERY");
public static final Key _RAILO=KeyImpl._const("RAILO");
public static final Key _RBundles=KeyImpl._const("RBundles");
public static final Key _RES=KeyImpl._const("RES");
public static final Key _RESULT=KeyImpl._const("RESULT");
public static final Key _RETURN=KeyImpl._const("RETURN");
public static final Key _RIGHT=KeyImpl._const("RIGHT");
public static final Key _RTN=KeyImpl._const("RTN");
public static final Key _Raw_Trace=KeyImpl._const("Raw_Trace");
public static final Key _Referer=KeyImpl._const("Referer");
public static final Key _Roulette=KeyImpl._const("Roulette");
public static final Key _SCOPE=KeyImpl._const("SCOPE");
public static final Key _SCT=KeyImpl._const("SCT");
public static final Key _SELECT=KeyImpl._const("SELECT");
public static final Key _SETLOG=KeyImpl._const("SETLOG");
public static final Key _SETMEMENTO=KeyImpl._const("SETMEMENTO");
public static final Key _SETPARENT=KeyImpl._const("SETPARENT");
public static final Key _SETTINGS=KeyImpl._const("SETTINGS");
public static final Key _SIZE=KeyImpl._const("SIZE");
public static final Key _SOAPAction=KeyImpl._const("SOAPAction");
public static final Key _SQL=KeyImpl._const("SQL");
public static final Key _SQLState=KeyImpl._const("SQLState");
public static final Key _STARTWITH=KeyImpl._const("STARTWITH");
public static final Key _STR=KeyImpl._const("STR");
public static final Key _STRXML=KeyImpl._const("STRXML");
public static final Key _SUPER=KeyImpl._const("SUPER");
public static final Key _SUSI=KeyImpl._const("SUSI");
public static final Key _Secure=KeyImpl._const("Secure");
public static final Key _Server=KeyImpl._const("Server");
public static final Key _Signing=KeyImpl._const("Signing");
public static final Key _Sql=KeyImpl._const("Sql");
public static final Key _Subject=KeyImpl._const("Subject");
public static final Key _TABLE=KeyImpl._const("TABLE");
public static final Key _TEMPLATE=KeyImpl._const("TEMPLATE");
public static final Key _TEST=KeyImpl._const("TEST");
public static final Key _TEST2=KeyImpl._const("TEST2");
public static final Key _TESTEMPTY=KeyImpl._const("TESTEMPTY");
public static final Key _TEXT=KeyImpl._const("TEXT");
public static final Key _THIS=KeyImpl._const("THIS");
public static final Key _THISTAG=KeyImpl._const("THISTAG");
public static final Key _THROW=KeyImpl._const("THROW");
public static final Key _TIME=KeyImpl._const("TIME");
public static final Key _TOTAL_HEAP=KeyImpl._const("TOTAL_HEAP");
public static final Key _TRANSFER=KeyImpl._const("TRANSFER");
public static final Key _TYPE=KeyImpl._const("TYPE");
public static final Key _Title=KeyImpl._const("Title");
public static final Key _TotalPages=KeyImpl._const("TotalPages");
public static final Key _Trapped=KeyImpl._const("Trapped");
public static final Key _Type=KeyImpl._const("Type");
public static final Key _USER=KeyImpl._const("USER");
public static final Key _UTILITY=KeyImpl._const("UTILITY");
public static final Key _User_Agent=KeyImpl._const("User_Agent");
public static final Key _VALUE=KeyImpl._const("VALUE");
public static final Key _VERSION=KeyImpl._const("VERSION");
public static final Key _Version=KeyImpl._const("Version");
public static final Key _WHERE=KeyImpl._const("WHERE");
public static final Key _WS=KeyImpl._const("WS");
public static final Key _X=KeyImpl._const("X");
public static final Key _XFAS=KeyImpl._const("XFAS");
public static final Key _XML=KeyImpl._const("XML");
public static final Key _XMLNAME=KeyImpl._const("XMLNAME");
public static final Key _XMLTEXT=KeyImpl._const("XMLTEXT");
public static final Key __COUNT=KeyImpl._const("_COUNT");
public static final Key __TIME=KeyImpl._const("_TIME");
public static final Key ___filename=KeyImpl._const("__filename");
public static final Key ___isweb=KeyImpl._const("__isweb");
public static final Key ___name=KeyImpl._const("__name");
public static final Key __count=KeyImpl._const("_count");
public static final Key __time=KeyImpl._const("_time");
public static final Key _a=KeyImpl._const("a");
public static final Key _aaa=KeyImpl._const("aaa");
public static final Key _abort=KeyImpl._const("abort");
public static final Key _access=KeyImpl._const("access");
public static final Key _action=KeyImpl._const("action");
public static final Key _add=KeyImpl._const("add");
public static final Key _addAll=KeyImpl._const("addAll");
public static final Key _alias=KeyImpl._const("alias");
public static final Key _app=KeyImpl._const("app");
public static final Key _appManager=KeyImpl._const("appManager");
public static final Key _append=KeyImpl._const("append");
public static final Key _appserver=KeyImpl._const("appserver");
public static final Key _arg1=KeyImpl._const("arg1");
public static final Key _arg2=KeyImpl._const("arg2");
public static final Key _args=KeyImpl._const("args");
public static final Key _asin=KeyImpl._const("asin");
public static final Key _attributes=KeyImpl._const("attributes");
public static final Key _attrsewwe=KeyImpl._const("attrsewwe");
public static final Key _auth_type=KeyImpl._const("auth_type");
public static final Key _auth_user=KeyImpl._const("auth_user");
public static final Key _author=KeyImpl._const("author");
public static final Key _avg=KeyImpl._const("avg");
public static final Key _b=KeyImpl._const("b");
public static final Key _body=KeyImpl._const("body");
public static final Key _buffer=KeyImpl._const("buffer");
public static final Key _by=KeyImpl._const("by");
public static final Key _c=KeyImpl._const("c");
public static final Key _cache=KeyImpl._const("cache");
public static final Key _call=KeyImpl._const("call");
public static final Key _catch=KeyImpl._const("catch");
public static final Key _category=KeyImpl._const("category");
public static final Key _cert_flags=KeyImpl._const("cert_flags");
public static final Key _cfclient_=KeyImpl._const("cfclient_");
public static final Key _cfdocument=KeyImpl._const("cfdocument");
public static final Key _cfglobals=KeyImpl._const("cfglobals");
public static final Key _cfhttp=KeyImpl._const("cfhttp");
public static final Key _cfid=KeyImpl._const("cfid");
public static final Key _cflock=KeyImpl._const("cflock");
public static final Key _cfscript=KeyImpl._const("cfscript");
public static final Key _cftoken=KeyImpl._const("cftoken");
public static final Key _circuits=KeyImpl._const("circuits");
public static final Key _class=KeyImpl._const("class");
public static final Key _classname=KeyImpl._const("classname");
public static final Key _className=KeyImpl._const("className");
public static final Key _clear=KeyImpl._const("clear");
public static final Key _client=KeyImpl._const("client");
public static final Key _clone=KeyImpl._const("clone");
public static final Key _close=KeyImpl._const("close");
public static final Key _code=KeyImpl._const("code");
public static final Key _coldfusion=KeyImpl._const("coldfusion");
public static final Key _collection=KeyImpl._const("collection");
public static final Key _column=KeyImpl._const("column");
public static final Key _comment=KeyImpl._const("comment");
public static final Key _compareTo=KeyImpl._const("compareTo");
public static final Key _component=KeyImpl._const("component");
public static final Key _cond=KeyImpl._const("cond");
public static final Key _condition=KeyImpl._const("condition");
public static final Key _configXML=KeyImpl._const("configXML");
public static final Key _configure=KeyImpl._const("configure");
public static final Key _contains=KeyImpl._const("contains");
public static final Key _content=KeyImpl._const("content");
public static final Key _contentArg=KeyImpl._const("contentArg");
public static final Key _context=KeyImpl._const("context");
public static final Key _controller=KeyImpl._const("controller");
public static final Key _count=KeyImpl._const("count");
public static final Key _cs=KeyImpl._const("cs");
public static final Key _custom=KeyImpl._const("custom");
public static final Key _custom1=KeyImpl._const("custom1");
public static final Key _custom2=KeyImpl._const("custom2");
public static final Key _custom3=KeyImpl._const("custom3");
public static final Key _custom4=KeyImpl._const("custom4");
public static final Key _customx=KeyImpl._const("customx");
public static final Key _d=KeyImpl._const("d");
public static final Key _data=KeyImpl._const("data");
public static final Key _data1=KeyImpl._const("data1");
public static final Key _data2=KeyImpl._const("data2");
public static final Key _data_ID=KeyImpl._const("data_ID");
public static final Key _data_id=KeyImpl._const("data_id");
public static final Key _datasource=KeyImpl._const("datasource");
public static final Key _datasources=KeyImpl._const("datasources");
public static final Key _date=KeyImpl._const("date");
public static final Key _dc_date=KeyImpl._const("dc_date");
public static final Key _dc_subject=KeyImpl._const("dc_subject");
public static final Key _debug=KeyImpl._const("debug");
public static final Key _debugging=KeyImpl._const("debugging");
public static final Key _decorator=KeyImpl._const("decorator");
public static final Key _default=KeyImpl._const("default");
public static final Key _delete=KeyImpl._const("delete");
public static final Key _detail=KeyImpl._const("detail");
public static final Key _dir=KeyImpl._const("dir");
public static final Key _directory=KeyImpl._const("directory");
public static final Key _duplicates=KeyImpl._const("duplicates");
public static final Key _email=KeyImpl._const("email");
public static final Key _en_US=KeyImpl._const("en_US");
public static final Key _encoded=KeyImpl._const("encoded");
public static final Key _entry=KeyImpl._const("entry");
public static final Key _equals=KeyImpl._const("equals");
public static final Key _errorcode=KeyImpl._const("errorcode");
public static final Key _errortext=KeyImpl._const("errortext");
public static final Key _eval=KeyImpl._const("eval");
public static final Key _evaluation=KeyImpl._const("evaluation");
public static final Key _event=KeyImpl._const("event");
public static final Key _eventArgs=KeyImpl._const("eventArgs");
public static final Key _exe=KeyImpl._const("exe");
public static final Key _expand=KeyImpl._const("expand");
public static final Key _fb_=KeyImpl._const("fb_");
public static final Key _field=KeyImpl._const("field");
public static final Key _field1=KeyImpl._const("field1");
public static final Key _field2=KeyImpl._const("field2");
public static final Key _file=KeyImpl._const("file");
public static final Key _first=KeyImpl._const("first");
public static final Key _fontColor=KeyImpl._const("fontColor");
public static final Key _format=KeyImpl._const("format");
public static final Key _from=KeyImpl._const("from");
public static final Key _fullpath=KeyImpl._const("fullpath");
public static final Key _fusebox=KeyImpl._const("fusebox");
public static final Key _geo=KeyImpl._const("geo");
public static final Key _ger=KeyImpl._const("ger");
public static final Key _get=KeyImpl._const("get");
public static final Key _getArg=KeyImpl._const("getArg");
public static final Key _getBytes=KeyImpl._const("getBytes");
public static final Key _getClass=KeyImpl._const("getClass");
public static final Key _getColumn=KeyImpl._const("getColumn");
public static final Key _getLink=KeyImpl._const("getLink");
public static final Key _getLog=KeyImpl._const("getLog");
public static final Key _getMethod=KeyImpl._const("getMethod");
public static final Key _getName=KeyImpl._const("getName");
public static final Key _getObject=KeyImpl._const("getObject");
public static final Key _getParent=KeyImpl._const("getParent");
public static final Key _getRooms=KeyImpl._const("getRooms");
public static final Key _getSetting=KeyImpl._const("getSetting");
public static final Key _getString=KeyImpl._const("getString");
public static final Key _getTable=KeyImpl._const("getTable");
public static final Key _getTo=KeyImpl._const("getTo");
public static final Key _getType=KeyImpl._const("getType");
public static final Key _guid=KeyImpl._const("guid");
public static final Key _happy=KeyImpl._const("happy");
public static final Key _hasNext=KeyImpl._const("hasNext");
public static final Key _hashCode=KeyImpl._const("hashCode");
public static final Key _header=KeyImpl._const("header");
public static final Key _headers=KeyImpl._const("headers");
public static final Key _height=KeyImpl._const("height");
public static final Key _hide=KeyImpl._const("hide");
public static final Key _highlight=KeyImpl._const("highlight");
public static final Key _hint=KeyImpl._const("hint");
public static final Key _hit_count=KeyImpl._const("hit_count");
public static final Key _hitcount=KeyImpl._const("hitcount");
public static final Key _hits=KeyImpl._const("hits");
public static final Key _href=KeyImpl._const("href");
public static final Key _hreflang=KeyImpl._const("hreflang");
public static final Key _html=KeyImpl._const("html");
public static final Key _http_Host=KeyImpl._const("http_Host");
public static final Key _http_host=KeyImpl._const("http_host");
public static final Key _https=KeyImpl._const("https");
public static final Key _i=KeyImpl._const("i");
public static final Key _id=KeyImpl._const("id");
public static final Key _idx=KeyImpl._const("idx");
public static final Key _indexOf=KeyImpl._const("indexOf");
public static final Key _init=KeyImpl._const("init");
public static final Key _innerJoin=KeyImpl._const("innerJoin");
public static final Key _insert=KeyImpl._const("insert");
public static final Key _instance=KeyImpl._const("instance");
public static final Key _is31=KeyImpl._const("is31");
public static final Key _is7=KeyImpl._const("is7");
public static final Key _is8=KeyImpl._const("is8");
public static final Key _isDSTon=KeyImpl._const("isDSTon");
public static final Key _isEmpty=KeyImpl._const("isEmpty");
public static final Key _israilo11=KeyImpl._const("israilo11");
public static final Key _item=KeyImpl._const("item");
public static final Key _iterator=KeyImpl._const("iterator");
public static final Key _j=KeyImpl._const("j");
public static final Key _java=KeyImpl._const("java");
public static final Key _javaLoader=KeyImpl._const("javaLoader");
public static final Key _jsessionid=KeyImpl._const("jsessionid");
public static final Key _key=KeyImpl._const("key");
public static final Key _keys=KeyImpl._const("keys");
public static final Key _label=KeyImpl._const("label");
public static final Key _lang=KeyImpl._const("lang");
public static final Key _lastvisit=KeyImpl._const("lastvisit");
public static final Key _layouts=KeyImpl._const("layouts");
public static final Key _left=KeyImpl._const("left");
public static final Key _len=KeyImpl._const("len");
public static final Key _length=KeyImpl._const("length");
public static final Key _letters=KeyImpl._const("letters");
public static final Key _level=KeyImpl._const("level");
public static final Key _lft=KeyImpl._const("lft");
public static final Key _line=KeyImpl._const("line");
public static final Key _link=KeyImpl._const("link");
public static final Key _list=KeyImpl._const("list");
public static final Key _listUsers=KeyImpl._const("listUsers");
public static final Key _listener=KeyImpl._const("listener");
public static final Key _load=KeyImpl._const("load");
public static final Key _local_addr=KeyImpl._const("local_addr");
public static final Key _local_host=KeyImpl._const("local_host");
public static final Key _logFactory=KeyImpl._const("logFactory");
public static final Key _logid=KeyImpl._const("logid");
public static final Key _login=KeyImpl._const("login");
public static final Key _logout=KeyImpl._const("logout");
public static final Key _m=KeyImpl._const("m");
public static final Key _main=KeyImpl._const("main");
public static final Key _max=KeyImpl._const("max");
public static final Key _maxEvents=KeyImpl._const("maxEvents");
public static final Key _memento=KeyImpl._const("memento");
public static final Key _message=KeyImpl._const("message");
public static final Key _messageid=KeyImpl._const("messageid");
public static final Key _meta=KeyImpl._const("meta");
public static final Key _metadata=KeyImpl._const("metadata");
public static final Key _metainfo=KeyImpl._const("metainfo");
public static final Key _method=KeyImpl._const("method");
public static final Key _methodcall=KeyImpl._const("methodcall");
public static final Key _min=KeyImpl._const("min");
public static final Key _minus=KeyImpl._const("minus");
public static final Key _mode=KeyImpl._const("mode");
public static final Key _moduleName=KeyImpl._const("moduleName");
public static final Key _myFusebox=KeyImpl._const("myFusebox");
public static final Key _name=KeyImpl._const("name");
public static final Key _needssetup=KeyImpl._const("needssetup");
public static final Key _next=KeyImpl._const("next");
public static final Key _nosetup=KeyImpl._const("nosetup");
public static final Key _notify=KeyImpl._const("notify");
public static final Key _notifyAll=KeyImpl._const("notifyAll");
public static final Key _nullable=KeyImpl._const("nullable");
public static final Key _nullvalue=KeyImpl._const("nullvalue");
public static final Key _obj=KeyImpl._const("obj");
public static final Key _object=KeyImpl._const("object");
public static final Key _officeMap=KeyImpl._const("officeMap");
public static final Key _onChange=KeyImpl._const("onChange");
public static final Key _opensample=KeyImpl._const("opensample");
public static final Key _os=KeyImpl._const("os");
public static final Key _out=KeyImpl._const("out");
public static final Key _output=KeyImpl._const("output");
public static final Key _override=KeyImpl._const("override");
public static final Key _overwrite=KeyImpl._const("overwrite");
public static final Key _owner=KeyImpl._const("owner");
public static final Key _package=KeyImpl._const("package");
public static final Key _page=KeyImpl._const("page");
public static final Key _pages=KeyImpl._const("pages");
public static final Key _parameters=KeyImpl._const("parameters");
public static final Key _parent=KeyImpl._const("parent");
public static final Key _password=KeyImpl._const("password");
public static final Key _username=KeyImpl._const("username");
public static final Key _path=KeyImpl._const("path");
public static final Key _path_info=KeyImpl._const("path_info");
public static final Key _pattern=KeyImpl._const("pattern");
public static final Key _pdf=KeyImpl._const("pdf");
public static final Key _permiss=KeyImpl._const("permiss");
public static final Key _plus=KeyImpl._const("plus");
public static final Key _pointer=KeyImpl._const("pointer");
public static final Key _pos=KeyImpl._const("pos");
public static final Key _preProcess=KeyImpl._const("preProcess");
public static final Key _prefix=KeyImpl._const("prefix");
public static final Key _prepend=KeyImpl._const("prepend");
public static final Key _primarykey=KeyImpl._const("primarykey");
public static final Key _productid=KeyImpl._const("productid");
public static final Key _property=KeyImpl._const("property");
public static final Key _published=KeyImpl._const("published");
public static final Key _put=KeyImpl._const("put");
public static final Key _q=KeyImpl._const("q");
public static final Key _qDir=KeyImpl._const("qDir");
public static final Key _qry=KeyImpl._const("qry");
public static final Key _qtest=KeyImpl._const("qtest");
public static final Key _query=KeyImpl._const("query");
public static final Key _queryCache=KeyImpl._const("queryCache");
public static final Key _queryError=KeyImpl._const("queryError");
public static final Key _r99f=KeyImpl._const("r99f");
public static final Key _railo=KeyImpl._const("railo");
public static final Key _railoweb=KeyImpl._const("railoweb");
public static final Key _rank=KeyImpl._const("rank");
public static final Key _rel=KeyImpl._const("rel");
public static final Key _remove=KeyImpl._const("remove");
public static final Key _replace=KeyImpl._const("replace");
public static final Key _replyto=KeyImpl._const("replyto");
public static final Key _required=KeyImpl._const("required");
public static final Key _res=KeyImpl._const("res");
public static final Key _result=KeyImpl._const("result");
public static final Key _resultArg=KeyImpl._const("resultArg");
public static final Key _return=KeyImpl._const("return");
public static final Key _rgt=KeyImpl._const("rgt");
public static final Key _right=KeyImpl._const("right");
public static final Key _rootpath=KeyImpl._const("rootpath");
public static final Key _rst=KeyImpl._const("rst");
public static final Key _sad=KeyImpl._const("sad");
public static final Key _scope=KeyImpl._const("scope");
public static final Key _scopeKey=KeyImpl._const("scopeKey");
public static final Key _score=KeyImpl._const("score");
public static final Key _sct=KeyImpl._const("sct");
public static final Key _search=KeyImpl._const("search");
public static final Key _security=KeyImpl._const("security");
public static final Key _separator=KeyImpl._const("separator");
public static final Key _server=KeyImpl._const("server");
public static final Key _servlet=KeyImpl._const("servlet");
public static final Key _sessionid=KeyImpl._const("sessionid");
public static final Key _set=KeyImpl._const("set");
public static final Key _setEL=KeyImpl._const("setEL");
public static final Key _setFirst=KeyImpl._const("setFirst");
public static final Key _setMemento=KeyImpl._const("setMemento");
public static final Key _show=KeyImpl._const("show");
public static final Key _showudfs=KeyImpl._const("showudfs");
public static final Key _size=KeyImpl._const("size");
public static final Key _sleep=KeyImpl._const("sleep");
public static final Key _source=KeyImpl._const("source");
public static final Key _sql=KeyImpl._const("sql");
public static final Key _src=KeyImpl._const("src");
public static final Key _start=KeyImpl._const("start");
public static final Key _end=KeyImpl._const("end");
public static final Key _startwith=KeyImpl._const("startwith");
public static final Key _state=KeyImpl._const("state");
public static final Key _status=KeyImpl._const("status");
public static final Key _stop=KeyImpl._const("stop");
public static final Key _store=KeyImpl._const("store");
public static final Key _str=KeyImpl._const("str");
public static final Key _strXML=KeyImpl._const("strXML");
public static final Key _subject=KeyImpl._const("subject");
public static final Key _substring=KeyImpl._const("substring");
public static final Key _succeeded=KeyImpl._const("succeeded");
public static final Key _summary=KeyImpl._const("summary");
public static final Key _susi=KeyImpl._const("susi");
public static final Key _susi2=KeyImpl._const("susi2");
public static final Key _table=KeyImpl._const("table");
public static final Key _tagname=KeyImpl._const("tagname");
public static final Key _tc=KeyImpl._const("tc");
public static final Key _template=KeyImpl._const("template");
public static final Key _templates=KeyImpl._const("templates");
public static final Key _test=KeyImpl._const("test");
public static final Key _test1=KeyImpl._const("test1");
public static final Key _test2=KeyImpl._const("test2");
public static final Key _testcustom=KeyImpl._const("testcustom");
public static final Key _testfile=KeyImpl._const("testfile");
public static final Key _testquery=KeyImpl._const("testquery");
public static final Key _text=KeyImpl._const("text");
public static final Key _this=KeyImpl._const("this");
public static final Key _thistag=KeyImpl._const("thistag");
public static final Key _thread=KeyImpl._const("thread");
public static final Key _time=KeyImpl._const("time");
public static final Key _timers=KeyImpl._const("timers");
public static final Key _timespan=KeyImpl._const("timespan");
public static final Key _title=KeyImpl._const("title");
public static final Key _to=KeyImpl._const("to");
public static final Key _toArray=KeyImpl._const("toArray");
public static final Key _toString=KeyImpl._const("toString");
public static final Key _top=KeyImpl._const("top");
public static final Key _total=KeyImpl._const("total");
public static final Key _traces=KeyImpl._const("traces");
public static final Key _transfer=KeyImpl._const("transfer");
public static final Key _tree=KeyImpl._const("tree");
public static final Key _type=KeyImpl._const("type");
public static final Key _uid=KeyImpl._const("uid");
public static final Key _updated=KeyImpl._const("updated");
public static final Key _uri=KeyImpl._const("uri");
public static final Key _url=KeyImpl._const("url");
public static final Key _urlBase=KeyImpl._const("urlBase");
public static final Key _urltoken=KeyImpl._const("urltoken");
public static final Key _usage=KeyImpl._const("usage");
public static final Key _utility=KeyImpl._const("utility");
public static final Key _v=KeyImpl._const("v");
public static final Key _v_pages=KeyImpl._const("v_pages");
public static final Key _validate=KeyImpl._const("validate");
public static final Key _value=KeyImpl._const("value");
public static final Key _valueOf=KeyImpl._const("valueOf");
public static final Key _var=KeyImpl._const("var");
public static final Key _varname=KeyImpl._const("varname");
public static final Key _varvalue=KeyImpl._const("varvalue");
public static final Key _version=KeyImpl._const("version");
public static final Key _visitBeach=KeyImpl._const("visitBeach");
public static final Key _visitHal=KeyImpl._const("visitHal");
public static final Key _visitJohn=KeyImpl._const("visitJohn");
public static final Key _visitOcean=KeyImpl._const("visitOcean");
public static final Key _wait=KeyImpl._const("wait");
public static final Key _where=KeyImpl._const("where");
public static final Key _width=KeyImpl._const("width");
public static final Key _writeLine=KeyImpl._const("writeLine");
public static final Key _wsdl=KeyImpl._const("wsdl");
public static final Key _x=KeyImpl._const("x");
public static final Key _xfa=KeyImpl._const("xfa");
public static final Key _xml=KeyImpl._const("xml");
public static final Key _xtags=KeyImpl._const("xtags");
public static final Key _returnFormat=KeyImpl._const("returnFormat");
public static final Key _s3=KeyImpl._const("s3");
public static final Key _super=KeyImpl._const("super");
public static final Key _argumentCollection=KeyImpl._const("argumentCollection");
public static final Key _argumentcollection=KeyImpl._const("argumentcollection");
public static final Key _setArgumentCollection=KeyImpl._const("setArgumentCollection");
public static final Key _returntype=KeyImpl._const("returntype");
public static final Key _description=KeyImpl._const("description");
public static final Key _displayname=KeyImpl._const("displayname");
public static final Key _arguments=KeyImpl._const("arguments");
public static final Key _variables=KeyImpl._const("variables");
public static final Key _fieldnames=KeyImpl._const("fieldnames");
public static final Key _local=KeyImpl._const("local");
public static final Key _exceptions=KeyImpl._const("exceptions");
public static final Key _closure=KeyImpl._const("closure");
public static final Key _function=KeyImpl._const("function");
public static final Key _cgi = KeyImpl._const("cgi");
public static final Key _all = KeyImpl._const("all");
public static final Key _tag = KeyImpl._const("tag");
public static final Key _classic = KeyImpl._const("classic");
public static final Key _simple = KeyImpl._const("simple");
public static final Key _hidden = KeyImpl._const("hidden");
public static final Key _external = KeyImpl._const("external");
public static final Key _charset = KeyImpl._const("charset");
public static final Key _created = KeyImpl._const("created");
public static final Key _language = KeyImpl._const("language");
public static final Key _online = KeyImpl._const("online");
public static final Key _lastmodified = KeyImpl._const("lastmodified");
public static final Key _lastModified = KeyImpl._const("lastModified");
public static final Key _task=KeyImpl._const("task");
public static final Key _port=KeyImpl._const("port");
public static final Key _timecreated=KeyImpl._const("timecreated");
public static final Key _hash=KeyImpl._const("hash");
public static final Key _root=KeyImpl._const("root");
public static final Key _sourcename=KeyImpl._const("sourcename");
public static final Key _readonly=KeyImpl._const("readonly");
public static final Key _isvalid=KeyImpl._const("isvalid");
public static final Key _config=KeyImpl._const("config");
public static final Key _executionTime = KeyImpl._const("executionTime");
public static final Key _RECORDCOUNT = KeyImpl._const("RECORDCOUNT");
public static final Key _cached = KeyImpl._const("cached");
public static final Key _COLUMNLIST = KeyImpl._const("COLUMNLIST");
public static final Key _CURRENTROW = KeyImpl._const("CURRENTROW");
public static final Key _IDENTITYCOL = KeyImpl._const("IDENTITYCOL");
public static final Key _dateLastModified = KeyImpl._const("dateLastModified");
public static final Key _statuscode = KeyImpl._const("statuscode");
public static final Key _statustext = KeyImpl._const("statustext");
public static final Key _extends = KeyImpl._const("extends");
public static final Key _implements = KeyImpl._const("implements");
public static final Key __toDateTime = KeyImpl._const("_toDateTime");
public static final Key __toNumeric = KeyImpl._const("_toNumeric");
public static final Key __toBoolean = KeyImpl._const("_toBoolean");
public static final Key __toString = KeyImpl._const("_toString");
public static final Key _onmissingmethod = KeyImpl._const("onmissingmethod");
public static final Key _functions = KeyImpl._const("functions");
public static final Key _fullname = KeyImpl._const("fullname");
public static final Key _skeleton = KeyImpl._const("skeleton");
public static final Key _properties = KeyImpl._const("properties");
public static final Key _mappedSuperClass = KeyImpl._const("mappedSuperClass");
public static final Key _persistent = KeyImpl._const("persistent");
public static final Key _accessors = KeyImpl._const("accessors");
public static final Key _synchronized = KeyImpl._const("synchronized");
public static final Key _queryFormat = KeyImpl._const("queryFormat");
public static final Key _Hint= KeyImpl._const("Hint");
public static final Key _Entities= KeyImpl._const("Entities");
public static final Key _Pattern= KeyImpl._const("Pattern");
public static final Key _last_modified = KeyImpl._const("last_modified");
public static final Key _context_path = KeyImpl._const("context_path");
public static final Key _query_string = KeyImpl._const("query_string");
public static final Key _path_translated = KeyImpl._const("path_translated");
public static final Key _server_port_secure = KeyImpl._const("server_port_secure");
public static final Key _server_port = KeyImpl._const("server_port");
public static final Key _server_protocol = KeyImpl._const("server_protocol");
public static final Key _server_name = KeyImpl._const("server_name");
public static final Key _script_name = KeyImpl._const("script_name");
public static final Key _http_if_modified_since = KeyImpl._const("http_if_modified_since");
public static final Key _cf_template_path = KeyImpl._const("cf_template_path");
public static final Key _remote_user = KeyImpl._const("remote_user");
public static final Key _remote_addr = KeyImpl._const("remote_addr");
public static final Key _remote_host = KeyImpl._const("remote_host");
public static final Key _request_method = KeyImpl._const("request_method");
public static final Key _REDIRECT_URL = KeyImpl._const("REDIRECT_URL");
public static final Key _request_uri = KeyImpl._const("request_uri");
public static final Key _REDIRECT_QUERY_STRING = KeyImpl._const("REDIRECT_QUERY_STRING");
public static final Key _auth_password = KeyImpl._const("auth_password");
public static final Key _cert_cookie = KeyImpl._const("cert_cookie");
public static final Key _cert_keysize = KeyImpl._const("cert_keysize");
public static final Key _cert_serialnumber = KeyImpl._const("cert_serialnumber");
public static final Key _cert_issuer = KeyImpl._const("cert_issuer");
public static final Key _cert_secretkeysize = KeyImpl._const("cert_secretkeysize");
public static final Key _cert_server_subject = KeyImpl._const("cert_server_subject");
public static final Key _cert_server_issuer = KeyImpl._const("cert_server_issuer");
public static final Key _cert_subject = KeyImpl._const("cert_subject");
public static final Key _gateway_interface = KeyImpl._const("gateway_interface");
public static final Key _content_length = KeyImpl._const("content_length");
public static final Key _http_accept = KeyImpl._const("http_accept");
public static final Key _content_type = KeyImpl._const("content_type");
public static final Key _http_connection = KeyImpl._const("http_connection");
public static final Key _http_cookie = KeyImpl._const("http_cookie");
public static final Key _http_accept_encoding = KeyImpl._const("http_accept_encoding");
public static final Key _http_accept_language = KeyImpl._const("http_accept_language");
public static final Key _http_user_agent = KeyImpl._const("http_user_agent");
public static final Key _https_keysize = KeyImpl._const("https_keysize");
public static final Key _http_referer = KeyImpl._const("http_referer");
public static final Key _https_secretkeysize = KeyImpl._const("https_secretkeysize");
public static final Key _https_server_issuer = KeyImpl._const("https_server_issuer");
public static final Key _https_server_subject = KeyImpl._const("https_server_subject");
public static final Key _web_server_api = KeyImpl._const("web_server_api");
public static final Key _server_software = KeyImpl._const("server_software");
public static final Key _application = KeyImpl._const("application");
public static final Key _cookie = KeyImpl._const("cookie");
public static final Key _cluster = KeyImpl._const("cluster");
public static final Key _form = KeyImpl._const("form");
public static final Key _request = KeyImpl._const("request");
public static final Key _session = KeyImpl._const("session");
public static final Key _cferror = KeyImpl._const("cferror");
public static final Key _error = KeyImpl._const("error");
public static final Key _cfthread = KeyImpl._const("cfthread");
public static final Key _cfcatch = KeyImpl._const("cfcatch");
public static final Key _used = KeyImpl._const("used");
public static final Key _use = KeyImpl._const("use");
public static final Key _Detail = KeyImpl._const("Detail");
public static final Key _attributecollection = KeyImpl._const("attributecollection");
public static final Key _attributeCollection = KeyImpl._const("attributeCollection");
public static final Key _secure = KeyImpl._const("secure");
public static final Key _httponly = KeyImpl._const("httponly");
public static final Key _domain = KeyImpl._const("domain");
public static final Key _preservecase = KeyImpl._const("preservecase");
public static final Key _encode = KeyImpl._const("encode");
public static final Key _encodevalue = KeyImpl._const("encodevalue");
public static final Key _each = KeyImpl._const("each");
public static final Key _member = KeyImpl._const("member");
public static final Key _resource = KeyImpl._const("resource");
public static final Key _img = KeyImpl._const("img");
public static final Key _cfcLocation = KeyImpl._const("cfcLocation");
public static final Key _cfcLocations = KeyImpl._const("cfcLocations");
public static final Key _skipCFCWithError = KeyImpl._const("skipCFCWithError");
public static final Key _destination = KeyImpl._const("destination");
public static final Key _codec = KeyImpl._const("codec");
public static final Key _chaining = KeyImpl._const("chaining");
public static final Key _protocol = KeyImpl._const("protocol");
public static final Key _enabled = KeyImpl._const("enabled");
public static final Key _fieldtype = KeyImpl._const("fieldtype");
public static final Key _cfc = KeyImpl._const("cfc");
public static final Key _memory = KeyImpl._const("memory");
public static final Key _scopes = KeyImpl._const("scopes");
public static final Key _mappings = KeyImpl._const("mappings");
public static final Key _web = KeyImpl._const("web");
public static final Key _mimetype = KeyImpl._const("mimetype");
public static final Key _0 = KeyImpl._const("0");
public static final Key _1 = KeyImpl._const("1");
public static final Key _2 = KeyImpl._const("2");
public static final Key _3 = KeyImpl._const("3");
public static final Key _4 = KeyImpl._const("4");
public static final Key _5 = KeyImpl._const("5");
public static final Key _6 = KeyImpl._const("6");
public static final Key _7 = KeyImpl._const("7");
public static final Key _8 = KeyImpl._const("8");
public static final Key _9 = KeyImpl._const("9");
public static final Key _PRODUCTNAME = KeyImpl._const("PRODUCTNAME");
public static final Key _BODY = KeyImpl._const("BODY");
public static final Key _XMLVALUE = KeyImpl._const("XMLVALUE");
public static final Key _EL = KeyImpl._const("EL");
public static final Key _M = KeyImpl._const("M");
public static final Key _N = KeyImpl._const("N");
public static final Key _TEST1 = KeyImpl._const("TEST1");
public static final Key _TEST3 = KeyImpl._const("TEST3");
public static final Key _XMLDATA = KeyImpl._const("XMLDATA");
public static final Key _XMLDOC = KeyImpl._const("XMLDOC");
public static final Key _XMLROOT = KeyImpl._const("XMLROOT");
public static final Key _XMLATTRIBUTES = KeyImpl._const("XMLATTRIBUTES");
public static final Key _XMLCHILDREN = KeyImpl._const("XMLCHILDREN");
public static final Key _XMLCOMMENT = KeyImpl._const("XMLCOMMENT");
public static final Key _CHILDREN = KeyImpl._const("CHILDREN");
public static final Key _ELEMENT = KeyImpl._const("ELEMENT");
public static final Key _WARNINGS = KeyImpl._const("WARNINGS");
public static final Key _VALIDATE = KeyImpl._const("VALIDATE");
public static final Key _ERRORS = KeyImpl._const("ERRORS");
public static final Key _STATUS = KeyImpl._const("STATUS");
public static final Key _FATALERRORS = KeyImpl._const("FATALERRORS");
public static final Key _timeout = KeyImpl._const("timeout");
public static final Key _host = KeyImpl._const("host");
public static final Key _urlpath = KeyImpl._const("urlpath");
public static final Key _extensions = KeyImpl._const("extensions");
public static final Key _STATE = KeyImpl._const("STATE");
public static final Key _START = KeyImpl._const("START");
public static final Key _STOP = KeyImpl._const("STOP");
public static final Key _LAST = KeyImpl._const("LAST");
public static final Key _CONFIG = KeyImpl._const("CONFIG");
public static final Key _DIFF = KeyImpl._const("DIFF");
public static final Key _COLL = KeyImpl._const("COLL");
public static final Key _FILTER = KeyImpl._const("FILTER");
public static final Key _recurse = KeyImpl._const("recurse");
public static final Key _rest = KeyImpl._const("rest");
public static final Key _httpmethod = KeyImpl._const("httpmethod");
public static final Key _restPath = KeyImpl._const("restPath");
public static final Key _restArgName = KeyImpl._const("restArgName");
public static final Key _restArgSource = KeyImpl._const("restArgSource");
public static final Key _consumes = KeyImpl._const("consumes");
public static final Key _produces = KeyImpl._const("produces");
public static final Key _ref = KeyImpl._const("ref");
public static final Key _script = KeyImpl._const("script");
public static final Key _applicationTimeout = KeyImpl._const("applicationTimeout");
public static final Key _clientManagement = KeyImpl._const("clientManagement");
public static final Key _queries = KeyImpl._const("queries");
public static final Key _history = KeyImpl._const("history");
public static final Key _group = KeyImpl._const("group");
public static final Key _orm = KeyImpl._const("orm");
public static final Key _create = KeyImpl._const("create");
public static final Key _drop = KeyImpl._const("drop");
public static final Key _grant = KeyImpl._const("grant");
public static final Key _revoke = KeyImpl._const("revoke");
public static final Key _select = KeyImpl._const("select");
public static final Key _update = KeyImpl._const("update");
public static final Key _alter = KeyImpl._const("alter");
private static HashSet<String> _____keys;
public static String getFieldName(String key) {
if(_____keys==null) {
Field[] fields = KeyConstants.class.getFields();
_____keys=new HashSet<String>();
for(int i=0;i<fields.length;i++){
if(fields[i].getType()!=Key.class) continue;
_____keys.add(fields[i].getName());
}
}
key="_"+key;
return _____keys.contains(key)?key:null;
}
}
|
package hudson.remoting;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Sits behind a proxy object and implements the proxy logic.
*
* @author Kohsuke Kawaguchi
*/
final class RemoteInvocationHandler implements InvocationHandler, Serializable {
/**
* This proxy acts as a proxy to the object of
* Object ID on the remote {@link Channel}.
*/
private final int oid;
/**
* Represents the connection to the remote {@link Channel}.
*
* <p>
* This field is null when a {@link RemoteInvocationHandler} is just
* created and not working as a remote proxy. Once tranferred to the
* remote system, this field is set to non-null.
*/
private transient Channel channel;
/**
* True if we are proxying the user object.
*/
private final boolean userProxy;
RemoteInvocationHandler(int id, boolean userProxy) {
this.oid = id;
this.userProxy = userProxy;
}
/**
* Creates a proxy that wraps an existing OID on the remote.
*/
RemoteInvocationHandler(Channel channel, int id, boolean userProxy) {
this.channel = channel;
this.oid = id;
this.userProxy = userProxy;
}
/**
* Wraps an OID to the typed wrapper.
*/
public static <T> T wrap(Channel channel, int id, Class<T> type, boolean userProxy) {
return type.cast(Proxy.newProxyInstance( type.getClassLoader(), new Class[]{type},
new RemoteInvocationHandler(channel,id,userProxy)));
}
/**
* If the given object is a proxy to a remote object in the specified channel,
* return its object ID. Otherwise return -1.
* <p>
* This method can be used to get back the original reference when
* a proxy is sent back to the channel it came from.
*/
public static int unwrap(Object proxy, Channel src) {
InvocationHandler h = Proxy.getInvocationHandler(proxy);
if (h instanceof RemoteInvocationHandler) {
RemoteInvocationHandler rih = (RemoteInvocationHandler) h;
if(rih.channel==src)
return rih.oid;
}
return -1;
}
/**
* If the given object is a proxy object, return the {@link Channel}
* object that it's associated with. Otherwise null.
*/
public static Channel unwrap(Object proxy) {
InvocationHandler h = Proxy.getInvocationHandler(proxy);
if (h instanceof RemoteInvocationHandler) {
RemoteInvocationHandler rih = (RemoteInvocationHandler) h;
return rih.channel;
}
return null;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(channel==null)
throw new IllegalStateException("proxy is not connected to a channel");
if(args==null) args = EMPTY_ARRAY;
Class<?> dc = method.getDeclaringClass();
if(dc ==Object.class) {
// handle equals and hashCode by ourselves
try {
return method.invoke(this,args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
// delegate the rest of the methods to the remote object
if(userProxy)
return channel.call(new RPCRequest(oid,method,args,dc.getClassLoader()));
else
return new RPCRequest(oid,method,args).call(channel);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
channel = Channel.current();
ois.defaultReadObject();
}
/**
* Two proxies are the same iff they represent the same remote object.
*/
public boolean equals(Object o) {
if(Proxy.isProxyClass(o.getClass()))
o = Proxy.getInvocationHandler(o);
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RemoteInvocationHandler that = (RemoteInvocationHandler) o;
return this.oid==that.oid && this.channel==that.channel;
}
public int hashCode() {
return oid;
}
protected void finalize() throws Throwable {
// unexport the remote object
if(channel!=null)
channel.send(new UnexportCommand(oid));
super.finalize();
}
private static final long serialVersionUID = 1L;
/**
* Executes the method call remotely.
*
* If used as {@link Request}, this can be used to provide a lower-layer
* for the use inside remoting, to implement the classloader delegation, and etc.
* The downside of this is that the classes used as a parameter/return value
* must be available to both JVMs.
*
* If used as {@link Callable} in conjunction with {@link UserRequest},
* this can be used to send a method call to user-level objects, and
* classes for the parameters and the return value are sent remotely if needed.
*/
private static final class RPCRequest extends Request<Serializable,Throwable> implements DelegatingCallable<Serializable,Throwable> {
/**
* Target object id to invoke.
*/
private final int oid;
private final String methodName;
/**
* Type name of the arguments to invoke. They are names because
* neither {@link Method} nor {@link Class} is serializable.
*/
private final String[] types;
/**
* Arguments to invoke the method with.
*/
private final Object[] arguments;
/**
* If this is used as {@link Callable}, we need to remember what classloader
* to be used to serialize the request and the response.
*/
private transient ClassLoader classLoader;
public RPCRequest(int oid, Method m, Object[] arguments) {
this(oid,m,arguments,null);
}
public RPCRequest(int oid, Method m, Object[] arguments, ClassLoader cl) {
this.oid = oid;
this.arguments = arguments;
this.methodName = m.getName();
this.classLoader = cl;
this.types = new String[arguments.length];
Class<?>[] params = m.getParameterTypes();
for( int i=0; i<arguments.length; i++ )
types[i] = params[i].getName();
}
public Serializable call() throws Throwable {
return perform(Channel.current());
}
public ClassLoader getClassLoader() {
if(classLoader!=null)
return classLoader;
else
return getClass().getClassLoader();
}
protected Serializable perform(Channel channel) throws Throwable {
Object o = channel.getExportedObject(oid);
if(o==null)
throw new IllegalStateException("Unable to call "+methodName+". Invalid object ID "+oid);
try {
Method m = choose(o);
m.setAccessible(true); // in case the class is not public
return (Serializable) m.invoke(o,arguments);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
/**
* Chooses the method to invoke.
*/
private Method choose(Object o) {
OUTER:
for(Method m : o.getClass().getMethods()) {
if(!m.getName().equals(methodName))
continue;
Class<?>[] paramTypes = m.getParameterTypes();
if(types.length!=arguments.length)
continue;
for( int i=0; i<types.length; i++ ) {
if(!types[i].equals(paramTypes[i].getName()))
continue OUTER;
}
return m;
}
return null;
}
public String toString() {
return "RPCRequest("+oid+","+methodName+")";
}
private static final long serialVersionUID = 1L;
}
private static final Object[] EMPTY_ARRAY = new Object[0];
}
|
package org.jboss.jbossts.star.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.jboss.jbossts.star.provider.HttpResponseException;
import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.Link;
/**
* Various utilities for sending HTTP messages
*/
public class TxSupport
{
protected static final Logger log = Logger.getLogger(TxSupport.class);
private static Pattern NVP_PATTERN = Pattern.compile("\\b\\w+\\s*=\\s*.*"); // matches name=value pairs
private static String LINK_REGEX = "<(.*?)>.*rel=\"(.*?)\"";
private static Pattern LINK_PATTERN = Pattern.compile(LINK_REGEX);
public static int PORT = 8080;
public static String BIND_ADDRESS = System.getProperty("jboss.bind.address", "127.0.0.1");
public static String BASE_URL = "http://" + BIND_ADDRESS + ':';
public static final String TX_CONTEXT = System.getProperty("rest.tx.context.path", "/rest-tx");
/**
* The REST path prefix for the transaction and recovery coordinator URLS
*/
public static final String TX_PATH = "/tx/";
/**
* The REST path for the transaction coordinator. Thus the full path for the coordinator
* is <web server context> + TX_PATH + TX_SEGMENT
*/
public static final String TX_SEGMENT = "transaction-manager";
public static final String RC_SEGMENT = "recovery-coordinator";
public static final String DEF_TX_URL = BASE_URL + PORT + TX_CONTEXT + TX_PATH + TX_SEGMENT;
public static String TXN_MGR_URL = DEF_TX_URL;
public static final String URI_SEPARATOR = ";";
public static final String ABORT_ONLY = "TransactionRollbackOnly";
public static final String ABORTING = "TransactionRollingBack";
public static final String ABORTED = "TransactionRolledBack";
public static final String COMMITTING = "TransactionCommitting";
public static final String COMMITTED = "TransactionCommitted";
public static final String COMMITTED_ONE_PHASE = "TransactionCommittedOnePhase";
public static final String H_ROLLBACK = "TransactionHeuristicRollback";
public static final String H_COMMIT = "TransactionHeuristicCommit";
public static final String H_HAZARD = "TransactionHeuristicHazard";
public static final String H_MIXED = "TransactionHeuristicMixed";
public static final String PREPARING = "TransactionPreparing";
public static final String PREPARED = "TransactionPrepared";
public static final String RUNNING = "TransactionActive";
public static final String READONLY = "TransactionReadOnly";
public static final String TX_ACTIVE = toStatusContent(RUNNING);
public static final String TX_PREPARED = toStatusContent(PREPARED);
public static final String TX_COMMITTED = toStatusContent(COMMITTED);
public static final String TX_ABORTED = toStatusContent(ABORTED);
public static final String TX_H_MIXED = toStatusContent(H_MIXED);
public static final String TX_H_ROLLBACK = toStatusContent(H_ROLLBACK);
public static final String DO_COMMIT = toStatusContent(COMMITTED);
public static final String DO_ABORT = toStatusContent(ABORTED);
public static final String STATUS_MEDIA_TYPE = "application/txstatus";
public static final String POST_MEDIA_TYPE = "application/x-www-form-urlencoded";
public static final String PLAIN_MEDIA_TYPE = "text/plain";
public static final String LOCATION_LINK = "location";
public static final String TERMINATOR_LINK = "terminator";
public static final String PARTICIPANT_LINK = "durableparticipant";
public static final String TIMEOUT_PROPERTY = "timeout";
public static final String STATUS_PROPERTY = "txStatus";
private Map<String, String> links = new HashMap<String, String>();
private int status = -1;
private String body = null;
private String txnMgr;
public static void setTxnMgrUrl(String txnMgrUrl) {
TXN_MGR_URL = txnMgrUrl;
}
public TxSupport(String txnMgr) {
this.txnMgr = txnMgr;
}
public TxSupport() {
this(TXN_MGR_URL);
}
public static void addLinkHeader(Response.ResponseBuilder response, UriInfo info, String title, String name, String ... pathComponents)
{
String basePath = info.getMatchedURIs().get(0);
UriBuilder builder = info.getBaseUriBuilder();
builder.path(basePath);
for (String component : pathComponents)
builder.path(component);
String uri = builder.build().toString();
setLinkHeader(response, title, name, uri, null);
}
public static void setLinkHeader(Response.ResponseBuilder builder, String title, String rel, String href, String type)
{
Link link = new Link(title, rel, href, type, null);
setLinkHeader(builder, link);
}
public static void setLinkHeader(Response.ResponseBuilder builder, Link link)
{
builder.header("Link", link);
}
public Collection<String> getTransactions() throws HttpResponseException {
String content = httpRequest(new int[] {HttpURLConnection.HTTP_OK}, txnMgr, "GET", STATUS_MEDIA_TYPE, null, null);
Collection<String> txns = new ArrayList<String> ();
// the returned document contains transaction URLs delimited by the TXN_LIST_SEP character
// If the string is empty split returns an array of size 1 with the empty string as the element
if(content.length() == 0) {
return txns;
}
for (String txn : content.split(URI_SEPARATOR))
txns.add(txn.trim());
return txns;
}
public int txCount() throws HttpResponseException {
String content = httpRequest(new int[] {HttpURLConnection.HTTP_OK}, txnMgr, "GET", STATUS_MEDIA_TYPE, null, null);
return content.length() == 0 ? 0 : content.split(URI_SEPARATOR).length;
}
// Transaction control methods
public TxSupport startTx() throws HttpResponseException {
httpRequest(new int[] {HttpURLConnection.HTTP_CREATED}, txnMgr, "POST", POST_MEDIA_TYPE, "", links);
return this;
}
public TxSupport startTx(long milliseconds) throws HttpResponseException {
httpRequest(new int[] {HttpURLConnection.HTTP_CREATED}, txnMgr, "POST", POST_MEDIA_TYPE, TIMEOUT_PROPERTY + "=" + milliseconds, links);
return this;
}
public String commitTx() throws HttpResponseException {
return httpRequest(new int[] {HttpURLConnection.HTTP_OK}, links.get(TERMINATOR_LINK), "PUT", STATUS_MEDIA_TYPE, DO_COMMIT, null);
}
public String rollbackTx() throws HttpResponseException {
return httpRequest(new int[] {HttpURLConnection.HTTP_OK}, links.get(TERMINATOR_LINK), "PUT", STATUS_MEDIA_TYPE, DO_ABORT, null);
}
public String txStatus() throws HttpResponseException {
return httpRequest(new int[] {HttpURLConnection.HTTP_OK}, links.get(LOCATION_LINK), "GET", null, null, null);
}
public String txUrl() {
return links.get(LOCATION_LINK);
}
public String txTerminatorUrl() {
return links.get(TERMINATOR_LINK);
}
public String enlistUrl() {
return links.get(PARTICIPANT_LINK);
}
public String getBody() {
return body;
}
public int getStatus() {
return status;
}
public void refreshLinkHeaders(Map<String, String> linkHeaders) throws HttpResponseException {
httpRequest(new int[] {HttpURLConnection.HTTP_OK}, links.get(LOCATION_LINK), "HEAD", STATUS_MEDIA_TYPE, null, linkHeaders);
}
public String enlist(String pUrl) throws HttpResponseException {
return httpRequest(new int[] {HttpURLConnection.HTTP_OK}, pUrl, "POST", POST_MEDIA_TYPE, enlistUrl(), null);
}
public String httpRequest(int[] expect, String url, String method, String mediaType, String content, Map<String, String> linkHeaders) throws HttpResponseException {
HttpURLConnection connection = null;
try {
connection = openConnection(null, url, method, mediaType, content);
connection.setReadTimeout(5000);
status = connection.getResponseCode();
try {
body = (status != -1 ? getContent(connection) : "");
} catch (IOException e) {
body = "";
}
if (linkHeaders != null) {
extractLinkHeaders(connection, linkHeaders);
addLocationHeader(connection, linkHeaders);
}
if (log.isTraceEnabled())
log.trace("httpRequest:" +
"\n\turl: " + url +
"\n\tmethod: " + method +
"\n\tmediaType: " + mediaType +
"\n\tcontent: " + content +
"\n\tresponse code: " + status +
"\n\tresponse body: " + body
);
if (expect != null && expect.length != 0) {
for (int sc : expect)
if (sc == status)
return body;
throw new HttpResponseException(null, body, expect, status);
} else {
return body;
}
} catch (IOException e) {
throw new HttpResponseException(e, "", expect, HttpURLConnection.HTTP_UNAVAILABLE);
} finally {
if (connection != null)
connection.disconnect();
}
}
private void extractLinkHeaders(HttpURLConnection connection, Map<String, String> links) {
Collection<String> linkHeaders = connection.getHeaderFields().get("Link");
if (linkHeaders == null)
linkHeaders = connection.getHeaderFields().get("link");
if (linkHeaders != null) {
for (String link : linkHeaders) {
String[] lhs = link.split(","); // links are separated by a comma
for (String lnk : lhs) {
Matcher m = LINK_PATTERN.matcher(lnk);
if (m.find() && m.groupCount() > 1)
links.put(m.group(2), m.group(1));
}
}
}
}
private void addLocationHeader(HttpURLConnection connection, Map<String, String> links) {
try {
if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED)
links.put("location", connection.getHeaderField("location"));
} catch (IOException e) {
}
}
private HttpURLConnection openConnection(HttpURLConnection connection, String url, String method, String contentType,
String content) throws IOException {
if (connection != null)
connection.disconnect();
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
if (contentType != null)
connection.setRequestProperty("Content-Type", contentType);
if (content != null) {
connection.setDoOutput(true);
OutputStream os = null;
try {
os = connection.getOutputStream();
os.write(content.getBytes());
os.flush();
} finally {
if (os != null) {
os.close();
}
}
}
return connection;
}
private String getContent(HttpURLConnection connection) throws IOException {
return getContent(connection, new StringBuilder()).toString();
}
private StringBuilder getContent(HttpURLConnection connection, StringBuilder builder) throws IOException {
char[] buffer = new char[1024];
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int wasRead;
do
{
wasRead = reader.read(buffer, 0, 1024);
if (wasRead > 0)
builder.append(buffer, 0, wasRead);
}
while (wasRead > -1);
} finally {
if (reader != null) {
reader.close();
}
}
return builder;
}
public static String getParticipantUrls(String terminatorUrl, String participantUrl) {
return new StringBuilder().append(TERMINATOR_LINK).append('=').append(terminatorUrl).
append(URI_SEPARATOR).append(PARTICIPANT_LINK).append('=').append(participantUrl).toString();
}
public static String getStringValue(String content, String name)
{
Map<String, String> matches = new HashMap<String, String>();
TxSupport.matchNames(matches, content, null);
return matches.get(name);
}
public static int getIntValue(String content, String name, int defValue)
{
String v = getStringValue(content, name);
if (v != null)
try {
return Integer.valueOf(v);
} catch (NumberFormatException e) {
}
return defValue;
}
/**
* Parse a string for name=value pairs
* TODO java.util.Scanner might be more efficient
* @param pairs the name value pairs contained in content
* @param content a string containing name=value substrings
*/
public static void matchNames(Map<String, String> pairs, String content, String splitChars) {
if (content != null) {
String[] lines;
if (splitChars == null) {
lines = new String[] {content};
} else {
lines = content.split(splitChars);
}
for (String line : lines) {
Matcher m = NVP_PATTERN.matcher(line);
while (m.find()) {
String[] tokens = m.group().trim().split("\\s+");
for (String tok : tokens) {
String[] pair = tok.split("=");
if (pair.length > 1)
pairs.put(pair[0], pair[1]);
}
}
}
}
}
public static UriBuilder getUriBuilder(UriInfo info, int npaths, String ... paths)
{
UriBuilder builder = info.getBaseUriBuilder();
if (npaths > 0){
List<PathSegment> segments = info.getPathSegments();
for (int i = 0; i < npaths; i++)
builder.path(segments.get(i).getPath());
} else {
String basePath = info.getMatchedURIs().get(0);
builder.path(basePath);
}
for (String path : paths)
builder.path(path);
return builder;
}
public static URI getUri(UriInfo info, int npaths, String ... paths)
{
return getUriBuilder(info, npaths, paths).build();
}
public static String buildURI(UriBuilder builder, String ... pathComponents)
{
for (String component : pathComponents)
builder.path(component);
return builder.build().toString();
}
public static String getStatus(String statusContent) {
return getStringValue(statusContent, STATUS_PROPERTY);
}
public static String toContent(String property, String status) {
return new StringBuilder(property).append('=').append(status).toString();
}
public static String toStatusContent(String status) {
return toContent(STATUS_PROPERTY, status);
}
public static boolean isPrepare(String status) {
return PREPARED.equals(status);
}
public static boolean isCommit(String status) {
return COMMITTED.equals(status);
}
public static boolean isAbort(String status) {
return ABORTED.equals(status);
}
public static boolean isReadOnly(String status) {
return READONLY.equals(status);
}
public static boolean isHeuristic(String status) {
return H_COMMIT.equals(status) ||
H_HAZARD.equals(status) ||
H_MIXED.equals(status) ||
H_ROLLBACK.equals(status);
}
public static boolean isComplete(String status) {
return COMMITTED.equals(status) ||
ABORTED.equals(status);
}
public static boolean isActive(String status) {
return ABORT_ONLY.equals(status) ||
ABORTING.equals(status) ||
COMMITTING.equals(status) ||
PREPARING.equals(status) ||
PREPARED.equals(status) ||
RUNNING.equals(status);
}
}
|
package org.fxmisc.richtext;
import static javafx.util.Duration.*;
import static org.fxmisc.richtext.PopupAlignment.*;
import static org.reactfx.EventStreams.*;
import static org.reactfx.util.Tuples.*;
import java.time.Duration;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.IntSupplier;
import java.util.function.IntUnaryOperator;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import javafx.beans.binding.Binding;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableBooleanValue;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.css.PseudoClass;
import javafx.css.StyleableObjectProperty;
import javafx.event.Event;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.IndexRange;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.TextFlow;
import javafx.stage.PopupWindow;
import org.fxmisc.flowless.Cell;
import org.fxmisc.flowless.VirtualFlow;
import org.fxmisc.flowless.VirtualFlowHit;
import org.fxmisc.flowless.Virtualized;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CssProperties.EditableProperty;
import org.fxmisc.richtext.model.Codec;
import org.fxmisc.richtext.model.EditActions;
import org.fxmisc.richtext.model.EditableStyledDocument;
import org.fxmisc.richtext.model.GenericEditableStyledDocument;
import org.fxmisc.richtext.model.Paragraph;
import org.fxmisc.richtext.model.StyledTextAreaModel;
import org.fxmisc.richtext.model.NavigationActions;
import org.fxmisc.richtext.model.PlainTextChange;
import org.fxmisc.richtext.model.RichTextChange;
import org.fxmisc.richtext.model.SegmentOps;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyledDocument;
import org.fxmisc.richtext.model.TextEditingArea;
import org.fxmisc.richtext.model.TextOps;
import org.fxmisc.richtext.model.TwoDimensional;
import org.fxmisc.richtext.model.TwoLevelNavigator;
import org.fxmisc.richtext.model.UndoActions;
import org.fxmisc.undo.UndoManager;
import org.fxmisc.undo.UndoManagerFactory;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import org.reactfx.StateMachine;
import org.reactfx.Subscription;
import org.reactfx.collection.LiveList;
import org.reactfx.util.Tuple2;
import org.reactfx.value.Val;
import org.reactfx.value.Var;
/**
* Text editing control. Accepts user input (keyboard, mouse) and
* provides API to assign style to text ranges. It is suitable for
* syntax highlighting and rich-text editors.
*
* <p>Subclassing is allowed to define the type of style, e.g. inline
* style or style classes.</p>
*
* <p>Note: Scroll bars no longer appear when the content spans outside
* of the viewport. To add scroll bars, the area needs to be wrapped in
* a {@link VirtualizedScrollPane}. For example, </p>
* <pre>
* {@code
* // shows area without scroll bars
* InlineCssTextArea area = new InlineCssTextArea();
*
* // add scroll bars that will display as needed
* VirtualizedScrollPane<InlineCssTextArea> vsPane = new VirtualizedScrollPane(area);
*
* Parent parent = //;
* parent.getChildren().add(vsPane)
* }
* </pre>
*
* <h3>Auto-Scrolling to the Caret</h3>
*
* <p>Every time the underlying {@link EditableStyledDocument} changes via user interaction (e.g. typing) through
* the {@code StyledTextArea}, the area will scroll to insure the caret is kept in view. However, this does not
* occur if changes are done programmatically. For example, let's say the area is displaying the bottom part
* of the area's {@link EditableStyledDocument} and some code changes something in the top part of the document
* that is not currently visible. If there is no call to {@link #requestFollowCaret()} at the end of that code,
* the area will not auto-scroll to that section of the document. The change will occur, and the user will continue
* to see the bottom part of the document as before. If such a call is there, then the area will scroll
* to the top of the document and no longer display the bottom part of it.</p>
*
* <p>Additionally, when overriding the default user-interaction behavior, remember to include a call
* to {@link #requestFollowCaret()}.</p>
*
* <h3>Overriding keyboard shortcuts</h3>
*
* {@code StyledTextArea} uses {@code KEY_TYPED} handler to handle ordinary
* character input and {@code KEY_PRESSED} handler to handle control key
* combinations (including Enter and Tab). To add or override some keyboard
* shortcuts, while keeping the rest in place, you would combine the default
* event handler with a new one that adds or overrides some of the default
* key combinations. This is how to bind {@code Ctrl+S} to the {@code save()}
* operation:
* <pre>
* {@code
* import static javafx.scene.input.KeyCode.*;
* import static javafx.scene.input.KeyCombination.*;
* import static org.fxmisc.wellbehaved.event.EventPattern.*;
* import static org.fxmisc.wellbehaved.event.InputMap.*;
*
* import org.fxmisc.wellbehaved.event.Nodes;
*
* Nodes.addInputMap(area, consume(keyPressed(S, CONTROL_DOWN), event -> save()));
* }
* </pre>
*
* @param <S> type of style that can be applied to text.
*/
public class GenericStyledArea<PS, SEG, S> extends Region
implements
TextEditingArea<PS, SEG, S>,
EditActions<PS, SEG, S>,
ClipboardActions<PS, SEG, S>,
NavigationActions<PS, SEG, S>,
UndoActions,
TwoDimensional,
Virtualized {
/**
* Index range [0, 0).
*/
public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0);
private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret");
private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph");
private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph");
/**
* Background fill for highlighted text.
*/
private final StyleableObjectProperty<Paint> highlightFill
= new CssProperties.HighlightFillProperty(this, Color.DODGERBLUE);
/**
* Text color for highlighted text.
*/
private final StyleableObjectProperty<Paint> highlightTextFill
= new CssProperties.HighlightTextFillProperty(this, Color.WHITE);
/**
* Controls the blink rate of the caret, when one is displayed. Setting
* the duration to zero disables blinking.
*/
private final StyleableObjectProperty<javafx.util.Duration> caretBlinkRate
= new CssProperties.CaretBlinkRateProperty(this, javafx.util.Duration.millis(500));
// editable property
/**
* Indicates whether this text area can be edited by the user.
* Note that this property doesn't affect editing through the API.
*/
private final BooleanProperty editable = new EditableProperty<>(this);
public final boolean isEditable() { return editable.get(); }
public final void setEditable(boolean value) { editable.set(value); }
public final BooleanProperty editableProperty() { return editable; }
// wrapText property
/**
* When a run of text exceeds the width of the text region,
* then this property indicates whether the text should wrap
* onto another line.
*/
private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText");
public final boolean isWrapText() { return wrapText.get(); }
public final void setWrapText(boolean value) { wrapText.set(value); }
public final BooleanProperty wrapTextProperty() { return wrapText; }
// showCaret property
/**
* Indicates when this text area should display a caret.
*/
private final Var<CaretVisibility> showCaret = Var.newSimpleVar(CaretVisibility.AUTO);
public final CaretVisibility getShowCaret() { return showCaret.getValue(); }
public final void setShowCaret(CaretVisibility value) { showCaret.setValue(value); }
public final Var<CaretVisibility> showCaretProperty() { return showCaret; }
public static enum CaretVisibility {
/** Caret is displayed. */
ON,
/** Caret is displayed when area is focused, enabled, and editable. */
AUTO,
/** Caret is not displayed. */
OFF
}
// undo manager
@Override public UndoManager getUndoManager() { return model.getUndoManager(); }
@Override public void setUndoManager(UndoManagerFactory undoManagerFactory) {
model.setUndoManager(undoManagerFactory);
}
/**
* Popup window that will be positioned by this text area relative to the
* caret or selection. Use {@link #popupAlignmentProperty()} to specify
* how the popup should be positioned relative to the caret or selection.
* Use {@link #popupAnchorOffsetProperty()} or
* {@link #popupAnchorAdjustmentProperty()} to further adjust the position.
*/
private final ObjectProperty<PopupWindow> popupWindow = new SimpleObjectProperty<>();
public void setPopupWindow(PopupWindow popup) { popupWindow.set(popup); }
public PopupWindow getPopupWindow() { return popupWindow.get(); }
public ObjectProperty<PopupWindow> popupWindowProperty() { return popupWindow; }
/** @deprecated Use {@link #setPopupWindow(PopupWindow)}. */
@Deprecated
public void setPopupAtCaret(PopupWindow popup) { popupWindow.set(popup); }
/** @deprecated Use {@link #getPopupWindow()}. */
@Deprecated
public PopupWindow getPopupAtCaret() { return popupWindow.get(); }
/** @deprecated Use {@link #popupWindowProperty()}. */
@Deprecated
public ObjectProperty<PopupWindow> popupAtCaretProperty() { return popupWindow; }
/**
* Specifies further offset (in pixels) of the popup window from the
* position specified by {@link #popupAlignmentProperty()}.
*
* <p>If {@link #popupAnchorAdjustmentProperty()} is also specified, then
* it overrides the offset set by this property.
*/
private final ObjectProperty<Point2D> popupAnchorOffset = new SimpleObjectProperty<>();
public void setPopupAnchorOffset(Point2D offset) { popupAnchorOffset.set(offset); }
public Point2D getPopupAnchorOffset() { return popupAnchorOffset.get(); }
public ObjectProperty<Point2D> popupAnchorOffsetProperty() { return popupAnchorOffset; }
/**
* Specifies how to adjust the popup window's anchor point. The given
* operator is invoked with the screen position calculated according to
* {@link #popupAlignmentProperty()} and should return a new screen
* position. This position will be used as the popup window's anchor point.
*
* <p>Setting this property overrides {@link #popupAnchorOffsetProperty()}.
*/
private final ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustment = new SimpleObjectProperty<>();
public void setPopupAnchorAdjustment(UnaryOperator<Point2D> f) { popupAnchorAdjustment.set(f); }
public UnaryOperator<Point2D> getPopupAnchorAdjustment() { return popupAnchorAdjustment.get(); }
public ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustmentProperty() { return popupAnchorAdjustment; }
/**
* Defines where the popup window given in {@link #popupWindowProperty()}
* is anchored, i.e. where its anchor point is positioned. This position
* can further be adjusted by {@link #popupAnchorOffsetProperty()} or
* {@link #popupAnchorAdjustmentProperty()}.
*/
private final ObjectProperty<PopupAlignment> popupAlignment = new SimpleObjectProperty<>(CARET_TOP);
public void setPopupAlignment(PopupAlignment pos) { popupAlignment.set(pos); }
public PopupAlignment getPopupAlignment() { return popupAlignment.get(); }
public ObjectProperty<PopupAlignment> popupAlignmentProperty() { return popupAlignment; }
/**
* Defines how long the mouse has to stay still over the text before a
* {@link MouseOverTextEvent} of type {@code MOUSE_OVER_TEXT_BEGIN} is
* fired on this text area. When set to {@code null}, no
* {@code MouseOverTextEvent}s are fired on this text area.
*
* <p>Default value is {@code null}.
*/
private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null);
public void setMouseOverTextDelay(Duration delay) { mouseOverTextDelay.set(delay); }
public Duration getMouseOverTextDelay() { return mouseOverTextDelay.get(); }
public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; }
/**
* Defines how to handle an event in which the user has selected some text, dragged it to a
* new location within the area, and released the mouse at some character {@code index}
* within the area.
*
* <p>By default, this will relocate the selected text to the character index where the mouse
* was released. To override it, use {@link #setOnSelectionDrop(IntConsumer)}.
*/
private Property<IntConsumer> onSelectionDrop = new SimpleObjectProperty<>(this::moveSelectedText);
public final void setOnSelectionDrop(IntConsumer consumer) { onSelectionDrop.setValue(consumer); }
public final IntConsumer getOnSelectionDrop() { return onSelectionDrop.getValue(); }
private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null);
public void setParagraphGraphicFactory(IntFunction<? extends Node> factory) { paragraphGraphicFactory.set(factory); }
public IntFunction<? extends Node> getParagraphGraphicFactory() { return paragraphGraphicFactory.get(); }
public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; }
/**
* Indicates whether the initial style should also be used for plain text
* inserted into this text area. When {@code false}, the style immediately
* preceding the insertion position is used. Default value is {@code false}.
*/
public BooleanProperty useInitialStyleForInsertionProperty() { return model.useInitialStyleForInsertionProperty(); }
public void setUseInitialStyleForInsertion(boolean value) { model.setUseInitialStyleForInsertion(value); }
public boolean getUseInitialStyleForInsertion() { return model.getUseInitialStyleForInsertion(); }
private Optional<Tuple2<Codec<PS>, Codec<SEG>>> styleCodecs = Optional.empty();
/**
* Sets codecs to encode/decode style information to/from binary format.
* Providing codecs enables clipboard actions to retain the style information.
*/
public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<SEG> textStyleCodec) {
styleCodecs = Optional.of(t(paragraphStyleCodec, textStyleCodec));
}
@Override
public Optional<Tuple2<Codec<PS>, Codec<SEG>>> getStyleCodecs() {
return styleCodecs;
}
/**
* The <em>estimated</em> scrollX value. This can be set in order to scroll the content.
* Value is only accurate when area does not wrap lines and uses the same font size
* throughout the entire area.
*/
@Override
public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); }
public double getEstimatedScrollX() { return virtualFlow.estimatedScrollXProperty().getValue(); }
public void setEstimatedScrollX(double value) { virtualFlow.estimatedScrollXProperty().setValue(value); }
/**
* The <em>estimated</em> scrollY value. This can be set in order to scroll the content.
* Value is only accurate when area does not wrap lines and uses the same font size
* throughout the entire area.
*/
@Override
public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); }
public double getEstimatedScrollY() { return virtualFlow.estimatedScrollYProperty().getValue(); }
public void setEstimatedScrollY(double value) { virtualFlow.estimatedScrollYProperty().setValue(value); }
// text
@Override public final String getText() { return model.getText(); }
@Override public final ObservableValue<String> textProperty() { return model.textProperty(); }
// rich text
@Override public final StyledDocument<PS, SEG, S> getDocument() { return model.getDocument(); }
// length
@Override public final int getLength() { return model.getLength(); }
@Override public final ObservableValue<Integer> lengthProperty() { return model.lengthProperty(); }
// caret position
@Override public final int getCaretPosition() { return model.getCaretPosition(); }
@Override public final ObservableValue<Integer> caretPositionProperty() { return model.caretPositionProperty(); }
// selection anchor
@Override public final int getAnchor() { return model.getAnchor(); }
@Override public final ObservableValue<Integer> anchorProperty() { return model.anchorProperty(); }
// selection
@Override public final IndexRange getSelection() { return model.getSelection(); }
@Override public final ObservableValue<IndexRange> selectionProperty() { return model.selectionProperty(); }
// selected text
@Override public final String getSelectedText() { return model.getSelectedText(); }
@Override public final ObservableValue<String> selectedTextProperty() { return model.selectedTextProperty(); }
// current paragraph index
@Override public final int getCurrentParagraph() { return model.getCurrentParagraph(); }
@Override public final ObservableValue<Integer> currentParagraphProperty() { return model.currentParagraphProperty(); }
// caret column
@Override public final int getCaretColumn() { return model.getCaretColumn(); }
@Override public final ObservableValue<Integer> caretColumnProperty() { return model.caretColumnProperty(); }
// paragraphs
@Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return model.getParagraphs(); }
// beingUpdated
public ObservableBooleanValue beingUpdatedProperty() { return model.beingUpdatedProperty(); }
public boolean isBeingUpdated() { return model.isBeingUpdated(); }
// total width estimate
/**
* The <em>estimated</em> width of the entire document. Accurate when area does not wrap lines and
* uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by
* the skin, not the user.
*/
@Override
public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); }
public double getTotalWidthEstimate() { return virtualFlow.totalWidthEstimateProperty().getValue(); }
// total height estimate
/**
* The <em>estimated</em> height of the entire document. Accurate when area does not wrap lines and
* uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by
* the skin, not the user.
*/
@Override
public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); }
public double getTotalHeightEstimate() { return virtualFlow.totalHeightEstimateProperty().getValue(); }
// text changes
@Override public final EventStream<PlainTextChange> plainTextChanges() { return model.plainTextChanges(); }
// rich text changes
@Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return model.richChanges(); }
private Subscription subscriptions = () -> {};
// Remembers horizontal position when traversing up / down.
private Optional<ParagraphBox.CaretOffsetX> targetCaretOffset = Optional.empty();
private final Binding<Boolean> caretVisible;
private final Val<UnaryOperator<Point2D>> _popupAnchorAdjustment;
private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> virtualFlow;
// used for two-level navigation, where on the higher level are
// paragraphs and on the lower level are lines within a paragraph
private final TwoLevelNavigator navigator;
private boolean followCaretRequested = false;
/**
* model
*/
private final StyledTextAreaModel<PS, SEG, S> model;
/**
* @return this area's {@link StyledTextAreaModel}
*/
final StyledTextAreaModel<PS, SEG, S> getModel() {
return model;
}
/**
* The underlying document that can be displayed by multiple {@code StyledTextArea}s.
*/
public final EditableStyledDocument<PS, SEG, S> getContent() { return model.getContent(); }
/**
* Style used by default when no other style is provided.
*/
public final S getInitialTextStyle() { return model.getInitialTextStyle(); }
/**
* Style used by default when no other style is provided.
*/
public final PS getInitialParagraphStyle() { return model.getInitialParagraphStyle(); }
/**
* Style applicator used by the default skin.
*/
private final BiConsumer<TextFlow, PS> applyParagraphStyle;
public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; }
/**
* Indicates whether style should be preserved on undo/redo,
* copy/paste and text move.
* TODO: Currently, only undo/redo respect this flag.
*/
public final boolean isPreserveStyle() { return model.isPreserveStyle(); }
private final TextOps<SEG, S> segmentOps;
@Override public final SegmentOps<SEG, S> getSegOps() { return segmentOps; }
/**
* Creates a text area with empty text content.
*
* @param initialParagraphStyle style to use in places where no other style is
* specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
* @param initialTextStyle style to use in places where no other style is
* specified (yet).
* @param segmentOps The operations which are defined on the text segment objects.
* @param nodeFactory A function which is used to create the JavaFX scene nodes for a
* particular segment.
*/
public GenericStyledArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle, TextOps<SEG, S> segmentOps,
Function<SEG, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory);
}
public GenericStyledArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle, TextOps<SEG, S> segmentOps,
boolean preserveStyle, Function<SEG, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle,
new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory);
}
/**
* The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that
* this constructor can be used to create another {@code GenericStyledArea} object that
* shares the same {@link EditableStyledDocument}.
*/
public GenericStyledArea(
PS initialParagraphStyle,
BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle,
EditableStyledDocument<PS, SEG, S> document,
TextOps<SEG, S> textOps,
Function<SEG, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, textOps, true, nodeFactory);
}
public GenericStyledArea(
PS initialParagraphStyle,
BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle,
EditableStyledDocument<PS, SEG, S> document,
TextOps<SEG, S> textOps,
boolean preserveStyle,
Function<SEG, Node> nodeFactory) {
this.model = new StyledTextAreaModel<>(initialParagraphStyle, initialTextStyle, document, textOps, preserveStyle);
this.applyParagraphStyle = applyParagraphStyle;
this.segmentOps = textOps;
// allow tab traversal into area
setFocusTraversable(true);
this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
getStyleClass().add("styled-text-area");
getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm());
// keeps track of currently used non-empty cells
@SuppressWarnings("unchecked")
ObservableSet<ParagraphBox<PS, SEG, S>> nonEmptyCells = FXCollections.observableSet();
// Initialize content
virtualFlow = VirtualFlow.createVertical(
getParagraphs(),
par -> {
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell(
par,
applyParagraphStyle,
nodeFactory);
nonEmptyCells.add(cell.getNode());
return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode()))
.afterUpdateItem(p -> nonEmptyCells.add(cell.getNode()));
});
getChildren().add(virtualFlow);
// initialize navigator
IntSupplier cellCount = () -> getParagraphs().size();
IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount();
navigator = new TwoLevelNavigator(cellCount, cellLength);
// relayout the popup when any of its settings values change (besides the caret being dirty)
EventStream<?> popupAlignmentDirty = invalidationsOf(popupAlignmentProperty());
EventStream<?> popupAnchorAdjustmentDirty = invalidationsOf(popupAnchorAdjustmentProperty());
EventStream<?> popupAnchorOffsetDirty = invalidationsOf(popupAnchorOffsetProperty());
EventStream<?> popupDirty = merge(popupAlignmentDirty, popupAnchorAdjustmentDirty, popupAnchorOffsetDirty);
subscribeTo(popupDirty, x -> layoutPopup());
// follow the caret every time the caret position or paragraphs change
EventStream<?> caretPosDirty = invalidationsOf(caretPositionProperty());
EventStream<?> paragraphsDirty = invalidationsOf(getParagraphs());
EventStream<?> selectionDirty = invalidationsOf(selectionProperty());
// need to reposition popup even when caret hasn't moved, but selection has changed (been deselected)
EventStream<?> caretDirty = merge(caretPosDirty, paragraphsDirty, selectionDirty);
// whether or not to display the caret
EventStream<Boolean> blinkCaret = EventStreams.valuesOf(showCaretProperty())
.flatMap(mode -> {
switch (mode) {
case ON:
return EventStreams.valuesOf(Val.constant(true));
case OFF:
return EventStreams.valuesOf(Val.constant(false));
default:
case AUTO:
return EventStreams.valuesOf(focusedProperty()
.and(editableProperty())
.and(disabledProperty().not()));
}
});
// the rate at which to display the caret
EventStream<javafx.util.Duration> blinkRate = EventStreams.valuesOf(caretBlinkRate);
// The caret is visible in periodic intervals,
// but only when blinkCaret is true.
caretVisible = EventStreams.combine(blinkCaret, blinkRate)
.flatMap(tuple -> {
Boolean blink = tuple.get1();
javafx.util.Duration rate = tuple.get2();
if(blink) {
return rate.lessThanOrEqualTo(ZERO)
? EventStreams.valuesOf(Val.constant(true))
: booleanPulse(rate, caretDirty);
} else {
return EventStreams.valuesOf(Val.constant(false));
}
})
.toBinding(false);
manageBinding(caretVisible);
// Adjust popup anchor by either a user-provided function,
// or user-provided offset, or don't adjust at all.
Val<UnaryOperator<Point2D>> userOffset = Val.map(
popupAnchorOffsetProperty(),
offset -> anchor -> anchor.add(offset));
_popupAnchorAdjustment =
Val.orElse(
popupAnchorAdjustmentProperty(),
userOffset)
.orElseConst(UnaryOperator.identity());
// dispatch MouseOverTextEvents when mouseOverTextDelay is not null
EventStreams.valuesOf(mouseOverTextDelayProperty())
.flatMap(delay -> delay != null
? mouseOverTextEvents(nonEmptyCells, delay)
: EventStreams.never())
.subscribe(evt -> Event.fireEvent(this, evt));
new StyledTextAreaBehavior(this);
}
/**
* Returns caret bounds relative to the viewport, i.e. the visual bounds
* of the embedded VirtualFlow.
*/
Optional<Bounds> getCaretBounds() {
return virtualFlow.getCellIfVisible(getCurrentParagraph())
.map(c -> {
Bounds cellBounds = c.getNode().getCaretBounds();
return virtualFlow.cellToViewport(c, cellBounds);
});
}
/**
* Returns x coordinate of the caret in the current paragraph.
*/
ParagraphBox.CaretOffsetX getCaretOffsetX() {
int idx = getCurrentParagraph();
return getCell(idx).getCaretOffsetX();
}
double getViewportHeight() {
return virtualFlow.getHeight();
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) {
int parIdx = targetLine.getMajor();
ParagraphBox<PS, SEG, S> cell = virtualFlow.getCell(parIdx).getNode();
CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor());
return parHit.offset(getParagraphOffset(parIdx));
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) {
VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(0.0, y);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hitText(x, cellOffset.getY());
return parHit.offset(parOffset);
}
}
/**
* Helpful for determining which letter is at point x, y:
* <pre>
* {@code
* StyledTextArea area = // creation code
* area.addEventHandler(MouseEvent.MOUSE_PRESSED, (MouseEvent e) -> {
* CharacterHit hit = area.hit(e.getX(), e.getY());
* int characterPosition = hit.getInsertionIndex();
*
* // move the caret to that character's position
* area.moveTo(characterPosition, SelectionPolicy.CLEAR);
* }}
* </pre>
*/
public CharacterHit hit(double x, double y) {
VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(x, y);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hit(cellOffset);
return parHit.offset(parOffset);
}
}
/**
* Returns the current line as a two-level index.
* The major number is the paragraph index, the minor
* number is the line number within the paragraph.
*
* <p>This method has a side-effect of bringing the current
* paragraph to the viewport if it is not already visible.
*/
TwoDimensional.Position currentLine() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
int lineIdx = cell.getNode().getCurrentLineIndex();
return _position(parIdx, lineIdx);
}
TwoDimensional.Position _position(int par, int line) {
return navigator.position(par, line);
}
@Override
public final String getText(int start, int end) {
return model.getText(start, end);
}
@Override
public String getText(int paragraph) {
return model.getText(paragraph);
}
public Paragraph<PS, SEG, S> getParagraph(int index) {
return model.getParagraph(index);
}
@Override
public StyledDocument<PS, SEG, S> subDocument(int start, int end) {
return model.subDocument(start, end);
}
@Override
public StyledDocument<PS, SEG, S> subDocument(int paragraphIndex) {
return model.subDocument(paragraphIndex);
}
/**
* Returns the selection range in the given paragraph.
*/
public IndexRange getParagraphSelection(int paragraph) {
return model.getParagraphSelection(paragraph);
}
/**
* Returns the style of the character with the given index.
* If {@code index} points to a line terminator character,
* the last style used in the paragraph terminated by that
* line terminator is returned.
*/
public S getStyleOfChar(int index) {
return model.getStyleOfChar(index);
}
/**
* Returns the style at the given position. That is the style of the
* character immediately preceding {@code position}, except when
* {@code position} points to a paragraph boundary, in which case it
* is the style at the beginning of the latter paragraph.
*
* <p>In other words, most of the time {@code getStyleAtPosition(p)}
* is equivalent to {@code getStyleOfChar(p-1)}, except when {@code p}
* points to a paragraph boundary, in which case it is equivalent to
* {@code getStyleOfChar(p)}.
*/
public S getStyleAtPosition(int position) {
return model.getStyleAtPosition(position);
}
/**
* Returns the range of homogeneous style that includes the given position.
* If {@code position} points to a boundary between two styled ranges, then
* the range preceding {@code position} is returned. If {@code position}
* points to a boundary between two paragraphs, then the first styled range
* of the latter paragraph is returned.
*/
public IndexRange getStyleRangeAtPosition(int position) {
return model.getStyleRangeAtPosition(position);
}
/**
* Returns the styles in the given character range.
*/
public StyleSpans<S> getStyleSpans(int from, int to) {
return model.getStyleSpans(from, to);
}
/**
* Returns the styles in the given character range.
*/
public StyleSpans<S> getStyleSpans(IndexRange range) {
return getStyleSpans(range.getStart(), range.getEnd());
}
/**
* Returns the style of the character with the given index in the given
* paragraph. If {@code index} is beyond the end of the paragraph, the
* style at the end of line is returned. If {@code index} is negative, it
* is the same as if it was 0.
*/
public S getStyleOfChar(int paragraph, int index) {
return model.getStyleOfChar(paragraph, index);
}
/**
* Returns the style at the given position in the given paragraph.
* This is equivalent to {@code getStyleOfChar(paragraph, position-1)}.
*/
public S getStyleAtPosition(int paragraph, int position) {
return model.getStyleAtPosition(paragraph, position);
}
/**
* Returns the range of homogeneous style that includes the given position
* in the given paragraph. If {@code position} points to a boundary between
* two styled ranges, then the range preceding {@code position} is returned.
*/
public IndexRange getStyleRangeAtPosition(int paragraph, int position) {
return model.getStyleRangeAtPosition(paragraph, position);
}
/**
* Returns styles of the whole paragraph.
*/
public StyleSpans<S> getStyleSpans(int paragraph) {
return model.getStyleSpans(paragraph);
}
/**
* Returns the styles in the given character range of the given paragraph.
*/
public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) {
return model.getStyleSpans(paragraph, from, to);
}
/**
* Returns the styles in the given character range of the given paragraph.
*/
public StyleSpans<S> getStyleSpans(int paragraph, IndexRange range) {
return getStyleSpans(paragraph, range.getStart(), range.getEnd());
}
@Override
public int getAbsolutePosition(int paragraphIndex, int columnIndex) {
return model.getAbsolutePosition(paragraphIndex, columnIndex);
}
@Override
public Position position(int row, int col) {
return model.position(row, col);
}
@Override
public Position offsetToPosition(int charOffset, Bias bias) {
return model.offsetToPosition(charOffset, bias);
}
void scrollBy(Point2D deltas) {
virtualFlow.scrollXBy(deltas.getX());
virtualFlow.scrollYBy(deltas.getY());
}
void show(double y) {
virtualFlow.show(y);
}
/**
* Shows the paragraph somewhere in the viewport. If the line is already visible, no noticeable change occurs.
* If line is above the current view, it appears at the top of the viewport. If the line is below the current
* view, it appears at the bottom of the viewport.
*/
public void showParagraphInViewport(int paragraphIndex) {
virtualFlow.show(paragraphIndex);
}
/**
* Lays out the viewport so that the paragraph is the first line (top) displayed in the viewport. Note: if
* the given area does not have enough lines that follow the given line to span its entire height, the paragraph
* may not appear at the very top of the viewport. Instead, it may simply be shown in the viewport. For example,
* given an unwrapped area whose height could show 10 lines but whose content only has 3 lines, calling
* {@code showParagraphAtTop(3)} would be no different than {@code showParagraphAtTop(1)}.
*/
public void showParagraphAtTop(int paragraphIndex) {
virtualFlow.showAsFirst(paragraphIndex);
}
/**
* Lays out the viewport so that the paragraph is the last line (bottom) displayed in the viewport. Note: if
* the given area does not have enough lines preceding the given line to span its entire height, the paragraph
* may not appear at the very bottom of the viewport. Instead, it may appear towards the bottom of the viewport
* with some extra space following it. For example, given an unwrapped area whose height could show 10 lines but
* whose content only has 7 lines, calling {@code showParagraphAtBottom(1)} would be no different than calling
* {@code showParagraphAtBottom(7)}.
*/
public void showParagraphAtBottom(int paragraphIndex) {
virtualFlow.showAsLast(paragraphIndex);
}
void showCaretAtBottom() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds();
double y = caretBounds.getMaxY();
virtualFlow.showAtOffset(parIdx, getViewportHeight() - y);
}
void showCaretAtTop() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds();
double y = caretBounds.getMinY();
virtualFlow.showAtOffset(parIdx, -y);
}
/**
* If the caret is not visible within the area's view, the area will scroll so that caret
* is visible in the next layout pass. Use this method when you wish to "follow the caret"
* (i.e. auto-scroll to caret) after making a change (add/remove/modify area's segments).
*/
public void requestFollowCaret() {
followCaretRequested = true;
requestLayout();
}
private void followCaret() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds();
double graphicWidth = cell.getNode().getGraphicPrefWidth();
Bounds region = extendLeft(caretBounds, graphicWidth);
virtualFlow.show(parIdx, region);
}
/**
* Moves caret to the previous page (i.e. page up)
* @param selectionPolicy use {@link SelectionPolicy#CLEAR} when no selection is desired and
* {@link SelectionPolicy#ADJUST} when a selection from starting point
* to the place to where the caret is moved is desired.
*/
public void prevPage(SelectionPolicy selectionPolicy) {
showCaretAtBottom();
CharacterHit hit = hit(getTargetCaretOffset(), 1.0);
model.moveTo(hit.getInsertionIndex(), selectionPolicy);
}
/**
* Moves caret to the next page (i.e. page down)
* @param selectionPolicy use {@link SelectionPolicy#CLEAR} when no selection is desired and
* {@link SelectionPolicy#ADJUST} when a selection from starting point
* to the place to where the caret is moved is desired.
*/
public void nextPage(SelectionPolicy selectionPolicy) {
showCaretAtTop();
CharacterHit hit = hit(getTargetCaretOffset(), getViewportHeight() - 1.0);
model.moveTo(hit.getInsertionIndex(), selectionPolicy);
}
/**
* Sets style for the given character range.
*/
public void setStyle(int from, int to, S style) {
model.setStyle(from, to, style);
}
/**
* Sets style for the whole paragraph.
*/
public void setStyle(int paragraph, S style) {
model.setStyle(paragraph, style);
}
/**
* Sets style for the given range relative in the given paragraph.
*/
public void setStyle(int paragraph, int from, int to, S style) {
model.setStyle(paragraph, from, to, style);
}
/**
* Set multiple style ranges at once. This is equivalent to
* <pre>
* for(StyleSpan{@code <S>} span: styleSpans) {
* setStyle(from, from + span.getLength(), span.getStyle());
* from += span.getLength();
* }
* </pre>
* but the actual implementation is more efficient.
*/
public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) {
model.setStyleSpans(from, styleSpans);
}
/**
* Set multiple style ranges of a paragraph at once. This is equivalent to
* <pre>
* for(StyleSpan{@code <S>} span: styleSpans) {
* setStyle(paragraph, from, from + span.getLength(), span.getStyle());
* from += span.getLength();
* }
* </pre>
* but the actual implementation is more efficient.
*/
public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) {
model.setStyleSpans(paragraph, from, styleSpans);
}
/**
* Sets style for the whole paragraph.
*/
public void setParagraphStyle(int paragraph, PS paragraphStyle) {
model.setParagraphStyle(paragraph, paragraphStyle);
}
/**
* Resets the style of the given range to the initial style.
*/
public void clearStyle(int from, int to) {
model.clearStyle(from, to);
}
/**
* Resets the style of the given paragraph to the initial style.
*/
public void clearStyle(int paragraph) {
model.clearStyle(paragraph);
}
/**
* Resets the style of the given range in the given paragraph
* to the initial style.
*/
public void clearStyle(int paragraph, int from, int to) {
model.clearStyle(paragraph, from, to);
}
/**
* Resets the style of the given paragraph to the initial style.
*/
public void clearParagraphStyle(int paragraph) {
model.clearParagraphStyle(paragraph);
}
@Override
public void replaceText(int start, int end, String text) {
model.replaceText(start, end, text);
}
@Override
public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) {
model.replace(start, end, replacement);
}
@Override
public void selectRange(int anchor, int caretPosition) {
model.selectRange(anchor, caretPosition);
}
/**
* {@inheritDoc}
* @deprecated You probably meant to use {@link #moveTo(int)}. This method will be made
* package-private in the future
*/
@Deprecated
@Override
public void positionCaret(int pos) {
model.positionCaret(pos);
}
public void dispose() {
subscriptions.unsubscribe();
model.dispose();
virtualFlow.dispose();
}
@Override
protected void layoutChildren() {
virtualFlow.resize(getWidth(), getHeight());
if(followCaretRequested) {
followCaretRequested = false;
followCaret();
}
// position popup
layoutPopup();
}
private Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> createCell(
Paragraph<PS, SEG, S> paragraph,
BiConsumer<TextFlow, PS> applyParagraphStyle,
Function<SEG, Node> nodeFactory) {
ParagraphBox<PS, SEG, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, nodeFactory);
box.highlightFillProperty().bind(highlightFill);
box.highlightTextFillProperty().bind(highlightTextFill);
box.wrapTextProperty().bind(wrapTextProperty());
box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty());
box.graphicOffset.bind(virtualFlow.breadthOffsetProperty());
Val<Boolean> hasCaret = Val.combine(
box.indexProperty(),
currentParagraphProperty(),
(bi, cp) -> bi.intValue() == cp.intValue());
Subscription hasCaretPseudoClass = hasCaret.values().subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value));
Subscription firstParPseudoClass = box.indexProperty().values().subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0));
Subscription lastParPseudoClass = EventStreams.combine(
box.indexProperty().values(),
getParagraphs().sizeProperty().values()
).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1)));
// caret is visible only in the paragraph with the caret
Val<Boolean> cellCaretVisible = hasCaret.flatMap(x -> x ? caretVisible : Val.constant(false));
box.caretVisibleProperty().bind(cellCaretVisible);
// bind cell's caret position to area's caret column,
// when the cell is the one with the caret
box.caretPositionProperty().bind(hasCaret.flatMap(has -> has
? caretColumnProperty()
: Val.constant(0)));
// keep paragraph selection updated
ObjectBinding<IndexRange> cellSelection = Bindings.createObjectBinding(() -> {
int idx = box.getIndex();
return idx != -1
? getParagraphSelection(idx)
: StyledTextArea.EMPTY_RANGE;
}, selectionProperty(), box.indexProperty());
box.selectionProperty().bind(cellSelection);
return new Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>() {
@Override
public ParagraphBox<PS, SEG, S> getNode() {
return box;
}
@Override
public void updateIndex(int index) {
box.setIndex(index);
}
@Override
public void dispose() {
box.highlightFillProperty().unbind();
box.highlightTextFillProperty().unbind();
box.wrapTextProperty().unbind();
box.graphicFactoryProperty().unbind();
box.graphicOffset.unbind();
hasCaretPseudoClass.unsubscribe();
firstParPseudoClass.unsubscribe();
lastParPseudoClass.unsubscribe();
box.caretVisibleProperty().unbind();
box.caretPositionProperty().unbind();
box.selectionProperty().unbind();
cellSelection.dispose();
}
};
}
private ParagraphBox<PS, SEG, S> getCell(int index) {
return virtualFlow.getCell(index).getNode();
}
private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, SEG, S>> cells, Duration delay) {
return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify(
l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)),
r -> MouseOverTextEvent.end())));
}
private int getParagraphOffset(int parIdx) {
return position(parIdx, 0).toOffset();
}
private void layoutPopup() {
PopupWindow popup = getPopupWindow();
PopupAlignment alignment = getPopupAlignment();
UnaryOperator<Point2D> adjustment = _popupAnchorAdjustment.getValue();
if(popup != null) {
positionPopup(popup, alignment, adjustment);
}
}
private void positionPopup(
PopupWindow popup,
PopupAlignment alignment,
UnaryOperator<Point2D> adjustment) {
Optional<Bounds> bounds = null;
switch(alignment.getAnchorObject()) {
case CARET: bounds = getCaretBoundsOnScreen(); break;
case SELECTION: bounds = getSelectionBoundsOnScreen(); break;
}
bounds.ifPresent(b -> {
double x = 0, y = 0;
switch(alignment.getHorizontalAlignment()) {
case LEFT: x = b.getMinX(); break;
case H_CENTER: x = (b.getMinX() + b.getMaxX()) / 2; break;
case RIGHT: x = b.getMaxX(); break;
}
switch(alignment.getVerticalAlignment()) {
case TOP: y = b.getMinY();
case V_CENTER: y = (b.getMinY() + b.getMaxY()) / 2; break;
case BOTTOM: y = b.getMaxY(); break;
}
Point2D anchor = adjustment.apply(new Point2D(x, y));
popup.setAnchorX(anchor.getX());
popup.setAnchorY(anchor.getY());
});
}
private Optional<Bounds> getCaretBoundsOnScreen() {
return virtualFlow.getCellIfVisible(getCurrentParagraph())
.map(c -> c.getNode().getCaretBoundsOnScreen());
}
private Optional<Bounds> getSelectionBoundsOnScreen() {
IndexRange selection = getSelection();
if(selection.getLength() == 0) {
return getCaretBoundsOnScreen();
}
Bounds[] bounds = virtualFlow.visibleCells().stream()
.map(c -> c.getNode().getSelectionBoundsOnScreen())
.filter(Optional::isPresent)
.map(Optional::get)
.toArray(Bounds[]::new);
if(bounds.length == 0) {
return Optional.empty();
}
double minX = Stream.of(bounds).mapToDouble(Bounds::getMinX).min().getAsDouble();
double maxX = Stream.of(bounds).mapToDouble(Bounds::getMaxX).max().getAsDouble();
double minY = Stream.of(bounds).mapToDouble(Bounds::getMinY).min().getAsDouble();
double maxY = Stream.of(bounds).mapToDouble(Bounds::getMaxY).max().getAsDouble();
return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY));
}
private <T> void subscribeTo(EventStream<T> src, Consumer<T> cOnsumer) {
manageSubscription(src.subscribe(cOnsumer));
}
private void manageSubscription(Subscription subscription) {
subscriptions = subscriptions.and(subscription);
}
private void manageBinding(Binding<?> binding) {
subscriptions = subscriptions.and(binding::dispose);
}
private static Bounds extendLeft(Bounds b, double w) {
if(w == 0) {
return b;
} else {
return new BoundingBox(
b.getMinX() - w, b.getMinY(),
b.getWidth() + w, b.getHeight());
}
}
void clearTargetCaretOffset() {
targetCaretOffset = Optional.empty();
}
ParagraphBox.CaretOffsetX getTargetCaretOffset() {
if(!targetCaretOffset.isPresent())
targetCaretOffset = Optional.of(getCaretOffsetX());
return targetCaretOffset.get();
}
private static EventStream<Boolean> booleanPulse(javafx.util.Duration javafxDuration, EventStream<?> restartImpulse) {
Duration duration = Duration.ofMillis(Math.round(javafxDuration.toMillis()));
EventStream<?> ticks = EventStreams.restartableTicks(duration, restartImpulse);
return StateMachine.init(false)
.on(restartImpulse.withDefaultEvent(null)).transition((state, impulse) -> true)
.on(ticks).transition((state, tick) -> !state)
.toStateStream();
}
}
|
package uk.org.ponder.rsf.processor;
import java.util.Map;
import uk.org.ponder.errorutil.TargettedMessage;
import uk.org.ponder.errorutil.TargettedMessageList;
import uk.org.ponder.rsf.flow.ARIResolver;
import uk.org.ponder.rsf.flow.ARIResult;
import uk.org.ponder.rsf.flow.ActionResultInterpreter;
import uk.org.ponder.rsf.flow.FlowStateManager;
import uk.org.ponder.rsf.flow.errors.ActionErrorStrategy;
import uk.org.ponder.rsf.flow.errors.ViewExceptionStrategy;
import uk.org.ponder.rsf.preservation.StatePreservationManager;
import uk.org.ponder.rsf.request.RequestSubmittedValueCache;
import uk.org.ponder.rsf.state.ErrorStateManager;
import uk.org.ponder.rsf.state.RSVCApplier;
import uk.org.ponder.rsf.viewstate.AnyViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.util.Logger;
import uk.org.ponder.util.RunnableInvoker;
import uk.org.ponder.util.UniversalRuntimeException;
/**
* ActionHandler is a request scope bean responsible for handling an HTTP POST
* request, or other non-idempotent web service "action" cycle. Defines the core
* logic for this processing cycle.
*
* @author Antranig Basman (antranig@caret.cam.ac.uk)
*/
public class RSFActionHandler implements ActionHandler, ErrorHandler {
// application-scope dependencies
private ARIResolver ariresolver;
private RunnableInvoker postwrapper;
private RequestSubmittedValueCache requestrsvc;
// request-scope dependencies
private Map normalizedmap;
private ViewParameters viewparams;
private ErrorStateManager errorstatemanager;
private RSVCApplier rsvcapplier;
private StatePreservationManager presmanager; // no, not that of OS/2
private ViewExceptionStrategy ves;
private ActionErrorStrategy actionerrorstrategy;
private FlowStateManager flowstatemanager;
private TargettedMessageList messages;
public void setFlowStateManager(FlowStateManager flowstatemanager) {
this.flowstatemanager = flowstatemanager;
}
public void setErrorStateManager(ErrorStateManager errorstatemanager) {
this.errorstatemanager = errorstatemanager;
}
public void setARIResolver(ARIResolver ariresolver) {
this.ariresolver = ariresolver;
}
public void setViewParameters(ViewParameters viewparams) {
this.viewparams = viewparams;
}
public void setRequestRSVC(RequestSubmittedValueCache requestrsvc) {
this.requestrsvc = requestrsvc;
}
public void setAlterationWrapper(RunnableInvoker postwrapper) {
this.postwrapper = postwrapper;
}
public void setRSVCApplier(RSVCApplier rsvcapplier) {
this.rsvcapplier = rsvcapplier;
}
public void setNormalizedRequestMap(Map normalizedmap) {
this.normalizedmap = normalizedmap;
}
public void setStatePreservationManager(StatePreservationManager presmanager) {
this.presmanager = presmanager;
}
public void setViewExceptionStrategy(ViewExceptionStrategy ves) {
this.ves = ves;
}
// actually the ActionErrorStrategyManager
public void setActionErrorStrategy(ActionErrorStrategy actionerrorstrategy) {
this.actionerrorstrategy = actionerrorstrategy;
}
public void setTargettedMessageList(TargettedMessageList messages) {
this.messages = messages;
}
// The public ARIResult after all inference is concluded.
private ARIResult ariresult = null;
// The original raw action result - cannot make this final for wrapper access
private Object actionresult = null;
/**
* The result of this post cycle will be of interest to some other request
* beans, in particular the alteration wrapper. This bean must however be
* propagated lazily since it is only constructed partway through this
* handler, if indeed it is a POST cycle at all.
*
* @return
*/
public ARIResult getARIResult() {
return ariresult;
}
public Object handleError(Object actionresult, Exception exception) {
// an ARIResult is at the end-of-line - this is now unsupported though.
if (actionresult != null && !(actionresult instanceof String))
return actionresult;
TargettedMessage tmessage = new TargettedMessage();
Object newcode = actionerrorstrategy.handleError((String) actionresult,
exception, null, viewparams.viewID, tmessage);
if (newcode != null && !(newcode instanceof String))
return newcode;
for (int i = 0; i < messages.size(); ++i) {
TargettedMessage message = messages.messageAt(i);
if (message.exception != null) {
Throwable target = message.exception instanceof UniversalRuntimeException ? ((UniversalRuntimeException) message.exception)
.getTargetException()
: message.exception;
try {
Object testcode = actionerrorstrategy.handleError((String) newcode,
(Exception) target, null, viewparams.viewID, message);
if (testcode != null)
newcode = testcode;
}
catch (Exception e) {
// rethrow *original* more accurate URE, as per Az discovery
throw UniversalRuntimeException.accumulate(message.exception,
"Error invoking action");
}
}
}
if (tmessage.messagecodes != null) {
messages.addMessage(tmessage);
}
return newcode;
}
public AnyViewParameters handle() {
final String actionmethod = PostDecoder.decodeAction(normalizedmap);
try {
// Do this FIRST in case it discovers any scopelocks required
presmanager.scopeRestore();
// invoke all state-altering operations within the runnable wrapper.
postwrapper.invokeRunnable(new Runnable() {
public void run() {
if (viewparams.flowtoken != null) {
presmanager.restore(viewparams.flowtoken,
viewparams.endflow != null);
}
Exception exception = null;
try {
rsvcapplier.applyValues(requestrsvc); // many errors possible here.
}
catch (Exception e) {
exception = e;
}
Object newcode = handleError(actionresult, exception);
exception = null;
if ((newcode == null && !messages.isError())
|| newcode instanceof String) {
// only proceed to actually invoke action if no ARIResult already
// note all this odd two-step procedure is only required to be able
// to pass AES error returns and make them "appear" to be the
// returns of the first action method in a Flow.
try {
if (actionmethod != null) {
actionresult = rsvcapplier.invokeAction(actionmethod,
(String) newcode);
}
}
catch (Exception e) {
exception = e;
}
newcode = handleError(actionresult, exception);
}
if (newcode != null)
actionresult = newcode;
// must interpret ARI INSIDE the wrapper, since it may need it
// on closure.
if (actionresult instanceof ARIResult) {
ariresult = (ARIResult) actionresult;
}
else {
ActionResultInterpreter ari = ariresolver
.getActionResultInterpreter();
ariresult = ari.interpretActionResult(viewparams, actionresult);
}
}
});
presmanager.scopePreserve();
flowstatemanager.inferFlowState(viewparams, ariresult);
// moved inside since this may itself cause an error!
String submitting = PostDecoder.decodeSubmittingControl(normalizedmap);
errorstatemanager.globaltargetid = submitting;
}
catch (Throwable e) { // avoid masking errors from the finally block
Logger.log.error("Error invoking action", e);
// ThreadErrorState.addError(new TargettedMessage(
// CoreMessages.GENERAL_ACTION_ERROR));
// Detect failure to fill out arires properly.
if (ariresult == null || ariresult.resultingview == null
|| e instanceof IllegalStateException) {
ariresult = new ARIResult();
ariresult.propagatebeans = ARIResult.FLOW_END;
ViewParameters defaultparameters = viewparams.copyBase();
ariresult.resultingview = defaultparameters;
}
}
finally {
String errortoken = errorstatemanager.requestComplete();
if (ariresult.resultingview instanceof ViewParameters) {
((ViewParameters)ariresult.resultingview).errortoken = errortoken;
}
}
return ariresult.resultingview;
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.common;
import android.location.Location;
/**
* Rappresenta un punto geografico come una coppia di valori "latitudine" e "longitudine".
*
* @use Viene utilizzato dalle componenti di persistenza e di presentazione per rappresentare geneerici punti nello spazio geografico.
* @field latitude : double Latitudine del punto
* @field longitude : double Longitudine del punto
* @author Filippo Sestini <sestini.filippo@gmail.com>
* @version 1.0
*/
public class GeoPoint
{
private double latitude;
private double longitude;
public static double MIN_LATITUDE = -90.0;
public static double MAX_LATITUDE = 90.0;
public static double MIN_LONGITUDE = -180.0;
public static double MAX_LONGITUDE = 180.0;
/**
* Crea una nuova istanza di GeoPoint da una coppia di coordinate.
*
* @param latitude Latitudine del punto geografico, -90 < x < 90.
* @param longitude Longitudine del punto geografico, -180 < x < 180.
*/
public GeoPoint(double latitude, double longitude) throws IllegalArgumentException {
if ( latitude < MIN_LATITUDE || latitude > MAX_LATITUDE ||
longitude < MIN_LONGITUDE || longitude >= MAX_LONGITUDE ) {
// Si: [0, 2pi) No: [0, 2pi]. 2pi mod 2pi == 0.
throw new IllegalArgumentException();
}
this.latitude = latitude;
this.longitude = longitude;
}
/**
* Restituisce la latitudine del punto geografico.
*
* @return Coordinata latitudinale.
*/
public double latitude() {
return latitude;
}
/**
* Restituisce la longitudine del punto geografico.
*
* @return Coordinata longitudinale.
*/
public double longitude() {
return longitude;
}
/**
* Restituisce la distanza da un altro punto geografico.
*
* @param other Punto da cui si vuole calcolare la distanza.
* @return Distanza in metri tra i due punti.
*/
public float distanceTo(GeoPoint other) {
float[] results = new float[1];
Location.distanceBetween(latitude(), longitude(), other.latitude(),
other.longitude(), results);
return results[0];
}
/**
* Overriding del metodo equals() della superclasse Object.
*
* @param o Oggetto da comparare.
* @return True se entrambi gli oggetti hanno tipo GeoPoint e si riferiscono
* al medesimo punto geografico, quindi con uguali valori di
* latitudine e longitudine. False altrimenti.
*/
public boolean equals(Object o) {
if (o != null && o instanceof GeoPoint) {
GeoPoint other = (GeoPoint) o;
return this.latitude() == other.latitude() &&
this.longitude() == other.longitude();
}
return false;
}
/**
* Overriding di Object.hashCode()
*
* @return Hash dell'oggetto.
*/
public int hashCode() {
return (int)(latitude + longitude);
}
public Location toLocation() {
Location newLocation = new Location("");
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
return newLocation;
}
}
|
package io.spine.server.entity.storage;
import com.google.common.testing.EqualsTester;
import com.google.protobuf.Any;
import io.spine.core.Version;
import io.spine.server.entity.Entity;
import io.spine.server.entity.EntityWithLifecycle;
import io.spine.server.entity.VersionableEntity;
import io.spine.server.entity.given.Given;
import io.spine.server.entity.storage.EntityColumn.MemoizedValue;
import io.spine.server.entity.storage.given.ColumnTestEnv.BrokenTestEntity;
import io.spine.server.entity.storage.given.ColumnTestEnv.EntityRedefiningColumnAnnotation;
import io.spine.server.entity.storage.given.ColumnTestEnv.EntityWithCustomColumnNameForStoring;
import io.spine.server.entity.storage.given.ColumnTestEnv.EntityWithDefaultColumnNameForStoring;
import io.spine.server.entity.storage.given.ColumnTestEnv.TestEntity;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import static com.google.common.testing.SerializableTester.reserializeAndAssert;
import static io.spine.server.entity.storage.given.ColumnTestEnv.CUSTOM_COLUMN_NAME;
import static io.spine.server.entity.storage.given.ColumnTestEnv.TaskStatus.SUCCESS;
import static io.spine.server.entity.storage.given.ColumnTestEnv.forMethod;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Dmytro Dashenkov
*/
@SuppressWarnings({"InnerClassMayBeStatic", "ClassCanBeStatic"
/* JUnit 5 Nested classes cannot to be static. */,
"DuplicateStringLiteralInspection" /* Many string literals for method names. */})
@DisplayName("Column should")
class ColumnTest {
@Test
@DisplayName("be serializable")
void beSerializable() {
EntityColumn column = forMethod("getVersion", VersionableEntity.class);
reserializeAndAssert(column);
}
@Nested
@DisplayName("restore")
class Restore {
@SuppressWarnings("ResultOfMethodCallIgnored")
// Just check that operation passes without an exception.
@Test
@DisplayName("non-null getter without errors")
void getter() {
final EntityColumn column = forMethod("getVersion", VersionableEntity.class);
column.restoreGetter();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
// Just check that operation passes without an exception.
@Test
@DisplayName("non-null value converter without errors")
void valueConverter() {
final EntityColumn column = forMethod("getVersion", VersionableEntity.class);
column.restoreValueConverter();
}
}
@Test
@DisplayName("support `toString`")
void supportToString() {
EntityColumn column = forMethod("getVersion", VersionableEntity.class);
assertEquals("VersionableEntity.version", column.toString());
}
@Test
@DisplayName("invoke getter")
void invokeGetter() {
String entityId = "entity-id";
int version = 2;
EntityColumn column = forMethod("getVersion", VersionableEntity.class);
TestEntity entity = Given.entityOfClass(TestEntity.class)
.withId(entityId)
.withVersion(version)
.build();
Version actualVersion = (Version) column.getFor(entity);
assertEquals(version, actualVersion.getNumber());
}
@Test
@DisplayName("have `equals` and `hashCode`")
void haveEqualsAndHashCode() {
EntityColumn col1 = forMethod("getVersion", VersionableEntity.class);
EntityColumn col2 = forMethod("getVersion", VersionableEntity.class);
EntityColumn col3 = forMethod("isDeleted", EntityWithLifecycle.class);
new EqualsTester()
.addEqualityGroup(col1, col2)
.addEqualityGroup(col3)
.testEquals();
}
@Test
@DisplayName("memoize value at point in time")
void memoizeValue() {
EntityColumn mutableColumn = forMethod("getMutableState", TestEntity.class);
TestEntity entity = new TestEntity("");
int initialState = 1;
int changedState = 42;
entity.setMutableState(initialState);
MemoizedValue memoizedState = mutableColumn.memoizeFor(entity);
entity.setMutableState(changedState);
int extractedState = (int) mutableColumn.getFor(entity);
Integer value = (Integer) memoizedState.getValue();
assertNotNull(value);
assertEquals(initialState, value.intValue());
assertEquals(changedState, extractedState);
}
@Nested
@DisplayName("not be constructed from")
class NotBeConstructedFrom {
@Test
@DisplayName("non-getter")
void nonGetter() {
assertThrows(IllegalArgumentException.class,
() -> forMethod("toString", Object.class));
}
@Test
@DisplayName("non-annotated getter")
void nonAnnotatedGetter() {
assertThrows(IllegalArgumentException.class,
() -> forMethod("getClass", Object.class));
}
@Test
@DisplayName("static method")
void staticMethod() {
assertThrows(IllegalArgumentException.class,
() -> forMethod("getStatic", TestEntity.class));
}
@Test
@DisplayName("private getter")
void privateGetter() {
assertThrows(IllegalArgumentException.class,
() -> forMethod("getFortyTwoLong", TestEntity.class));
}
@Test
@DisplayName("getter with non-serializable return type")
void nonSerializableGetter() {
assertThrows(IllegalArgumentException.class,
() -> forMethod("getFoo", BrokenTestEntity.class));
}
@Test
@DisplayName("getter with parameters")
void getterWithParams() throws NoSuchMethodException {
Method method = TestEntity.class.getDeclaredMethod("getParameter", String.class);
assertThrows(IllegalArgumentException.class, () -> EntityColumn.from(method));
}
}
@Test
@DisplayName("fail to get value from wrong object")
void notGetForWrongObject() {
EntityColumn column = forMethod("getMutableState", TestEntity.class);
assertThrows(IllegalArgumentException.class,
() -> column.getFor(new EntityWithCustomColumnNameForStoring("")));
}
@Test
@DisplayName("tell if property is nullable")
void tellIfNullable() {
EntityColumn notNullColumn = forMethod("getNotNull", TestEntity.class);
EntityColumn nullableColumn = forMethod("getNull", TestEntity.class);
assertFalse(notNullColumn.isNullable());
assertTrue(nullableColumn.isNullable());
}
@Test
@DisplayName("check value for null if getter is not nullable")
void checkNonNullable() {
EntityColumn column = forMethod("getNotNull", TestEntity.class);
assertThrows(NullPointerException.class, () -> column.getFor(new TestEntity("")));
}
@Test
@DisplayName("allow null values if getter is nullable")
void allowNullForNullable() {
EntityColumn column = forMethod("getNull", TestEntity.class);
Object value = column.getFor(new TestEntity(""));
assertNull(value);
}
@Test
@DisplayName("contain property type")
void containType() {
EntityColumn column = forMethod("getLong", TestEntity.class);
assertEquals(Long.TYPE, column.getType());
}
@Nested
@DisplayName("memoize value")
class MemoizeValue {
@Test
@DisplayName("which is null")
void whichIsNull() {
EntityColumn nullableColumn = forMethod("getNull", TestEntity.class);
MemoizedValue memoizedNull = nullableColumn.memoizeFor(new TestEntity(""));
assertTrue(memoizedNull.isNull());
assertNull(memoizedNull.getValue());
}
@Test
@DisplayName("referencing column itself")
void referencingColumn() {
EntityColumn column = forMethod("getMutableState", TestEntity.class);
Entity<String, Any> entity = new TestEntity("");
MemoizedValue memoizedValue = column.memoizeFor(entity);
assertSame(column, memoizedValue.getSourceColumn());
}
@Test
@DisplayName("of ordinal enum type")
void ofOrdinalEnumType() {
EntityColumn column = forMethod("getEnumOrdinal", TestEntity.class);
TestEntity entity = new TestEntity("");
MemoizedValue actualValue = column.memoizeFor(entity);
int expectedValue = entity.getEnumOrdinal()
.ordinal();
assertEquals(expectedValue, actualValue.getValue());
}
@Test
@DisplayName("of string enum type")
void ofStringEnumType() {
EntityColumn column = forMethod("getEnumString", TestEntity.class);
TestEntity entity = new TestEntity("");
MemoizedValue actualValue = column.memoizeFor(entity);
String expectedValue = entity.getEnumOrdinal()
.name();
assertEquals(expectedValue, actualValue.getValue());
}
}
@Nested
@DisplayName("have name for storing")
class HaveNameForStoring {
@Test
@DisplayName("custom if specified")
void custom() {
EntityColumn column = forMethod("getValue", EntityWithCustomColumnNameForStoring.class);
assertEquals("value", column.getName());
assertEquals(CUSTOM_COLUMN_NAME.trim(), column.getStoredName());
}
@Test
@DisplayName("same as getter name if no custom one was specified")
void sameAsGetter() {
EntityColumn column = forMethod("getValue",
EntityWithDefaultColumnNameForStoring.class);
String expectedName = "value";
assertEquals(expectedName, column.getName());
assertEquals(expectedName, column.getStoredName());
}
}
@Test
@DisplayName("not allow to redefine column annotation")
void rejectRedefinedAnnotation() {
assertThrows(IllegalStateException.class,
() -> forMethod("getVersion", EntityRedefiningColumnAnnotation.class));
}
@Test
@DisplayName("be constructed from enumerated type getter")
void acceptEnumGetter() {
EntityColumn column = forMethod("getEnumOrdinal", TestEntity.class);
Class<?> expectedType = Integer.class;
Class actualType = column.getPersistedType();
assertEquals(expectedType, actualType);
}
@Nested
@DisplayName("return persisted type which")
class ReturnPersistedType {
@Test
@DisplayName("is same as column type for non-enum getter")
void forNonEnumGetter() {
EntityColumn column = forMethod("getLong", TestEntity.class);
assertEquals(column.getType(), column.getPersistedType());
}
@Test
@DisplayName("is Integer for ordinal enum getter")
void forOrdinalEnumGetter() {
EntityColumn column = forMethod("getEnumOrdinal", TestEntity.class);
Class expectedType = Integer.class;
Class actualType = column.getPersistedType();
assertEquals(expectedType, actualType);
}
@Test
@DisplayName("is String for string enum getter")
void forStringEnumGetter() {
EntityColumn column = forMethod("getEnumString", TestEntity.class);
Class expectedType = String.class;
Class actualType = column.getPersistedType();
assertEquals(expectedType, actualType);
}
}
@Nested
@DisplayName("when converting to persisted type, return")
class Convert {
@Test
@DisplayName("same value for non-enum values")
void nonEnumToSame() {
EntityColumn column = forMethod("getLong", TestEntity.class);
Object value = 15L;
Object converted = column.toPersistedValue(value);
assertEquals(value, converted);
}
@Test
@DisplayName("persisted value for enum values")
void enumToPersisted() {
EntityColumn columnOrdinal = forMethod("getEnumOrdinal", TestEntity.class);
Object ordinalValue = columnOrdinal.toPersistedValue(SUCCESS);
assertEquals(SUCCESS.ordinal(), ordinalValue);
EntityColumn columnString = forMethod("getEnumString", TestEntity.class);
Object stringValue = columnString.toPersistedValue(SUCCESS);
assertEquals(SUCCESS.name(), stringValue);
}
@Test
@DisplayName("null for null values")
void nullToNull() {
EntityColumn column = forMethod("getLong", TestEntity.class);
Object value = null;
Object converted = column.toPersistedValue(value);
assertNull(converted);
}
}
@Test
@DisplayName("allow conversion only for type stored in column")
void convertOnlyStoredType() {
EntityColumn column = forMethod("getEnumOrdinal", TestEntity.class);
String value = "test";
assertThrows(IllegalArgumentException.class, () -> column.toPersistedValue(value));
}
}
|
package org.sagebionetworks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.sagebionetworks.repo.transactions.MandatoryWriteTransaction;
import org.sagebionetworks.repo.transactions.NewWriteTransaction;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class BeanTest implements ApplicationContextAware {
ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
private static final List<String> EXCEPTIONS = Lists.newArrayList(
"org.springframework.transaction.annotation.AnnotationTransactionAttributeSource",
"org.springframework.transaction.interceptor.TransactionInterceptor",
"org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor");
private static final Pattern UNNAMED_BEAN_PATTERN = Pattern.compile("^(.*)
@Test
public void testNoUnnamedBeans() {
List<String> foundBeans = Lists.newLinkedList();
for (String beanName : applicationContext.getBeanDefinitionNames()) {
Matcher matcher = UNNAMED_BEAN_PATTERN.matcher(beanName);
if (matcher.matches() && !EXCEPTIONS.contains(matcher.group(1))) {
foundBeans.add(beanName);
}
}
assertEquals(
"Found beans without name/id. Either give the bean a name/id or add to exceptions in the test, otherwise Spring will not guarantee that the bean is a singleton",
"",
StringUtils.join(foundBeans, ","));
}
@Test
public void testTransactionalNotUsed() {
// Transactional is not used anymore, use @WriteTransaction, @NewWriteTransaction or @MandatoryWriteTransaction
Reflections reflections = new Reflections("org.sagebionetworks", new MethodAnnotationsScanner(), new TypeAnnotationsScanner());
assertEquals(0, reflections.getTypesAnnotatedWith(Transactional.class).size());
assertEquals(0, reflections.getMethodsAnnotatedWith(Transactional.class).size());
}
private static final List<String> readMethodPrefixes = Lists.newArrayList("check", "get");
private static final List<String> exceptions = Lists.newArrayList(
"checkSessionToken",
"getSessionToken",
"getEtagForUpdate",
"getForumByProjectId",
"getForUpdate",
"getAccessRequirementForUpdate");
@Test
public void testNoGetterWriteTransactions() {
Reflections reflections = new Reflections("org.sagebionetworks", new MethodAnnotationsScanner());
Set<Method> writeMethods = reflections.getMethodsAnnotatedWith(WriteTransaction.class);
writeMethods.addAll(reflections.getMethodsAnnotatedWith(NewWriteTransaction.class));
writeMethods.addAll(reflections.getMethodsAnnotatedWith(MandatoryWriteTransaction.class));
Set<String> prefixes = Sets.newHashSet();
for (Method method : writeMethods) {
String prefix = method.getName().replaceAll("[A-Z].*$", "");
if (readMethodPrefixes.contains(prefix)) {
if (!exceptions.contains(method.getName())) {
fail("Possible read only method that has write transaction: " + method);
}
} else {
prefixes.add(prefix);
}
}
System.out.println("method prefixes for modifying methods: " + prefixes);
}
}
|
// @author A0116538A
package bakatxt.gui;
// TODO comments
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JPanel;
import bakatxt.core.Task;
/**
* This class places the elements of a single task correctly in their box.
*
*/
abstract class TaskBox extends JPanel {
// TODO set min/max size
protected static final boolean IS_LINE_WRAP = true;
private static final String AT = " @";
public TaskBox(Task task, int index, Color backgroundColor) {
setOpaque(false);
setBackground(backgroundColor);
setLayout(new GridBagLayout());
addComponentsToPane(task, index);
}
protected void addComponentsToPane(Task task, int index) {
GridBagConstraints layout = new GridBagConstraints();
setNumber(layout, index);
setTaskAndLocation(layout, task.getTitle(), task.getVenue());
setTimeStart(layout, task.getTime());
setDescription(layout, task.getDescription());
setTimeEnd(layout);
}
private void setNumber(GridBagConstraints layout, int number) {
FormattedText index = new FormattedText(Integer.toString(number),
Font.PLAIN, 16, UIHelper.GRAY_MEDIUM);
layout.fill = GridBagConstraints.NONE;
layout.anchor = GridBagConstraints.CENTER;
layout.weightx = 1.0;
layout.weighty = 0.0;
layout.gridx = 0;
layout.gridy = 0;
layout.gridwidth = 1;
layout.gridheight = 1;
layout.insets = new Insets(0, 3 * UIHelper.BORDER, 0, 0);
this.add(index, layout);
}
// TODO make locationText a different color
private void setTaskAndLocation(GridBagConstraints layout, String taskText,
String locationText) {
locationText = removeNullValues(AT, locationText);
FormattedText task = new FormattedText(taskText + locationText,
UIHelper.PRESET_TYPE_TITLE, UIHelper.PRESET_SIZE_TITLE,
UIHelper.PRESET_COLOR_TITLE, IS_LINE_WRAP);
layout.fill = GridBagConstraints.HORIZONTAL;
layout.anchor = GridBagConstraints.LINE_START;
layout.weightx = 0.01;
layout.weighty = 0.0;
layout.gridx = 1;
layout.gridy = 0;
layout.gridwidth = 1;
layout.gridheight = 1;
layout.insets = new Insets(0, 5 * UIHelper.BORDER, 0, 0);
this.add(task, layout);
}
private void setDescription(GridBagConstraints layout,
String descriptionText) {
FormattedText description = new FormattedText(descriptionText,
UIHelper.PRESET_TYPE_DEFAULT, UIHelper.PRESET_SIZE_DEFAULT,
UIHelper.PRESET_COLOR_DEFAULT, IS_LINE_WRAP);
layout.fill = GridBagConstraints.BOTH;
layout.anchor = GridBagConstraints.FIRST_LINE_START;
layout.weightx = 1.0;
layout.weighty = 1.0;
layout.gridx = 1;
layout.gridy = 1;
layout.gridwidth = 1;
layout.gridheight = 1;
layout.insets = new Insets(0, 4 * UIHelper.BORDER, 0, 0);
this.add(description, layout);
}
private void setTimeStart(GridBagConstraints layout, String startTimeText) {
startTimeText = removeNullValues(startTimeText);
FormattedText time = new FormattedText(startTimeText,
UIHelper.PRESET_TYPE_DATE, UIHelper.PRESET_SIZE_DATE,
UIHelper.PRESET_COLOR_DATE);
layout.fill = GridBagConstraints.NONE;
layout.anchor = GridBagConstraints.FIRST_LINE_END;
layout.weightx = 0.01;
layout.weighty = 1.0;
layout.gridx = 2;
layout.gridy = 0;
layout.gridwidth = 1;
layout.gridheight = 1;
layout.insets = new Insets(3 * UIHelper.BORDER, 0, 0,
2 * UIHelper.BORDER);
this.add(time, layout);
}
private void setTimeEnd(GridBagConstraints layout) {
FormattedText time = new FormattedText("<end time>",
UIHelper.PRESET_TYPE_DATE, UIHelper.PRESET_SIZE_DATE,
UIHelper.PRESET_COLOR_DATE);
layout.fill = GridBagConstraints.NONE;
layout.anchor = GridBagConstraints.LAST_LINE_END;
layout.weightx = 0.01;
layout.weighty = 1.0;
layout.gridx = 2;
layout.gridy = 1;
layout.gridwidth = 1;
layout.gridheight = 1;
layout.insets = new Insets(0, 0, 3 * UIHelper.BORDER,
2 * UIHelper.BORDER);
this.add(time, layout);
}
private static String removeNullValues(String s) {
if (s == null || s.equals("null")) {
return "";
}
return s;
}
private static String removeNullValues(String prefix, String s) {
if (s == null || s.equals("null")) {
return "";
}
return prefix + s;
}
@Override
protected void paintBorder(Graphics g) {
g.setColor(UIHelper.TRANSPARENT);
}
}
|
package beans;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import resources.Food;
import resources.Ingredient;
import resources.Menu;
/**
* Session Bean implementation class ClientSession
*/
@Stateful
@LocalBean
public class ClientSession
{
@EJB
private ResourceEAO resources;
private Menu selectedMenu;
public ResourceEAO getResources()
{
return resources;
}
public void setResources( ResourceEAO resources )
{
this.resources = resources;
}
public List< Menu > getMenus()
{
return resources.getMenus();
}
public Menu getSelectedMenu()
{
return selectedMenu;
}
public String setSelectedMenu( Menu menuItem )
{
if( menuItem == null )
return "failure";
this.selectedMenu = menuItem;
return "goToFoodCustomizationPage";
}
public List< Food > getFoodsFromSelectedMenu()
{
return this.getSelectedMenu().getFoods();
}
public String getAllergensFor( Food food )
{
String result = "";
String delim = "";
for( Ingredient ingred : food.getIngredients() )
{
if( ingred.getAllergen() != null )
{
result += delim + ingred.getAllergen();
delim = ", ";
}
}
if( result.length() == 0 )
result = "no allergens";
return result;
}
}
|
package sudoku.parse;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import sudoku.Puzzle;
public class SadmanParser implements Parser{
/**
* <p>Content of the line prior to the statement of the initial
* state of the puzzle.</p>
*/
public static final String INITIAL_PUZZLE_MARKER = "[Puzzle]";
/**
* <p>Indicates an empty cell in the initial puzzle state.</p>
*/
public static final char EMPTY_CELL = '.';
private final int mag;
private final List<Integer> values;
public SadmanParser(File f) throws FileNotFoundException{
Scanner s = new Scanner(f);
while(s.hasNext() && !INITIAL_PUZZLE_MARKER.equals(s.nextLine()));
if(!s.hasNext()){
s.close();
s = new Scanner(f);
}
StringBuilder initCells;
try{
initCells = new StringBuilder(s.nextLine());
this.mag = (int)Math.sqrt(initCells.length());
for(int i=1; i<mag*mag; ++i){
initCells.append(s.nextLine());
}
} catch(java.util.NoSuchElementException e){
throw new IllegalArgumentException("Could not parse the file as Sadman format", e);
} finally{
s.close();
}
this.values = new ArrayList<>(initCells.length());
for(int i=0; i<initCells.length(); ++i){
char c = initCells.charAt(i);
values.add(c == EMPTY_CELL
? Puzzle.BLANK_CELL
: Integer.parseInt(Character.toString(c), mag*mag+1));
}
}
@Override
public int mag() {
return mag;
}
@Override
public List<Integer> values() {
return values;
}
}
|
package sudoku.parse;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import sudoku.Puzzle;
public class SadmanParser implements Parser{
/**
* <p>Content of the line prior to the statement of the initial state of the puzzle.</p>
*/
public static final String INITIAL_PUZZLE_MARKER = "[Puzzle]";
/**
* <p>Indicates an empty cell in the initial puzzle state.</p>
*/
public static final char EMPTY_CELL = '.';
private final int mag;
private final List<Integer> values;
/**
* <p>Constructs a Parser that interprets the contents of the file {@code f} as a Sadman-format
* sudoku puzzle, using the specified {@code charset} to read the file.</p>
* @param f the file to be interpreted
* @param charset the name of the charset to be used in reading the file. If the
* @throws FileNotFoundException
*/
public SadmanParser(File f, String charset) throws FileNotFoundException{
this(() -> new Scanner(f, charset));
}
public SadmanParser(File f) throws FileNotFoundException{
this(() -> new Scanner(f));
}
/**
* <p>This is a knockoff of {@literal java.util.function.Supplier<Scanner>} that declares that it
* throws a FileNotFoundException as part of its method header. This allows the two public
* constructors to send Scanner-suppliers to the relevant constructor without needing to include
* try-catch blocks inside the lambda bodies they send.</p>
* @author fiveham
*/
@FunctionalInterface
private interface FNFSupplier{
public Scanner get() throws FileNotFoundException;
}
private SadmanParser(FNFSupplier supplier) throws FileNotFoundException{
Scanner s = supplier.get();
while(s.hasNext() && !INITIAL_PUZZLE_MARKER.equals(s.nextLine()));
if(!s.hasNext()){
s.close();
s = supplier.get();
}
StringBuilder initCells;
try{
initCells = new StringBuilder(s.nextLine());
this.mag = (int)Math.sqrt(initCells.length());
for(int i=1; i<mag*mag; ++i){
initCells.append(s.nextLine());
}
} catch(NoSuchElementException e){
throw new IllegalArgumentException("Could not parse the file as Sadman format", e);
} finally{
s.close();
}
this.values = new ArrayList<>(initCells.length());
for(int i=0; i<initCells.length(); ++i){
char c = initCells.charAt(i);
values.add(c == EMPTY_CELL
? Puzzle.BLANK_CELL
: Integer.parseInt(Character.toString(c), mag*mag+1));
}
}
@Override
public int mag() {
return mag;
}
@Override
public List<Integer> values() {
return values;
}
}
|
package org.commcare.android.view;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.commcare.android.models.RangeXYValueSeries;
import org.commcare.android.util.InvalidStateException;
import org.commcare.dalvik.R;
import org.commcare.suite.model.graph.AnnotationData;
import org.commcare.suite.model.graph.BubblePointData;
import org.commcare.suite.model.graph.Graph;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.suite.model.graph.SeriesData;
import org.commcare.suite.model.graph.XYPointData;
import org.javarosa.core.model.utils.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
/*
* View containing a graph. Note that this does not derive from View; call renderView to get a view for adding to other views, etc.
* @author jschweers
*/
public class GraphView {
private Context mContext;
private int mTextSize;
private GraphData mData;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer mRenderer;
public GraphView(Context context, String title) {
mContext = context;
mTextSize = (int) context.getResources().getDimension(R.dimen.text_large);
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer(2); // initialize with two scales, to support a secondary y axis
mRenderer.setChartTitle(title);
mRenderer.setChartTitleTextSize(mTextSize);
}
/*
* Set margins.
*/
private void setMargins() {
int textAllowance = (int) mContext.getResources().getDimension(R.dimen.graph_text_margin);
int topMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getChartTitle().equals("")) {
topMargin += textAllowance;
}
int rightMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle(1).equals("")) {
rightMargin += textAllowance;
}
int leftMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle().equals("")) {
leftMargin += textAllowance;
}
int bottomMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getXTitle().equals("")) {
bottomMargin += textAllowance;
}
// Bar charts have text labels that are likely to be long (names, etc.).
// This is a terrible, temporary way to give them extra space. At some point
// there'll need to be a more robust solution for setting margins that
// respond to data and screen size.
if (mData.getType().equals(Graph.TYPE_BAR)) {
bottomMargin += 100;
}
mRenderer.setMargins(new int[]{topMargin, leftMargin, bottomMargin, rightMargin});
}
private void render(GraphData data) throws InvalidStateException {
mData = data;
mRenderer.setInScroll(true);
for (SeriesData s : data.getSeries()) {
renderSeries(s);
}
renderAnnotations();
configure();
setMargins();
}
public Intent getIntent(GraphData data) throws InvalidStateException {
render(data);
String title = mRenderer.getChartTitle();
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return ChartFactory.getBubbleChartIntent(mContext, mDataset, mRenderer, title);
}
if (mData.getType().equals(Graph.TYPE_TIME)) {
return ChartFactory.getTimeChartIntent(mContext, mDataset, mRenderer, title, getTimeFormat());
}
if (mData.getType().equals(Graph.TYPE_BAR)) {
return ChartFactory.getBarChartIntent(mContext, mDataset, mRenderer, BarChart.Type.DEFAULT, title);
}
return ChartFactory.getLineChartIntent(mContext, mDataset, mRenderer, title);
}
/*
* Get a View object that will display this graph. This should be called after making
* any changes to graph's configuration, title, etc.
*/
public View getView(GraphData data) throws InvalidStateException {
render(data);
// Graph will not render correctly unless it has data, so
// add a dummy series if needed.
boolean hasPoints = false;
Vector<SeriesData> allSeries = data.getSeries();
for (int i = 0; i < allSeries.size() && !hasPoints; i++) {
hasPoints = hasPoints || allSeries.get(i).getPoints().size() > 0;
}
if (!hasPoints) {
SeriesData s = new SeriesData();
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
s.addPoint(new BubblePointData("0", "0", "0"));
}
else if (mData.getType().equals(Graph.TYPE_TIME)) {
s.addPoint(new XYPointData(DateUtils.formatDate(new Date(), DateUtils.FORMAT_ISO8601), "0"));
}
else {
s.addPoint(new XYPointData("0", "0"));
}
s.setConfiguration("line-color", "#00000000");
s.setConfiguration("point-style", "none");
renderSeries(s);
}
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return ChartFactory.getBubbleChartView(mContext, mDataset, mRenderer);
}
if (mData.getType().equals(Graph.TYPE_TIME)) {
return ChartFactory.getTimeChartView(mContext, mDataset, mRenderer, getTimeFormat());
}
if (mData.getType().equals(Graph.TYPE_BAR)) {
return ChartFactory.getBarChartView(mContext, mDataset, mRenderer, BarChart.Type.STACKED);
}
return ChartFactory.getLineChartView(mContext, mDataset, mRenderer);
}
/**
* Fetch date format for displaying time-based x labels.
* @return String, a SimpleDateFormat pattern.
*/
private String getTimeFormat() {
return mData.getConfiguration("x-labels-time-format", "yyyy-MM-dd");
}
/*
* Allow or disallow clicks on this graph - really, on the view generated by getView.
*/
public void setClickable(boolean enabled) {
mRenderer.setClickEnabled(enabled);
}
/*
* Set up a single series.
*/
private void renderSeries(SeriesData s) throws InvalidStateException {
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(currentRenderer);
configureSeries(s, currentRenderer);
XYSeries series = createSeries(Boolean.valueOf(s.getConfiguration("secondary-y", "false")).equals(Boolean.TRUE) ? 1 : 0);
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
if (s.getConfiguration("radius-max") != null) {
((RangeXYValueSeries) series).setMaxValue(parseYValue(s.getConfiguration("radius-max"), "radius-max"));
}
}
mDataset.addSeries(series);
// Bubble charts will throw an index out of bounds exception if given points out of order
Vector<XYPointData> sortedPoints = new Vector<XYPointData>(s.size());
for (XYPointData d : s.getPoints()) {
sortedPoints.add(d);
}
Comparator<XYPointData> comparator;
if (Graph.TYPE_BAR.equals(mData.getType())) {
String barSort = s.getConfiguration("bar-sort", "");
if (barSort.equals("ascending")) {
comparator = new AscendingValuePointComparator();
} else if (barSort.equals("descending")) {
comparator = new DescendingValuePointComparator();
} else {
comparator = new StringPointComparator();
}
} else {
comparator = new NumericPointComparator();
}
Collections.sort(sortedPoints, comparator);
int barIndex = 1;
JSONObject barLabels = new JSONObject();
for (XYPointData p : sortedPoints) {
String description = "point (" + p.getX() + ", " + p.getY() + ")";
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
BubblePointData b = (BubblePointData) p;
description += " with radius " + b.getRadius();
((RangeXYValueSeries) series).add(parseXValue(b.getX(), description), parseYValue(b.getY(), description), parseRadiusValue(b.getRadius(), description));
}
else if (mData.getType().equals(Graph.TYPE_TIME)) {
((TimeSeries) series).add(parseXValue(p.getX(), description), parseYValue(p.getY(), description));
}
else if (mData.getType().equals(Graph.TYPE_BAR)) {
// In CommCare, bar graphs are specified with x as a set of text labels
// and y as a set of values. In AChartEngine, bar graphs are a subclass
// of XY graphs, with numeric x and y values. Deal with this by
// assigning an arbitrary, evenly-spaced x value to each bar and then
// populating x-labels with the user's x values.
series.add(barIndex, parseYValue(p.getY(), description));
try {
barLabels.put(Double.toString(barIndex), p.getX());
}
catch (JSONException e) {
throw new InvalidStateException("Could not handle bar label '" + p.getX() + "': " + e.getMessage());
}
barIndex++;
}
else {
series.add(parseXValue(p.getX(), description), parseYValue(p.getY(), description));
}
}
if (mData.getType().equals(Graph.TYPE_BAR)) {
mData.setConfiguration("x-min", Double.toString(0.5));
mData.setConfiguration("x-max", Double.toString(sortedPoints.size() + 0.5));
mData.setConfiguration("x-labels", barLabels.toString());
}
}
/*
* Get layout params for this graph, which assume that graph will fill parent
* unless dimensions have been provided via setWidth and/or setHeight.
*/
public static LinearLayout.LayoutParams getLayoutParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
}
/**
* Get graph's desired aspect ratio.
* @return Ratio, expressed as a double: width / height.
*/
public double getRatio() {
// Most graphs are drawn with aspect ratio 2:1, which is mostly arbitrary
// and happened to look nice for partographs. Vertically-oriented graphs,
// however, get squished unless they're drawn as a square. Expect to revisit
// this eventually (make all graphs square? user-configured aspect ratio?).
if (mData.getType().equals(Graph.TYPE_BAR)) {
return 1;
}
return 2;
}
/**
* Create series appropriate to the current graph type.
* @return An XYSeries-derived object.
*/
private XYSeries createSeries() {
return createSeries(0);
}
/**
* Create series appropriate to the current graph type.
* @param scaleIndex
* @return An XYSeries-derived object.
*/
private XYSeries createSeries(int scaleIndex) {
// TODO: Bubble and time graphs ought to respect scaleIndex, but XYValueSeries
// and TimeSeries don't expose the (String title, int scaleNumber) constructor.
if (scaleIndex > 0 && !mData.getType().equals(Graph.TYPE_XY)) {
throw new IllegalArgumentException("This series does not support a secondary y axis");
}
if (mData.getType().equals(Graph.TYPE_TIME)) {
return new TimeSeries("");
}
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return new RangeXYValueSeries("");
}
return new XYSeries("", scaleIndex);
}
/*
* Set up any annotations.
*/
private void renderAnnotations() throws InvalidStateException {
Vector<AnnotationData> annotations = mData.getAnnotations();
if (!annotations.isEmpty()) {
// Create a fake series for the annotations
XYSeries series = createSeries();
for (AnnotationData a : annotations) {
String text = a.getAnnotation();
String description = "annotation '" + text + "' at (" + a.getX() + ", " + a.getY() + ")";
series.addAnnotation(text, parseXValue(a.getX(), description), parseYValue(a.getY(), description));
}
// Annotations won't display unless the series has some data in it
series.add(0.0, 0.0);
mDataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
currentRenderer.setAnnotationsTextSize(mTextSize);
currentRenderer.setAnnotationsColor(mContext.getResources().getColor(R.color.black));
mRenderer.addSeriesRenderer(currentRenderer);
}
}
/*
* Apply any user-requested look and feel changes to graph.
*/
private void configureSeries(SeriesData s, XYSeriesRenderer currentRenderer) {
// Default to circular points, but allow other shapes or no points at all
String pointStyle = s.getConfiguration("point-style", "circle").toLowerCase();
if (!pointStyle.equals("none")) {
PointStyle style = null;
if (pointStyle.equals("circle")) {
style = PointStyle.CIRCLE;
}
else if (pointStyle.equals("x")) {
style = PointStyle.X;
}
else if (pointStyle.equals("square")) {
style = PointStyle.SQUARE;
}
else if (pointStyle.equals("triangle")) {
style = PointStyle.TRIANGLE;
}
else if (pointStyle.equals("diamond")) {
style = PointStyle.DIAMOND;
}
currentRenderer.setPointStyle(style);
currentRenderer.setFillPoints(true);
currentRenderer.setPointStrokeWidth(2);
}
String lineColor = s.getConfiguration("line-color");
if (lineColor == null) {
currentRenderer.setColor(Color.BLACK);
}
else {
currentRenderer.setColor(Color.parseColor(lineColor));
}
fillOutsideLine(s, currentRenderer, "fill-above", XYSeriesRenderer.FillOutsideLine.Type.ABOVE);
fillOutsideLine(s, currentRenderer, "fill-below", XYSeriesRenderer.FillOutsideLine.Type.BELOW);
}
/*
* Helper function for setting up color fills above or below a series.
*/
private void fillOutsideLine(SeriesData s, XYSeriesRenderer currentRenderer, String property, XYSeriesRenderer.FillOutsideLine.Type type) {
property = s.getConfiguration(property);
if (property != null) {
XYSeriesRenderer.FillOutsideLine fill = new XYSeriesRenderer.FillOutsideLine(type);
fill.setColor(Color.parseColor(property));
currentRenderer.addFillOutsideLine(fill);
}
}
/*
* Configure graph's look and feel based on default assumptions and user-requested configuration.
*/
private void configure() throws InvalidStateException{
// Default options
mRenderer.setBackgroundColor(mContext.getResources().getColor(R.color.white));
mRenderer.setMarginsColor(mContext.getResources().getColor(R.color.white));
mRenderer.setLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(0, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(1, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setYLabelsAlign(Align.LEFT, 1);
mRenderer.setYAxisAlign(Align.RIGHT, 1);
mRenderer.setAxesColor(mContext.getResources().getColor(R.color.grey_lighter));
mRenderer.setLabelsTextSize(mTextSize);
mRenderer.setAxisTitleTextSize(mTextSize);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setShowLegend(false);
mRenderer.setShowGrid(true);
int padding = 10;
mRenderer.setXLabelsPadding(padding);
mRenderer.setYLabelsPadding(padding);
mRenderer.setYLabelsVerticalPadding(padding);
if (mData.getType().equals(Graph.TYPE_BAR)) {
mRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.VERTICAL);
mRenderer.setBarSpacing(0.5);
}
// User-configurable options
mRenderer.setXTitle(mData.getConfiguration("x-title", ""));
mRenderer.setYTitle(mData.getConfiguration("y-title", ""));
mRenderer.setYTitle(mData.getConfiguration("secondary-y-title", ""), 1);
if (mData.getConfiguration("x-min") != null) {
mRenderer.setXAxisMin(parseXValue(mData.getConfiguration("x-min"), "x-min"));
}
if (mData.getConfiguration("y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("y-min"), "y-min"));
}
if (mData.getConfiguration("secondary-y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("secondary-y-min"), "secondary-y-min"), 1);
}
if (mData.getConfiguration("x-max") != null) {
mRenderer.setXAxisMax(parseXValue(mData.getConfiguration("x-max"), "x-max"));
}
if (mData.getConfiguration("y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("y-max"), "y-max"));
}
if (mData.getConfiguration("secondary-y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("secondary-y-max"), "secondary-y-max"), 1);
}
boolean showGrid = Boolean.valueOf(mData.getConfiguration("show-grid", "true")).equals(Boolean.TRUE);
mRenderer.setShowGridX(showGrid);
mRenderer.setShowGridY(showGrid);
mRenderer.setShowCustomTextGridX(showGrid);
mRenderer.setShowCustomTextGridY(showGrid);
String showAxes = mData.getConfiguration("show-axes", "true");
if (Boolean.valueOf(showAxes).equals(Boolean.FALSE)) {
mRenderer.setShowAxes(false);
}
// Labels
boolean hasX = configureLabels("x-labels");
boolean hasY = configureLabels("y-labels");
configureLabels("secondary-y-labels");
boolean showLabels = hasX || hasY;
mRenderer.setShowLabels(showLabels);
mRenderer.setShowTickMarks(showLabels);
boolean panAndZoom = Boolean.valueOf(mData.getConfiguration("zoom", "false")).equals(Boolean.TRUE);
mRenderer.setPanEnabled(panAndZoom, panAndZoom);
mRenderer.setZoomEnabled(panAndZoom, panAndZoom);
mRenderer.setZoomButtonsVisible(panAndZoom);
}
/**
* Parse given string into Double for AChartEngine.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
*/
private Double parseXValue(String value, String description) throws InvalidStateException {
if (mData.getType().equals(Graph.TYPE_TIME)) {
Date parsed = DateUtils.parseDateTime(value);
if (parsed == null) {
throw new InvalidStateException("Could not parse date '" + value + "' in " + description);
}
return parseDouble(String.valueOf(parsed.getTime()), description);
}
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
* @throws InvalidStateException
*/
private Double parseYValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
*/
private Double parseRadiusValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Attempt to parse a double, but fail on NumberFormatException.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
* @throws InvalidStateException
*/
private Double parseDouble(String value, String description) throws InvalidStateException {
try {
Double numeric = Double.valueOf(value);
if (numeric.isNaN()) {
throw new InvalidStateException("Could not understand '" + value + "' in " + description);
}
return numeric;
}
catch (NumberFormatException nfe) {
throw new InvalidStateException("Could not understand '" + value + "' in " + description);
}
}
/**
* Customize labels.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @return True iff axis has any labels at all
*/
private boolean configureLabels(String key) throws InvalidStateException {
boolean hasLabels = true;
// The labels setting might be a JSON array of numbers,
// a JSON object of number => string, or a single number
String labelString = mData.getConfiguration(key);
if (labelString != null) {
try {
// Array: label each given value
JSONArray labels = new JSONArray(labelString);
setLabelCount(key, 0);
for (int i = 0; i < labels.length(); i++) {
String value = labels.getString(i);
addTextLabel(key, parseXValue(value, "x label '" + key + "'"), value);
}
hasLabels = labels.length() > 0;
}
catch (JSONException je) {
// Assume try block failed because labelString isn't an array.
// Try parsing it as an object.
try {
// Object: each keys is a location on the axis,
// and the value is the text with which to label it
JSONObject labels = new JSONObject(labelString);
setLabelCount(key, 0);
Iterator i = labels.keys();
hasLabels = false;
while (i.hasNext()) {
String location = (String) i.next();
addTextLabel(key, parseXValue(location, "x label at " + location), labels.getString(location));
hasLabels = true;
}
}
catch (JSONException e) {
// Assume labelString is just a scalar, which
// represents the number of labels the user wants.
Integer count = Integer.valueOf(labelString);
setLabelCount(key, count);
hasLabels = count != 0;
}
}
}
return hasLabels;
}
/**
* Helper for configureLabels. Adds a label to the appropriate axis.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param location Point on axis to add label
* @param text String for label
*/
private void addTextLabel(String key, Double location, String text) {
if (isXKey(key)) {
mRenderer.addXTextLabel(location, text);
}
else {
int scaleIndex = getScaleIndex(key);
if (mRenderer.getYAxisAlign(scaleIndex) == Align.RIGHT) {
text = " " + text;
}
mRenderer.addYTextLabel(location, text, scaleIndex);
}
}
/**
* Helper for configureLabels. Sets desired number of labels for the appropriate axis.
* AChartEngine will then determine how to space the labels.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param value Number of labels
*/
private void setLabelCount(String key, int value) {
if (isXKey(key)) {
mRenderer.setXLabels(value);
}
else {
mRenderer.setYLabels(value);
}
}
/**
* Helper for turning key into scale.
* @param key Something like "x-labels" or "y-secondary-labels"
* @return Index for passing to AChartEngine functions that accept a scale
*/
private int getScaleIndex(String key) {
return key.contains("secondary") ? 1 : 0;
}
/**
* Helper for parsing axis from configuration key.
* @param key Something like "x-min" or "y-labels"
* @return True iff key is relevant to x axis
*/
private boolean isXKey(String key) {
return key.startsWith("x-");
}
/**
* Comparator to sort XYPointData-derived objects by x value.
* @author jschweers
*/
private class NumericPointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(lhs.getX(), "").compareTo(parseXValue(rhs.getX(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
/**
* Comparator to sort XYPointData-derived objects by x value without parsing them.
* Useful for bar graphs, where x values are text.
* @author jschweers
*/
private class StringPointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
return lhs.getX().compareTo(rhs.getX());
}
}
/**
* Comparator to sort XYPoint-derived data by y value, in ascending order.
* Useful for bar graphs, nonsensical for other graphs.
* @author jschweers
*/
private class AscendingValuePointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(lhs.getY(), "").compareTo(parseXValue(rhs.getY(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
/**
* Comparator to sort XYPoint-derived data by y value, in descending order.
* Useful for bar graphs, nonsensical for other graphs.
* @author jschweers
*/
private class DescendingValuePointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(rhs.getY(), "").compareTo(parseXValue(lhs.getY(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
}
|
package main;
import telas.TelaPrincipal;
import modelos.Aluno;
import java.util.ArrayList;
import util.Arquivos;
/**
*
* @author douglasdanieldelfrari
*/
public class ProgramaPrincipal {
private static ArrayList<Aluno> listaAlunos;
private static ArrayList<Aluno> listaAlunosArquivo;
private static ArrayList<Aluno> listaAlunosPastaArquivos;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
recuperarDadosEmArquivo();
// testando GIT
//new TelaPrincipal().setVisible(true);
TelaPrincipal minhaTela = new TelaPrincipal();
minhaTela.setVisible(true);
}
public static void salvarAluno(Aluno aluno) {
listaAlunos.add(aluno);
// tambem gravando objeto em arquivo (OPCIONAL)
Arquivos.gravarAlunoEmArquivo(aluno);
}
public static ArrayList<Aluno> getAlunos() {
return listaAlunos;
}
public static void salvarDadosEmArquivo() {
Arquivos.salvarAlunos(listaAlunos,listaAlunosArquivo);
}
public static void recuperarDadosEmArquivo() {
listaAlunosArquivo = Arquivos.recuperarAlunos();
listaAlunos = new ArrayList<Aluno>(listaAlunosArquivo);
// usado para backup
listaAlunosPastaArquivos = Arquivos.processarArquivos();
}
public static Aluno getAlunoByLogin(String login) {
Aluno alunoResult = null;
for (Aluno aluno : listaAlunos) {
if (aluno.getLogin().equals(login)) {
alunoResult = aluno;
break;
}
}
return alunoResult;
}
}
|
package info.tregmine.currency;
import info.tregmine.database.ConnectionPool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerLoginEvent;
public class CurrencyPlayer implements Listener {
private final Main plugin;
public CurrencyPlayer(Main instance) {
plugin = instance;
plugin.getServer();
}
@EventHandler
public void onPlayerLogin (PlayerLoginEvent event){
Wallet wallet = new Wallet(event.getPlayer());
wallet.create();
}
@EventHandler
public void onPlayerDropItem (PlayerDropItemEvent event) {
if (event.getPlayer().getGameMode() == GameMode.CREATIVE) {
event.setCancelled(true);
return;
}
if (
event.getItemDrop().getLocation().getBlockX() < 509 &&
event.getItemDrop().getLocation().getBlockX() > 498 &&
event.getItemDrop().getLocation().getBlockZ() > -165 &&
event.getItemDrop().getLocation().getBlockZ() < -153
){
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionPool.getConnection();
String sql = "SELECT value FROM items_destroyvalue WHERE itemid = ?";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, event.getItemDrop().getItemStack().getTypeId());
stmt.execute();
rs = stmt.getResultSet();
rs.first();
int total = rs.getInt("value") * event.getItemDrop().getItemStack().getAmount();
// event.getPlayer().sendMessage("value: " + total);
if (total > 0) {
Wallet wallet = new Wallet(event.getPlayer().getName());
// event.getItemDrop().remove();
event.getItemDrop().getItemStack().setAmount(0);
// wallet.add(total);
event.getPlayer().sendMessage(ChatColor.AQUA + "You got " + ChatColor.GOLD + total + " Tregs " + ChatColor.AQUA +"(You have " + wallet.formatBalance() + ")");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
// event.getPlayer().sendMessage("If you see this, you are in a dropzone");
}
}
}
|
package com.plugin.gcm;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
public class PushHandlerActivity extends Activity
{
private static String TAG = "PushHandlerActivity";
/*
* this activity will be started if the user touches a notification that we own.
* We send it's data off to the push plugin for processing.
* If needed, we boot up the main activity to kickstart the application.
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
boolean isPushPluginActive = PushPlugin.isActive();
processPushBundle(isPushPluginActive);
finish();
if (!isPushPluginActive) {
forceMainActivityReload();
}
}
/**
* Takes the pushBundle extras from the intent,
* and sends it through to the PushPlugin for processing.
*/
private void processPushBundle(boolean isPushPluginActive)
{
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bundle originalExtras = extras.getBundle("pushBundle");
originalExtras.putBoolean("foreground", false);
originalExtras.putBoolean("coldstart", !isPushPluginActive);
}
}
/**
* Forces the main activity to re-launch if it's unloaded.
*/
private void forceMainActivityReload()
{
PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage(getApplicationContext().getPackageName());
startActivity(launchIntent);
}
@Override
protected void onResume() {
super.onResume();
final NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
}
|
package goldrush;
import java.util.Random;
/**
*
* @author cl426792
*/
public class FumagalliGiulia extends GoldDigger {
int place, days, diggers[];
FumagalliGiulia(){
days = 0;
}
@Override
public void dailyOutcome(int revenue, int[] distances, int[] diggers) {
this.diggers = diggers;
System.out.println(place + " - " + diggers[place]);
}
@Override
public int chooseDiggingSite(int[] distances){
if(days > 0){
for(int i = distances.length - 1; i >= 0 ; i
if(diggers[i]<5){
place = i;
}
}
} else {
place = new RandomDigger().chooseDiggingSite(distances);
}
days++;
return place;
}
}
|
package api.web.gw2.mapping.v2.guild.id;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LevelValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.core.OptionalValue;
import api.web.gw2.mapping.core.QuantityValue;
import java.util.Optional;
import java.util.OptionalInt;
public final class JsonpGuild implements Guild {
@IdValue(flavor = IdValue.Flavor.STRING)
private String id = IdValue.DEFAULT_STRING_ID;
private String name = LocalizedResource.DEFAULT;
private String tag = LocalizedResource.DEFAULT;
@OptionalValue
@LevelValue
private OptionalInt level = OptionalInt.empty();
@OptionalValue
private Optional<String> motd = Optional.empty();
@OptionalValue
@QuantityValue
private OptionalInt influence = OptionalInt.empty();
@OptionalValue
@QuantityValue
private OptionalInt aetherium = OptionalInt.empty();
@OptionalValue
@QuantityValue
private OptionalInt favor = OptionalInt.empty();
@OptionalValue
@QuantityValue
private OptionalInt resonance = OptionalInt.empty();
private GuildEmblem emblem;
@QuantityValue
private int memberCount = QuantityValue.DEFAULT;
@QuantityValue
private int memberCapacity = QuantityValue.DEFAULT;
/**
* Creates a new empty instance.
*/
public JsonpGuild() {
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getTag() {
return tag;
}
@Override
public OptionalInt getLevel() {
return level;
}
@Override
public Optional<String> getMotd() {
return motd;
}
@Override
public OptionalInt getInfluence() {
return influence;
}
@Override
public OptionalInt getAetherium() {
return aetherium;
}
@Override
public OptionalInt getFavor() {
return favor;
}
@Override
public OptionalInt getResonance() {
return resonance;
}
@Override
public GuildEmblem getEmblem() {
return emblem;
}
@Override
public int getMemberCount() {
return memberCount;
}
@Override
public int getMemberCapacity() {
return memberCapacity;
}
}
|
package api.web.gw2.mapping.v2.guild.id;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LevelValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.core.OptionalValue;
import api.web.gw2.mapping.core.QuantityValue;
import java.util.Optional;
import java.util.OptionalInt;
public final class JsonpGuild implements Guild {
@IdValue(flavor = IdValue.Flavor.STRING)
private String id = IdValue.DEFAULT_STRING_ID;
private String name = LocalizedResource.DEFAULT;
private String tag = LocalizedResource.DEFAULT;
@OptionalValue
@LevelValue
private OptionalInt level = OptionalInt.empty();
@OptionalValue
private Optional<String> motd = Optional.empty();
@OptionalValue
@QuantityValue
private OptionalInt influence = OptionalInt.empty();
@OptionalValue
@QuantityValue
private OptionalInt aetherium = OptionalInt.empty();
@OptionalValue
@QuantityValue
private OptionalInt favor = OptionalInt.empty();
@OptionalValue
@QuantityValue
private OptionalInt resonance = OptionalInt.empty();
private GuildEmblem emblem;
/**
* Creates a new empty instance.
*/
public JsonpGuild() {
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getTag() {
return tag;
}
@Override
public OptionalInt getLevel() {
return level;
}
@Override
public Optional<String> getMotd() {
return motd;
}
@Override
public OptionalInt getInfluence() {
return influence;
}
@Override
public OptionalInt getAetherium() {
return aetherium;
}
@Override
public OptionalInt getFavor() {
return favor;
}
@Override
public OptionalInt getResonance() {
return resonance;
}
@Override
public GuildEmblem getEmblem() {
return emblem;
}
}
|
package com.levelup.logutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
public class FileLogger {
private static final String LOG_NAME = "log.csv";
private static final String LOG_NAME_ALTERNATIVE = "log_a.csv";
private static final String LOG_HEAD = "Time,Level,PID,TID,App,Tag,Message";
private static final String TAG = "FileLogger";
private static final int MSG_WRITE = 0; // paired with a LogMessage
private static final int MSG_COLLECT = 1;
private static final int MSG_CLEAR = 2;
private static final int MSG_OPEN = 3;
private final File file1;
private final File file2;
private long maxFileSize = 102400;
private File mCurrentLogFile;
private Writer writer;
private String mTag;
private String applicationTag;
private Handler mSaveStoreHandler;
/**
* Path where the log must be collected
*/
private File finalPath;
private FLogLevel logLevel = FLogLevel.I;
/**
* Create a file for writing logs.
*
* @param logFolder
* the folder path where the logs are stored
* @param tag
* tag used for message without tag
* @throws IOException
*/
public FileLogger(File logFolder, String tag) throws IOException {
this(logFolder);
this.mTag = tag;
}
/**
* Create a file for writing logs.
*
* @param logFolder
* the folder path where the logs are stored
* @throws IOException
*/
@SuppressLint("HandlerLeak")
public FileLogger(File logFolder) throws IOException {
this.file1 = new File(logFolder, LOG_NAME);
this.file2 = new File(logFolder, LOG_NAME_ALTERNATIVE);
if (!logFolder.exists()) logFolder.mkdirs();
if (!logFolder.isDirectory()) {
Log.e(TAG, logFolder + " is not a folder");
throw new IOException("Path is not a directory");
}
if (!logFolder.canWrite()) {
Log.e(TAG, logFolder + " is not a writable");
throw new IOException("Folder is not writable");
}
mCurrentLogFile = chooseFileToWrite();
// Initializing the HandlerThread
HandlerThread handlerThread = new HandlerThread("FileLogger", android.os.Process.THREAD_PRIORITY_BACKGROUND);
if (!handlerThread.isAlive()) {
handlerThread.start();
mSaveStoreHandler = new Handler(handlerThread.getLooper()) {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_OPEN:
try {
closeWriter();
} catch (IOException e) {
}
openWriter();
break;
case MSG_WRITE:
try {
LogMessage logmsg = (LogMessage) msg.obj;
if (writer==null)
Log.e(TAG, "no writer");
else {
writer.append(logmsg.formatCsv());
writer.flush();
}
} catch (IOException e) {
Log.e(TAG, e.getClass().getSimpleName() + " : " + e.getMessage());
}
verifyFileSize();
break;
case MSG_COLLECT:
if (!mCurrentLogFile.exists() || mCurrentLogFile.length() == 0) {
((LogCollecting) msg.obj).onEmptyLogCollected();
break;
}
// Get the phone information
if (finalPath.getParentFile()!=null)
finalPath.getParentFile().mkdirs();
try {
finalPath.createNewFile();
if (!finalPath.canWrite())
((LogCollecting) msg.obj).onLogCollectingError("Can't write on "+finalPath);
else {
finalPath.delete();
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(finalPath, true), "UTF-8");
out.append(LOG_HEAD);
out.append('\n');
out.flush();
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "UnsupportedEncodingException: " + e.getMessage(), e);
} catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException: " + e.getMessage(), e);
}
// Merge the files
final File olderLogFile;
if (mCurrentLogFile==file2)
olderLogFile = file1;
else
olderLogFile = file2;
if (olderLogFile.exists())
mergeFile(olderLogFile, finalPath);
mergeFile(mCurrentLogFile, finalPath);
((LogCollecting) msg.obj).onLogCollected(finalPath, "text/csv");
}
} catch (IOException e) {
((LogCollecting) msg.obj).onLogCollectingError(e.getMessage()+" - file:"+finalPath);
}
break;
case MSG_CLEAR:
try {
closeWriter();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
} finally {
file1.delete();
file2.delete();
mCurrentLogFile = file1;
openWriter();
}
break;
}
};
};
if (mSaveStoreHandler == null) throw new NullPointerException("Handler is null");
mSaveStoreHandler.sendEmptyMessage(MSG_OPEN);
}
}
public void setLogLevel(FLogLevel level) {
logLevel = level;
}
public void setMaxFileSize(long maxFileSize) {
this.maxFileSize = maxFileSize;
}
private File chooseFileToWrite() {
if (!file1.exists() && !file2.exists())
return file1;
if (file1.exists() && file1.length() < maxFileSize)
return file1;
return file2;
}
public void d(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.D))
write('d', tag, msg, tr);
}
public void d(String tag, String msg) {
if (logLevel.allows(FLogLevel.D))
write('d', tag, msg);
}
public void d(String msg) {
if (logLevel.allows(FLogLevel.D))
write('d', msg);
}
public void e(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.E))
write('e', tag, msg, tr);
}
public void e(String tag, String msg) {
if (logLevel.allows(FLogLevel.E))
write('e', tag, msg);
}
public void e(String msg) {
if (logLevel.allows(FLogLevel.E))
write('e', msg);
}
public void wtf(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.WTF))
write('f', tag, msg, tr);
}
public void wtf(String tag, String msg) {
if (logLevel.allows(FLogLevel.WTF))
write('f', tag, msg);
}
public void wtf(String msg) {
if (logLevel.allows(FLogLevel.WTF))
write('f', msg);
}
public void i(String msg, String tag, Throwable tr) {
if (logLevel.allows(FLogLevel.I))
write('i', tag, msg, tr);
}
public void i(String msg, String tag) {
if (logLevel.allows(FLogLevel.I))
write('i', tag, msg);
}
public void i(String msg) {
if (logLevel.allows(FLogLevel.I))
write('i', msg);
}
public void v(String msg, String tag, Throwable tr) {
if (logLevel.allows(FLogLevel.V))
write('v', tag, msg, tr);
}
public void v(String msg, String tag) {
if (logLevel.allows(FLogLevel.V))
write('v', tag, msg);
}
public void v(String msg) {
if (logLevel.allows(FLogLevel.V))
write('v', msg);
}
public void w(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.W))
write('w', tag, msg, tr);
}
public void w(String tag, String msg) {
if (logLevel.allows(FLogLevel.W))
write('w', tag, msg);
}
public void w(String msg) {
if (logLevel.allows(FLogLevel.W))
write('w', msg);
}
private void write(char lvl, String message) {
String tag;
if (mTag == null)
tag = TAG;
else
tag = mTag;
write(lvl, tag, message);
}
private void write(char lvl, String tag, String message) {
write(lvl, tag, message, null);
}
protected void write(char lvl, String tag, String message, Throwable tr) {
if (tag == null) {
write(lvl, message);
return;
}
Message htmsg = Message.obtain(mSaveStoreHandler, MSG_WRITE, new LogMessage(lvl, tag, getApplicationLocalTag(), Thread.currentThread().getName(), message, tr));
mSaveStoreHandler.sendMessage(htmsg);
}
private static class LogMessage {
private static SimpleDateFormat dateFormat; // must always be used in the same thread
private static Date mDate;
private final long now;
private final char level;
private final String tag;
private final String appTag;
private final String threadName;
private final String msg;
private final Throwable cause;
private String date;
LogMessage(char lvl, String tag, String appTag, String threadName, String msg, Throwable tr) {
this.now = System.currentTimeMillis();
this.level = lvl;
this.tag = tag;
this.appTag = appTag;
this.threadName = threadName;
this.msg = msg;
this.cause = tr;
if (msg == null) {
Log.e(TAG, "No message");
}
}
private void addCsvHeader(final StringBuilder csv) {
if (dateFormat==null)
dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.getDefault());
if (date==null && null!=dateFormat) {
if (null==mDate)
mDate = new Date();
mDate.setTime(now);
date = dateFormat.format(mDate);
}
csv.append(date.toString());
csv.append(',');
csv.append(level);
csv.append(',');
csv.append(android.os.Process.myPid());
csv.append(',');
if (threadName!=null)
csv.append(threadName);
csv.append(',');
if (appTag!=null)
csv.append(appTag);
csv.append(',');
if (tag!=null)
csv.append(tag);
csv.append(',');
}
private void addException(final StringBuilder csv, Throwable tr) {
if (tr==null)
return;
final StringBuilder sb = new StringBuilder(256);
sb.append(cause.getClass());
sb.append(": ");
sb.append(cause.getMessage());
sb.append('\n');
for (StackTraceElement trace : cause.getStackTrace()) {
//addCsvHeader(csv);
sb.append(" at ");
sb.append(trace.getClassName());
sb.append('.');
sb.append(trace.getMethodName());
sb.append('(');
sb.append(trace.getFileName());
sb.append(':');
sb.append(trace.getLineNumber());
sb.append(')');
sb.append('\n');
}
addException(sb, tr.getCause());
csv.append(sb.toString().replace(';', '-').replace(',', '-').replace('"', '\''));
}
public CharSequence formatCsv() {
final StringBuilder csv = new StringBuilder(256);
addCsvHeader(csv);
csv.append('"');
if (msg != null) csv.append(msg.replace(';', '-').replace(',', '-').replace('"', '\''));
csv.append('"');
csv.append('\n');
if (cause!=null) {
addCsvHeader(csv);
csv.append('"');
addException(csv, cause);
csv.append('"');
csv.append('\n');
}
return csv.toString();
}
}
private String getApplicationLocalTag() {
if (applicationTag == null) applicationTag = getApplicationTag();
return applicationTag;
}
/**
* remove all the current log entries and start from scratch
*/
public void clear() {
mSaveStoreHandler.sendEmptyMessage(MSG_CLEAR);
}
/**
* Collects the logs. Make sure finalPath have been set before.
*
* @param context
* @param listener
*/
public void collectlogs(Context context, LogCollecting listener) {
if (mCurrentLogFile == null) {
listener.onLogCollectingError("Log file is invalid.");
} else if (finalPath==null) {
listener.onLogCollectingError("Final path have not been set");
} else {
Message msg = Message.obtain(mSaveStoreHandler, MSG_COLLECT, listener);
mSaveStoreHandler.sendMessage(msg);
}
}
private void mergeFile(File otherFile, File finalFile) {
try {
InputStream instream = new FileInputStream(otherFile);
BufferedReader in = new BufferedReader(new InputStreamReader(instream));
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(finalFile, true), "UTF-8");
String line;
while ((line = in.readLine()) != null) {
out.append(line);
out.append('\n');
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
FLog.e(TAG, "FileNotFoundException: " + e.getMessage(), e);
} catch (IOException e) {
FLog.e(TAG, "IOException: " + e.getMessage(), e);
}
}
/**
* a special tag to be added to the logs
* @return
*/
public String getApplicationTag() {
return "";
}
private void verifyFileSize() {
if (mCurrentLogFile != null) {
long size = mCurrentLogFile.length();
if (size > maxFileSize) {
try {
closeWriter();
} catch (IOException e) {
FLog.e(TAG, "Can't use file : "+ mCurrentLogFile, e);
} finally {
if (mCurrentLogFile==file2)
mCurrentLogFile = file1;
else
mCurrentLogFile = file2;
mCurrentLogFile.delete();
openWriter();
}
}
}
}
private void openWriter() {
if (writer==null)
try {
writer = new OutputStreamWriter(new FileOutputStream(mCurrentLogFile, true), "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "can't get a writer for " +mCurrentLogFile+" : "+e.getMessage());
} catch (FileNotFoundException e) {
Log.e(TAG, "can't get a writer for " +mCurrentLogFile+" : "+e.getMessage());
}
}
private void closeWriter() throws IOException {
if (writer!=null) {
writer.close();
writer = null;
}
}
void setFinalPath(File finalPath) {
this.finalPath = finalPath;
}
}
|
package JDownLoadComic.parseHtml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import JDownLoadComic.Config;
import JDownLoadComic.util.HttpReader;
import JDownLoadComic.util.Log;
import JDownLoadComic.util.WriteFile;
/**
*
*
* @author Ray
*
*/
public class LoadComicData {
private static Log sLog = Log.newInstance(true);
// private String vision; //
protected HttpReader loadHtml;
protected String[][] indexData;
protected Map cviewUrlHash;
protected WriteFile wf;
public interface Callback {
void onSynced(ActDataObj actObj);
}
public LoadComicData() {
loadHtml = new HttpReader();
}
/**
*
* @param path
*
*/
public LoadComicData(ArrayList ary) {
this();
initLoadCartoonData(ary);
}
/**
*
*
* @param path
*
*/
public void initLoadCartoonData(ArrayList aryList) {
// wf = new WriteFile();
Object[] ary = aryList.toArray();
indexData = new String[ary.length][];
for (int i = 0; i < ary.length; i++) {
indexData[i] = (String[]) ary[i];
}
}
/**
* ,
*
* @return
*/
public String[][] getIndexData() {
return indexData;
}
/**
* n
*
* @param rowIndex
* idnex
* @return
*/
public String getCartoonID(int rowIndex) {
return indexData[rowIndex][0];
}
/**
* n
*
* @param rowIndex
* idnex
* @return
*/
public String getCartoonName(int rowIndex) {
return indexData[rowIndex][1];
}
/**
*
*
* @return
*/
public int getDataLength() {
return indexData.length;
}
/**
* n
*
* @param deletRowIndex
*
* @param type
* 0:,1:
*/
public void clearLoveComicData(int[] deletRowIndex) {
if (deletRowIndex.length <= 0) {
return;
}
// clear
for (int i = 0; i < deletRowIndex.length; i++) {
// System.out.println(indexData[deletRowIndex[i]][0]);
indexData[deletRowIndex[i]][0] = null;
indexData[deletRowIndex[i]][1] = null;
}
Config.db.clearLoveComicList();
for (int i = 0; i < indexData.length; i++) {
if (indexData[i][0] != null) {
Config.db.addLoveComicList(indexData[i]);
}
}
initLoadCartoonData(Config.db.getLoveComicList());
}
/**
*
*
* @param findName
*
* @param startIndex
*
* @return
*/
public int findCartoonIndex(String findName, int startIndex) {
if (startIndex >= getDataLength()) {
return -1;
}
// Config.db.loveComicInfo();
for (int i = startIndex; i < getDataLength(); i++) {
String cartoonName = indexData[i][1];
if (cartoonName.indexOf(findName) != -1) {
return i;
}
}
return -1;
}
/**
*
*
* @param comicNumber
* @return
*/
public String findComicName(String comicNumber) {
int size = getDataLength();
for (int i = size - 1; i >= 0; i
String cNumber = indexData[i][0].trim();
if (cNumber.equals(comicNumber.trim())) {
return indexData[i][1];
}
}
return null;
}
/**
*
*
* @param findName
* @return
*/
public ArrayList<String> findCatroonToArrayList(String findName) {
if (findName.trim().equals("")) {
return null;
}
ArrayList<String> catList = new ArrayList<String>();
for (int i = 0; i < getDataLength(); i++) {
String cartoonName = getCartoonName(i);
if (cartoonName.indexOf(findName) != -1) {
String dataName = getCartoonID(i) + "|" + cartoonName;
catList.add(dataName);
}
}
return catList;
}
/**
*
*
* @param actObj
*/
public void startSync(ActDataObj actObj, Callback callback) {
new Thread(createSyncRunobject(actObj, callback)).start();
}
private Runnable createSyncRunobject(final ActDataObj actObj,
final Callback callback) {
Runnable runObj = new Runnable() {
private Callback mCallback;
@Override
public void run() {
mCallback = callback;
actObj.syncState = ActDataObj.STATE_SYNC_START;
String comicUrl = Config.indexHtml + "/html/" + actObj.id
+ ".html";
String imgurl = Config.imgUrl + "/" + actObj.id + ".jpg";
String imgSavePath = Config.defaultImgPath;
actObj.stargLoadImg(comicUrl, imgurl, imgSavePath);
ArrayList dataAry = loadHtml.getHTMLtoArrayList(comicUrl,
Config.actLang);
String viewData = "";
String tmpch = "";
String findCview = "cview(";
String findDeaitlTag = "style=\"padding:10px;line-height:25px\">";
// String replaceStr =
// "<td colspan=\"2\" nowrap=\"nowrap\">";//replaceAll
for (int i = 0; i < dataAry.size(); i++) {
String txt = (String) dataAry.get(i);
if (txt.indexOf(findCview) != -1) {
viewData = txt;
sLog.println(viewData);
String[] data = viewData
.substring(
viewData.indexOf(findCview)
+ findCview.length(),
viewData.indexOf(");return"))
.replaceAll("'", "").split("[,]");
tmpch = data[0];
String comicOneBookName = dataAry.get(i + 1).toString();
comicOneBookName = removeScriptsTag(comicOneBookName);// 2012/11/07
// scripts
// tag
comicOneBookName = replaceTag(comicOneBookName);// 2012/11/07
// td tag
// 2013/09/15 ":"
comicOneBookName = comicOneBookName.replaceAll("[:]",
"");
actObj.addActComic(comicOneBookName,
cview(data[0], data[1]));
} else {
if (actObj.getDetail().equals("")) {
if (txt.indexOf(findDeaitlTag) != -1) {
int detailStart = txt.indexOf(findDeaitlTag)
+ findDeaitlTag.length();
int detailEnd = txt.indexOf("</td>");
actObj.setDetail(txt.substring(detailStart,
detailEnd));
}
}
if (actObj.getAuthor().equals("")) {
String authorTag = "</td>";
if (txt.indexOf(authorTag) != -1) {
// 2012/11/07 tag
// actObj.setAuthor(replaceTag(findBookData(authorTag,(String)dataAry.get(i+1))));
String author = replaceTag((String) dataAry
.get(i + 1));
actObj.setAuthor(author);
}
} else if (actObj.getLastUpdateDate().equals("")) {
String lastUpdateDateTag = "</td>";
if (txt.indexOf(lastUpdateDateTag) != -1) {
// 2012/11/07 tag
String updateDate = replaceTag((String) dataAry
.get(i + 1));
actObj.setLastUpdateDate(updateDate);
// actObj.setLastUpdateDate(replaceTag(findBookData(lastUpdateDateTag,(String)dataAry.get(i+1))));
}
}/*
* else
* if(actObj.getPublishDate().equals("")){//2010/08/14
* String publishDateTag = "</td>";
* if(txt.indexOf(publishDateTag) != -1){//
* actObj.setPublishDate
* (findBookData(publishDateTag,(String
* )dataAry.get(i+1))); } }
*/
}
}
actObj.ch = Integer
.parseInt(tmpch.split("[.]")[0].split("[-]")[1]);
actObj.syncState = ActDataObj.STATE_SYNC_SUCCESS;
mCallback.onSynced(actObj);
mCallback = null;
}
};
return runObj;
}
/**
* tag
*
* @param findTag
* @param nextTxt
* @return
*/
public String findBookData(String findTag, String nextTxt) {
String findAu = "nowrap>";
int auStart = nextTxt.indexOf(findAu) + findAu.length();
int auEnd = nextTxt.indexOf("</td>");
return nextTxt.substring(auStart, auEnd);
}
/**
* javascript function [0]:itemid,[1]:baseurl + url
*
* @param url
* @param catid
* @return
*/
public String[] cview(String url, String catid) {
String[] data = new String[2];
String baseurl = "";
if (cviewUrlHash == null) {
cviewUrlHash = loadCviewJS(Config.cviewURL, Config.actLang);
}
baseurl = cviewUrlHash.get(catid).toString();
url = url.replaceAll(".html", "").replaceAll("-", ".html?ch=");
// System.out.println(" url" +url);
data[0] = url.split("[.]")[0];
data[1] = baseurl + url;
return data;
}
/**
* comicview.js
*
* @param url
* @param fmt
* @return
*/
private Map loadCviewJS(String url, String fmt) {
ArrayList dataAry = loadHtml.getHTMLtoArrayList(Config.cviewURL,
Config.actLang);
HashMap cviewHash = new HashMap();
String startTag = "if(";
String endTab = "baseurl+=\"";
String urlStratTag = endTab;
String urlEndTag = "\";";
for (int i = 0; i < dataAry.size(); i++) {
String txt = (String) dataAry.get(i);
if (txt.length() > 0) {
if (txt.indexOf(startTag) != -1) {
txt = txt.replaceAll("[)]", "");
String[] numCodeAry = txt.substring(startTag.length(),
txt.indexOf(endTab)).split("[|][|]");
String cviewUrl = txt.substring(
txt.indexOf(urlStratTag) + urlStratTag.length(),
txt.indexOf(urlEndTag)).trim();
for (int j = 0; j < numCodeAry.length; j++) {
String numCode = (numCodeAry[j].trim()).split("[=][=]")[1]
.trim();
cviewHash.put(numCode, cviewUrl);
}
}
}
if (txt.indexOf("url=url") != -1) {
break;
}
}
dataAry.clear();
System.out.println(cviewHash);
return cviewHash;
}
/**
*
*
* @return [0]:,[1]:
*/
public String[][] updateComic(ArrayList<NewComic> newComicAry) {
Hashtable data = new Hashtable();
for (int i = 1; i <= Config.db.refrushPage; i++) {
String url = Config.indexHtml + "comic/u-" + i + ".html";
updateNewComic(url, Config.actLang, data, newComicAry);
}
for (int i = 0; i < getDataLength(); i++) {
data.remove(getCartoonID(i));
}
String[][] comicArray = new String[data.size()][2];
if (data.size() > 0) {
Set set = data.entrySet();
Iterator t = set.iterator();
// array
int i = 0;
while (t.hasNext()) {
Map.Entry m = (Map.Entry) t.next();
String id = (String) m.getKey();
String name = (String) m.getValue();
comicArray[i][0] = id;
comicArray[i][1] = name;
i++;
}
// 2012/11/07
comicArray = sortComicAry(comicArray);
for (int j = 0; j < comicArray.length; j++) {
String id = comicArray[j][0];
String name = comicArray[j][1];
Config.db.addComicList(new String[] { id, name });
}
Config.db.save();
}
return comicArray;
}
/**
* id()
*
* @param ary
* @return
*/
private String[][] sortComicAry(String[][] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (Integer.parseInt(a[j + 1][0]) < Integer.parseInt(a[j][0])) {
String[] temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
return a;
}
/**
*
*
* @param comicID
*
* @param comicName
*
* @return
*/
public String writeMyLove(String comicID, String comicName) {
String str = "";
int find = findCartoonIndex(comicName, 0);
// System.out.println("["+comicName+"]==>" + find);
if (find == -1) {
str = comicID + "|" + comicName;
// wf.writeText_UTF8_Apend(str + "\r\n", Config.defaultSavePath +
// "/" + Config.myLoveFileName);
}
return str;
}
/**
*
*
* @param url
*
* @param fmt
*
* @param data
* ,key:,value:
*/
public void updateNewComic(String url, String fmt, Hashtable data,
ArrayList<NewComic> newComicAry) {
HttpReader lf = new HttpReader();
ArrayList al = lf.getHTMLtoArrayList(url, fmt);
for (int i = 0; i < al.size(); i++) {
String html = al.get(i).toString();
if (NewComic.hasTag(html)) {
String nextHtml = al.get(i + 1).toString();
NewComic obj = NewComic.parser(html, nextHtml);
if (obj != null) {
data.put(obj.id, obj.name);
newComicAry.add(obj);
}
}
}
}
/**
* "<"">"
*
* @param txt
* @return
*/
public static String replaceTag(String txt) {
StringBuffer data = new StringBuffer();
char st = '<';
char ed = '>';
char[] charAry = txt.toCharArray();
boolean check = false;
for (int i = 0; i < charAry.length; i++) {
char c = charAry[i];
if (c == st) {
check = true;
} else if (c == ed) {
check = false;
continue;
}
if (check) {
continue;
}
if (c == '\r' || c == '\n') {
continue;
}
data.append(c);
}
return data.toString();
}
// javascriptstag(tag)
public static String removeScriptsTag(String st) {
String ret = st;
String beginStr = "<script>";
String endStr = "</script>";
int bIndex = st.indexOf(beginStr);
int eIndex = st.indexOf(endStr);
// System.out.println(bIndex+"==" + eIndex);
if (bIndex != -1 && eIndex != -1) {
ret = st.substring(0, bIndex);
ret += st.substring(eIndex + endStr.length(), st.length());
// st = st.substring(bIndex + beginStr.length(), eIndex);
}
return ret;
}
}
|
package com.axelby.podax;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import com.axelby.podax.R.drawable;
class PodcastDownloader {
private Context _context;
private boolean _isRunning = false;
PodcastDownloader(Context context) {
_context = context;
}
public void download() {
new Thread(_worker).start();
}
public Runnable _worker = new Runnable() {
public void run() {
if (_isRunning)
return;
if (!PodaxApp.ensureWifi(_context))
return;
Cursor cursor = null;
try {
_isRunning = true;
Uri uri = Uri.withAppendedPath(PodcastProvider.URI, "to_download");
String[] projection = {
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_TITLE,
PodcastProvider.COLUMN_MEDIA_URL,
};
cursor = _context.getContentResolver().query(uri, projection, null, null, null);
while (cursor.moveToNext()) {
InputStream instream = null;
PodcastCursor podcast = new PodcastCursor(_context, cursor);
File mediaFile = new File(podcast.getFilename());
try {
Log.d("Podax", "Downloading " + podcast.getTitle());
updateDownloadNotification(podcast, 0);
URL u = new URL(podcast.getMediaUrl());
HttpURLConnection c = (HttpURLConnection)u.openConnection();
if (mediaFile.exists() && mediaFile.length() > 0)
c.setRequestProperty("Range", "bytes=" + mediaFile.length() + "-");
// response code 206 means partial content and range header worked
boolean append = false;
if (c.getResponseCode() == 206) {
if (c.getContentLength() <= 0) {
podcast.setFileSize(mediaFile.length());
continue;
}
append = true;
}
else {
podcast.setFileSize(c.getContentLength());
}
FileOutputStream outstream = new FileOutputStream(mediaFile, append);
instream = c.getInputStream();
int read;
byte[] b = new byte[1024*64];
while ((read = instream.read(b, 0, b.length)) != -1)
outstream.write(b, 0, read);
instream.close();
outstream.close();
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(podcast.getFilename());
mp.prepare();
podcast.setDuration(mp.getDuration());
mp.release();
Log.d("Podax", "Done downloading " + podcast.getTitle());
} catch (Exception e) {
Log.d("Podax", "Exception while downloading " + podcast.getTitle() + ": " + e.getMessage());
removeDownloadNotification();
try {
if (instream != null)
instream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
break;
}
}
} catch (MissingFieldException e) {
e.printStackTrace();
}
finally {
if (cursor != null)
cursor.close();
removeDownloadNotification();
_isRunning = false;
}
}
};
void updateDownloadNotification(PodcastCursor podcast, long downloaded) throws MissingFieldException {
int icon = drawable.icon;
CharSequence tickerText = "Downloading podcast: " + podcast.getTitle();
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
CharSequence contentTitle = "Downloading Podcast";
CharSequence contentText = podcast.getTitle();
Intent notificationIntent = new Intent(_context, ActiveDownloadListActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, notificationIntent, 0);
notification.setLatestEventInfo(_context, contentTitle, contentText, contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) _context.getSystemService(ns);
notificationManager.notify(Constants.PODCAST_DOWNLOAD_ONGOING, notification);
}
void removeDownloadNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) _context.getSystemService(ns);
notificationManager.cancel(Constants.PODCAST_DOWNLOAD_ONGOING);
}
}
|
package be.kuleuven.cs.distrinet.rejuse.graph;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import be.kuleuven.cs.distrinet.rejuse.java.collections.SafeTransitiveClosure;
/**
* @author Marko van Dooren
*/
public class Node<V> {
/**
* Initialize a new node for the given object.
*
* @param object
* The object that is put in the graph.
*/
/*@
@ public behavior
@
@ pre object != null;
@
@ post getObject() == object;
@ post getEdges().isEmpty();
@*/
public Node(V object) {
_object = object;
_outgoing = new HashSet<>();
_incoming = new HashSet<>();
}
/**
* Return the object of this node.
*/
/*@
@ public behavior
@
@ post \result != null;
@*/
public V object() {
return _object;
}
/**
* The object of this edge.
*/
private V _object;
/**
* Add the given edge to this node.
*
* @param edge
* The edge to be added.
*/
/*@
@ public behavior
@
@ pre edge != null;
@ // The edge must already haven been connected to this node.
@ pre edge.startsIn(this) || edge.endsIn(this)
@
@ post edge.startsIn(this) ==> getStartEdges().contains(edge)
@ post edge.endsIn(this) ==> getEndEdges().contains(edge)
@*/
void addEdge(Edge<V> edge) {
if(edge.startsIn(this)) {
_outgoing.add(edge);
}
if(edge.endsIn(this)) {
_incoming.add(edge);
}
}
/**
* Remove the given edge from this node.
*
* @param edge
* The edge to be removed.
*/
/*@
@ public behavior
@
@ post ! getEdges().contains(edge);
@*/
void removeEdge(Edge<V> edge) {
_outgoing.remove(edge);
_incoming.remove(edge);
}
/**
* Return all edges starting in this node.
*/
/*@
@ public behavior
@
@ post \result != null
@ post ! \result.contains(null);
@ post (\forall Edge e; e != null; \result.contains(e) == e.startsIn(this));
@*/
public Set<Edge<V>> outgoingEdges() {
return ImmutableSet.copyOf(_outgoing);
}
public Set<Edge<V>> outgoingEdges(Node<V> target) {
Set<Edge<V>> result = new HashSet<>();
for(Edge<V> out: _outgoing) {
if(out.opposite(this) == target) {
result.add(out);
}
}
return result;
}
public Edge<V> someOutgoingEdge(Node<V> target) {
for(Edge<V> out: _outgoing) {
if(out.opposite(this) == target) {
return out;
}
}
return null;
}
/**
* Return all edges ending in this node.
*/
/*@
@ public behavior
@
@ post \result != null
@ post ! \result.contains(null);
@ post (\forall Edge e; e != null; \result.contains(e) == e.endsIn(this));
@*/
public Set<Edge<V>> incomingEdges() {
return new HashSet<>(_outgoing);
}
/**
* Return the number of edges starting in this node.
*/
/*@
@ public behavior
@
@ post \result == outgoingEdges().size();
@*/
public int nbOutgoingEdges() {
return _outgoing.size();
}
/**
* Return the number of edges ending in this node.
*/
/*@
@ public behavior
@
@ post \result == incomingEdges().size();
@*/
public int nbIncomingEdges() {
return _incoming.size();
}
/**
* Return all edges connected to this node
*/
/*@
@ public behavior
@
@ post \result != null;
@ post \result.containsAll(getStartEdges());
@ post \result.containsAll(getEndEdges());
@ post (\forall Object o; result.contains(o);
@ getStartEdges().contains(o) || getEndEdges().contains(o));
@*/
public Set<Edge<V>> edges() {
ImmutableSet.Builder<Edge<V>> builder = ImmutableSet.builder();
builder.addAll(_outgoing);
builder.addAll(_incoming);
return builder.build();
}
/**
* Check whether or not this node is a leaf node.
*/
/*@
@ public behavior
@
@ post \result == getStartEdges().isEmpty();
@*/
public boolean isLeaf() {
return _outgoing.isEmpty();
}
/**
* The edges starting in this node.
*/
private Set<Edge<V>> _outgoing;
/**
* The edges ending in this node.
*/
private Set<Edge<V>> _incoming;
/**
* Check whether or not the given node is reachable when starting from this
* node.
*
* @param other
* The node to be reached.
*/
/*@
@ public behavior
@
@ pre node != null;
@*/
public boolean canReach(Node<V> other) {
//TODO inefficient, but it works
return new SafeTransitiveClosure() {
public void addConnectedNodes(Object node, Set acc) {
acc.addAll(((Node)node).directSuccessorNodes());
}
}.closureFromAll(directSuccessorNodes()).contains(other);
}
/*@
@ also public behavior
@
@ post \result.equals(getObject().toString());
@*/
public String toString() {
return _object.toString();
}
public void terminate() {
Set<Edge<V>> incoming = ImmutableSet.copyOf(_incoming);
for(Edge<V> edge: incoming) {
edge.terminate();
}
Set<Edge<V>> outgoing = ImmutableSet.copyOf(_outgoing);
for(Edge<V> edge: outgoing) {
edge.terminate();
}
}
/**
*
* @return
*/
/*@
@ public behavior
@
@ TODO: specs
@*/
public Set<Node<V>> directSuccessorNodes() {
Set<Node<V>> result = new HashSet<>();
for(Edge<V> edge: _outgoing) {
result.add(edge.endFor(this));
}
return result;
}
/**
*
* @return
*/
/*@
@ public behavior
@
@ TODO: specs
@*/
public Set<Node<V>> directPredecessorNodes() {
Set<Node<V>> result = new HashSet<>();
for(Edge<V> edge: _incoming) {
result.add(edge.startFor(this));
}
return result;
}
/**
*
* @return
*/
/*@
@ public behavior
@
@ TODO: specs
@*/
public Set<V> directSuccessors() {
Set<V> result = new HashSet<>();
for(Edge<V> edge: _outgoing) {
result.add(edge.endFor(this).object());
}
return result;
}
/**
*
* @return
*/
/*@
@ public behavior
@
@ TODO: specs
@*/
public Set<V> directPredecessors() {
Set<V> result = new HashSet<>();
for(Edge<V> edge: _incoming) {
result.add(edge.startFor(this).object());
}
return result;
}
/**
* Check whether this node has the given node as a
* direct successor.
*
* @param node The node of which must be determined if it
* is a direct successor of this node.
*/
/*@
@ public behavior
@
@ pre node != null;
@
@ post \result == \exists(Edge<V> e; incomingEdges().contains(e); e.getEndFor(this) == node);
@*/
public boolean hasDirectSuccessor(Node<V> node) {
for(Edge<V> edge: _outgoing) {
if(edge.endFor(this) == node) {
return true;
}
}
return false;
}
/**
* Check whether this node has the given node as a
* direct predecessor.
*
* @param node The node of which must be determined if it
* is a direct predecessor of this node.
*/
/*@
@ public behavior
@
@ pre node != null;
@
@ post \result == \exists(Edge<V> e; outgoingEdges().contains(e); e.getEndFor(this) == node);
@*/
public boolean hasDirectPredecessor(Node<V> node) {
for(Edge<V> edge: _outgoing) {
if(edge.startFor(this) == node) {
return true;
}
}
return false;
}
/**
* Return the edges that directly connect this node to the
* given node. If no such edge exists, null is returned.
* @param node
* @return
*/
public List<Edge<V>> directlySuccessorEdges(Node<V> node) {
List<Edge<V>> result = new ArrayList<>();
for(Edge<V> edge: _outgoing) {
if(edge.endFor(this) == node) {
result.add(edge);
}
}
return result;
}
public Node<V> bareClone() {
return new Node<V>(object());
}
}
|
package com.brein.time.utils;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class TimeTruncater {
private static final ZoneId UTC = ZoneId.of("UTC");
/**
* Truncates the passed time-stamp to the first of the month information only, i.e., the 09/10/2016 00:14:43 will be
* truncated to 01/10/2016 00:00:00.
*
* @param unixTimeStamp the time-stamp to be truncated
*
* @return the date information only
*/
public static long toMonth(final long unixTimeStamp) {
final Instant instant = Instant.ofEpochSecond(unixTimeStamp);
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, UTC);
return zonedDateTime.withDayOfMonth(1)
.with(LocalTime.of(0, 0))
.toEpochSecond();
}
/**
* Truncates the passed time-stamp to the date information only, i.e., the 09/10/2016 00:14:43 will be truncated to
* 09/10/2016 00:00:00.
*
* @param unixTimeStamp the time-stamp to be truncated
*
* @return the date information only
*/
public static long toDay(final long unixTimeStamp) {
final Instant instant = Instant.ofEpochSecond(unixTimeStamp);
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, UTC);
return zonedDateTime.with(LocalTime.of(0, 0)).toEpochSecond();
}
/**
* Truncates the minute and second from the passed time-stamp, i.e., the 09/10/2016 02:14:43 will be truncated to
* 09/10/2016 02:00:00.
*
* @param unixTimeStamp the time-stamp to be truncated
*
* @return the truncated time-stamp
*/
public static long toHour(final long unixTimeStamp) {
final Instant instant = Instant.ofEpochSecond(unixTimeStamp);
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, UTC);
return zonedDateTime.with(LocalTime.of(zonedDateTime.getHour(), 0)).toEpochSecond();
}
/**
* Truncates the second from the passed time-stamp, i.e., the 09/10/2016 02:14:43 will be truncated to
* 09/10/2016 02:14:00.
*
* @param unixTimeStamp the time-stamp to be truncated
*
* @return the truncated time-stamp
*/
public static long toMinute(final long unixTimeStamp) {
final Instant instant = Instant.ofEpochSecond(unixTimeStamp);
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, UTC);
return zonedDateTime.with(LocalTime.of(zonedDateTime.getHour(), zonedDateTime.getMinute())).toEpochSecond();
}
}
|
package ch.ntb.inf.deep.eclipse.ui.view;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import ch.ntb.inf.deep.eclipse.ui.model.MemorySegment;
import ch.ntb.inf.deep.loader.Downloader;
import ch.ntb.inf.deep.loader.DownloaderException;
import ch.ntb.inf.deep.loader.UsbMpc555Loader;
public class MemoryView extends ViewPart implements Listener {
public static final String ID = "ch.ntb.inf.deep.eclipse.ui.view.MemoryView";
private TableViewer viewer;
private Text addr;
private Text count;
private Button button;
private Downloader bdi;
static final byte slotSize = 4; // 4 bytes
static {
assert (slotSize & (slotSize - 1)) == 0; // assert: slotSize == power of
}
class ViewLabelProvider extends LabelProvider implements
ITableLabelProvider {
public String getColumnText(Object obj, int index) {
switch (index) {
case 0:
if (((MemorySegment) obj).addr == -1) {
return "";
}
return String.format("0x%08X",((MemorySegment) obj).addr);
case 1:
if (((MemorySegment) obj).addr == -1) {
return "";
}
return String.format("0x%08X", ((MemorySegment) obj).value);
default:
throw new RuntimeException("Should not happen");
}
}
public Image getColumnImage(Object obj, int index) {
return null;
}
}
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(5, false);
parent.setLayout(layout);
Label label = new Label(parent, SWT.NONE);
label.setText("start address: ");
addr = new Text(parent, SWT.BORDER);
addr.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = addr.getText() + e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
if (chars[0] == '0' && chars.length > 1) {// hex value
if ((chars[1] == 'x' || chars[1] == 'X')) {
if (chars.length > 2) {
for (int i = 2; i < chars.length; i++) {
if (!(('0' <= chars[i] && chars[i] <= '9')
|| ('A' <= chars[i] && chars[i] <= 'F') || ('a' <= chars[i] && chars[i] <= 'f'))) {
e.doit = false;
return;
}
}
}
} else {
e.doit = false;
return;
}
} else {
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
}
});
Label label2 = new Label(parent, SWT.NONE);
label2.setText("nofWords: ");
count = new Text(parent, SWT.BORDER);
count.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = addr.getText() + e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
if (chars[0] == '0' && chars.length > 1) {// hex value
if ((chars[1] == 'x' || chars[1] == 'X')) {
if (chars.length > 2) {
for (int i = 2; i < chars.length; i++) {
if (!(('0' <= chars[i] && chars[i] <= '9')
|| ('A' <= chars[i] && chars[i] <= 'F') || ('a' <= chars[i] && chars[i] <= 'f'))) {
e.doit = false;
return;
}
}
}
} else {
e.doit = false;
return;
}
} else {
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
}
});
button = new Button(parent, SWT.PUSH);
button.setText("read");
button.addListener(SWT.Selection, this);
createViewer(parent);
}
private void createViewer(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
String[] titels = { "Address", "Value" };
int[] bounds = { 60, 230 };
for (int i = 0; i < titels.length; i++) {
TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[i]);
column.getColumn().setWidth(bounds[i]);
column.getColumn().setMoveable(false);
}
Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
// create the cell editors
CellEditor[] editors = new CellEditor[2];
editors[1] = new TextCellEditor(table);
viewer.setColumnProperties(titels);
viewer.setCellEditors(editors);
viewer.setCellModifier(new MemoryCellModifier(viewer));
viewer.setContentProvider(new ArrayContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
// Get the content for the viewer, setInput will call getElements in the
// contentProvider
viewer.setInput(new MemorySegment[] { new MemorySegment(),
new MemorySegment(), new MemorySegment() });// TODO fill Array
// into
// Layout the viewer
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 5;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
}
@Override
public void setFocus() {
viewer.getControl().setFocus();
}
@Override
public void handleEvent(Event event) {
if (event.widget.equals(button)) {
int startAddr = 0;
int size = 0;
String addrStr = addr.getText();
String countStr = count.getText();
//work around for problem when in hex-int-number the most significant bit is set;
//once for the start addres
if(addrStr.charAt(0) == '0' && addrStr.length() > 9 && addrStr.charAt(2) > '7'){
String most = addrStr.substring(2, 3);
addrStr = "0x0" + addrStr.substring(3);
startAddr = (Integer.parseInt(most,16) << 28) |Integer.decode(addrStr);
}else{
startAddr = Integer.decode(addr.getText());
}
//once for the size
if(countStr.charAt(0) == '0' && countStr.length() > 9 && countStr.charAt(2) > '7'){
String most = countStr.substring(2, 3);
countStr = "0x0" + countStr.substring(3);
size = (Integer.parseInt(most,16) << 28) |Integer.decode(countStr);
}else{
size = Integer.decode(count.getText());
}
if (bdi == null) {
bdi = UsbMpc555Loader.getInstance();
}
if(bdi.isConnected()){//reopen
bdi.closeConnection();
try {
bdi.openConnection();
} catch (DownloaderException e) {
e.printStackTrace();
}
}
if (size > 0) {
MemorySegment[] segs = new MemorySegment[size];
try {
boolean wasFreezeAsserted = bdi.isFreezeAsserted();
if (!wasFreezeAsserted) {
bdi.stopTarget();
}
for (int i = 0; i < size; i++) {
segs[i] = new MemorySegment(startAddr + i * 4, bdi
.getMem(startAddr + i * 4, 4));
}
if (!wasFreezeAsserted) {
bdi.startTarget();
}
} catch (DownloaderException e1) {
e1.printStackTrace();
}
viewer.setInput(segs);
viewer.refresh();
}
}
}
/**
* This class represents the cell modifier for the Memory View
*/
class MemoryCellModifier implements ICellModifier {
private Viewer viewer;
public MemoryCellModifier(Viewer viewer) {
this.viewer = viewer;
}
/**
* Returns whether the property can be modified
*
* @param element
* the element
* @param property
* the property
* @return boolean
*/
public boolean canModify(Object element, String property) {
MemorySegment p = (MemorySegment)element;
if (p.addr > -1 && property.equals("Value")) {
return true;
}
return false;
}
/**
* Returns the value for the property
*
* @param element
* the element
* @param property
* the property
* @return Object
*/
public Object getValue(Object element, String property) {
MemorySegment p = (MemorySegment) element;
if ("Value".equals(property))
return String.format("0x%08X",p.value);
else if ("Address".equals(property))
return String.format("0x%08X",p.addr);
else
return null;
}
/**
* Modifies the element
*
* @param element
* the element
* @param property
* the property
* @param value
* the value
*/
public void modify(Object element, String property, Object value) {
if (element instanceof Item)
element = ((Item) element).getData();
MemorySegment p = (MemorySegment) element;
if ("Value".equals(property)){
try{
p.value =Integer.decode((String) value);
if(bdi == null){
bdi = UsbMpc555Loader.getInstance();
}
boolean wasFreezeAsserted = bdi.isFreezeAsserted();
if(!wasFreezeAsserted){
bdi.stopTarget();
}
bdi.setMem(p.addr, p.value, slotSize);
if(!wasFreezeAsserted){
bdi.startTarget();
}
}catch (NumberFormatException e) {
}catch (DownloaderException e1){
e1.printStackTrace();
}
// Force the viewer to refresh
viewer.refresh();
}
}
}
}
|
package ch.unizh.ini.jaer.projects.npp;
import com.jogamp.opengl.GL;
import java.awt.Font;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;
import gnu.io.NRSerialPort;
import java.io.File;
import java.io.InputStream;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.tracking.RectangularClusterTracker;
import net.sf.jaer.eventprocessing.tracking.RectangularClusterTracker.Cluster;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
import net.sf.jaer.util.SoundWavFilePlayer;
import net.sf.jaer.util.SpikeSound;
/**
* Extends DavisClassifierCNNProcessor to add annotation graphics to show
* RoShamBo demo output for development of rock-scissors-paper robot
*
* @author Tobi
*/
@Description("Displays RoShamBo (rock-scissors-paper) CNN results; subclass of DavisDeepLearnCnnProcessor")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class RoShamBoCNN extends DavisClassifierCNNProcessor {
private boolean showAnalogDecisionOutput = getBoolean("showAnalogDecisionOutput", false);
private boolean showSymbol = getBoolean("showSymbol", true);
protected Statistics statistics = new Statistics();
protected float decisionLowPassMixingFactor = getFloat("decisionLowPassMixingFactor", 1f);
private SpikeSound spikeSound = null;
// for arduino robot (code in F:\Dropbox\NPP roshambo robot training data\arduino\RoShamBoHandControl)
NRSerialPort serialPort = null;
private String serialPortName = getString("serialPortName", "COM3");
private boolean serialPortCommandsEnabled = getBoolean("serialPortCommandsEnabled", false);
private int serialBaudRate = getInt("serialBaudRate", 115200);
private DataOutputStream serialPortOutputStream = null;
private Enumeration portList = null;
private boolean playSounds = getBoolean("playSounds", false);
private int playSoundsMinIntervalMs = getInt("playSoundsMinIntervalMs", 1000);
private float decisionThresholdActivation = getFloat("decisionThresholdActivation", .7f);
private SoundPlayer soundPlayer = null;
protected boolean playToWin = getBoolean("playToWin", true);
private boolean addedStatisticsListener = false;
/**
* for game state machine
*/
private volatile boolean useGameStatesToPlay = getBoolean("useGameStatesToPlay", false);
private RectangularClusterTracker tracker = null;
private float trackerUpperEdgeThreshold = getFloat("trackerUpperEdgeThreshold", .7f);
private float trackerLowerEdgeThreshold = getFloat("trackerLowerEdgeThreshold", .3f);
private int throwIntervalTimeoutMs = getInt("throwIntervalTimeoutMs", 2000);
private int winningSymbolShowTimeMs = getInt("winningSymbolShowTimeMs", 4000);
public enum GameState {
Idle, Throw1, Throw2, ThrowShow
};
private GameState gameState = GameState.Idle;
private long gameStateUpdateTimeMs;
public enum HandTrackerState {
Idle, CrossedUpper, CrossedLower
};
private HandTrackerState handTrackerState = HandTrackerState.Idle;
private long handTrackerStateUpdateTimeMs;
/**
* output units
*/
protected static final int DECISION_PAPER = 0, DECISION_SCISSORS = 1, DECISION_ROCK = 2, DECISION_BACKGROUND = 3;
protected static final String[] DECISION_STRINGS = {"Paper", "Scissors", "Rock", "Background"};
protected boolean showDecisionStatistics = getBoolean("showDecisionStatistics", true);
/**
* Symbols
*/
private Texture[] symbolTextures = null;
public RoShamBoCNN(AEChip chip) {
super(chip);
tracker = new RectangularClusterTracker(chip);
tracker.setMaxNumClusters(1);
tracker.setClusterMassDecayTauUs(100000);
tracker.setEnableClusterExitPurging(false);
getEnclosedFilterChain().add(tracker); // super chain alredy has DvsFramer
setEnclosedFilterChain(getEnclosedFilterChain()); // to correctly set enclosed status of filters
String roshamboGame = "0a. RoShamBo Game";
setPropertyTooltip(roshamboGame, "trackerUpperEdgeThreshold", "Upper (higher) edge of scene as fraction of image which the tracker must pass to start detecting a throw");
setPropertyTooltip(roshamboGame, "trackerLowerEdgeThreshold", "Lower edge of scene as fraction of image which the tracker must pass to finish detecting a throw");
setPropertyTooltip(roshamboGame, "tracker2EdgeCrossingTimeoutMs", "The tracker must cross the two edges within this time to be classified as a throw");
setPropertyTooltip(roshamboGame, "throwIntervalTimeoutMs", "Throws must follow each other within this time or the game will go back to idle state");
setPropertyTooltip(roshamboGame, "winningSymbolShowTimeMs", "How long the winning symbol is shown by the hand");
setPropertyTooltip(roshamboGame, "useGameStatesToPlay", "Select to use the Roshambo state machine; if unselected, then instantaneous (filtered by mixing factor) CNN output is used");
String roshambo = "0b. RoShamBo Engine";
setPropertyTooltip(roshambo, "showAnalogDecisionOutput", "Shows face detection as analog activation of face unit in softmax of network output");
setPropertyTooltip(roshambo, "decisionLowPassMixingFactor", "The softmax outputs of the CNN are low pass filtered using this mixing factor; reduce decisionLowPassMixingFactor to filter more decisions");
setPropertyTooltip(roshambo, "playSpikeSounds", "Play a spike sound on change of network output decision");
setPropertyTooltip(roshambo, "serialPortName", "Name of serial port to send robot commands to");
setPropertyTooltip(roshambo, "serialPortCommandsEnabled", "Send commands to serial port for Arduino Nano hand robot");
setPropertyTooltip(roshambo, "serialBaudRate", "Baud rate (default 115200), upper limit 12000000");
setPropertyTooltip(roshambo, "playSounds", "Play sound effects (Rock/Scissors/Paper) every time the decision changes and playSoundsMinIntervalMs has intervened");
setPropertyTooltip(roshambo, "playSoundsMinIntervalMs", "Minimum time inteval for playing sound effects in ms");
setPropertyTooltip(roshambo, "decisionThresholdActivation", "Minimum winner activation to activate hand or play a sound");
setPropertyTooltip(roshambo, "showDecisionStatistics", "Displays statistics of decisions");
setPropertyTooltip(roshambo, "playToWin", "If selected, symbol showsn and sent to hand will beat human; if unselected, it ties the human");
setPropertyTooltip(roshambo, "showSymbol", "If selected, symbol is displayed as overlay, either the one recognized or the winner, depending on playToWin");
dvsFramer.setRectifyPolarities(true);
dvsFramer.setNormalizeDVSForZsNullhop(true); // to make it work out of the box
if (apsDvsNet != null) {
apsDvsNet.getSupport().addPropertyChangeListener(AbstractDavisCNN.EVENT_MADE_DECISION, statistics);
}
}
@Override
protected void loadNetwork(File f) throws Exception {
super.loadNetwork(f);
if (apsDvsNet != null) {
apsDvsNet.getSupport().addPropertyChangeListener(AbstractDavisCNN.EVENT_MADE_DECISION, statistics);
}
}
@Override
public synchronized EventPacket<?> filterPacket(EventPacket<?> in) {
EventPacket out = super.filterPacket(in);
if (apsDvsNet == null) {
showWarningDialogInSwingThread("null CNN, load a valid CNN and re-enable filter", "No CNN loaded");
setFilterEnabled(false);
return in;
}
if (!addedStatisticsListener) {
apsDvsNet.getSupport().addPropertyChangeListener(AbstractDavisCNN.EVENT_MADE_DECISION, statistics);
addedStatisticsListener = true;
}
out = getEnclosedFilterChain().filterPacket(out); // compute tracker always, since we use it to move the texture around a bit
if (useGameStatesToPlay) {
if (tracker.getVisibleClusters().size() > 0) {
RectangularClusterTracker.Cluster handCluster = tracker.getVisibleClusters().getFirst();
boolean crossedUpper = false, crossedLower = false;
int handlasty = (int) Math.round(handCluster.getLastPacketLocation().getY());
int handy = (int) Math.round(handCluster.getLocation().getY());
int upperthreshold = (int) (trackerUpperEdgeThreshold * chip.getSizeY());
int lowerthreshold = (int) (trackerLowerEdgeThreshold * chip.getSizeY());
if (handlasty > upperthreshold && handy < upperthreshold) {
crossedUpper = true;
}
if (handlasty > lowerthreshold && handy < lowerthreshold) {
crossedLower = true;
}
if (System.currentTimeMillis() - handTrackerStateUpdateTimeMs > throwIntervalTimeoutMs) {
handTrackerState = handTrackerState.Idle;
}
switch (handTrackerState) {
case Idle:
if (crossedUpper) {
handTrackerState = HandTrackerState.CrossedUpper;
handTrackerStateUpdateTimeMs = System.currentTimeMillis();
}
break;
case CrossedUpper:
if (crossedLower) {
handTrackerState = HandTrackerState.CrossedLower;
handTrackerStateUpdateTimeMs = System.currentTimeMillis();
}
break;
case CrossedLower:
handTrackerState = HandTrackerState.Idle;
handTrackerStateUpdateTimeMs = System.currentTimeMillis();
}
}
switch (gameState) {
case Idle:
if (handTrackerState == HandTrackerState.CrossedLower) {
gameState = GameState.Throw1;
twitch();
gameStateUpdateTimeMs = System.currentTimeMillis();
}
break;
case Throw1:
if (System.currentTimeMillis() - gameStateUpdateTimeMs > throwIntervalTimeoutMs) {
gameState = GameState.Idle;
break;
}
if (handTrackerState == HandTrackerState.CrossedLower) {
gameState = GameState.Throw2;
twitch();
gameStateUpdateTimeMs = System.currentTimeMillis();
}
break;
case Throw2:
if (System.currentTimeMillis() - gameStateUpdateTimeMs > throwIntervalTimeoutMs) {
gameState = GameState.Idle;
break;
}
if (handTrackerState == HandTrackerState.CrossedLower) { // only cross upper to show
gameState = GameState.ThrowShow;
sendDecisionToHand();
gameStateUpdateTimeMs = System.currentTimeMillis();
}
break;
case ThrowShow:
if (System.currentTimeMillis() - gameStateUpdateTimeMs > winningSymbolShowTimeMs) {
gameState = GameState.Idle;
}
}
} else {
sendDecisionToHand();
}
return out;
}
private void twitch() {
sendCommandToHand('6');
}
/**
* commands to physical hand and light box as defined in arduino code
*/
private final int HAND_CMD_PAPER = 1, HAND_CMD_SCISSORS = 2, HAND_CMD_ROCK = 3, HAND_CMD_SLOWLY_WIGGLE = 4, HAND_CMD_TURN_OFF = 5, HAND_CMD_TWITCH = 6;
/**
* Hand firmware has option WIN that programs it to show the symbol that
* beats the symbol sent to it, e.g. if HAND_CMD_ROCK is sent, hand will
* show PAPER.
*/
private final boolean HAND_PROGRAMED_TO_WIN = true;
private void sendDecisionToHand() {
if (!serialPortCommandsEnabled || statistics.maxActivation < decisionThresholdActivation) {
return;
}
char cmd = 0;
if (!HAND_PROGRAMED_TO_WIN) {
switch (statistics.symbolOutput) { // this is symbol shown on screen
case DECISION_ROCK:
cmd = '0' + HAND_CMD_ROCK;
break;
case DECISION_SCISSORS:
cmd = '0' + HAND_CMD_SCISSORS;
break;
case DECISION_PAPER:
cmd = '0' + HAND_CMD_PAPER;
break;
case DECISION_BACKGROUND:
cmd = '0' + HAND_CMD_SLOWLY_WIGGLE;
break;
default:
// log.warning("maxUnit=" + statistics.descision + " is not a valid network output state");
}
} else {
switch (statistics.symbolOutput) {
case DECISION_ROCK:
cmd = '0' + HAND_CMD_SCISSORS;
break;
case DECISION_SCISSORS:
cmd = '0' + HAND_CMD_PAPER;
break;
case DECISION_PAPER:
cmd = '0' + HAND_CMD_ROCK;
break;
case DECISION_BACKGROUND:
cmd = '0' + HAND_CMD_SLOWLY_WIGGLE;
break;
default:
// log.warning("maxUnit=" + statistics.descision + " is not a valid network output state");
}
}
sendCommandToHand(cmd);
}
private void sendCommandToHand(char cmd) {
if (serialPortCommandsEnabled && (serialPortOutputStream != null)) {
try {
serialPortOutputStream.write((byte) cmd);
} catch (IOException ex) {
log.warning(ex.toString());
}
}
}
@Override
public void resetFilter() {
super.resetFilter();
statistics.reset();
gameState = GameState.Idle;
handTrackerState = HandTrackerState.Idle;
}
private void loadAndBindSymbolTextures(GL2 gl) {
try {
Texture[] textures = new Texture[3];
InputStream is;
is = RoShamBoCNN.class.getResourceAsStream("rock.png");
textures[DECISION_ROCK] = TextureIO.newTexture(is, false, "png");
is = RoShamBoCNN.class.getResourceAsStream("scissors.png");
textures[DECISION_SCISSORS] = TextureIO.newTexture(is, false, "png");
is = RoShamBoCNN.class.getResourceAsStream("paper.png");
textures[DECISION_PAPER] = TextureIO.newTexture(is, false, "png");
symbolTextures = textures;
// for (Texture texture : textures) {
// texture.enable(gl);
} catch (Exception e) {
log.warning("couldn't load symbol textures: " + e.toString());
}
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
chip.getAeViewer().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, statistics);
super.setFilterEnabled(yes);
if (!yes) {
closeSerial();
} else {
try {
openSerial();
} catch (Exception ex) {
log.warning("caught exception enabling serial port when filter was enabled: " + ex.toString());
}
}
}
@Override
public void annotate(GLAutoDrawable drawable) {
tracker.setAnnotationEnabled(false);
super.annotate(drawable);
GL2 gl = drawable.getGL().getGL2();
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 72), true, false);
}
checkBlend(gl);
if ((apsDvsNet != null) && (apsDvsNet.getOutputLayer() != null) && (apsDvsNet.getOutputLayer().getActivations() != null)) {
showRoshamboDescision(drawable);
}
if (showDecisionStatistics) {
statistics.draw(gl);
}
if (useGameStatesToPlay) {
int upperthreshold = (int) (trackerUpperEdgeThreshold * chip.getSizeY());
int lowerthreshold = (int) (trackerLowerEdgeThreshold * chip.getSizeY());
gl.glPushMatrix();
gl.glColor3f(.25f, .25f, .25f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, upperthreshold);
gl.glVertex2f(chip.getSizeX(), upperthreshold);
gl.glVertex2f(0, lowerthreshold);
gl.glVertex2f(chip.getSizeX(), lowerthreshold);
gl.glEnd();
String s = gameState.toString() + " " + handTrackerState.toString();
textRenderer.setColor(1, 1, 1, 1);
textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
Rectangle2D r = textRenderer.getBounds(s);
textRenderer.draw(s, (drawable.getSurfaceWidth() / 2) - ((int) r.getWidth() / 2), (int) (0.75f * drawable.getSurfaceHeight()));
textRenderer.endRendering();
gl.glPopMatrix();
}
if (playSounds && isShowOutputAsBarChart()) {
gl.glColor3f(.5f, 0, 0);
gl.glBegin(GL.GL_LINES);
final float h = decisionThresholdActivation * DavisCNNPureJava.HISTOGRAM_HEIGHT_FRACTION * chip.getSizeY();
gl.glVertex2f(0, h);
gl.glVertex2f(chip.getSizeX(), h);
gl.glEnd();
}
}
private void showRoshamboDescision(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
if (playSounds && statistics.symbolDetected >= 0 && statistics.symbolDetected < 3 && statistics.maxActivation > decisionThresholdActivation) {
if (soundPlayer == null) {
soundPlayer = new SoundPlayer();
}
soundPlayer.playSound(statistics.symbolOutput);
}
if (!showSymbol) {
return;
}
if (statistics.maxActivation > decisionThresholdActivation) {
if (symbolTextures == null) {
loadAndBindSymbolTextures(gl);
}
drawSymbolOverlay(drawable, statistics.symbolOutput);
}
// float brightness = 0.0f;
// if (showAnalogDecisionOutput) {
// brightness = statistics.maxActivation; // brightness scale
// } else {
// brightness = 1;
// gl.glColor3f(0.0f, brightness, brightness);
// gl.glPushMatrix();
// gl.glTranslatef(chip.getSizeX() / 2, chip.getSizeY() / 2, 0);
// textRenderer.setColor(brightness, brightness, brightness, 1);
// textRenderer.beginRendering(width, height);
// if ((statistics.symbolDetected >= 0) && (statistics.symbolDetected < DECISION_STRINGS.length)) {
// Rectangle2D r = textRenderer.getBounds(DECISION_STRINGS[statistics.symbolDetected]);
// String decisionString = DECISION_STRINGS[statistics.symbolDetected];
// if (apsDvsNet.getLabels() != null && apsDvsNet.getLabels().size() > 0) {
// decisionString = apsDvsNet.getLabels().get(statistics.symbolDetected);
// textRenderer.draw(decisionString, (width / 2) - ((int) r.getWidth() / 2), height / 2);
// textRenderer.endRendering();
// gl.glPopMatrix();
}
private void drawSymbolOverlay(GLAutoDrawable drawable, int symbolID) {
GL2 gl = drawable.getGL().getGL2();
if (symbolTextures == null || symbolID < 0 || symbolID >= symbolTextures.length || symbolTextures[symbolID] == null) {
return;
}
int left = 10, bot = 10, offset = 0;
final int w = chip.getSizeX() / 2, h = chip.getSizeY() / 2, sw = drawable.getSurfaceWidth(), sh = drawable.getSurfaceHeight();
if (tracker.getNumVisibleClusters() > 0) {
Cluster hand = tracker.getVisibleClusters().getFirst();
offset = (int) ((float) hand.getLocation().y / 5);
}
symbolTextures[symbolID].bind(gl);
symbolTextures[symbolID].enable(gl);
drawPolygon(gl, left, bot + offset, w, h);
symbolTextures[symbolID].disable(gl);
String s = playToWin ? "Playing to win" : "Playing to tie";
textRenderer.setColor(.75f, 0.75f, 0.75f, 1);
textRenderer.begin3DRendering();
Rectangle2D r = textRenderer.getBounds(s);
textRenderer.draw3D(s, left, bot, 0, (float) w / sw);
textRenderer.end3DRendering();
}
private void drawPolygon(final GL2 gl, final int xLowerLeft, final int yLowerLeft, final int width, final int height) {
gl.glPushMatrix();
gl.glDisable(GL.GL_DEPTH_TEST);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL.GL_BLEND);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
final double xRatio = (double) chip.getSizeX() / (double) width;
final double yRatio = (double) chip.getSizeY() / (double) height;
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(0, 0);
gl.glVertex2d(xLowerLeft, yLowerLeft);
gl.glTexCoord2d(xRatio, 0);
gl.glVertex2d(xRatio * width + xLowerLeft, yLowerLeft);
gl.glTexCoord2d(xRatio, yRatio);
gl.glVertex2d(xRatio * width + xLowerLeft, yRatio * height + yLowerLeft);
gl.glTexCoord2d(0, yRatio);
gl.glVertex2d(+xLowerLeft, yRatio * height + yLowerLeft);
gl.glEnd();
gl.glPopMatrix();
}
/**
* @return the showAnalogDecisionOutput
*/
public boolean isShowAnalogDecisionOutput() {
return showAnalogDecisionOutput;
}
/**
* @param showAnalogDecisionOutput the showAnalogDecisionOutput to set
*/
public void setShowAnalogDecisionOutput(boolean showAnalogDecisionOutput) {
this.showAnalogDecisionOutput = showAnalogDecisionOutput;
putBoolean("showAnalogDecisionOutput", showAnalogDecisionOutput);
}
/**
* @return the decisionLowPassMixingFactor
*/
public float getDecisionLowPassMixingFactor() {
return decisionLowPassMixingFactor;
}
/**
* @param decisionLowPassMixingFactor the decisionLowPassMixingFactor to set
*/
public void setDecisionLowPassMixingFactor(float decisionLowPassMixingFactor) {
if (decisionLowPassMixingFactor > 1) {
decisionLowPassMixingFactor = 1;
}
this.decisionLowPassMixingFactor = decisionLowPassMixingFactor;
putFloat("decisionLowPassMixingFactor", decisionLowPassMixingFactor);
}
/**
* @return the serialPortName
*/
public String getSerialPortName() {
return serialPortName;
}
/**
* @param serialPortName the serialPortName to set
*/
public void setSerialPortName(String serialPortName) {
try {
this.serialPortName = serialPortName;
putString("serialPortName", serialPortName);
openSerial();
} catch (IOException ex) {
Logger.getLogger(RoShamBoCNN.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @return the serialPortCommandsEnabled
*/
public boolean isSerialPortCommandsEnabled() {
return serialPortCommandsEnabled;
}
/**
* @param serialPortCommandsEnabled the serialPortCommandsEnabled to set
*/
public void setSerialPortCommandsEnabled(boolean serialPortCommandsEnabled) {
this.serialPortCommandsEnabled = serialPortCommandsEnabled;
putBoolean("serialPortCommandsEnabled", serialPortCommandsEnabled);
if (!isFilterEnabled()) {
return;
}
if (!serialPortCommandsEnabled) {
closeSerial();
return;
}
// come here to open port
try {
openSerial();
} catch (IOException e) {
log.warning("caught exception on serial port " + serialPortName + ": " + e.toString());
}
}
private void openSerial() throws IOException {
if (!isSerialPortCommandsEnabled()) {
return;
}
if (serialPort != null) {
closeSerial();
}
StringBuilder sb = new StringBuilder("List of all available serial ports: ");
final Set<String> availableSerialPorts = NRSerialPort.getAvailableSerialPorts();
if (availableSerialPorts.isEmpty()) {
sb.append("\nNo ports found, sorry. If you are on linux, serial port support may suffer");
} else {
for (String s : availableSerialPorts) {
sb.append(s).append(" ");
}
}
log.info(sb.toString());
if (!availableSerialPorts.contains(serialPortName)) {
log.warning(serialPortName + " is not in avaiable " + sb.toString());
return;
}
serialPort = new NRSerialPort(serialPortName, serialBaudRate);
if (serialPort == null) {
log.warning("null serial port returned when trying to open " + serialPortName + "; available " + sb.toString());
return;
}
serialPort.connect();
serialPortOutputStream = new DataOutputStream(serialPort.getOutputStream());
log.info("opened serial port " + serialPortName + " with baud rate=" + serialBaudRate);
}
private void closeSerial() {
if (serialPortOutputStream != null) {
try {
serialPortOutputStream.write((byte) '0'); // rest; turn off servos
serialPortOutputStream.close();
} catch (IOException ex) {
Logger.getLogger(RoShamBoCNN.class.getName()).log(Level.SEVERE, null, ex);
}
serialPortOutputStream = null;
}
if ((serialPort != null) && serialPort.isConnected()) {
serialPort.disconnect();
serialPort = null;
}
// log.info("closed serial port");
}
/**
* @return the serialBaudRate
*/
public int getSerialBaudRate() {
return serialBaudRate;
}
/**
* @param serialBaudRate the serialBaudRate to set
*/
public void setSerialBaudRate(int serialBaudRate) {
try {
this.serialBaudRate = serialBaudRate;
putInt("serialBaudRate", serialBaudRate);
openSerial();
} catch (IOException ex) {
Logger.getLogger(RoShamBoCNN.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @return the playSounds
*/
public boolean isPlaySounds() {
return playSounds;
}
/**
* @param playSounds the playSounds to set
*/
public void setPlaySounds(boolean playSounds) {
boolean old = this.playSounds;
this.playSounds = playSounds;
putBoolean("playSounds", playSounds);
getSupport().firePropertyChange("playSounds", old, this.playSounds); // in case disabled by error loading file
}
protected class Statistics implements PropertyChangeListener {
protected final int INITIAL_NUM_CLASSES = 4;
protected int totalCount;
protected int[] decisionCounts = new int[INITIAL_NUM_CLASSES];
protected float[] lowpassFilteredOutputUnits = new float[INITIAL_NUM_CLASSES];
protected final int HISTORY_LENGTH = 10;
protected int[] decisionHistory = new int[HISTORY_LENGTH];
protected float maxActivation = Float.NEGATIVE_INFINITY;
protected int symbolDetected = -1;
protected int symbolOutput = -1;
protected boolean outputChanged = false;
public Statistics() {
reset();
}
protected void reset() {
totalCount = 0;
Arrays.fill(decisionCounts, 0);
Arrays.fill(lowpassFilteredOutputUnits, 0);
}
@Override
public String toString() {
if (totalCount == 0) {
return "Error: no samples yet";
}
StringBuilder sb = new StringBuilder("Decision statistics: ");
try {
for (int i = 0; i < INITIAL_NUM_CLASSES; i++) {
sb.append(String.format(" %s: %d (%.1f%%) \n", DECISION_STRINGS[i], decisionCounts[i], (100 * (float) decisionCounts[i]) / totalCount));
}
} catch (ArrayIndexOutOfBoundsException e) {
sb.append(" out of bounds exception; did you load valid CNN?");
}
return sb.toString();
}
protected void computeOutputSymbol() {
if (!playToWin) {
symbolOutput = symbolDetected;
} else { // beat human
switch (statistics.symbolDetected) {
case DECISION_ROCK:
symbolOutput = DECISION_PAPER;
break;
case DECISION_SCISSORS:
symbolOutput = DECISION_ROCK;
break;
case DECISION_PAPER:
symbolOutput = DECISION_SCISSORS;
break;
case DECISION_BACKGROUND:
default:
symbolOutput = DECISION_BACKGROUND;
break;
}
}
}
@Override
public synchronized void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == AbstractDavisCNN.EVENT_MADE_DECISION) {
processDecision(evt);
} else if (evt.getPropertyName() == AEViewer.EVENT_FILEOPEN) {
reset();
}
}
protected void processDecision(PropertyChangeEvent evt) {
int lastOutput = symbolDetected;
AbstractDavisCNN net = (AbstractDavisCNN) evt.getNewValue();
if (net.getOutputLayer().getActivations().length != 4) {
return; // do nothing with this decision since it was from RoshamboIncremental
}
maxActivation = Float.NEGATIVE_INFINITY;
symbolDetected = -1;
try {
for (int i = 0; i < net.getOutputLayer().getActivations().length; i++) {
float output = net.getOutputLayer().getActivations()[i];
lowpassFilteredOutputUnits[i] = ((1 - decisionLowPassMixingFactor) * lowpassFilteredOutputUnits[i]) + (output * decisionLowPassMixingFactor);
if (lowpassFilteredOutputUnits[i] > maxActivation) {
maxActivation = lowpassFilteredOutputUnits[i];
symbolDetected = i;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
log.warning("Array index out of bounds in rendering output. Did you load a valid CNN with 4 output units?");
return;
}
if (symbolDetected < 0) {
log.warning("negative descision, network must not have run correctly");
return;
}
decisionCounts[symbolDetected]++;
totalCount++;
if ((symbolDetected != lastOutput)) {
// CNN output changed, respond here
outputChanged = true;
} else {
outputChanged = false;
}
computeOutputSymbol();
}
protected void draw(GL2 gl) {
MultilineAnnotationTextRenderer.resetToYPositionPixels(.8f * chip.getSizeY());
MultilineAnnotationTextRenderer.renderMultilineString(toString());
}
}
private class SoundPlayer {
private String[] soundFiles = {"paper.wav", "scissors.wav", "rock.wav"};
private long lastTimePlayed = Integer.MIN_VALUE, lastSymbolPlayed = -1, lastInput = -1;
private SoundWavFilePlayer[] soundPlayers = new SoundWavFilePlayer[soundFiles.length];
private String path = "/eu/visualize/ini/convnet/resources/";
public SoundPlayer() {
for (int i = 0; i < soundPlayers.length; i++) {
try {
soundPlayers[i] = new SoundWavFilePlayer(path + soundFiles[i]);
} catch (Exception ex) {
log.warning("couldn't load " + path + soundFiles[i] + ": caught " + ex + "; disabling playSounds");
setPlaySounds(false);
}
}
}
void playSound(int symbol) {
if (symbol < 0 || symbol >= soundFiles.length) {
return;
}
if (soundPlayers[symbol] == null) {
log.warning("No player for symbol " + symbol);
return;
}
if (soundPlayers[symbol].isPlaying()) {
return;
}
long now = System.currentTimeMillis();
if (now - lastTimePlayed < playSoundsMinIntervalMs) {
return;
}
if (soundPlayers[symbol].isPlaying()) {
return;
}
if (symbol == lastSymbolPlayed) {
return;
}
lastInput = symbol;
lastTimePlayed = now;
lastSymbolPlayed = symbol;
soundPlayers[symbol].play();
}
}
/**
* @return the playSoundsMinIntervalMs
*/
public int getPlaySoundsMinIntervalMs() {
return playSoundsMinIntervalMs;
}
/**
* @param playSoundsMinIntervalMs the playSoundsMinIntervalMs to set
*/
public void setPlaySoundsMinIntervalMs(int playSoundsMinIntervalMs) {
this.playSoundsMinIntervalMs = playSoundsMinIntervalMs;
putInt("playSoundsMinIntervalMs", playSoundsMinIntervalMs);
}
/**
* @return the decisionThresholdActivation
*/
public float getDecisionThresholdActivation() {
return decisionThresholdActivation;
}
/**
* @param decisionThresholdActivation the decisionThresholdActivation to set
*/
public void setDecisionThresholdActivation(float decisionThresholdActivation) {
if (decisionThresholdActivation > 1) {
decisionThresholdActivation = 1;
} else if (decisionThresholdActivation < 0) {
decisionThresholdActivation = 0;
}
this.decisionThresholdActivation = decisionThresholdActivation;
putFloat("decisionThresholdActivation", decisionThresholdActivation);
}
/**
* @return the showDecisionStatistics
*/
public boolean isShowDecisionStatistics() {
return showDecisionStatistics;
}
/**
* @param showDecisionStatistics the showDecisionStatistics to set
*/
public void setShowDecisionStatistics(boolean showDecisionStatistics) {
this.showDecisionStatistics = showDecisionStatistics;
putBoolean("showDecisionStatistics", showDecisionStatistics);
}
/**
* @return the playToWin
*/
public boolean isPlayToWin() {
return playToWin;
}
/**
* @param playToWin the playToWin to set
*/
public void setPlayToWin(boolean playToWin) {
this.playToWin = playToWin;
putBoolean("playToWin", playToWin);
}
/**
* @return the trackerUpperEdgeThreshold
*/
public float getTrackerUpperEdgeThreshold() {
return trackerUpperEdgeThreshold;
}
/**
* @param trackerUpperEdgeThreshold the trackerUpperEdgeThreshold to set
*/
public void setTrackerUpperEdgeThreshold(float trackerUpperEdgeThreshold) {
this.trackerUpperEdgeThreshold = trackerUpperEdgeThreshold;
putFloat("trackerUpperEdgeThreshold", trackerUpperEdgeThreshold);
}
/**
* @return the trackerLowerEdgeThreshold
*/
public float getTrackerLowerEdgeThreshold() {
return trackerLowerEdgeThreshold;
}
/**
* @param trackerLowerEdgeThreshold the trackerLowerEdgeThreshold to set
*/
public void setTrackerLowerEdgeThreshold(float trackerLowerEdgeThreshold) {
this.trackerLowerEdgeThreshold = trackerLowerEdgeThreshold;
putFloat("trackerLowerEdgeThreshold", trackerLowerEdgeThreshold);
}
/**
* @return the throwIntervalTimeoutMs
*/
public int getThrowIntervalTimeoutMs() {
return throwIntervalTimeoutMs;
}
/**
* @param throwIntervalTimeoutMs the throwIntervalTimeoutMs to set
*/
public void setThrowIntervalTimeoutMs(int throwIntervalTimeoutMs) {
this.throwIntervalTimeoutMs = throwIntervalTimeoutMs;
putInt("throwIntervalTimeoutMs", throwIntervalTimeoutMs);
}
/**
* @return the winningSymbolShowTimeMs
*/
public int getWinningSymbolShowTimeMs() {
return winningSymbolShowTimeMs;
}
/**
* @param winningSymbolShowTimeMs the winningSymbolShowTimeMs to set
*/
public void setWinningSymbolShowTimeMs(int winningSymbolShowTimeMs) {
this.winningSymbolShowTimeMs = winningSymbolShowTimeMs;
putInt("winningSymbolShowTimeMs", winningSymbolShowTimeMs);
}
/**
* @return the useGameStatesToPlay
*/
public boolean isUseGameStatesToPlay() {
return useGameStatesToPlay;
}
/**
* @param useGameStatesToPlay the useGameStatesToPlay to set
*/
public void setUseGameStatesToPlay(boolean useGameStatesToPlay) {
this.useGameStatesToPlay = useGameStatesToPlay;
putBoolean("useGameStatesToPlay", useGameStatesToPlay);
// tracker.setFilterEnabled(useGameStatesToPlay);
}
/**
* @return the showSymbol
*/
public boolean isShowSymbol() {
return showSymbol;
}
/**
* @param showSymbol the showSymbol to set
*/
public void setShowSymbol(boolean showSymbol) {
this.showSymbol = showSymbol;
putBoolean("showSymbol", showSymbol);
}
}
|
package com.ecyrd.jspwiki;
import java.io.*;
import java.util.*;
import java.text.*;
import org.apache.log4j.Category;
import org.apache.oro.text.*;
import org.apache.oro.text.regex.*;
import com.ecyrd.jspwiki.plugin.PluginManager;
import com.ecyrd.jspwiki.plugin.PluginException;
/**
* Handles conversion from Wiki format into fully featured HTML.
* This is where all the magic happens. It is CRITICAL that this
* class is tested, or all Wikis might die horribly.
* <P>
* The output of the HTML has not yet been validated against
* the HTML DTD. However, it is very simple.
*
* @author Janne Jalkanen
*/
// FIXME: Class still has problems with {{{: all conversion on that line where the {{{
// appears is done, but after that, conversion is not done. The only real solution
// is to move away from a line-based system into a pure stream-based system.
public class TranslatorReader extends Reader
{
public static final int READ = 0;
public static final int EDIT = 1;
private static final int EMPTY = 2; // Empty message
private static final int LOCAL = 3;
private static final int LOCALREF = 4;
private static final int IMAGE = 5;
private static final int EXTERNAL = 6;
private static final int INTERWIKI = 7;
private static final int IMAGELINK = 8;
private static final int IMAGEWIKILINK = 9;
private BufferedReader m_in;
private StringReader m_data = new StringReader("");
private static Category log = Category.getInstance( TranslatorReader.class );
private boolean m_iscode = false;
private boolean m_isbold = false;
private boolean m_isitalic = false;
private boolean m_isTypedText = false;
private boolean m_istable = false;
private int m_listlevel = 0;
private int m_numlistlevel = 0;
private WikiEngine m_engine;
private WikiContext m_context;
/** Optionally stores internal wikilinks */
private ArrayList m_localLinkMutatorChain = new ArrayList();
private ArrayList m_externalLinkMutatorChain = new ArrayList();
/** Keeps image regexp Patterns */
private ArrayList m_inlineImagePatterns;
private PatternMatcher m_inlineMatcher = new Perl5Matcher();
private ArrayList m_linkMutators = new ArrayList();
/**
* This property defines the inline image pattern. It's current value
* is jspwiki.translatorReader.inlinePattern
*/
public static final String PROP_INLINEIMAGEPTRN = "jspwiki.translatorReader.inlinePattern";
/** Property name for the "match english plurals" -hack. */
public static final String PROP_MATCHPLURALS = "jspwiki.translatorReader.matchEnglishPlurals";
/** If true, consider CamelCase hyperlinks as well. */
public static final String PROP_CAMELCASELINKS = "jspwiki.translatorReader.camelCaseLinks";
/** If true, all hyperlinks are translated as well, regardless whether they
are surrounded by brackets. */
public static final String PROP_PLAINURIS = "jspwiki.translatorReader.plainUris";
/** If true, we'll also consider english plurals (+s) a match. */
private boolean m_matchEnglishPlurals = true;
/** If true, then considers CamelCase links as well. */
private boolean m_camelCaseLinks = false;
/** If true, consider URIs that have no brackets as well. */
private boolean m_plainUris = false;
private PatternMatcher m_matcher = new Perl5Matcher();
private PatternCompiler m_compiler = new Perl5Compiler();
private Pattern m_camelCasePtrn;
/**
* The default inlining pattern. Currently "*.png"
*/
public static final String DEFAULT_INLINEPATTERN = "*.png";
/**
* @param engine The WikiEngine this reader is attached to. Is
* used to figure out of a page exits.
*/
// FIXME: TranslatorReaders should be pooled for better performance.
public TranslatorReader( WikiContext context, Reader in )
{
PatternCompiler compiler = new GlobCompiler();
ArrayList compiledpatterns = new ArrayList();
m_in = new BufferedReader( in );
m_engine = context.getEngine();
m_context = context;
Collection ptrns = getImagePatterns( m_engine );
// Make them into Regexp Patterns. Unknown patterns
// are ignored.
for( Iterator i = ptrns.iterator(); i.hasNext(); )
{
try
{
compiledpatterns.add( compiler.compile( (String)i.next() ) );
}
catch( MalformedPatternException e )
{
log.error("Malformed pattern in properties: ", e );
}
}
m_inlineImagePatterns = compiledpatterns;
try
{
m_camelCasePtrn = m_compiler.compile( "(^|\\W)([A-Z][a-z]+([A-Z][a-z]+)+)" );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: Someone put in a faulty pattern.",e);
throw new InternalWikiException("Faulty camelcasepattern in TranslatorReader");
}
// Set the properties.
Properties props = m_engine.getWikiProperties();
m_matchEnglishPlurals = "true".equals( props.getProperty( PROP_MATCHPLURALS, "false" ) );
m_camelCaseLinks = "true".equals( props.getProperty( PROP_CAMELCASELINKS, "false" ) );
m_plainUris = "true".equals( props.getProperty( PROP_PLAINURIS, "false" ) );
}
/**
* Adds a hook for processing link texts. This hook is called
* when the link text is written into the output stream, and
* you may use it to modify the text. It does not affect the
* actual link, only the user-visible text.
*
* @param mutator The hook to call. Null is safe.
*/
public void addLinkTransmutator( StringTransmutator mutator )
{
if( mutator != null )
{
m_linkMutators.add( mutator );
}
}
/**
* Adds a hook for processing local links. The engine
* transforms both non-existing and existing page links.
*
* @param mutator The hook to call. Null is safe.
*/
public void addLocalLinkHook( StringTransmutator mutator )
{
if( mutator != null )
{
m_localLinkMutatorChain.add( mutator );
}
}
public void addExternalLinkHook( StringTransmutator mutator )
{
if( mutator != null )
{
m_externalLinkMutatorChain.add( mutator );
}
}
/**
* Figure out which image suffixes should be inlined.
* @return Collection of Strings with patterns.
*/
protected static Collection getImagePatterns( WikiEngine engine )
{
Properties props = engine.getWikiProperties();
ArrayList ptrnlist = new ArrayList();
for( Enumeration e = props.propertyNames(); e.hasMoreElements(); )
{
String name = (String) e.nextElement();
if( name.startsWith( PROP_INLINEIMAGEPTRN ) )
{
String ptrn = props.getProperty( name );
ptrnlist.add( ptrn );
}
}
if( ptrnlist.size() == 0 )
{
ptrnlist.add( DEFAULT_INLINEPATTERN );
}
return ptrnlist;
}
/**
* Returns link name, if it exists; otherwise it returns null.
*/
private String linkExists( String page )
{
boolean isThere = m_engine.pageExists( page );
if( !isThere && m_matchEnglishPlurals )
{
if( page.endsWith("s") )
{
page = page.substring( 0, page.length()-1 );
}
else
{
page += "s";
}
isThere = m_engine.pageExists( page );
}
return isThere ? page : null ;
}
/**
* Calls a transmutator chain.
*
* @param list Chain to call
* @param text Text that should be passed to the mutate() method
* of each of the mutators in the chain.
* @return The result of the mutation.
*/
private String callMutatorChain( Collection list, String text )
{
if( list == null || list.size() == 0 )
{
return text;
}
for( Iterator i = list.iterator(); i.hasNext(); )
{
StringTransmutator m = (StringTransmutator) i.next();
text = m.mutate( m_context, text );
}
return text;
}
/**
* Write a HTMLized link depending on its type.
* The link mutator chain is processed.
*
* @param type Type of the link.
* @param link The actual link.
* @param text The user-visible text for the link.
*/
public String makeLink( int type, String link, String text )
{
String result;
if( text == null ) text = link;
// Make sure we make a link name that can be accepted
// as a valid URL.
String encodedlink = m_engine.encodeName( link );
if( encodedlink.length() == 0 )
{
type = EMPTY;
}
text = callMutatorChain( m_linkMutators, text );
switch(type)
{
case READ:
result = "<A CLASS=\"wikipage\" HREF=\""+m_engine.getBaseURL()+"Wiki.jsp?page="+encodedlink+"\">"+text+"</A>";
break;
case EDIT:
result = "<U>"+text+"</U><A HREF=\""+m_engine.getBaseURL()+"Edit.jsp?page="+encodedlink+"\">?</A>";
break;
case EMPTY:
result = "<U>"+text+"</U>";
break;
// These two are for local references - footnotes and
// references to footnotes.
// We embed the page name (or whatever WikiContext gives us)
// to make sure the links are unique across Wiki.
case LOCALREF:
result = "<A CLASS=\"footnoteref\" HREF=\"#ref-"+
m_context.getPage().getName()+"-"+
link+"\">[["+text+"]</A>";
break;
case LOCAL:
result = "<A CLASS=\"footnote\" NAME=\"ref-"+
m_context.getPage().getName()+"-"+
link.substring(1)+"\">[["+text+"]</A>";
break;
// With the image, external and interwiki types we need to
// make sure nobody can put in Javascript or something else
// annoying into the links themselves. We do this by preventing
// a haxor from stopping the link name short with quotes in
// fillBuffer().
case IMAGE:
result = "<IMG CLASS=\"inline\" SRC=\""+link+"\" ALT=\""+text+"\">";
break;
case IMAGELINK:
result = "<A HREF=\""+text+"\"><IMG CLASS=\"inline\" SRC=\""+link+"\"></A>";
break;
case IMAGEWIKILINK:
String pagelink = m_engine.getBaseURL()+"Wiki.jsp?page="+text;
result = "<A CLASS=\"wikipage\" HREF=\""+pagelink+"\"><IMG CLASS=\"inline\" SRC=\""+link+"\" ALT=\""+text+"\"></A>";
break;
case EXTERNAL:
result = "<A CLASS=\"external\" HREF=\""+link+"\">"+text+"</A>";
break;
case INTERWIKI:
result = "<A CLASS=\"interwiki\" HREF=\""+link+"\">"+text+"</A>";
break;
default:
result = "";
break;
}
return result;
}
/**
* [ This is a link ] -> ThisIsALink
*/
private String cleanLink( String link )
{
StringBuffer clean = new StringBuffer();
// Compress away all whitespace and capitalize
// all words in between.
StringTokenizer st = new StringTokenizer( link, " -" );
while( st.hasMoreTokens() )
{
StringBuffer component = new StringBuffer(st.nextToken());
component.setCharAt(0, Character.toUpperCase( component.charAt(0) ) );
clean.append( component );
}
// Remove non-alphanumeric characters that should not
// be put inside WikiNames. Note that all valid
// Unicode letters are considered okay for WikiNames.
// It is the problem of the WikiPageProvider to take
// care of actually storing that information.
for( int i = 0; i < clean.length(); i++ )
{
if( !(Character.isLetterOrDigit(clean.charAt(i)) ||
clean.charAt(i) == '_' ||
clean.charAt(i) == '.') )
{
clean.deleteCharAt(i);
--i; // We just shortened this buffer.
}
}
return clean.toString();
}
/**
* Figures out if a link is an off-site link. This recognizes
* the most common protocols by checking how it starts.
*/
private boolean isExternalLink( String link )
{
return link.startsWith("http:") || link.startsWith("ftp:") ||
link.startsWith("https:") || link.startsWith("mailto:") ||
link.startsWith("news:") || link.startsWith("file:");
}
/**
* Matches the given link to the list of image name patterns
* to determine whether it should be treated as an inline image
* or not.
*/
private boolean isImageLink( String link )
{
for( Iterator i = m_inlineImagePatterns.iterator(); i.hasNext(); )
{
if( m_inlineMatcher.matches( link, (Pattern) i.next() ) )
return true;
}
return false;
}
/**
* Returns true, if the argument contains a number, otherwise false.
* In a quick test this is roughly the same speed as Integer.parseInt()
* if the argument is a number, and roughly ten times the speed, if
* the argument is NOT a number.
*/
private boolean isNumber( String s )
{
if( s == null ) return false;
if( s.length() > 1 && s.charAt(0) == '-' )
s = s.substring(1);
for( int i = 0; i < s.length(); i++ )
{
if( !Character.isDigit(s.charAt(i)) )
return false;
}
return true;
}
/**
* Attempts to set traditional, CamelCase style WikiLinks.
*/
private String setCamelCaseLinks( String line )
{
PatternMatcherInput input;
input = new PatternMatcherInput( line );
while( m_matcher.contains( input, m_camelCasePtrn ) )
{
// Weed out links that will be matched later on.
MatchResult res = m_matcher.getMatch();
int lastOpen = line.substring(0,res.endOffset(2)).lastIndexOf('[');
int lastClose = line.substring(0,res.endOffset(2)).lastIndexOf(']');
if( (lastOpen < lastClose && lastOpen >= 0) || // Links closed ok
lastOpen < 0 ) // No links yet
{
int start = res.beginOffset(2);
int end = res.endOffset(2);
String link = res.group(2);
String matchedLink;
// System.out.println("LINE="+line);
// System.out.println(" Replacing: "+link);
// System.out.println(" open="+lastOpen+", close="+lastClose);
if( (matchedLink = linkExists( link )) != null )
{
link = makeLink( READ, matchedLink, link );
}
else
{
link = makeLink( EDIT, link, link );
}
line = TextUtil.replaceString( line,
start,
end,
link );
input.setInput( line );
input.setCurrentOffset( start+link.length() );
}
} // while
return line;
}
/**
* Gobbles up all hyperlinks that are encased in square brackets.
*/
private String setHyperLinks( String line )
{
int start, end = 0;
while( ( start = line.indexOf('[', end) ) != -1 )
{
// Words starting with multiple [[s are not hyperlinks.
if( line.charAt( start+1 ) == '[' )
{
for( end = start; end < line.length() && line.charAt(end) == '['; end++ );
line = TextUtil.replaceString( line, start, start+1, "" );
continue;
}
end = line.indexOf( ']', start );
if( end != -1 )
{
// Everything between these two is a link
String link = line.substring( start+1, end );
String reallink;
int cutpoint;
if( (cutpoint = link.indexOf('|')) != -1 )
{
reallink = link.substring( cutpoint+1 ).trim();
link = link.substring( 0, cutpoint );
}
else
{
reallink = link.trim();
}
int interwikipoint = -1;
// Yes, we now have the components separated.
// link = the text the link should have
// reallink = the url or page name.
// In many cases these are the same. [link|reallink].
if( PluginManager.isPluginLink( link ) )
{
String included;
try
{
included = m_engine.getPluginManager().execute( m_context, link );
}
catch( PluginException e )
{
log.error( "Failed to insert plugin", e );
log.error( "Root cause:",e.getRootThrowable() );
included = "<FONT COLOR=\"#FF0000\">Plugin insertion failed: "+e.getMessage()+"</FONT>";
}
line = TextUtil.replaceString( line, start, end+1,
included );
}
else if( isExternalLink( reallink ) )
{
// It's an external link, out of this Wiki
callMutatorChain( m_externalLinkMutatorChain, reallink );
if( isImageLink( reallink ) )
{
// Image links are handled differently:
// 1. If the text is a WikiName of an existing page,
// it gets linked.
// 2. If the text is an external link, then it is inlined.
// 3. Otherwise it becomes an ALT text.
String possiblePage = cleanLink( link );
String matchedLink;
if( isExternalLink( link ) && (cutpoint != -1) )
{
line = TextUtil.replaceString( line, start, end+1,
makeLink( IMAGELINK, reallink, link ) );
}
else if( (matchedLink = linkExists( possiblePage )) != null &&
(cutpoint != -1) )
{
// System.out.println("Orig="+link+", Matched: "+matchedLink);
callMutatorChain( m_localLinkMutatorChain, possiblePage );
line = TextUtil.replaceString( line, start, end+1,
makeLink( IMAGEWIKILINK, reallink, link ) );
}
else
{
line = TextUtil.replaceString( line, start, end+1,
makeLink( IMAGE, reallink, link ) );
}
}
else
{
line = TextUtil.replaceString( line, start, end+1,
makeLink( EXTERNAL, reallink, link ) );
}
}
else if( (interwikipoint = reallink.indexOf(":")) != -1 )
{
// It's an interwiki link
// InterWiki links also get added to external link chain
// after the links have been resolved.
// FIXME: There is an interesting issue here: We probably should
// URLEncode the wikiPage, but we can't since some of the
// Wikis use slashes (/), which won't survive URLEncoding.
// Besides, we don't know which character set the other Wiki
// is using, so you'll have to write the entire name as it appears
// in the URL. Bugger.
String extWiki = reallink.substring( 0, interwikipoint );
String wikiPage = reallink.substring( interwikipoint+1 );
String urlReference = m_engine.getInterWikiURL( extWiki );
if( urlReference != null )
{
urlReference = TextUtil.replaceString( urlReference, "%s", wikiPage );
callMutatorChain( m_externalLinkMutatorChain, urlReference );
line = TextUtil.replaceString( line, start, end+1,
makeLink( INTERWIKI, urlReference, link ) );
}
else
{
line = TextUtil.replaceString( line, start, end+1,
link+" <FONT COLOR=\"#FF0000\">(No InterWiki reference defined in properties for Wiki called '"+extWiki+"'!)</FONT>");
}
}
else if( reallink.startsWith("
{
// It defines a local footnote
line = TextUtil.replaceString( line, start, end+1,
makeLink( LOCAL, reallink, link ) );
}
else if( isNumber( reallink ) )
{
// It defines a reference to a local footnote
line = TextUtil.replaceString( line, start, end+1,
makeLink( LOCALREF, reallink, link ) );
}
else
{
// It's an internal Wiki link
reallink = cleanLink( reallink );
callMutatorChain( m_localLinkMutatorChain, reallink );
String matchedLink;
if( (matchedLink = linkExists( reallink )) != null )
{
line = TextUtil.replaceString( line, start, end+1,
makeLink( READ, matchedLink, link ) );
}
else
{
line = TextUtil.replaceString( line, start, end+1, makeLink( EDIT, reallink, link ) );
}
}
}
else
{
log.error("Unterminated link");
break;
}
}
return line;
}
/**
* Checks if this line is a heading line.
*/
private String setHeadings( String line )
{
if( line.startsWith("!!!") )
{
line = TextUtil.replaceString( line, 0, 3, "<H2>" ) + "</H2>";
}
else if( line.startsWith("!!") )
{
line = TextUtil.replaceString( line, 0, 2, "<H3>" ) + "</H3>";
}
else if( line.startsWith("!") )
{
line = TextUtil.replaceString( line, 0, 1, "<H4>" ) + "</H4>";
}
return line;
}
/**
* Translates horizontal rulers.
*/
private String setHR( String line )
{
StringBuffer buf = new StringBuffer();
int start = line.indexOf("
if( start != -1 )
{
int i;
buf.append( line.substring( 0, start ) );
for( i = start; i<line.length() && line.charAt(i) == '-'; i++ )
{
}
buf.append("<HR>");
buf.append( line.substring( i ) );
return buf.toString();
}
return line;
}
/**
* Closes all annoying lists and things that the user might've
* left open.
*/
private String closeAll()
{
StringBuffer buf = new StringBuffer();
if( m_isbold )
{
buf.append("</B>");
m_isbold = false;
}
if( m_isitalic )
{
buf.append("</I>");
m_isitalic = false;
}
if( m_isTypedText )
{
buf.append("</TT>");
m_isTypedText = false;
}
for( ; m_listlevel > 0; m_listlevel
{
buf.append( "</UL>\n" );
}
for( ; m_numlistlevel > 0; m_numlistlevel
{
buf.append( "</OL>\n" );
}
if( m_iscode )
{
buf.append("</PRE>\n");
m_iscode = false;
}
if( m_istable )
{
buf.append( "</TABLE>" );
m_istable = false;
}
return buf.toString();
}
/**
* Sets bold text.
*/
private String setBold( String line )
{
StringBuffer buf = new StringBuffer();
for( int i = 0; i < line.length(); i++ )
{
if( line.charAt(i) == '_' && i < line.length()-1 )
{
if( line.charAt(i+1) == '_' )
{
buf.append( m_isbold ? "</B>" : "<B>" );
m_isbold = !m_isbold;
i++;
}
else buf.append( "_" );
}
else buf.append( line.charAt(i) );
}
return buf.toString();
}
/**
* Counts how many consecutive characters of a certain type exists on the line.
* @param line String of chars to check.
* @param startPos Position to start reading from.
* @param char Character to check for.
*/
private int countChar( String line, int startPos, char c )
{
int count;
for( count = 0; (startPos+count < line.length()) && (line.charAt(count+startPos) == c); count++ );
return count;
}
/**
* Returns a new String that has char c n times.
*/
private String repeatChar( char c, int n )
{
StringBuffer sb = new StringBuffer();
for( int i = 0; i < n; i++ ) sb.append(c);
return sb.toString();
}
/**
* {{text}} = <TT>text</TT>
*/
private String setTT( String line )
{
StringBuffer buf = new StringBuffer();
for( int i = 0; i < line.length(); i++ )
{
if( line.charAt(i) == '{' && !m_isTypedText )
{
int count = countChar( line, i, '{' );
if( count == 2 )
{
buf.append( "<TT>" );
m_isTypedText = true;
}
else
{
buf.append( repeatChar( '{', count ) );
}
i += count-1;
}
else if( line.charAt(i) == '}' && m_isTypedText )
{
int count = countChar( line, i, '}' );
if( count == 2 )
{
buf.append( "</TT>" );
m_isTypedText = false;
}
else
{
buf.append( repeatChar( '}', count ) );
}
i += count-1;
}
else
{
buf.append( line.charAt(i) );
}
}
return buf.toString();
}
private String setItalic( String line )
{
StringBuffer buf = new StringBuffer();
for( int i = 0; i < line.length(); i++ )
{
if( line.charAt(i) == '\'' && i < line.length()-1 )
{
if( line.charAt(i+1) == '\'' )
{
buf.append( m_isitalic ? "</I>" : "<I>" );
m_isitalic = !m_isitalic;
i++;
}
else buf.append( "'" );
}
else buf.append( line.charAt(i) );
}
return buf.toString();
}
private void fillBuffer()
throws IOException
{
int pre;
String postScript = ""; // Gets added at the end of line.
StringBuffer buf = new StringBuffer();
String line = m_in.readLine();
if( line == null )
{
m_data = new StringReader("");
return;
}
String trimmed = line.trim();
// Replace the most obvious items that could possibly
// break the resulting HTML code.
line = TextUtil.replaceEntities( line );
if( !m_iscode )
{
// Tables
if( trimmed.startsWith("|") )
{
StringBuffer tableLine = new StringBuffer();
if( !m_istable )
{
buf.append( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n" );
m_istable = true;
}
buf.append( "<TR>" );
// The following piece of code will go through the line character
// by character, and replace all references to the table markers (|)
// by a <TD>, EXCEPT when '|' can be found inside a link.
boolean islink = false;
for( int i = 0; i < line.length(); i++ )
{
char c = line.charAt(i);
switch( c )
{
case '|':
if( !islink )
{
if( i < line.length()-1 && line.charAt(i+1) == '|' )
{
// It's a heading.
tableLine.append( "<TH>" );
i++;
}
else
{
// It's a normal thingy.
tableLine.append( "<TD>" );
}
}
else
{
tableLine.append( c );
}
break;
case '[':
islink = true;
tableLine.append( c );
break;
case ']':
islink = false;
tableLine.append( c );
break;
default:
tableLine.append( c );
break;
}
} // for
line = tableLine.toString();
postScript = "</TR>";
}
else if( !trimmed.startsWith("|") && m_istable )
{
buf.append( "</TABLE>" );
m_istable = false;
}
// FIXME: The following two blocks of code are temporary
// solutions for code going all wonky if you do multiple #*:s inside
// each other.
// A real solution is needed - this only closes down the other list
// before the other one gets started.
if( line.startsWith("*") )
{
for( ; m_numlistlevel > 0; m_numlistlevel
{
buf.append("</OL>\n");
}
}
if( line.startsWith("
{
for( ; m_listlevel > 0; m_listlevel
{
buf.append("</UL>\n");
}
}
// Make a bulleted list
if( line.startsWith("*") )
{
// Close all other lists down.
int numBullets = countChar( line, 0, '*' );
if( numBullets > m_listlevel )
{
for( ; m_listlevel < numBullets; m_listlevel++ )
buf.append("<UL>\n");
}
else if( numBullets < m_listlevel )
{
for( ; m_listlevel > numBullets; m_listlevel
buf.append("</UL>\n");
}
buf.append("<LI>");
line = line.substring( numBullets );
}
else if( line.startsWith(" ") && m_listlevel > 0 && trimmed.length() != 0 )
{
// This is a continuation of a previous line.
}
else if( line.startsWith("#") && m_listlevel > 0 )
{
// We don't close all things for the other list type.
}
else
{
// Close all lists down.
for( ; m_listlevel > 0; m_listlevel
{
buf.append("</UL>\n");
}
}
// Ordered list
if( line.startsWith("
{
// Close all other lists down.
if( m_numlistlevel == 0 )
{
for( ; m_listlevel > 0; m_listlevel
{
buf.append("</UL>\n");
}
}
int numBullets = countChar( line, 0, '
if( numBullets > m_numlistlevel )
{
for( ; m_numlistlevel < numBullets; m_numlistlevel++ )
buf.append("<OL>\n");
}
else if( numBullets < m_numlistlevel )
{
for( ; m_numlistlevel > numBullets; m_numlistlevel
buf.append("</OL>\n");
}
buf.append("<LI>");
line = line.substring( numBullets );
}
else if( line.startsWith(" ") && m_numlistlevel > 0 && trimmed.length() != 0 )
{
// This is a continuation of a previous line.
}
else if( line.startsWith("*") && m_numlistlevel > 0 )
{
// We don't close things for the other list type.
}
else
{
// Close all lists down.
for( ; m_numlistlevel > 0; m_numlistlevel
{
buf.append("</OL>\n");
}
}
// Do the standard settings
if( m_camelCaseLinks )
{
line = setCamelCaseLinks( line );
}
line = setHeadings( line );
line = setHR( line );
line = setBold( line );
line = setItalic( line );
line = setTT( line );
line = TextUtil.replaceString( line, "\\\\", "<BR>" );
line = setHyperLinks( line );
// Is this an empty line?
if( trimmed.length() == 0 )
{
buf.append( "<P>" );
}
if( (pre = line.indexOf("{{{")) != -1 )
{
line = TextUtil.replaceString( line, pre, pre+3, "<PRE>" );
m_iscode = true;
}
}
if( (pre = line.indexOf("}}}")) != -1 )
{
line = TextUtil.replaceString( line, pre, pre+3, "</PRE>" );
m_iscode = false;
}
buf.append( line );
buf.append( postScript );
buf.append( "\n" );
m_data = new StringReader( buf.toString() );
}
public int read()
throws IOException
{
int val = m_data.read();
if( val == -1 )
{
fillBuffer();
val = m_data.read();
if( val == -1 )
{
m_data = new StringReader( closeAll() );
val = m_data.read();
}
}
return val;
}
public int read( char[] buf, int off, int len )
throws IOException
{
return m_data.read( buf, off, len );
}
public boolean ready()
throws IOException
{
log.debug("ready ? "+m_data.ready() );
if(!m_data.ready())
{
fillBuffer();
}
return m_data.ready();
}
public void close()
{
}
}
|
package com.ecyrd.jspwiki.auth;
import java.security.Principal;
import java.util.Date;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.auth.authorize.DefaultGroupManager;
import com.ecyrd.jspwiki.auth.authorize.GroupManager;
import com.ecyrd.jspwiki.auth.user.DefaultUserProfile;
import com.ecyrd.jspwiki.auth.user.DuplicateUserException;
import com.ecyrd.jspwiki.auth.user.UserDatabase;
import com.ecyrd.jspwiki.auth.user.UserProfile;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Provides a facade for user and group information.
*
* @author Janne Jalkanen
*
*/
public class UserManager
{
private WikiEngine m_engine;
private static final Logger log = Logger.getLogger(UserManager.class);
private static final String PROP_USERDATABASE = "jspwiki.userdatabase";
// private static final String PROP_ACLMANAGER = "jspwiki.aclManager";
/** The user database loads, manages and persists user identities */
private UserDatabase m_database = null;
/** The group manager loads, manages and persists wiki groups */
private GroupManager m_groupManager = null;
/**
* Initializes the engine for its nefarious purposes.
*
* @param engine
* @param props
*/
public void initialize( WikiEngine engine, Properties props )
{
m_engine = engine;
}
/**
* Returns the GroupManager employed by this WikiEngine.
* The GroupManager is lazily initialized.
* @since 2.3
*/
public GroupManager getGroupManager()
{
if( m_groupManager == null )
{
// TODO: make this pluginizable
m_groupManager = new DefaultGroupManager();
m_groupManager.initialize( m_engine, m_engine.getWikiProperties() );
}
return m_groupManager;
}
/**
* Returns the UserDatabase employed by this WikiEngine.
* The UserDatabase is lazily initialized by this method, if
* it does not exist yet. If the initialization fails, this
* method will use the inner class DummyUserDatabase as
* a default (which is enough to get JSPWiki running).
*
* @since 2.3
*/
// FIXME: Must not throw RuntimeException, but something else.
public UserDatabase getUserDatabase()
{
if( m_database != null )
{
return m_database;
}
String dbClassName = "<unknown>";
try
{
dbClassName = WikiEngine.getRequiredProperty( m_engine.getWikiProperties(),
PROP_USERDATABASE );
log.info("Attempting to load user database class "+dbClassName);
Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.user", dbClassName );
m_database = (UserDatabase) dbClass.newInstance();
m_database.initialize( m_engine, m_engine.getWikiProperties() );
log.info("UserDatabase initialized.");
}
catch( NoRequiredPropertyException e )
{
log.error( "You have not set the '"+PROP_USERDATABASE+"'. You need to do this if you want to enable user management by JSPWiki." );
}
catch( ClassNotFoundException e )
{
log.error( "UserDatabase class " + dbClassName + " cannot be found", e );
}
catch( InstantiationException e )
{
log.error( "UserDatabase class " + dbClassName + " cannot be created", e );
}
catch( IllegalAccessException e )
{
log.error( "You are not allowed to access this user database class", e );
}
finally
{
if( m_database == null )
{
log.info("I could not create a database object you specified (or didn't specify), so I am falling back to a default.");
m_database = new DummyUserDatabase();
}
}
return m_database;
}
public UserProfile getUserProfile( WikiContext context ) throws WikiSecurityException
{
// Figure out if this is a new profile
Principal user = context.getCurrentUser();
UserProfile profile;
try
{
profile = m_database.find( user.getName() );
}
catch( NoSuchPrincipalException e )
{
profile = m_database.newProfile();
if ( !profile.isNew() )
{
throw new IllegalStateException(
"New profile should be marked 'new'. Check your UserProfile implementation." );
}
Principal principal = context.getWikiSession().getLoginPrincipal();
profile.setLoginName( principal.getName() );
}
return profile;
}
/**
* Saves the {@link com.ecyrd.jspwiki.auth.user.UserProfile}for the user in
* a wiki context. This method verifies that a user profile to be saved
* doesn't collide with existing profiles; that is, the login name, wiki
* name or full name is already used by another profile. If the profile
* collides, a DuplicateUserException is thrown. After saving the profile,
* the user database changes are committed, and the user's credential set is
* refreshed.
* @param context the wiki context, which may not be <code>null</code>
* @param profile the user profile, which may not be <code>null</code>
*/
public void setUserProfile( WikiContext context, UserProfile profile ) throws WikiSecurityException,
DuplicateUserException
{
boolean newProfile = profile.isNew();
UserProfile oldProfile = getUserProfile( context );
// User profiles that may already have wikiname, fullname or loginname
UserProfile otherProfile;
try
{
otherProfile = m_database.findByLoginName( profile.getLoginName() );
if ( otherProfile != null && !otherProfile.equals( oldProfile ) )
{
throw new DuplicateUserException( "The login name '" + profile.getLoginName() + "' is already taken." );
}
}
catch( NoSuchPrincipalException e )
{
}
try
{
otherProfile = m_database.findByFullName( profile.getFullname() );
if ( otherProfile != null && !otherProfile.equals( oldProfile ) )
{
throw new DuplicateUserException( "The full name '" + profile.getFullname() + "' is already taken." );
}
}
catch( NoSuchPrincipalException e )
{
}
try
{
otherProfile = m_database.findByWikiName( profile.getWikiName() );
if ( otherProfile != null && !otherProfile.equals( oldProfile ) )
{
throw new DuplicateUserException( "The wiki name '" + profile.getWikiName() + "' is already taken." );
}
}
catch( NoSuchPrincipalException e )
{
}
Date modDate = new Date();
if ( newProfile )
{
profile.setCreated( modDate );
}
profile.setLastModified( modDate );
m_database.save( profile );
m_database.commit();
// Refresh the credential set
AuthenticationManager mgr = m_engine.getAuthenticationManager();
if ( newProfile )
{
mgr.loginCustom( profile.getLoginName(), profile.getPassword(), context.getHttpRequest() );
}
else
{
mgr.refreshCredentials( context.getWikiSession() );
}
}
/**
* Extracts user profile parameters from the HTTP request and populates a
* new UserProfile with them. For security reasons, the password attribute
* is <i>not</i> extracted. Attributes that are not parsed are set to
* <code>null</code>.
* @param request the current HTTP request
* @return a new, populated user profile
*/
public UserProfile parseProfile( WikiContext context )
{
// TODO:this class is probably the wrong place for this method...
UserProfile profile = m_database.newProfile();
UserProfile existingProfile = null;
try
{
// Look up the existing profile, if it exists
existingProfile = getUserProfile( context );
}
catch( WikiSecurityException e )
{
}
HttpServletRequest request = context.getHttpRequest();
// Set e-mail to user's supplied value; if null, use existing value
String email = request.getParameter( "email" );
email = isNotBlank( email ) ? email : existingProfile.getEmail();
profile.setEmail( email );
// Set password to user's supplied value; if null, skip it
String password = request.getParameter( "password" );
password = isNotBlank( password ) ? password : null;
// For new profiles, we use what the user supplied for
// full name and wiki name
String fullname = request.getParameter( "fullname" );
String wikiname = request.getParameter( "wikiname" );
if ( existingProfile.isNew() )
{
fullname = isNotBlank( fullname ) ? fullname : null;
wikiname = isNotBlank( wikiname ) ? wikiname : null;
}
else
{
fullname = existingProfile.getFullname();
wikiname = existingProfile.getWikiName();
}
profile.setFullname( fullname );
profile.setWikiName( wikiname );
// For all profiles, we get the login principal from the looked-up
// profile
profile.setLoginName( existingProfile.getLoginName() );
// Always use existing profile's lastModified and Created properties
profile.setCreated( existingProfile.getCreated() );
profile.setLastModified( existingProfile.getLastModified() );
return profile;
}
/**
* Returns <code>true</code> if a supplied string is null or blank
* @param parameter
*/
private static boolean isNotBlank( String parameter )
{
return ( parameter != null && parameter.length() > 0 );
}
/**
* Validates a user profile, and appends any errors to a user-supplied Set
* of error strings.
* @param profile the supplied UserProfile
* @param errors the set of error strings
*/
public void validateProfile( UserProfile profile, boolean isNew, Set errors )
{
// TODO:this class is probably the wrong place for this method...
if ( profile.getFullname() == null )
{
errors.add( "Full name cannot be blank" );
}
if ( profile.getLoginName() == null )
{
errors.add( "Login name cannot be blank" );
}
if ( profile.getWikiName() == null )
{
errors.add( "Wiki name cannot be blank" );
}
if ( !m_engine.getAuthenticationManager().isContainerAuthenticated() && isNew && profile.getPassword() == null )
{
errors.add( "Password cannot be blank" );
}
}
/**
* This is a database that gets used if nothing else is available. It does
* nothing of note - it just mostly thorws NoSuchPrincipalExceptions if
* someone tries to log in.
* @author jalkanen
*/
public class DummyUserDatabase implements UserDatabase
{
public void commit() throws WikiSecurityException
{
// No operation
}
public UserProfile find(String index) throws NoSuchPrincipalException
{
throw new NoSuchPrincipalException("No user profiles available");
}
public UserProfile findByEmail(String index) throws NoSuchPrincipalException
{
throw new NoSuchPrincipalException("No user profiles available");
}
public UserProfile findByFullName(String index) throws NoSuchPrincipalException
{
throw new NoSuchPrincipalException("No user profiles available");
}
public UserProfile findByLoginName(String index) throws NoSuchPrincipalException
{
throw new NoSuchPrincipalException("No user profiles available");
}
public UserProfile findByWikiName(String index) throws NoSuchPrincipalException
{
throw new NoSuchPrincipalException("No user profiles available");
}
public Principal[] getPrincipals(String identifier) throws NoSuchPrincipalException
{
throw new NoSuchPrincipalException("No user profiles available");
}
public void initialize(WikiEngine engine, Properties props) throws NoRequiredPropertyException
{
}
public UserProfile newProfile()
{
return new DefaultUserProfile();
}
public void save( UserProfile profile ) throws WikiSecurityException
{
}
public boolean validatePassword(String loginName, String password)
{
return false;
}
}
}
|
package com.ecyrd.jspwiki.tags;
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiPage;
/**
* Writes an edit link. Body of the link becomes the link text.
* <P><B>Attributes</B></P>
* <UL>
* <LI>page - Page name to refer to. Default is the current page.
* <LI>format - Format, either "anchor" or "url".
* <LI>version - Version number of the page to refer to. Possible values
* are "this", meaning the version of the current page; or a version
* number. Default is always to point at the latest version of the page.
* <LI>title - Is used in page actions to display hover text (tooltip)
* <LI>accesskey - Set an accesskey (ALT+[Char])
* </UL>
*
* @author Janne Jalkanen
* @since 2.0
*/
public class EditLinkTag
extends WikiLinkTag
{
private static final long serialVersionUID = 0L;
public String m_version = null;
public String m_title = "";
public String m_accesskey = "";
public void initTag()
{
super.initTag();
m_version = null;
}
public void setVersion( String vers )
{
m_version = vers;
}
public void setTitle( String title )
{
m_title = title;
}
public void setAccesskey( String access )
{
m_accesskey = access;
}
public final int doWikiStartTag()
throws IOException
{
WikiEngine engine = m_wikiContext.getEngine();
WikiPage page = null;
String versionString = "";
String pageName = null;
// Determine the page and the link.
if( m_pageName == null )
{
page = m_wikiContext.getPage();
if( page == null )
{
// You can't call this on the page itself anyways.
return SKIP_BODY;
}
pageName = page.getName();
}
else
{
pageName = m_pageName;
}
// Determine the latest version, if the version attribute is "this".
if( m_version != null )
{
if( "this".equalsIgnoreCase(m_version) )
{
if( page == null )
{
// No page, so go fetch according to page name.
page = engine.getPage( m_pageName );
}
if( page != null )
{
versionString = "version="+page.getVersion();
}
}
else
{
versionString = "version="+m_version;
}
}
// Finally, print out the correct link, according to what
// user commanded.
JspWriter out = pageContext.getOut();
switch( m_format )
{
case ANCHOR:
out.print("<a href=\""+m_wikiContext.getURL(WikiContext.EDIT,pageName, versionString)
+"\" accesskey=\"" + m_accesskey + "\" title=\"" + m_title + "\">");
break;
case URL:
out.print( m_wikiContext.getURL(WikiContext.EDIT,pageName,versionString) );
break;
}
return EVAL_BODY_INCLUDE;
}
}
|
package vebugger;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.reflections.Reflections;
public final class VisualDebuggerAid {
private static Map<Class<?>, VebuggerTemplate> templates = new HashMap<>();
static {
Reflections reflections = new Reflections("vebugger.templates");
Set<Class<? extends VebuggerTemplate>> templateClasses = reflections.getSubTypesOf(VebuggerTemplate.class);
for (Class<? extends VebuggerTemplate> templateClass : templateClasses) {
try {
VebuggerTemplate template = templateClass.newInstance();
templates.put(template.getType(), template);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
public static final String toString(Object obj) {
return toString(obj, true);
}
public static final String toString(Object obj, boolean includeHtmlWrapper) {
if (obj != null) {
VebuggerTemplate template = findMatchingTemplate(obj.getClass());
if (template != null) {
StringBuilder sb = new StringBuilder();
if (includeHtmlWrapper) {
sb.append("<html><body>");
}
template.render(sb, obj);
if (includeHtmlWrapper) {
sb.append("</body></html>");
}
return sb.toString();
}
}
return String.valueOf(obj);
}
private static final VebuggerTemplate findMatchingTemplate(Class<?> clazz) {
VebuggerTemplate template = findMatchingClassTemplate(clazz);
if (template == null) {
template = findMatchingInterfaceTemplate(clazz);
}
if (template == null && clazz.isArray()) {
template = findMatchingClassTemplate(Object[].class);
}
return template;
}
private static final VebuggerTemplate findMatchingClassTemplate(Class<?> clazz) {
if (!clazz.equals(Object.class)) {
VebuggerTemplate template;
if ((template = templates.get(clazz)) != null) {
return template;
}
return findMatchingClassTemplate(clazz.getSuperclass());
}
return null;
}
private static VebuggerTemplate findMatchingInterfaceTemplate(Class<?> clazz) {
if (!clazz.equals(Object.class)) {
VebuggerTemplate template;
for (Class<?> interfaze : clazz.getInterfaces()) {
if ((template = templates.get(interfaze)) != null) {
return template;
}
}
return findMatchingInterfaceTemplate(clazz.getSuperclass());
}
return null;
}
}
|
package com.jcwhatever.arborianquests.quests;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.jcwhatever.arborianquests.ArborianQuests;
import com.jcwhatever.arborianquests.quests.QuestStatus.CurrentQuestStatus;
import com.jcwhatever.nucleus.mixins.IHierarchyNode;
import com.jcwhatever.nucleus.mixins.INamed;
import com.jcwhatever.nucleus.storage.DataBatchOperation;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.utils.CollectionUtils;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.text.TextUtils;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
/**
* Represents a quest and players within the quest.
*/
public abstract class Quest implements INamed, IHierarchyNode<Quest> {
private static Multimap<UUID, Quest> _playerQuests =
MultimapBuilder.hashKeys(100).hashSetValues().build();
private final String _questName;
private String _displayName;
private final IDataNode _dataNode;
private final IDataNode _playerNodes;
private final IDataNode _questNodes;
private final ObjectiveDescriptions _objectives;
private final Map<String, Quest> _subQuests = new HashMap<>(5);
/**
* Get an unmodifiable {@code Set} of {@code Quest}'s that
* the player is in.
*
* @param player The player.
*/
public static Set<Quest> getPlayerQuests(Player player) {
return CollectionUtils.unmodifiableSet(_playerQuests.get(player.getUniqueId()));
}
/**
* Get a quest using a quest path.
*
* @param questPath The quest path.
*
* @return The quest or null if not found.
*/
@Nullable
public static Quest getQuestFromPath(String questPath) {
PreCon.notNull(questPath, "questPath");
String[] pathComponents = TextUtils.PATTERN_DOT.split(questPath);
Quest quest = ArborianQuests.getQuestManager().getQuest(pathComponents[0]);
if (quest == null)
return null;
for (int i=1; i < pathComponents.length; i++) {
quest = quest.getQuest(pathComponents[i]);
if (quest == null)
return null;
}
return quest;
}
/**
* Constructor.
*
* @param questName The name of the quest.
* @param displayName The quest display name.
* @param dataNode The quest data node.
*/
public Quest(String questName, String displayName, IDataNode dataNode) {
PreCon.notNullOrEmpty(questName);
PreCon.notNullOrEmpty(displayName);
PreCon.notNull(dataNode);
_questName = questName;
_displayName = displayName;
_dataNode = dataNode;
_playerNodes = dataNode.getNode("players");
_questNodes = dataNode.getNode("quests");
_objectives = new ObjectiveDescriptions(dataNode.getNode("objectives"), _playerNodes);
}
/**
* Get the quests data node name.
*/
@Override
public String getName() {
return _questName;
}
public String getPathName() {
return _questName;
}
/**
* Get the quests display name.
*/
public String getDisplayName() {
return _displayName;
}
/**
* Set the quests display name.
*
* @param displayName The display name.
*/
public void setDisplayName(String displayName) {
_displayName = displayName;
}
/**
* Get the quests objective descriptions manager.
*/
public ObjectiveDescriptions getObjectives() {
return _objectives;
}
/**
* Get a sub quest of the quest by name.
*
* @param questName The name of the sub quest.
*/
@Nullable
public Quest getQuest(String questName) {
PreCon.notNullOrEmpty(questName);
return _subQuests.get(questName.toLowerCase());
}
/**
* Get all sub quests.
*/
public List<Quest> getQuests() {
return new ArrayList<>(_subQuests.values());
}
/**
* Get or create a sub quest of the quest.
*
* @param questName The quest name.
* @param displayName The quest display name.
*/
public Quest createQuest(String questName, String displayName) {
PreCon.notNullOrEmpty(questName);
PreCon.notNullOrEmpty(displayName);
questName = questName.toLowerCase();
Quest quest = _subQuests.get(questName);
if (quest != null) {
quest.setDisplayName(displayName);
return quest;
}
IDataNode node = _dataNode.getNode("quests." + questName);
quest = new SubQuest(this, questName, displayName, node);
node.set("display", displayName);
node.save();
_subQuests.put(questName, quest);
return quest;
}
/**
* Remove a sub quest of the quest.
*
* @param questName The name of the quest to remove.
*
* @return True if found and removed.
*/
public boolean removeQuest(String questName) {
PreCon.notNullOrEmpty(questName);
questName = questName.toLowerCase();
Quest quest = _subQuests.remove(questName);
if (quest == null)
return false;
IDataNode node = _dataNode.getNode("quests." + questName);
node.remove();
node.save();
return true;
}
/**
* Get a players current status in the quest.
*
* @param player The player to check.
*/
public QuestStatus getStatus(Player player) {
//noinspection ConstantConditions
return getStatus(player.getUniqueId());
}
/**
* Get a players current status in the quest.
*
* @param playerId The id of the player to check.
*/
public QuestStatus getStatus(UUID playerId) {
//noinspection ConstantConditions
return _playerNodes.getEnum(playerId.toString() + ".status", QuestStatus.NONE, QuestStatus.class);
}
/**
* Accept the player into the quest.
*
* @param player The player to accept.
*/
public void accept(Player player) {
accept(player.getUniqueId());
}
/**
* Accept the player into the quest.
*
* @param playerId The id of the player.
*/
public void accept(UUID playerId) {
QuestStatus status = getStatus(playerId);
switch (status) {
case NONE:
setStatus(playerId, QuestStatus.INCOMPLETE);
break;
case COMPLETED:
setStatus(playerId, QuestStatus.RERUN);
break;
case INCOMPLETE:
// fall through
case RERUN:
// do nothing
break;
}
}
/**
* Flag a player as having completed the quest.
*
* @param player The player to flag.
*/
public void finish(Player player) {
finish(player.getUniqueId());
}
/**
* Flag a player as having completed the quest.
*
* @param playerId The id of the player to flag.
*/
public void finish(UUID playerId) {
QuestStatus status = getStatus(playerId);
switch (status) {
case RERUN:
// fall through
case INCOMPLETE:
setStatus(playerId, QuestStatus.COMPLETED);
break;
case NONE:
// fall through
case COMPLETED:
break;
}
}
/**
* Cancel the quest for a player.
*
* @param player The player.
*/
public void cancel(Player player) {
cancel(player.getUniqueId());
}
/**
* Cancel the quest for a player.
*
* @param playerId The id of the player.
*/
public void cancel(UUID playerId) {
QuestStatus status = getStatus(playerId);
switch (status) {
case RERUN:
// fall through
case COMPLETED:
setStatus(playerId, QuestStatus.COMPLETED);
break;
case NONE:
// fall through
case INCOMPLETE:
setStatus(playerId, QuestStatus.NONE);
break;
}
}
/**
* Determine if a player has a flag set.
*
* @param playerId The ID of the player to check
* @param flagName The name of the flag
*
* @return True if the flag is set.
*/
public boolean hasFlag(UUID playerId, String flagName) {
PreCon.notNull(playerId);
PreCon.notNullOrEmpty(flagName);
return _playerNodes.getBoolean(playerId.toString() + ".flags." + flagName, false);
}
/**
* Set a flag on a player.
*
* @param playerId The players ID.
* @param flagName The name of the flag.
*/
public void setFlag(UUID playerId, String flagName) {
PreCon.notNull(playerId);
PreCon.notNullOrEmpty(flagName);
_playerNodes.set(playerId.toString() + ".flags." + flagName, true);
_playerNodes.save();
}
/**
* Clear a flag on a player.
*
* @param playerId The players ID.
* @param flagName The name of the flag.
*/
public void clearFlag(UUID playerId, String flagName) {
PreCon.notNull(playerId);
PreCon.notNullOrEmpty(flagName);
_playerNodes.remove(playerId.toString() + ".flags." + flagName);
_playerNodes.save();
}
/**
* Clear all flags set on a player.
*
* @param playerId The ID of the player.
*/
public void clearFlags(final UUID playerId) {
PreCon.notNull(playerId);
cancel(playerId);
_playerNodes.runBatchOperation(new DataBatchOperation() {
@Override
public void run(IDataNode dataNode) {
_playerNodes.remove(playerId.toString());
_playerNodes.save();
for (Quest quest : _subQuests.values()) {
quest.clearFlags(playerId);
quest.setStatus(playerId, QuestStatus.NONE);
}
}
});
}
/**
* Get the flags set on a player.
*
* @param playerId The unique ID of the player.
*/
public Set<String> getFlags(UUID playerId) {
PreCon.notNull(playerId);
IDataNode flagNode = _playerNodes.getNode(playerId.toString() + ".flags");
Set<String> flagNames = flagNode.getSubNodeNames();
return CollectionUtils.unmodifiableSet(flagNames);
}
// Set the quest status of a player
private void setStatus(UUID playerId, QuestStatus status) {
if (status == QuestStatus.NONE) {
_playerNodes.remove(playerId.toString());
}
else {
_playerNodes.set(playerId.toString() + ".status", status);
}
if (status.getCurrentStatus() == CurrentQuestStatus.NONE) {
_playerQuests.remove(playerId, this);
}
else if (status.getCurrentStatus() == CurrentQuestStatus.IN_PROGRESS) {
_playerQuests.put(playerId, this);
}
_playerNodes.save();
}
// initial settings load
private void loadSettings() {
// load players
for (IDataNode playerNode : _playerNodes) {
UUID id = TextUtils.parseUUID(playerNode.getName());
if (id == null)
continue;
QuestStatus status = playerNode.getEnum("", QuestStatus.NONE, QuestStatus.class);
//noinspection ConstantConditions
if (status.getCurrentStatus() != CurrentQuestStatus.IN_PROGRESS)
continue;
_playerQuests.put(id, this);
}
// load sub quests
for (IDataNode questNode : _questNodes) {
String questName = questNode.getName();
assert questName != null;
String displayName = questNode.getString("display", questName);
if (displayName == null)
throw new AssertionError();
SubQuest quest = new SubQuest(this, questName, displayName, questNode);
_subQuests.put(questName.toLowerCase(), quest);
}
}
}
|
package com.googlecode.networklog;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Iptables {
public static HashMap<String, String> targets = null;
public static boolean getTargets(Context context) {
if(targets != null) {
return true;
}
targets = new HashMap<String, String>();
if(!NetworkLog.shell.sendCommand("cat /proc/net/ip_tables_targets")) {
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_check_rules), NetworkLog.shell.getError(true));
return false;
}
List<String> output = new ArrayList<String>();
if(NetworkLog.shell.waitForCommandExit(output) != 0) {
String error = "";
for(String line : output) {
error += line;
}
Log.e("NetworkLog", "Bad exit for getTargets (exit " + NetworkLog.shell.exitval + ")");
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_check_rules), error);
return false;
}
StringBuilder result = new StringBuilder();
for(String line : output) {
line = line.trim();
targets.put(line, line);
result.append(line).append(" ");
}
MyLog.d("getTargets result: [" + result + "]");
return true;
}
public static boolean addRules(Context context) {
String iptablesBinary = SysUtils.getIptablesBinary(context);
if(iptablesBinary == null) {
return false;
}
if(targets == null && getTargets(context) == false) {
return false;
}
if(!removeRules(context)) {
return false;
}
ArrayList<String> commands = new ArrayList<String>();
if(targets.get("LOG") != null) {
if(NetworkLogService.behindFirewall) {
commands.add(iptablesBinary + " -A OUTPUT ! -o lo -j LOG --log-prefix \"{NL}\" --log-uid");
commands.add(iptablesBinary + " -A INPUT ! -i lo -j LOG --log-prefix \"{NL}\" --log-uid");
} else {
commands.add(iptablesBinary + " -I OUTPUT 1 ! -o lo -j LOG --log-prefix \"{NL}\" --log-uid");
commands.add(iptablesBinary + " -I INPUT 1 ! -i lo -j LOG --log-prefix \"{NL}\" --log-uid");
}
} else if(targets.get("NFLOG") != null) {
if(NetworkLogService.behindFirewall) {
commands.add(iptablesBinary + " -A OUTPUT ! -o lo -j NFLOG --nflog-prefix \"{NL}\"");
commands.add(iptablesBinary + " -A INPUT ! -i lo -j NFLOG --nflog-prefix \"{NL}\"");
} else {
commands.add(iptablesBinary + " -I OUTPUT 1 ! -o lo -j NFLOG --nflog-prefix \"{NL}\"");
commands.add(iptablesBinary + " -I INPUT 1 ! -i lo -j NFLOG --nflog-prefix \"{NL}\"");
}
} else {
SysUtils.showError(context,
context.getResources().getString(R.string.iptables_error_unsupported_title),
context.getResources().getString(R.string.iptables_error_missingfeatures_text));
return false;
}
for(String command : commands) {
if(!NetworkLog.shell.sendCommand(command)) {
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_add_rules), NetworkLog.shell.getError(true));
return false;
}
List<String> output = new ArrayList<String>();
NetworkLog.shell.waitForCommandExit(output);
StringBuilder result = new StringBuilder();
for(String line : output) {
result.append(line);
}
if(MyLog.enabled) {
MyLog.d("addRules result: [" + result + "]");
}
if(NetworkLog.shell.exitval != 0) {
Log.e("NetworkLog", "Bad exit for addRules (exit " + NetworkLog.shell.exitval + ")");
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_add_rules), result.toString());
return false;
}
if(result.indexOf("No chain/target/match by that name", 0) != -1) {
Resources res = context.getResources();
SysUtils.showError(context,
res.getString(R.string.iptables_error_unsupported_title),
res.getString(R.string.iptables_error_missingfeatures_text));
return false;
}
}
return true;
}
public static boolean removeRules(Context context) {
String iptablesBinary = SysUtils.getIptablesBinary(context);
if(iptablesBinary == null) {
return false;
}
if(targets == null && getTargets(context) == false) {
return false;
}
int tries = 0;
while(checkRules(context) == true) {
ArrayList<String> commands = new ArrayList<String>();
if(targets.get("LOG") != null) {
commands.add(iptablesBinary + " -D OUTPUT ! -o lo -j LOG --log-prefix \"{NL}\" --log-uid");
commands.add(iptablesBinary + " -D INPUT ! -i lo -j LOG --log-prefix \"{NL}\" --log-uid");
} else if(targets.get("NFLOG") != null) {
commands.add(iptablesBinary + " -D OUTPUT ! -o lo -j NFLOG --nflog-prefix \"{NL}\"");
commands.add(iptablesBinary + " -D INPUT ! -i lo -j NFLOG --nflog-prefix \"{NL}\"");
} else {
SysUtils.showError(context,
context.getResources().getString(R.string.iptables_error_unsupported_title),
context.getResources().getString(R.string.iptables_error_missingfeatures_text));
return false;
}
for(String command : commands) {
if(!NetworkLog.shell.sendCommand(command)) {
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_remove_rules), NetworkLog.shell.getError(true));
return false;
}
List<String> output = new ArrayList<String>();
NetworkLog.shell.waitForCommandExit(output);
StringBuilder result = new StringBuilder();
for(String line : output) {
result.append(line);
}
if(MyLog.enabled) {
MyLog.d("removeRules result: [" + result + "]");
}
if(NetworkLog.shell.exitval != 0) {
Log.e("NetworkLog", "Bad exit for removeRules (exit " + NetworkLog.shell.exitval + ")");
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_remove_rules), result.toString());
return false;
}
}
tries++;
if(tries > 3) {
Log.w("NetworkLog", "Too many attempts to remove rules, moving along...");
return false;
}
}
return true;
}
public static String getRules(Context context) {
return getRules(context, false);
}
public static String getRules(Context context, boolean verbose) {
String iptablesBinary = SysUtils.getIptablesBinary(context);
if(iptablesBinary == null) {
return null;
}
String command;
if(verbose) {
command = iptablesBinary + " -L -v";
} else {
command = iptablesBinary + " -L";
}
if(!NetworkLog.shell.sendCommand(command)) {
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_check_rules), NetworkLog.shell.getError(true));
return null;
}
List<String> output = new ArrayList<String>();
NetworkLog.shell.waitForCommandExit(output);
StringBuilder result = new StringBuilder();
for(String line : output) {
result.append(line);
}
if(MyLog.enabled) {
MyLog.d("getRules result: [" + result + "]");
}
if(NetworkLog.shell.exitval != 0) {
Log.e("NetworkLog", "Bad exit for getRules (exit " + NetworkLog.shell.exitval + ")");
SysUtils.showError(context, context.getResources().getString(R.string.iptables_error_check_rules), result.toString());
return null;
}
return result.toString();
}
public static boolean checkRules(Context context) {
String rules = getRules(context, true);
if(rules == null) {
return false;
}
if(rules.indexOf("Perhaps iptables or your kernel needs to be upgraded", 0) != -1) {
Resources res = context.getResources();
SysUtils.showError(context, res.getString(R.string.iptables_error_unsupported_title), res.getString(R.string.iptables_error_unsupported_text));
return false;
}
return rules.indexOf("{NL}", 0) == -1 ? false : true;
}
}
|
package com.karateca.jstoolbox.joiner;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.karateca.jstoolbox.MyAction;
/**
* @author Andres Dominguez.
*/
public class JoinerAction extends MyAction {
private static final String VAR_DECLARATION = "^\\s*var.*";
private static final String MULTI_LINE_STRING = ".+\\+\\s*$";
private static final String MULTI_LINE_STRING_SECOND_LINE = "^\\s*'.+";
private Document document;
private Editor editor;
private Project project;
public void actionPerformed(AnActionEvent actionEvent) {
editor = actionEvent.getData(PlatformDataKeys.EDITOR);
if (editor == null) {
return;
}
project = getEventProject(actionEvent);
document = editor.getDocument();
String currentLine = getLineAtCaret();
String nextLine = getNextLine();
// Is the caret in a multi line string ('foo' +) and the next line is a
// string?
if (currentLine.matches(MULTI_LINE_STRING) &&
nextLine.matches(MULTI_LINE_STRING_SECOND_LINE)) {
joinStringWithNextLine();
return;
}
// Is it a variable declaration?
if (currentLine.endsWith(";") && nextLine.matches(VAR_DECLARATION)) {
joinCurrentVariableDeclaration(currentLine);
}
}
private void joinCurrentVariableDeclaration(final String currentLine) {
final String nextLine = getNextLine();
int lineNumber = getLineNumberAtCaret();
final TextRange currentLineTextRange = getTextRange(lineNumber);
final TextRange nextLineTextRange = getTextRange(lineNumber + 1);
runWriteActionInsideCommand(new Runnable() {
@Override
public void run() {
// Replace var from next line.
String newLine = nextLine.replaceFirst("var", " ");
document.replaceString(nextLineTextRange.getStartOffset(),
nextLineTextRange.getEndOffset(), newLine);
// Replace ; from current line.
newLine = currentLine.replaceAll(";$", ",");
document.replaceString(currentLineTextRange.getStartOffset(),
currentLineTextRange.getEndOffset(), newLine);
}
});
}
private void joinStringWithNextLine() {
int lineNumber = getLineNumberAtCaret();
TextRange currentLineTextRange = getTextRange(lineNumber);
// Get the text for the next line.
TextRange nextLineTextRange = getTextRange(lineNumber + 1);
String nextLine = getLine(nextLineTextRange);
// Merge the current line into the next line.
final String newLine = getLineAtCaret().replaceAll("'\\s*\\+\\s*$", "") +
nextLine.replaceAll("^\\s*'", "");
final int start = currentLineTextRange.getStartOffset();
final int end = nextLineTextRange.getEndOffset();
runWriteActionInsideCommand(new Runnable() {
@Override
public void run() {
document.replaceString(start, end, newLine);
}
});
}
private String getLineAtCaret() {
int lineNumber = getLineNumberAtCaret();
return getLine(getTextRange(lineNumber));
}
private String getNextLine() {
int lineNumber = getLineNumberAtCaret();
return getLine(getTextRange(lineNumber + 1));
}
private int getLineNumberAtCaret() {
int offset = editor.getCaretModel().getOffset();
return document.getLineNumber(offset);
}
private String getLine(TextRange range) {
return document.getText(range);
}
/**
* Get the text range for a line of code.
*
* @param lineNumber The line number.
* @return The text range for the line.
*/
private TextRange getTextRange(int lineNumber) {
int lineStart = document.getLineStartOffset(lineNumber);
int lineEnd = document.getLineEndOffset(lineNumber);
return new TextRange(lineStart, lineEnd);
}
/**
* Run a write operation within a command.
*
* @param action The action to run.
*/
private void runWriteActionInsideCommand(final Runnable action) {
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(action);
}
}, "Join", null);
}
}
|
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import java.util.*;
import javax.servlet.http.*;
public class CmsAdminModuleCreate extends CmsWorkplaceDefault implements I_CmsConstants {
private final String C_PACKETNAME = "packetname";
private final String C_STEP = "step";
private final String C_VERSION = "version";
private final String C_MODULENAME = "modulename";
private final String C_DESCRIPTION = "description";
private final String C_VIEW = "view";
private final String C_ADMINPOINT = "adminpoint";
private final String C_MAINTENANCE = "maintenance";
private final String C_AUTHOR = "author";
private final String C_EMAIL = "email";
private final String C_DATE = "date";
private final String C_SESSION_DATA = "module_create_data";
/**
* Gets the content of a defined section in a given template file and its subtemplates
* with the given parameters.
*
* @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters)
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException {
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "getting content of element " + ((elementName==null)?"<root>":elementName));
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "template file is: " + templateFile);
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "selected template section is: " + ((templateSelector==null)?"<default>":templateSelector));
}
CmsXmlTemplateFile templateDocument = getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector);
CmsRequestContext reqCont = cms.getRequestContext();
I_CmsRegistry reg = cms.getRegistry();
I_CmsSession session = cms.getRequestContext().getSession(true);
String step = (String)parameters.get(C_STEP);
if ((step == null) || "".equals(step)){
templateDocument.setData(C_PACKETNAME, "");
templateDocument.setData(C_VERSION, "1");
templateDocument.setData(C_MODULENAME, "");
templateDocument.setData(C_DESCRIPTION, "");
templateDocument.setData(C_VIEW, "");
templateDocument.setData(C_ADMINPOINT, "");
templateDocument.setData(C_MAINTENANCE, "");
templateDocument.setData(C_AUTHOR, "");
templateDocument.setData(C_EMAIL, "");
templateDocument.setData(C_DATE, "");
}else{
if ("OK".equals(step)){
String packetname = (String)parameters.get(C_PACKETNAME);
String modulename = (String)parameters.get(C_MODULENAME);
String version = (String)parameters.get(C_VERSION);
String description = (String)parameters.get(C_DESCRIPTION);
String view = (String)parameters.get(C_VIEW);
String adminpoint = (String)parameters.get(C_ADMINPOINT);
String maintenance = (String)parameters.get(C_MAINTENANCE);
String author = (String)parameters.get(C_AUTHOR);
String email = (String)parameters.get(C_EMAIL);
String createDate = (String)parameters.get(C_DATE);
boolean moduleExists = reg.moduleExists(packetname);
int v = -1;
try{
v=Integer.parseInt(version);
}catch(Exception e){}
if ((packetname == null) || ("".equals(packetname)) ||(version == null)||("".equals(version))|| moduleExists || (v == -1)){
Hashtable sessionData = new Hashtable();
sessionData.put(C_MODULENAME, getStringValue(modulename));
sessionData.put(C_VERSION, getStringValue(version));
sessionData.put(C_DESCRIPTION, getStringValue(description));
sessionData.put(C_VIEW, getStringValue(view));
sessionData.put(C_ADMINPOINT, getStringValue(adminpoint));
sessionData.put(C_MAINTENANCE, getStringValue(maintenance));
sessionData.put(C_AUTHOR, getStringValue(author));
sessionData.put(C_EMAIL, getStringValue(email));
sessionData.put(C_DATE, getStringValue(createDate));
session.putValue(C_SESSION_DATA, sessionData);
if (moduleExists){
templateSelector = "errorexists";
}else{
templateSelector = "errornoname";
}
}else{
reg.createModule(packetname, getStringValue(modulename),
getStringValue(description),
getStringValue(author), getStringValue(createDate), v);
reg.setModuleAuthorEmail(packetname, getStringValue(email));
reg.setModuleMaintenanceEventClass(packetname, getStringValue(maintenance));
tryToCreateFolder(cms, "/system/", "modules");
tryToCreateFolder(cms, "/system/", "classes");
tryToCreateFolder(cms, "/", "moduledemos");
tryToCreateFolder(cms, "/moduledemos/", packetname );
// create the class folder:
Vector cFolders = new Vector();
String workString = packetname;
while(workString.lastIndexOf('.') >-1){
cFolders.addElement(workString.substring(workString.lastIndexOf('.')+1));
workString = workString.substring(0, workString.lastIndexOf('.'));
}
tryToCreateFolder(cms, "/system/classes/", workString);
workString = "/system/classes/" + workString +"/";
for (int i = cFolders.size()-1; i>= 0; i
tryToCreateFolder(cms, workString, (String)cFolders.elementAt(i));
workString = workString + (String)cFolders.elementAt(i) + "/";
}
tryToCreateFolder(cms, "/system/modules/", packetname);
String modulePath = "/system/modules/"+ packetname+"/";
tryToCreateFolder(cms, modulePath, "templates");
tryToCreateFolder(cms, modulePath, "language");
tryToCreateFolder(cms, modulePath + "language/", "de");
tryToCreateFolder(cms, modulePath + "language/", "uk");
if ("checked".equals(view)){
reg.setModuleView(packetname, packetname.replace('.','_'), modulePath+"view/index.html");
tryToCreateFolder(cms, modulePath, "view");
}
if ("checked".equals(adminpoint)){
tryToCreateFolder(cms, modulePath, "administration");
}
try{
cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceAdministrationPath() +"module/index.html");
} catch (Exception e) {
throw new CmsException("Redirect fails :system/workplace/administration/module/index.html",CmsException.C_UNKNOWN_EXCEPTION,e);
}
return null;
}
}else if ("fromerrorpage".equals(step)){
Hashtable sessionData = (Hashtable)session.getValue(C_SESSION_DATA);
session.removeValue(C_SESSION_DATA);
templateDocument.setData(C_PACKETNAME, "");
templateDocument.setData(C_VERSION, (String)sessionData.get(C_VERSION));
templateDocument.setData(C_MODULENAME, (String)sessionData.get(C_MODULENAME));
templateDocument.setData(C_DESCRIPTION, (String)sessionData.get(C_DESCRIPTION));
templateDocument.setData(C_VIEW, (String)sessionData.get(C_VIEW));
templateDocument.setData(C_ADMINPOINT, (String)sessionData.get(C_ADMINPOINT));
templateDocument.setData(C_MAINTENANCE, (String)sessionData.get(C_MAINTENANCE));
templateDocument.setData(C_AUTHOR, (String)sessionData.get(C_AUTHOR));
templateDocument.setData(C_EMAIL, (String)sessionData.get(C_EMAIL));
templateDocument.setData(C_DATE, (String)sessionData.get(C_DATE));
templateSelector = "";
}
}
// Now load the template file and start the processing
return startProcessing(cms, templateDocument, elementName, parameters, templateSelector);
}
private String getStringValue(String param) {
if(param == null){
return "";
}
return param;
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
private void tryToCreateFolder(CmsObject cms, String folder, String newFolder) {
System.err.println("mgm----tryToCreateFolder: "+ folder+" - "+ newFolder);
try{
cms.createFolder(folder, newFolder);
}catch(Exception e){
System.err.println("mgm-Exception: "+e.toString());
}
}
}
|
package com.turbomanage.httpclient;
/**
* An HTTP client that completes all requests asynchronously using
* {@link DoHttpRequestTask}. All methods take a callback argument which is
* passed to the task and whose methods are invoked when the request completes
* or throws on exception.
*
* @author David M. Chandler
*/
public class AsyncHttpClient extends AbstractHttpClient {
private int maxRetries = 3;
/*
* The factory that will be used to obtain an async wrapper for the
* request. Usually set in a subclass that provides a platform-specific
* async wrapper such as a new thread or Android AsyncTask.
*/
protected final AsyncRequestExecutorFactory execFactory;
/**
* Constructs a new client with empty baseUrl. When used this way, the path
* passed to a request method must be the complete URL.
*/
public AsyncHttpClient(AsyncRequestExecutorFactory factory) {
this(factory, "");
}
/**
* Constructs a new client using the default {@link RequestHandler} and
* {@link RequestLogger}.
*/
public AsyncHttpClient(AsyncRequestExecutorFactory factory, String baseUrl) {
super(baseUrl);
this.execFactory = factory;
setRequestHandler(new AbstractRequestHandler() {
});
setRequestLogger(new ConsoleRequestLogger());
}
/**
* Execute a GET request and invoke the callback on completion. The supplied
* parameters are URL encoded and sent as the query string.
*
* @param path
* @param params
* @param callback
*/
public void get(String path, ParameterMap params, AsyncCallback callback) {
HttpRequest req = new HttpGetRequest(path, params);
executeAsync(req, callback);
}
/**
* Execute a POST request with parameter map and invoke the callback on
* completion.
*
* @param path
* @param params
* @param callback
*/
public void post(String path, ParameterMap params, AsyncCallback callback) {
HttpRequest req = new HttpPostRequest(path, params);
executeAsync(req, callback);
}
/**
* Execute a POST request with a chunk of data and invoke the callback on
* completion.
*
* @param path
* @param contentType
* @param data
* @param callback
*/
public void post(String path, String contentType, byte[] data, AsyncCallback callback) {
HttpPostRequest req = new HttpPostRequest(path, contentType, data);
executeAsync(req, callback);
}
/**
* Execute a PUT request with the supplied content and invoke the callback
* on completion.
*
* @param path
* @param contentType
* @param data
* @param callback
*/
public void put(String path, String contentType, byte[] data, AsyncCallback callback) {
HttpPutRequest req = new HttpPutRequest(path, contentType, data);
executeAsync(req, callback);
}
/**
* Execute a DELETE request and invoke the callback on completion. The
* supplied parameters are URL encoded and sent as the query string.
*
* @param path
* @param params
* @param callback
*/
public void delete(String path, ParameterMap params, AsyncCallback callback) {
HttpDeleteRequest req = new HttpDeleteRequest(path, params);
executeAsync(req, callback);
}
/**
* Execute an {@link HttpRequest} asynchronously. Uses a factory to obtain a
* suitable async wrapper in order to decouple from Android.
*
* @param httpRequest
* @param callback
*/
protected void executeAsync(HttpRequest httpRequest, AsyncCallback callback) {
AsyncRequestExecutor executor = execFactory.getAsyncRequestExecutor(this, callback);
executor.execute(httpRequest);
}
/**
* Tries several times until successful or maxRetries exhausted.
* Must throw exception in order for the async process to forward
* it to the callback's onError method.
*
* @param httpRequest
* @return
* @throws HttpRequestException
*/
public HttpResponse tryMany(HttpRequest httpRequest) throws HttpRequestException {
int n = getMaxRetries();
HttpResponse res = null;
while (n > 0) {
try {
System.out.println("n=" + n + " Trying " + httpRequest.getPath());
res = doHttpMethod(httpRequest.getPath(),
httpRequest.getHttpMethod(), httpRequest.getContentType(),
httpRequest.getContent());
n = 0;
// TODO This should be the only kind we get--can we ensure?
} catch (HttpRequestException e) {
if (isTimeoutException(e)) {
// try again with exponential backoff
setConnectionTimeout(connectionTimeout * 2);
} else {
n = 0;
requestHandler.onError(res, e);
// rethrow to caller
throw e;
}
} finally {
n
}
}
return res;
}
public int getMaxRetries() {
return maxRetries;
}
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
}
|
package com.hits.modules.order;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;
import com.hits.common.action.BaseAction;
import com.hits.common.dao.ObjectCtl;
import com.hits.common.filter.GlobalsFilter;
import com.hits.common.filter.UserLoginFilter;
import com.hits.common.util.DateUtil;
import com.hits.common.util.StringUtil;
import com.hits.modules.bean.Cs_value;
import com.hits.modules.bean.File_info;
import com.hits.modules.com.YWCL;
import com.hits.modules.com.comUtil;
import com.hits.modules.order.bean.OrderBean;
import com.hits.modules.sys.bean.Sys_unit;
import com.hits.modules.sys.bean.Sys_user;
import com.hits.util.EmptyUtils;
import com.hits.util.PageObj;
import com.hits.util.SysLogUtil;
/**
* @author JJF E-mail:
* @version 201788 7:55:26
*
*/
@IocBean
@At("/private/order")
@Filters({ @By(type = GlobalsFilter.class), @By(type = UserLoginFilter.class) })
public class OrderAction extends BaseAction{
@Inject
protected Dao dao;
@At("")
@Ok("->:/private/order/orderList.html")
public void order(HttpSession session, HttpServletRequest req,@Param("startdate") String startdate,@Param("enddate") String enddate,@Param("unitid") String unitid) {
Sys_user user = (Sys_user) session.getAttribute("userSession");
req.setAttribute("unitid", unitid);//unitid
req.setAttribute("czrunitid", user.getUnitid());
req.setAttribute("startdate", startdate);
req.setAttribute("enddate", enddate);
req.setAttribute("isfhHash", JSONObject.fromObject(comUtil.isfhHash));
req.setAttribute("loginname",user.getLoginname());
Sql sql=Sqls.create("select id,name from sys_unit where unittype=88");
List<Map> unitMap = new ArrayList<Map>();
unitMap=daoCtl.list(dao, sql);
req.setAttribute("unitMap", unitMap);
req.setAttribute("isfhMap",comUtil.isfhMap);
}
@At
@Ok("raw")
public String orderList(HttpServletRequest req,@Param("unitid") String unitid,@Param("isfh") String isfh,HttpSession session,@Param("startdate") String startdate,@Param("enddate") String enddate,
@Param("name") String name,@Param("page") int curPage, @Param("rows") int pageSize,@Param("sort") String sort,@Param("order") String order){
Sys_user user=(Sys_user) session.getAttribute("userSession");
Criteria cri = Cnd.cri();
String sql="";
if(user.getUnitid().equals("0016")){
sql="select * from l_jsgg where 1=1 ";
}else{
sql="select * from l_jsgg where (actor = '"+user.getLoginname()+"' or unitid = '"+user.getUnitid()+"') ";
cri.where().and(Cnd.exps("actor", "=", user.getLoginname()).or("unitid", "=", user.getUnitid()));
}
if(EmptyUtils.isNotEmpty(unitid)){
cri.where().and("unitid","like",unitid+"%");
sql+=" and unitid like '"+unitid+"%'";
}
if(EmptyUtils.isNotEmpty(isfh)){
cri.where().and("isfh","=",isfh);
sql+=" and isfh = '"+isfh+"'";
}
if(EmptyUtils.isNotEmpty(startdate)&&EmptyUtils.isNotEmpty(enddate)){
cri.where().and("add_time",">=",startdate).and("add_time","<=",enddate);
sql+=" and add_time >= '"+startdate+"' and add_time <= '"+enddate+"'";
}
sql += " order by add_time desc";
QueryResult qr = daoCtl.listPage(dao,OrderBean.class ,curPage, pageSize,Sqls.create(sql),cri);
List<Map<String,Object>> list = (List<Map<String, Object>>) qr.getList();
sql="select code,name from Cs_value where typeid = '00010039'";
Map<String,String> loadselectMap=daoCtl.getHTable(dao, Sqls.create(sql));
sql="select id,name from sys_unit where unittype=88";
Map<String,String> unitMap=daoCtl.getHTable(dao, Sqls.create(sql));
for(int i=0;i<list.size();i++){
String odKz=StringUtil.null2String(list.get(i).get("hhgg"));
sql="select code from Cs_value where value='"+odKz+"' and typeid = '00010039'";
String code=daoCtl.getStrRowValue(dao, Sqls.create(sql));
int lg=code.length()/4;
String value="";
for (int j = 1; j <= lg; j++) {
value+=loadselectMap.get(code.substring(0,j*4))+"/";
}
int lg2=value.length()>0?value.length()-1:0;
value=value.substring(0,lg2);
list.get(i).put("hhgg",EmptyUtils.isEmpty(value)?odKz:value);
String unitname = StringUtil.null2String(list.get(i).get("unitid"));
list.get(i).put("unit", unitMap.get(unitname));
}
return PageObj.getPageJSON(qr);
}
@At
@Ok("->:/private/order/orderAdd.html")
public void toAdd(HttpServletRequest req,HttpSession session) {
req.setAttribute("isfhMap", comUtil.isfhMap);
req.setAttribute("today", DateUtil.getToday());
Sql sql=Sqls.create("select id,name from sys_unit where unittype=88");
List<Map> unitMap = new ArrayList<Map>();
unitMap=daoCtl.list(dao, sql);
req.setAttribute("unitMap", unitMap);
}
@At
@Ok("raw")
public boolean addSave(final HttpServletRequest req,HttpSession session,@Param("..") final OrderBean order,@Param("filepath") final String path,
@Param("filename") final String name,@Param("filesize") final String filesize){
final Sys_user user= (Sys_user)session.getAttribute("userSession");
final ThreadLocal<Boolean> re = new ThreadLocal<Boolean>();
try {
re.set(false);
Trans.exec(new Atom() {
public void run() {
order.setActor(user.getLoginname());
order.setXzqh_unit(daoCtl.detailByName(dao, Sys_unit.class, order.getUnitid()).getXzqh());
order.setHtid(getHtid());
order.setCreate_time(DateUtil.getCurDateTime());
dao.insert(order);
String[] paths=path.split(";");
String[] names=name.split(";");
String[] sizes=filesize.split(";");
for(int i=0;i<paths.length;i++){
File_info att = new File_info();
if(EmptyUtils.isNotEmpty(paths[i])&&EmptyUtils.isNotEmpty(names[i])){
att.setFilename(names[i]);
att.setFilepath(paths[i]);
att.setTablekey(order.getHtid()+"");
att.setTablename("l_jsgg");
att.setFieldname("fj");
att.setCreate_time(DateUtil.getCurDateTime());
att.setFilesize(sizes[i]);
dao.insert(att);
}
}
re.set(true);
}
});
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return re.get();
}
/**
*
* @param loginname
* @return
*/
@At
@Ok("raw")
public String getUnit(@Param("unitid") String unitid) {
if(EmptyUtils.isNotEmpty(unitid)){
Sql sql=Sqls.create("select * from sys_unit where id = "+unitid);
Sys_unit unit = daoCtl.detailByName(dao, Sys_unit.class, unitid);
String fzrxx = unit.getHandler()+";"+unit.getHandlerphone();
return fzrxx;
}else{
return null;
}
}
@At
@Ok("->:/private/order/orderUpdate.html")
public void toUpdate(@Param("htid") String id,HttpServletRequest req,HttpSession session){
OrderBean order = daoCtl.detailByName(dao, OrderBean.class, id);
req.setAttribute("order", order);
req.setAttribute("fileList", daoCtl.getMulRowValue(dao, Sqls.create("select filename,filepath||'*'||filesize from file_info where tablekey='"+id+"' and tablename='l_jsgg' order by create_time asc")));
req.setAttribute("isfhMap", comUtil.isfhMap);
Sql sql=Sqls.create("select id,name from sys_unit where unittype=88");
List<Map> unitMap = new ArrayList<Map>();
unitMap=daoCtl.list(dao, sql);
req.setAttribute("unitMap", unitMap);
}
@At
@Ok("raw")
public boolean updateSave(final HttpServletRequest req,HttpSession session,@Param("..") final OrderBean order,@Param("filepath") final String path,
@Param("filename") final String name,@Param("filesize") final String filesize){
final Sys_user user= (Sys_user)session.getAttribute("userSession");
final ThreadLocal<Boolean> re = new ThreadLocal<Boolean>();
try {
re.set(false);
Trans.exec(new Atom() {
public void run() {
String sqlfile="delete from file_info where tablekey='"+order.getHtid()+"' and tableName='l_jsgg'";
dao.execute(Sqls.create(sqlfile));
String[] paths=path.split(";");
String[] names=name.split(";");
String[] sizes=filesize.split(";");
for(int i=0;i<paths.length;i++){
File_info att = new File_info();
if(EmptyUtils.isNotEmpty(paths[i])&&EmptyUtils.isNotEmpty(names[i])){
att.setFilename(names[i]);
att.setFilepath(paths[i]);
att.setTablekey(order.getHtid()+"");
att.setTablename("l_jsgg");
att.setFieldname("fj");
att.setCreate_time(DateUtil.getCurDateTime());
att.setFilesize(sizes[i]);
dao.insert(att);
}
}
dao.update(order);
re.set(true);
}
});
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return re.get();
}
@At
@Ok("->:/private/order/orderDetail.html")
public void toPreview(@Param("htid") String id,HttpServletRequest req,HttpSession session){
OrderBean order = daoCtl.detailByName(dao, OrderBean.class, id);
order.setHhgg(YWCL.getValueFromCs(daoCtl, dao, "00010039", order.getHhgg()));
order.setIsfh(YWCL.getValueFromCs(daoCtl, dao, "00010038", order.getIsfh()));
req.setAttribute("unit",daoCtl.detailByName(dao, Sys_unit.class, order.getUnitid()) );
req.setAttribute("fileList", daoCtl.getMulRowValue(dao, Sqls.create("select filename,filepath from file_info where tablekey='"+id+"' and tablename='l_jsgg' order by create_time asc")));
req.setAttribute("isfhMap", comUtil.isfhMap);
Sql sql=Sqls.create("select id,name from sys_unit where unittype=88");
List<Map> unitMap = new ArrayList<Map>();
unitMap=daoCtl.list(dao, sql);
req.setAttribute("unitMap", unitMap);
req.setAttribute("order", order);
}
/**
*
* @return
*/
@At
@Ok("raw")
public boolean delete(final @Param("htid") String htid){
boolean resule = false;
if(EmptyUtils.isNotEmpty(htid)){
resule= daoCtl.deleteByName(dao, OrderBean.class, htid);
}
return resule;
}
public synchronized static String getHtid() {
String letterid="";
Dao dao = Mvcs.getIoc().get(Dao.class);
ObjectCtl daoCtl=new ObjectCtl();
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
String ymd=sdf.format(new java.util.Date());
letterid=ymd;
letterid=daoCtl.getSubMenuId(dao, "l_jsgg", "htid", letterid);
return letterid;
}
@At
public void dcXxsb(HttpServletRequest req,HttpSession session,@Param("unitid")String unitid,
@Param("startdate")String startdate,@Param("enddate")String enddate,@Param("czrunitid")String czrunitid,
HttpServletResponse response) {
try {
String sqlstr = "";
String sqlzj = "";
sqlstr = "select ddmc,unitid,hhgg,add_time,yfjk from l_jsgg where isfh='0002' ";
sqlzj = "select sum(yfjk) as zj from l_jsgg where isfh='0002'";
if(EmptyUtils.isNotEmpty(unitid)){
sqlstr+=" and unitid='"+unitid+"' ";
sqlzj+=" and unitid='"+unitid+"' ";
}
if(EmptyUtils.isNotEmpty(czrunitid)){
sqlstr+=" and unitid='"+czrunitid+"' ";
sqlzj+=" and unitid='"+czrunitid+"' ";
}
if(EmptyUtils.isNotEmpty(startdate)&&EmptyUtils.isNotEmpty(enddate)){
sqlstr += "and add_time between '" + startdate + "' and '" + enddate + "'";
sqlzj += "and add_time between '" + startdate + "' and '" + enddate + "'";
}
sqlstr += " order by add_time desc";
List<Map> list=daoCtl.list(dao, Sqls.create(sqlstr));
String zj = daoCtl.getStrRowValue(dao, Sqls.create(sqlzj));
for(Map yytjmap:list){
yytjmap.put("unitid",daoCtl.detailByName(dao, Sys_unit.class, yytjmap.get("unitid").toString()).getName());
yytjmap.put("hhgg", daoCtl.detailBySql(dao, Cs_value.class, Sqls.create("select * from cs_value where code ='"+yytjmap.get("hhgg")+"' and typeid='00010039'")).getName());
}
// webbookExcel
HSSFWorkbook wb = new HSSFWorkbook();
// webbooksheet,Excelsheet
HSSFSheet sheet = wb.createSheet("");
sheet.setColumnWidth(1, 20 * 256);
sheet.setColumnWidth(2, 30 * 256);
sheet.setColumnWidth(3, 20 * 256);
sheet.setColumnWidth(4, 30 * 256);
sheet.setColumnWidth(5, 20 * 256);
// sheet0,poiExcelshort
int rowIndex = 0;
HSSFRow row = sheet.createRow(rowIndex++);
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
String[] headers = {"","","","","",""};
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell((short) i);
cell.setCellValue(headers[i]);
cell.setCellStyle(style);
}
HSSFCell cell = row.createCell((short) 0);
for(int i=0;i<list.size();i++){
row = sheet.createRow(i+1);
Map map=list.get(i);
cell= row.createCell((short) 0);
cell.setCellValue(i+1);
cell.setCellStyle(style);
cell= row.createCell((short) 1);
cell.setCellValue(StringUtil.null2String(map.get("ddmc")));
cell.setCellStyle(style);
cell= row.createCell((short) 2);
cell.setCellValue(StringUtil.null2String(map.get("unitid")));
cell.setCellStyle(style);
cell= row.createCell((short) 3);
cell.setCellValue(StringUtil.null2String(map.get("hhgg")));
cell.setCellStyle(style);
cell= row.createCell((short) 4);
cell.setCellValue(StringUtil.null2String(map.get("add_time")));
cell.setCellStyle(style);
cell= row.createCell((short) 5);
cell.setCellValue(StringUtil.null2String(map.get("yfjk")));
cell.setCellStyle(style);
}
cell= row.createCell((short) 6);
cell.setCellValue(""+zj);
response.setContentType("application/vnd.ms-excel;charset=ISO8859-1");
String fileName="";
response.setHeader("Content-Disposition", "attachment;filename=\""+ new String(fileName.getBytes("gb18030"),"ISO8859-1") + ".xls" + "\"");
OutputStream output;
output = response.getOutputStream();
wb.write(output);
output.flush();
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.font.Font;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.misc.IntRange;
import lombok.Getter;
import lombok.Setter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import java.util.Optional;
public class Component {
/** The x-axis (column) coordinate of the top-left character. */
@Getter private int columnIndex;
/** The y-axis (row) coordinate of the top-left character. */
@Getter private int rowIndex;
/** The width, in characters. */
@Getter private int width;
/** The height, in characters. */
@Getter private int height;
/** Whether or not the component is currently the target of the user's input. */
@Getter private boolean isFocused = false;
/** The bounding box. */
@Getter private Rectangle boundingBox = new Rectangle();
/** The strings representing the character-rows of the component. */
@Getter private AsciiString[] strings;
/** The radio to transmit events to. */
@Getter private Radio<String> radio;
/** The screen that the component is on. */
@Getter @Setter private Screen screen;
/**
* Constructs a new AsciiComponent.
*
* @param columnIndex
* The x-axis (column) coordinate of the top-left character.
*
* @param rowIndex
* The y-axis (row) coordinate of the top-left character.
*
* @param width
* The width, in characters.
*
* @param height
* The height, in characters.
*/
public Component(final int columnIndex, final int rowIndex, final int width, final int height) {
if (columnIndex < 0) {
throw new IllegalArgumentException("You must specify a columnIndex of 0 or greater.");
}
if (rowIndex < 0) {
throw new IllegalArgumentException("You must specify a rowIndex of 0 or greater.");
}
if (width < 1) {
throw new IllegalArgumentException("You must specify a width of 1 or greater.");
}
if (height < 1) {
throw new IllegalArgumentException("You must specify a height of 1 or greater.");
}
this.columnIndex = columnIndex;
this.rowIndex = rowIndex;
this.width = width;
this.height = height;
boundingBox.setLocation(columnIndex, rowIndex);
boundingBox.setSize(width, height);
strings = new AsciiString[height];
for (int row = 0 ; row < height ; row++) {
strings[row] = new AsciiString(width);
}
}
@Override
public boolean equals(final Object other) {
if (other instanceof Component == false) {
return false;
}
// Left out a check for isFocused since two components could be
// virtually identical other than their focus.
// Left out a check for radio.
final Component otherComp = (Component) other;
boolean isEqual = columnIndex == otherComp.getColumnIndex();
isEqual &= rowIndex == otherComp.getRowIndex();
isEqual &= width == otherComp.getWidth();
isEqual &= height == otherComp.getHeight();
isEqual &= boundingBox.equals(otherComp.getBoundingBox());
isEqual &= Arrays.equals(strings, otherComp.getStrings());
return isEqual;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Component:");
sb.append("\n\tColumn Index:\t").append(columnIndex);
sb.append("\n\tRow Index:\t").append(rowIndex);
sb.append("\n\tWidth:\t").append(width);
sb.append("\n\tHeight:\t").append(height);
sb.append("\n\tIs Focused:\t").append(isFocused);
sb.append("\n\tBounding Box:\t" + boundingBox);
sb.append("\n\tStrings:\n");
for (final AsciiString string : strings) {
for (final AsciiCharacter character : string.getCharacters()) {
sb.append(character.getCharacter());
}
sb.append("\n\t\t");
}
sb.append("\n\tRadio:\t" + radio);
return sb.toString();
}
/**
* Registers events, required by the component, with the specified panel.
*
* @param panel
* The panel to register events with.
*/
public void registerEventHandlers(final Panel panel) {
final Font font = panel.getAsciiFont();
final int fontWidth = font.getWidth();
final int fontHeight = font.getHeight();
panel.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
isFocused = intersects(e, fontWidth, fontHeight);
}
}
@Override
public void mousePressed(final MouseEvent e) {}
@Override
public void mouseReleased(final MouseEvent e) {}
@Override
public void mouseEntered(final MouseEvent e) {}
@Override
public void mouseExited(final MouseEvent e) {}
});
}
/**
* Draws the component on the specified screen.
*
* @param screen
* The screen to draw on.
*/
public void draw(final Screen screen) {
for (int row = 0 ; row < strings.length ; row++) {
screen.write(strings[row], columnIndex, rowIndex + row);
}
}
/** Attempts to transmit a "DRAW" event to the assigned Radio. */
public void transmitDraw() {
if (radio != null) {
radio.transmit("DRAW");
}
}
/**
* Determines if the specified component intersects with this component.
*
* @param otherComponent
* The component to check intersection with.
*
* @return
* Whether or not the components intersect.
*/
public boolean intersects(final Component otherComponent) {
return otherComponent != null && boundingBox.intersects(otherComponent.getBoundingBox());
}
/**
* Determines if the specified point intersects with this component.
*
* @param pointX
* The x-axis (column) coordinate.
*
* @param pointY
* The y-axis (row) coordinate.
*
* @return
* Whether or not the point intersects with this component.
*/
public boolean intersects(final int pointX, final int pointY) {
boolean intersects = pointX >= columnIndex;
intersects &= pointX < (boundingBox.getWidth() + columnIndex);
intersects &= pointY >= rowIndex;
intersects &= pointY < (boundingBox.getHeight() + rowIndex);
return intersects;
}
/**
* Determines whether or not the specified mouse event is at a point that intersects this component.
*
* @param event
* The event.
*
* @param fontWidth
* The width of the font being used to draw the component's characters.
*
* @param fontHeight
* The height of the font being used to draw the component's characters.
*
* @return
* Whether or not the mouse event is at a point that intersects this component.
*/
public boolean intersects(final MouseEvent event, final int fontWidth, final int fontHeight) {
final int mouseX = event.getX() / fontWidth;
final int mouseY = event.getY() / fontHeight;
return intersects(mouseX, mouseY);
}
/**
* Determines whether or not the specified position is within the bounds of the component.
*
* @param columnIndex
* The x-axis (column) coordinate.
*
* @param rowIndex
* The y-axis (row) coordinate.
*
* @return
* Whether or not the specified position is within the bounds of the component.
*/
public boolean isPositionValid(final int columnIndex, final int rowIndex) {
if (rowIndex < 0 || rowIndex > boundingBox.getHeight() - 1) {
return false;
}
if (columnIndex < 0 || columnIndex > boundingBox.getWidth() - 1) {
return false;
}
return true;
}
/**
* Enables the blink effect for every character.
*
* @param millsBetweenBlinks
* The amount of time, in milliseconds, before the blink effect can occur.
*
* @param radio
* The Radio to transmit a DRAW event to whenever a blink occurs.
*/
public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) {
for (final AsciiString s: strings) {
for (final AsciiCharacter c : s.getCharacters()) {
c.enableBlinkEffect(millsBetweenBlinks, radio);
}
}
}
/** Resumes the blink effect for every character. */
public void resumeBlinkEffect() {
for (final AsciiString s: strings) {
for (final AsciiCharacter c : s.getCharacters()) {
c.resumeBlinkEffect();
}
}
}
/** Pauses the blink effect for every character. */
public void pauseBlinkEffect() {
for (final AsciiString s: strings) {
for (final AsciiCharacter c : s.getCharacters()) {
c.pauseBlinkEffect();
}
}
}
/** Disables the blink effect for every character. */
public void disableBlinkEffect() {
for (final AsciiString s: strings) {
for (final AsciiCharacter c : s.getCharacters()) {
c.disableBlinkEffect();
}
}
}
/** Sets all characters to be redrawn. */
public void setAllCharactersToBeRedrawn() {
for (final AsciiString string : strings) {
string.setAllCharactersToBeRedrawn();
}
}
/**
* Sets every character, on the Screen that the component
* resides on, at the component's current location to be
* redrawn.
*
* This should only be called when the component is moved
* on-screen or resized.
*/
private void setLocationOnScreenToBeRedrawn() {
for (int y = rowIndex ; y <= rowIndex + height ; y++) {
screen.getStrings()[y].setCharacterRangeToBeRedrawn(new IntRange(columnIndex, columnIndex + width));
}
System.out.println();
}
/**
* Retrieves the AsciiCharacter at a specific location.
*
* @param columnIndex
* The x-axis (column) coordinate of the location.
*
* @param rowIndex
* The y-axis (row) coordinate of the location.
*
* @return
* The AsciiCharacter at the specified location or nothing
* if the location is invalid.
*/
public Optional<AsciiCharacter> getCharacterAt(final int columnIndex, final int rowIndex) {
if (isPositionValid(columnIndex, rowIndex)) {
return Optional.of(strings[rowIndex].getCharacters()[columnIndex]);
}
return Optional.empty();
}
/**
* Sets a new value for the columnIndex.
*
* Does nothing if the specified columnIndex is < 0.
*
* @param columnIndex
* The new x-axis (column) coordinate of the top-left character of the component.
*
* @return
* Whether or not the new value was set.
*/
public void setColumnIndex(final int columnIndex) {
if (columnIndex >= 0) {
setLocationOnScreenToBeRedrawn();
this.columnIndex = columnIndex;
boundingBox.setLocation(columnIndex, rowIndex);
setAllCharactersToBeRedrawn();
}
}
/**
* Sets a new value for the rowIndex.
*
* Does nothing if the specified rowIndex is < 0.
*
* @param rowIndex
* The y-axis (row) coordinate of the top-left character of the component.
*
* @return
* Whether or not the new value was set.
*/
public void setRowIndex(final int rowIndex) {
if (rowIndex >= 0) {
setLocationOnScreenToBeRedrawn();
this.rowIndex = rowIndex;
boundingBox.setLocation(columnIndex, rowIndex);
setAllCharactersToBeRedrawn();
}
}
/**
* Sets a new value for the width.
*
* Does nothing if the specified width is < 0 or < columnIndex.
*
* @param width
* The new width, in characters, of the component.
*
* @return
* Whether or not the new value was set.
*/
public void setWidth(final int width) {
if (width < 0 || width < columnIndex) {
return;
}
setLocationOnScreenToBeRedrawn();
this.width = width;
boundingBox.setSize(width, height);
setAllCharactersToBeRedrawn();
}
/**
* Sets a new value for the height.
*
* Does nothing if the specified height is < 0 or < rowIndex.
*
* @param height
* The new height, in characters, of the component.
*
* @return
* Whether or not the new value was set.
*/
public void setHeight(final int height) {
if (height < 0 || height < rowIndex) {
return;
}
setLocationOnScreenToBeRedrawn();
this.height = height;
boundingBox.setSize(width, height);
setAllCharactersToBeRedrawn();
}
/**
* Sets a new radio.
*
* @param radio
* The new radio.
*/
public void setRadio(final Radio<String> radio) {
if (radio != null) {
this.radio = radio;
}
}
}
|
package com.jensen.game.view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* A view in which to setup a game.
*/
public class GameSetupView extends JPanel {
public static void main(String[] args) {
GameSetupView a = new GameSetupView("acb");
a.showDifficulties(new String[] { "Aaifhsio", "soifseo" });
a.showOpponentType(new String[] { "afjei", "pohjrs" });
a.showPlayerCount(5, 10);
JFrame frame = new JFrame();
frame.add(a);
//frame.setSize(new Dimension(300, 500));
frame.pack();
frame.setVisible(true);
}
private String name;
private JPanel centerPanel;
private JButton startButton;
private JComboBox difficultyComboBox;
private JComboBox opponentComboBox;
private JSpinner playerCountSpinner;
private JSpinner boardSizeSpinner;
public GameSetupView(String name) {
this.name = name;
setLayout(new BorderLayout(5, 5));
initCenterPanel();
initExitPanel();
}
private void initExitPanel() {
JPanel startPanel = new JPanel();
startPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
startButton = new JButton("Done");
startPanel.add(startButton);
add(startPanel, BorderLayout.SOUTH);
}
private void initCenterPanel() {
JPanel centerPanelWrapper = new JPanel();
centerPanelWrapper.setLayout(new FlowLayout(FlowLayout.CENTER));
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(0, 1, 0, 10));
centerPanelWrapper.add(centerPanel);
add(centerPanelWrapper);
}
public void showDifficulties(String[] difficulties) {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel difficultyDescription = new JLabel("Difficulty: ");
panel.add(difficultyDescription);
difficultyComboBox = new JComboBox(difficulties);
panel.add(difficultyComboBox);
centerPanel.add(panel);
}
public Object getDifficulty() {
if (difficultyComboBox == null) {
return null;
}
return difficultyComboBox.getSelectedItem();
}
public void showPlayerCount(int min, int max) {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel playerCountDescription = new JLabel("Player count: ");
panel.add(playerCountDescription);
playerCountSpinner = new JSpinner(new SpinnerNumberModel(min, min, max, 1));
panel.add(playerCountSpinner);
centerPanel.add(panel);
}
public Object getPlayerCount() {
if (playerCountSpinner == null) {
return null;
}
return playerCountSpinner.getModel().getValue();
}
public void showOpponentType(String[] types) {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel opponentDescription = new JLabel("Opponent: ");
panel.add(opponentDescription);
opponentComboBox = new JComboBox(types);
panel.add(opponentComboBox);
centerPanel.add(panel);
}
public Object getOpponentType() {
if (opponentComboBox == null) {
return null;
}
return opponentComboBox.getSelectedItem();
}
public void showBoardSize(int min, int max, int stepSize) {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel boardSizeDescription = new JLabel("Board size: ");
panel.add(boardSizeDescription);
boardSizeSpinner = new JSpinner(new SpinnerNumberModel(min, min, max, stepSize));
panel.add(boardSizeSpinner);
centerPanel.add(panel);
}
public Object getBoardSize() {
if (boardSizeSpinner == null) {
return null;
}
return boardSizeSpinner.getModel().getValue();
}
public String getName() {
return name;
}
public void addListeners(ActionListener l) {
startButton.addActionListener(l);
}
}
|
package com.valkryst.generator;
import com.valkryst.NameGenerator;
import com.valkryst.builder.MarkovBuilder;
import com.valkryst.markov.MarkovChain;
import java.util.Optional;
public final class MarkovNameGenerator implements NameGenerator {
/** The chain to use when generating names. */
private final MarkovChain markovChain = new MarkovChain();
/**
* Constructs a MarkovNameGenerator.
*
* @param builder
* Builder containing the training names.
*/
public MarkovNameGenerator(final MarkovBuilder builder) {
markovChain.train(builder.getTrainingNames());
}
@Override
public String generateName(int length) {
if (length == 0) {
length = 2;
}
final StringBuilder sb = new StringBuilder();
sb.append(markovChain.chooseRandomString()); // Begin the name with a random pair of two characters.
for (int i = 2; i < length; ++i) {
final Optional<Character> next = markovChain.chooseRandomCharacter(sb.substring(i - 2, i));
if (next.isPresent()) {
sb.append(next.get());
} else {
break;
}
}
// Capitalize the first letter of the name:
return sb.toString().substring(0, 1).toUpperCase() + sb.toString().substring(1);
}
}
|
package com.wake_e.services.managers;
import java.util.Calendar;
import android.content.Context;
import android.content.Intent;
import com.wake_e.constants.WakeEConstants;
import com.wake_e.exceptions.NoRouteFoundException;
import com.wake_e.model.Location;
import com.wake_e.model.sqlite.WakeEDBHelper;
import com.wake_e.services.AlarmIntentService;
import com.wake_e.services.AlarmSynchroIntentService;
/**
* @brief Manage all alarms
* @author Wake-E team
*/
public class AlarmsManager{
// the synchronized alarm of the application
private AlarmSynchroIntentService alarmSynchro;
private static final int SECOND = 1000;
private static final int MINUTE = 60 * SECOND;
private static final int HOUR = 60 * MINUTE;
private static final int DAY = 24 * HOUR;
private WakeEDBHelper db;
public AlarmsManager(WakeEDBHelper db) {
super();
this.db = db;
}
public void loadAlarm(){
this.db.loadAlarm();
}
/**
* @return
* @brief create an alarm and add it to the list
*/
public Intent createAlarm(Context context, Location depart, Location arrivee,
long preparationDuration, String ringtone, String transport,
long endHour) throws NoRouteFoundException {
// TODO On teste si une Route est trouvee avec le depart et l'arrivee
// Si ce n'est pas le cas, on throw une exception
Intent intent = new Intent(context, AlarmIntentService.class);
intent.putExtra(WakeEConstants.AlarmServiceExtras.DEPART, depart);
intent.putExtra(WakeEConstants.AlarmServiceExtras.ARRIVEE, arrivee);
intent.putExtra(WakeEConstants.AlarmServiceExtras.PREPARATION, preparationDuration);
intent.putExtra(WakeEConstants.AlarmServiceExtras.RINGTONE, ringtone);
intent.putExtra(WakeEConstants.AlarmServiceExtras.TRANSPORT, transport);
intent.putExtra(WakeEConstants.AlarmServiceExtras.END_HOUR, endHour);
return intent;
}
/**
* @brief retrieve an alarm
* @param alarmId
* the alarm id
* @return the alarm
*/
public AlarmIntentService getAlarm() {
return AlarmIntentService.getInstance();
}
/**
* @brief enable or disable an alarm
* @param alarmId
* @param enabled
* TRUE=enabled FALSE=disabled
* @param context
*/
public void enableAlarm(boolean enabled, Context context) {
AlarmIntentService a = this.getAlarm();
if (a != null) {
if (enabled) {
if (!a.isEnabled()) {
this.db.insertAlarm(this.getAlarm());
a.enable(context);
}
} else {
if (a.isEnabled()) {
a.disable();
}
}
}
}
/**
* @brief get the alarm synchro
* @return the alarm synchro
*/
public AlarmSynchroIntentService getAlarmSynchro() {
return this.alarmSynchro;
}
/**
* @brief enable the alarm synchro
* @param enabled
* TRUE=enabled FALSE=disabled
* @param context
*/
public void enableAlarmSynchro(boolean enabled, Context context) {
this.alarmSynchro.enable(context);
}
public String getWakeUpHour() {
Long ms = AlarmIntentService.getInstance().computeWakeUp();
StringBuffer text = new StringBuffer("");
if (ms > HOUR) {
text.append(ms / HOUR).append(" hours ");
ms %= HOUR;
}
if (ms > MINUTE) {
text.append(ms / MINUTE).append(" minutes ");
ms %= MINUTE;
}
return text.toString();
}
}
|
package com.yidejia.app.mall.fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.yidejia.app.mall.MyApplication;
import com.yidejia.app.mall.R;
import com.yidejia.app.mall.datamanage.AddressDataManage;
import com.yidejia.app.mall.datamanage.CartsDataManage;
import com.yidejia.app.mall.datamanage.PreferentialDataManage;
import com.yidejia.app.mall.model.Addresses;
import com.yidejia.app.mall.model.UserComment;
import com.yidejia.app.mall.util.CartUtil;
import com.yidejia.app.mall.util.Consts;
import com.yidejia.app.mall.view.ExchangeFreeActivity;
import com.yidejia.app.mall.view.GoCartActivity;
import com.yidejia.app.mall.view.LoginActivity;
import com.yidejia.app.mall.view.NewAddressActivity;
//import com.yidejia.app.mall.view.PayActivity;
public class CartActivity extends SherlockFragment implements OnClickListener {
private ImageView subtract;
private TextView number;
private ImageView addImageView;
private ImageView subtract2;
private TextView number2;
private ImageView addImageView2;
private int sumString;
private TextView sumTextView;
private TextView counTextView;
private TextView priceTextView1;
private TextView priceTextView2;
private View person;
private View person2;
private CartsDataManage dataManage;
private Button shoppingCartTopay;
private ImageView mImageView;
private ArrayList<UserComment> mlist;
private CartUtil cartUtil;
private CheckBox mBox;
private final int MENU1 = 0x111;
private final int MENU2 = 0x112;
private final int MENU3 = 0x113;
private LinearLayout layout;
private View view;
private CartsDataManage dataManage2;
// private AddressDataManage addressManage;//
private PullToRefreshScrollView mPullToRefreshScrollView;
private Fragment mFragment;
private MyApplication myApplication;
private PreferentialDataManage preferentialDataManage;
private List<HashMap<String, Float>> mlList = null;
// private InnerReceiver receiver;
// private InnerReceiver receiver;
// private void doClick(View v) {
// switch (v.getId()) {
// case R.id.shopping_cart_go_pay://
// Intent intent = new Intent(getSherlockActivity(),
// GoodsInfoActivity.class);
// getSherlockActivity().startActivity(intent);
// break;
// @Override
// public void onClick(View v) {
// if(v==person){
// int sum = Integer.parseInt(number.getText().toString());
// switch (v.getId()) {
// case R.id.shopping_cart_item_subtract://
// if (sum <= 0) {
// Toast.makeText(getSherlockActivity(), "",
// Toast.LENGTH_LONG).show();
// } else {
// sum--;
// number.setText(sum + "");
// sumTextView
// .setText(Double.parseDouble(priceTextView1.getText()
// .toString())
// * Double.parseDouble(number.getText()
// .toString())
// + Double.parseDouble(priceTextView2.getText()
// .toString())
// * Double.parseDouble(number2.getText()
// .toString()) + "");
// counTextView.setText(Integer.parseInt(number.getText()
// .toString())
// + Integer.parseInt(number2.getText().toString()) + "");
// break;
// case R.id.shopping_cart_item_add://
// if (sum >= 9999) {
// Toast.makeText(getSherlockActivity(), "",
// Toast.LENGTH_LONG).show();
// } else {
// sum++;
// number.setText(sum + "");
// sumTextView
// .setText(Double.parseDouble(priceTextView1.getText()
// .toString())
// * Double.parseDouble(number.getText()
// .toString())
// + Double.parseDouble(priceTextView2.getText()
// .toString())
// * Double.parseDouble(number2.getText()
// .toString()) + "");
// counTextView.setText(Integer.parseInt(number.getText()
// .toString())
// + Integer.parseInt(number2.getText().toString()) + "");
// break;
// }else if(v.equals(person2)) {
// int sum = Integer.parseInt(number2.getText().toString());
// switch (v.getId()) {
// case R.id.shopping_cart_item_subtract://
// if (sum <= 0) {
// Toast.makeText(getSherlockActivity(), "",
// Toast.LENGTH_LONG).show();
// } else {
// sum--;
// number2.setText(sum + "");
// sumTextView
// .setText(Double.parseDouble(priceTextView1.getText()
// .toString())
// * Double.parseDouble(number.getText()
// .toString())
// + Double.parseDouble(priceTextView2.getText()
// .toString())
// * Double.parseDouble(number2.getText()
// .toString()) + "");
// counTextView.setText(Integer.parseInt(number.getText()
// .toString())
// + Integer.parseInt(number2.getText().toString()) + "");
// break;
// case R.id.shopping_cart_item_add://
// if (sum >= 9999) {
// Toast.makeText(getSherlockActivity(), "",
// Toast.LENGTH_LONG).show();
// } else {
// sum++;
// number2.setText(sum + "");
// sumTextView
// .setText(Double.parseDouble(priceTextView1.getText()
// .toString())
// * Double.parseDouble(number.getText()
// .toString())
// + Double.parseDouble(priceTextView2.getText()
// .toString())
// * Double.parseDouble(number2.getText()
// .toString()) + "");
// counTextView.setText(Integer.parseInt(number.getText()
// .toString())
// + Integer.parseInt(number2.getText().toString()) + "");
// break;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// addressManage = new AddressDataManage(getSherlockActivity());
myApplication = (MyApplication) getSherlockActivity()
.getApplicationContext();
preferentialDataManage = new PreferentialDataManage(
getSherlockActivity());
Log.i(CartActivity.class.getName(), "CartActivity__onCreateView");
view = inflater.inflate(R.layout.shopping_cart, container, false);
// dataManage = new CartsDataManage();
// TODO Auto-generated method stub
// receiver = new InnerReceiver();
// IntentFilter filter = new IntentFilter();
// filter.addAction(Consts.UPDATE_CHANGE);
// getSherlockActivity().registerReceiver(receiver, filter);
// // registerForContextMenu(layout);
mBox = (CheckBox) view.findViewById(R.id.shopping_cart_checkbox);
sumTextView = (TextView) view
.findViewById(R.id.shopping_cart_sum_money);
counTextView = (TextView) view
.findViewById(R.id.shopping_cart_sum_number);
layout = (LinearLayout) view.findViewById(R.id.shopping_cart_relative2);
// getSherlockActivity().getSupportActionBar().setCustomView(
// R.layout.actionbar_cart);
cartUtil = new CartUtil(getSherlockActivity(), layout, counTextView,
sumTextView, mBox);
cartUtil.AllComment();
mPullToRefreshScrollView = (PullToRefreshScrollView) view
.findViewById(R.id.shopping_cart_item_goods_scrollView);
String label = getResources().getString(R.string.update_time)
+ DateUtils.formatDateTime(getSherlockActivity(),
System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_ABBREV_ALL
| DateUtils.FORMAT_SHOW_DATE);
mPullToRefreshScrollView.getLoadingLayoutProxy().setLastUpdatedLabel(
label);
mPullToRefreshScrollView.onRefreshComplete();
mPullToRefreshScrollView.setOnRefreshListener(listener);
shoppingCartTopay = (Button) getSherlockActivity().findViewById(
R.id.shopping_cart_go_pay);
shoppingCartTopay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// getAddresses();
if (!myApplication.getIsLogin()) {
Toast.makeText(getSherlockActivity(), "",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(getSherlockActivity(),
LoginActivity.class);
startActivity(intent);
return;
} else {
preferentialDataManage.getPreferential("1337,10n;",myApplication.getUserId());
if (preferentialDataManage.getFreeGoods().size() != 0
|| preferentialDataManage.getScoreGoods().size() != 0) {
Intent intent = new Intent(getSherlockActivity(),
ExchangeFreeActivity.class);
Bundle bundle = new Bundle();
float sum = Float.parseFloat(sumTextView.getText()
.toString());
if (sum > 0) {
bundle.putString("price", sum + "");
intent.putExtras(bundle);
getSherlockActivity().startActivity(intent);
} else {
Toast.makeText(getSherlockActivity(), "",
Toast.LENGTH_LONG).show();
}
}
}
}
});
return view;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// getSherlockActivity().unregisterReceiver(receiver);
}
private int fromIndex = 0;
private int amontIndex = 10;
private OnRefreshListener<ScrollView> listener = new OnRefreshListener<ScrollView>() {
@Override
public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
// TODO Auto-generated method stub
String label = ""
+ DateUtils.formatDateTime(getSherlockActivity(),
System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_ABBREV_ALL);
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
// fromIndex += amontIndex;
mPullToRefreshScrollView.onRefreshComplete();
}
};
// @Override
// public void onCreateContextMenu(ContextMenu menu, View v,
// ContextMenuInfo menuInfo) {
// menu.add(0, MENU1, 0, "");
// menu.add(0, MENU2, 0, "");
// menu.add(0, MENU3, 0, "");
// menu.setGroupCheckable(0, true, true);
// menu.setHeaderIcon(android.R.drawable.menu_frame);
// menu.setHeaderTitle("");
// super.onCreateContextMenu(menu, v, menuInfo);
// @Override
// public void onDestroy() {
// getActivity().unregisterReceiver(receiver);
// super.onDestroy();
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
Addresses address = null;
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i(CartActivity.class.getName(), "cart on start");
}
@Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
// private void getAddresses() {
// String userId = ((MyApplication) getSherlockActivity().getApplication())
// .getUserId();
// ArrayList<Addresses> mAddresses = addressManage.getAddressesArray(
// Integer.parseInt(userId), 0, 5);
// if (mAddresses.size() == 0) {
// Intent intent = new Intent(getSherlockActivity(),
// NewAddressActivity.class);
// getSherlockActivity().startActivity(intent);
// // Log.i("info", "nihao");
// } else {
// address = mAddresses.remove(0);
// // Log.i("info", address + "address");
// public class InnerReceiver extends BroadcastReceiver {
// @Override
// public void onReceive(Context context, Intent intent) {
// // TODO Auto-generated method stub
// String action = intent.getAction();
// if (Consts.UPDATE_CHANGE.equals(action)) {
// layout.removeAllViews();
// cartUtil = new CartUtil(getSherlockActivity(), layout, counTextView,
// sumTextView, mBox);
// cartUtil.AllComment();
// // number = cartsDataManage.getCartAmount();
// // cartImage.setText(number + "");
}
|
package com.opera.core.systems;
import java.awt.Dimension;
import java.awt.Point;
import java.util.List;
import org.openqa.selenium.ElementNotVisibleException;
import com.opera.core.systems.scope.internal.OperaFlags;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo;
import com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType;
import com.opera.core.systems.scope.protos.SystemInputProtos.ModifierPressed;
import com.opera.core.systems.scope.protos.SystemInputProtos.MouseInfo.MouseButton;
import com.opera.core.systems.scope.services.IDesktopWindowManager;
import com.opera.core.systems.scope.services.ums.DesktopWindowManager;
import com.opera.core.systems.scope.services.ums.SystemInputManager;
public class QuickWidget {
private final QuickWidgetInfo info;
private final IDesktopWindowManager desktopWindowManager;
private final SystemInputManager systemInputManager;
public QuickWidget(DesktopWindowManager desktopWindowManager, SystemInputManager inputManager, QuickWidgetInfo info) {
this.info = info;
this.desktopWindowManager = desktopWindowManager;
this.systemInputManager = inputManager;
}
public void click(MouseButton button, int numClicks, List<ModifierPressed> modifiers) {
//System.out.println(" Click "+ info.getName() + "!");
if (OperaFlags.ENABLE_CHECKS){
if(!isVisible())
throw new ElementNotVisibleException("You can't click an element that is not displayed");
}
systemInputManager.click(getCenterLocation(), button, numClicks, modifiers);
}
/*public void dragAndDropOn(QuickWidget element) {
Point currentLocation = this.getLocation();
Point dragPoint = element.getLocation();
systemInputManager.mouseDown(currentLocation, 0, 0);
systemInputManager.mouseMove(dragPoint, 0, 0);
systemInputManager.mouseUp(dragPoint, 0, 0);
}*/
/**
*
* @return name of widget
*/
public String getName() {
return info.getName();
}
/**
*
* @return text of widget
*/
public String getText() {
return info.getText();
}
/**
* Check if widget text equals the text specified by @param string_id
*
* @return true if text specified by string_id equals widget text
*/
public boolean verifyText(String string_id) {
String text = desktopWindowManager.getString(string_id);
// Remember to remove all CRLF
text = removeCRLF(text);
String text_internal = getText();
text_internal = removeCRLF(text_internal);
return text_internal.equals(text);
}
/**
* Check if widget text contains the text specified by @param string_id
*
* @param String string_id - id of string
* @return true if text specified by string_id is contained in widget text
*/
public boolean verifyContainsText(String string_id) {
String text = desktopWindowManager.getString(string_id);
// Remember to remove all CRLF
text = removeCRLF(text);
String text_internal = getText();
text_internal = removeCRLF(text_internal);
return text_internal.indexOf(text) >= 0;
}
private String removeCRLF(String text) {
// Hack to remove all \r and \n's as we sometimes get just \n and sometimes
// \r\n then the string comparison doesn't work
return text.replaceAll("(\\r|\\n)", "");
}
/**
* @return true if widget is default, else false
*/
public boolean isDefault() {
return info.getDefaultLook();
}
/**
*
* @return
*/
public boolean hasFocusedLook() {
return info.getFocusedLook();
}
/**
* Check if widget is enabled
* @return true if enabled, else false
*/
public boolean isEnabled() {
return info.getEnabled();
}
/**
* @return if widget is selected, else false
*/
public boolean isSelected() {
return info.getValue() == 1;
}
public boolean isSelected(String string_id) {
String text = desktopWindowManager.getString(string_id);
return text.equals(info.getText());
}
/**
* @return true if widget is visible
*/
public boolean isVisible(){
return info.getVisible();
}
/**
*
* @return
*/
public QuickWidgetType getType(){
return info.getType();
}
/**
* @return DesktopWindowRect of the widget
*/
private DesktopWindowRect getRect() {
return info.getRect();
}
private Point getCenterLocation() {
DesktopWindowRect rect = getRect();
Point top_left = getLocation();
return new Point(top_left.x + rect.getWidth() / 2, top_left.y + rect.getHeight() / 2);
}
/**
* @return Point describing location of widget
*/
public Point getLocation() {
DesktopWindowRect rect = getRect();
return new Point(rect.getX(), rect.getY());
}
/**
* @return size of widget
*/
public Dimension getSize() {
DesktopWindowRect rect = getRect();
return new Dimension(rect.getWidth(), rect.getHeight());
}
protected int getValue() {
return info.getValue();
}
public String getParentName() {
return info.getParentName();
}
@Override
// TODO: FIXME
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof QuickWidget)) return false;
QuickWidget ref = (QuickWidget) obj;
return (ref.getName().equals(this.getName()));
}
@Override
// TODO: FIXME
public int hashCode() {
int result = 42;
result = 31 * result + getName().hashCode();
return result;
}
@Override
public String toString() {
return "QuickWidget " + getName();
}
public String toFullString() {
return "QuickWidget\n" +
" Widget name: " + getName() + "\n"
// + " type: " + getType() + "\n" // TODO: FIXME
+ " visible: " + isVisible() + "\n"
+ " text: " + getText() + "\n"
+ " state: " + getValue() + "\n"
+ " enabled: " + isEnabled() + "\n"
+ " default: " + isDefault() + "\n"
+ " focused: " + hasFocusedLook() + "\n"
+ " x: " + getRect().getX() + "\n"
+ " y: " + getRect().getY() + "\n"
+ " width: " + getRect().getWidth() + "\n"
+ " height: " + getRect().getHeight() + " \n";
}
}
|
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
import states.GameState;
import states.GameStateManager;
import util.ImageManager;
import util.Util;
/**
* The panel that displays what is happening in the program
* @author Connor Murphy
*
*/
public class GamePanel extends JPanel implements KeyListener, MouseListener, MouseMotionListener
{
/**
* A generated serialVersionUID so eclipse does not yell at me
*/
private static final long serialVersionUID = -7906909062119976256L;
private boolean running;
private long lastTime;
private JLabel fpsLabel;
private int oldWidth, oldHeight;
public GamePanel()
{
super();
running = true;
setPreferredSize(new Dimension(1024, 768));
lastTime = System.nanoTime();
fpsLabel = new JLabel();
add(fpsLabel);
oldWidth = getWidth();
oldHeight = getHeight();
setFocusable(true);
requestFocus();
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
/**
* Initializes any resources and starts the program
*/
public void go()
{
//Initialize static classes
ImageManager.init();
GameStateManager.init();
//Program loop
while (running)
{
// Calculate the time between frames
long currentTime = System.nanoTime();
double deltaTime = (currentTime - lastTime) / 1000000000.0;
Util.setDeltaTime(deltaTime);
// Update the simulation
update();
//Check if the window was resized
int height = getHeight();
int width = getWidth();
if(width != oldWidth || height != oldHeight )
{
ImageManager.resizeImages(width, height);
oldWidth = width;
oldHeight = height;
}
// Draw the updates
draw();
lastTime = currentTime;
fpsLabel.setText("fps: " + (int)Util.calcFPS(deltaTime));
}
}
/**
* Updates the program
*/
private void update()
{
GameStateManager.update();
}
/**
* Draws the program to the panel
*/
private void draw()
{
repaint();
}
@Override
public void paintComponent(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
try
{
GameStateManager.draw(g);
}
catch (NullPointerException npe)
{
// Do nothing as trying to repaint before the game state manager has something to paint
}
}
/**
* Closes any resources used by the program
*/
public void stop()
{
running = false;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
GameStateManager.keyPressed(e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
GameStateManager.keyReleased(e.getKeyCode());
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
GameStateManager.mousePressed(e.getX(), e.getY());
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
GameStateManager.mousePressed(e.getX(), e.getY());
}
}
|
package com.qubling.sidekick.search;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import com.qubling.sidekick.R;
import com.qubling.sidekick.fetch.Fetcher;
import com.qubling.sidekick.instance.Instance;
import com.qubling.sidekick.model.AuthorModel;
import com.qubling.sidekick.model.GravatarModel;
import com.qubling.sidekick.model.ModuleModel;
import com.qubling.sidekick.model.ReleaseModel;
import com.qubling.sidekick.search.Search.OnSearchActivity;
import android.app.Activity;
import android.util.Log;
public class Schema implements OnSearchActivity {
private static final String METACPAN_API_USER_AGENT_SUFFIX = " (Android)";
private static int schemaIdCounter = 0;
private final GravatarModel gravatarModel;
private final AuthorModel authorModel;
private final ReleaseModel releaseModel;
private final ModuleModel moduleModel;
private int schemaId;
private int runningSearches = 0;
private Activity activity;
private HttpClient httpClient;
public Schema(Activity activity) {
schemaId = ++schemaIdCounter;
gravatarModel = new GravatarModel(this);
authorModel = new AuthorModel(this);
releaseModel = new ReleaseModel(this);
moduleModel = new ModuleModel(this);
this.activity = activity;
}
private void setupHttpClient() {
try {
String userAgent = activity.getString(R.string.app_name)
+ "/"
+ activity.getString(R.string.app_version)
+ METACPAN_API_USER_AGENT_SUFFIX;
httpClient = (HttpClient) Class.forName("android.net.http.AndroidHttpClient")
.getMethod("newInstance", String.class).invoke(null, userAgent);
Log.i("HttpClientManager", "Using AndroidHttpClient");
}
catch (Throwable t) {
Log.i("HttpClientManager", "Falling back to DefaultHttpClient");
httpClient = new DefaultHttpClient();
}
}
public void closeHttpClient() {
try {
Class<?> androidHttpClient = Class.forName("android.net.http.AndroidHttpClient");
if (androidHttpClient.isInstance(httpClient)) {
Method close = androidHttpClient.getMethod("close");
close.invoke(httpClient);
}
}
catch (ClassNotFoundException e) {
// ignore
}
catch (NoSuchMethodException e) {
// ignore
}
catch (InvocationTargetException e) {
// ignore
}
catch (IllegalAccessException e) {
// ignore
}
httpClient = null;
}
public GravatarModel getGravatarModel() {
return gravatarModel;
}
public AuthorModel getAuthorModel() {
return authorModel;
}
public ReleaseModel getReleaseModel() {
return releaseModel;
}
public ModuleModel getModuleModel() {
return moduleModel;
}
public Activity getActivity() {
return activity;
}
public HttpClient getHttpClient() {
return httpClient;
}
public <SomeInstance extends Instance<SomeInstance>> Search<SomeInstance> doFetch(Fetcher<SomeInstance> fetcher, Fetcher.OnFinished<SomeInstance> listener) {
Search<SomeInstance> search = new Search<SomeInstance>(activity, fetcher, listener);
search.addOnSearchActivityListener(this);
return search;
}
@Override
public synchronized void onSearchStart() {
// Log.d("Schema", "onSearchStart()");
if (runningSearches == 0) setupHttpClient();
runningSearches++;
}
@Override
public synchronized void onSearchComplete() {
// Log.d("Schema", "onSearchComplete()");
runningSearches
if (runningSearches == 0) closeHttpClient();
}
@Override
public String toString() {
return "Session #" + schemaId;
}
}
|
package com.team254.lib;
/**
* @author Tom Bottiglieri Team 254, The Cheesy Poofs
*/
import edu.wpi.first.wpilibj.Timer;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
public class CheesyVisionServer {
private static CheesyVisionServer INSTANCE = null;
private final Thread serverThread = new Thread(new ServerTask());
private final int port;
private final Vector connections = new Vector();
private boolean counting = false;
private int leftCount = 0, rightCount = 0, totalCount = 0;
private boolean curLeftStatus = false, curRightStatus = false;
private double lastHeartbeatTime = -1.0d;
private boolean listening = true;
public static CheesyVisionServer getInstance(final int port) {
if (INSTANCE == null) {
INSTANCE = new CheesyVisionServer(port);
}
return INSTANCE;
}
public void start() {
serverThread.start();
}
public void stop() {
listening = false;
}
private CheesyVisionServer() {
this(1180);
}
private CheesyVisionServer(final int port) {
this.port = port;
}
public boolean hasClientConnection() {
return lastHeartbeatTime > 0 && (Timer.getFPGATimestamp() - lastHeartbeatTime) < 3.0;
}
private void updateCounts(final boolean left, final boolean right) {
if (counting) {
leftCount += left ? 1 : 0;
rightCount += right ? 1 : 0;
totalCount++;
}
}
public void startSamplingCounts() {
counting = true;
}
public void stopSamplingCounts() {
counting = false;
}
public void reset() {
leftCount = rightCount = totalCount = 0;
curLeftStatus = curRightStatus = false;
}
public int getLeftCount() {
return leftCount;
}
public int getRightCount() {
return rightCount;
}
public int getTotalCount() {
return totalCount;
}
public boolean getLeftStatus() {
return curLeftStatus;
}
public boolean getRightStatus() {
return curRightStatus;
}
// This class handles incoming TCP connections
private class VisionServerConnectionHandler implements Runnable {
SocketConnection connection;
public VisionServerConnectionHandler(SocketConnection c) {
connection = c;
}
public void run() {
try {
final InputStream is = connection.openInputStream();
final byte[] b = new byte[1024];
final double timeout = 10.0d;
double lastHeartbeat = Timer.getFPGATimestamp();
lastHeartbeatTime = lastHeartbeat;
while (Timer.getFPGATimestamp() < lastHeartbeat + timeout) {
while (is.available() > 0) {
final int read = is.read(b);
for (int i = 0; i < read; ++i) {
final byte reading = b[i];
final boolean leftStatus = (reading & (1 << 1)) > 0;
final boolean rightStatus = (reading & 1) > 0;
curLeftStatus = leftStatus;
curRightStatus = rightStatus;
updateCounts(leftStatus, rightStatus);
}
lastHeartbeat = Timer.getFPGATimestamp();
lastHeartbeatTime = lastHeartbeat;
}
try {
Thread.sleep(50);
} catch (final InterruptedException ex) {
System.out.println("Thread sleep failed.");
}
}
is.close();
connection.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
private class ServerTask implements Runnable {
// This method listens for incoming connections and spawns new
// VisionServerConnectionHandlers to handle them
public void run() {
try {
final ServerSocketConnection s = (ServerSocketConnection) Connector.open("serversocket://:" + port);
while (listening) {
final SocketConnection connection = (SocketConnection) s.acceptAndOpen(); // blocks until a connection is made
final Thread t = new Thread(new VisionServerConnectionHandler(connection));
t.start();
connections.addElement(connection);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
System.out.println("Thread sleep failed.");
}
}
} catch (final IOException e) {
System.out.println("Socket failure.");
e.printStackTrace();
}
}
}
}
|
package com.temnenkov.jjbot.bot;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.temnenkov.jjbot.util.Helper;
public class LogManager {
private Connection connection;
private PreparedStatement storeMsg;
public void init() throws SQLException, ClassNotFoundException {
Class.forName("org.sqlite.JDBC");
connection = DriverManager
.getConnection("jdbc:sqlite:/opt/jjbot/ConfLog.sqlite");
storeMsg = connection
.prepareStatement("insert into Log ([Jid], [From], [Message], [Type]) values (?,?,?,?);");
}
public void storeMsg(String jid, String from, String payload, boolean isDelayed)
throws SQLException {
storeMsg.setString(1, jid);
storeMsg.setString(2, Helper.extractUser(from));
storeMsg.setString(3, Helper.safeStr(payload));
storeMsg.setString(4, isDelayed ? "D" : "N");
storeMsg.executeUpdate();
}
}
|
package com.wordwise.activity.game;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.wordwise.R;
import com.wordwise.gameengine.Game;
public class Hangman extends Activity implements Game {
private final int DOESNT_EXIST = -1;
private final int MAXIMUM_WRONG_GUESSES = 9;
private static boolean savedGame = false;
private boolean wonGame = false;
private boolean lostGame = false;
private ImageView hangmanImageView;
// dummy test initialization for the mystery word
private String mysteryWord = "ÜBUNG";
private int numWrongGuesses;
private TextView wrongLettersTextView;
private TextView mysteryWordTextView;
private static final String PREFERENCES_MYSTERY_WORD_TEXT_VIEW = "mysteryWordTextView";
private static final String PREFERENCES_MYSTERY_WORD = "mysteryWord";
private static final String PREFERENCES_WRONG_LETTERS = "wrongLetters";
private static final String PREFERENCES_NUM_WRONG_GUESSES = "numWrongGuesses";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This is the fragment of the coede that changes the lanuguage
String languageToLoad = "de"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
getActionBar().hide();
setContentView(R.layout.hangman);
this.init();
if (Hangman.savedGame == true) {
this.loadTheSavedGame();
}
this.start();
}
public void onStop() {
super.onStop();
this.pause();
this.stop();
}
public void onDestroy() {
super.onDestroy();
this.stop();
}
public void onPause() {
super.onPause();
this.pause();
}
public void onResume() {
super.onResume();
this.openTheSoftKeyboard();
}
// TODO Implement method to read the mysteryWord from the server
// TODO Edit checkWin() and checkLose() and link them with GameManager
// This is the method that checks for the unicode characters that are
// accessed useing multiple keys or long press
public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_UNKNOWN
&& event.getAction() == KeyEvent.ACTION_MULTIPLE
&& this.isALetter(keyCode)) {
String letter = event.getCharacters();
letter = letter.toUpperCase();
validateGuess(letter.charAt(0));
}
return true;
}
// This method checks for the normal characters accessed with one click (no
// long, no several keys)
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Implement saving of the game state
return super.onKeyDown(keyCode, event);
} else if (this.isALetter(keyCode)) {
String letter = "" + (char) event.getUnicodeChar();
letter = letter.toUpperCase();
validateGuess(letter.charAt(0));
return true;
}
return true;
}
//This method adds constraint about which chars should not be used at all. For example numbers ...
private boolean isALetter(int keyCode) {
// Letter ASCII constraints
// Only numbers added
if (((keyCode < 7) || (keyCode > 16))) {
return true;
} else {
return false;
}
}
private void checkWin() {
if (mysteryWordTextView.getText().toString().indexOf("_ ") == DOESNT_EXIST) {
this.closeTheSoftKeyboard();
Toast msg = Toast.makeText(this, "VERY GOOD!", Toast.LENGTH_LONG);
msg.show();
this.wonGame = true;
// IMPLEMENT THE MOVE TO THE OTHER ACTIVITY
}
}
private void checkLose() {
if (numWrongGuesses == MAXIMUM_WRONG_GUESSES) {
this.closeTheSoftKeyboard();
Toast msg = Toast.makeText(this, "MORE LUCK NEXT TIME!",
Toast.LENGTH_LONG);
msg.show();
this.lostGame = true;
// IMPLEMENT THE MOVE TO THE OTHER ACTIVITY
}
}
private void validateGuess(char guess) {
if (mysteryWord.indexOf(guess) == DOESNT_EXIST) {
String wrongLetters = wrongLettersTextView.getText().toString();
if (wrongLetters.indexOf(guess) == DOESNT_EXIST) {
if (numWrongGuesses < MAXIMUM_WRONG_GUESSES) {
numWrongGuesses++;
updateWrongGuesses(guess);
updateHangmanImage();
}
checkLose();
}
} else {
if (numWrongGuesses < MAXIMUM_WRONG_GUESSES) {
updateMysteriousWord(guess);
checkWin();
} else {
checkLose();
}
}
}
private void updateMysteriousWord(char ch) {
char[] updatedWord = mysteryWordTextView.getText().toString()
.toCharArray();
for (int i = 0; i < mysteryWord.length(); i++) {
if (ch == mysteryWord.charAt(i)) {
updatedWord[i * 2] = mysteryWord.charAt(i);
}
}
mysteryWordTextView.setText(new String(updatedWord));
}
private void openTheSoftKeyboard() {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
private void closeTheSoftKeyboard() {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(mysteryWordTextView.getWindowToken(),
0);
}
private void loadTheSavedGame() {
this.openTheSoftKeyboard();
this.mysteryWord = getPreferences(MODE_PRIVATE).getString(
PREFERENCES_MYSTERY_WORD, this.mysteryWord);
this.mysteryWordTextView.setText(getPreferences(MODE_PRIVATE)
.getString(PREFERENCES_MYSTERY_WORD_TEXT_VIEW,
underscoreTheMysteryWord(this.mysteryWord)));
this.wrongLettersTextView.setText(getPreferences(MODE_PRIVATE)
.getString(PREFERENCES_WRONG_LETTERS, ""));
this.numWrongGuesses = getPreferences(MODE_PRIVATE).getInt(
PREFERENCES_NUM_WRONG_GUESSES, 0);
this.updateHangmanImage();
// give the information that the saved game is already initialized
Hangman.savedGame = false;
}
private void linkTheViews() {
hangmanImageView = (ImageView) this.findViewById(R.id.hangman_img);
wrongLettersTextView = (TextView) this
.findViewById(R.id.hangman_wrong_letters);
mysteryWordTextView = (TextView) this
.findViewById(R.id.hangman_mystery_word);
}
private void initWrongGuesses() {
numWrongGuesses = 0;
}
private void updateWrongGuesses(char wrongLetter) {
wrongLettersTextView.setText(wrongLettersTextView.getText().toString()
+ " " + Character.toString(wrongLetter));
}
// This method will initialize the mysteryTextView with underscores
private String underscoreTheMysteryWord(String mysteryWord) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < mysteryWord.length(); i++) {
result.append("_ ");
}
return result.toString();
}
/*
* sets the Hangman image to the starting image
*/
private void initTheHangmanImage() {
hangmanImageView.setImageResource(R.drawable.hangman_img00);
}
/*
* updates the Hangman image based on the number of wrong guesses
*/
private void updateHangmanImage() {
switch (numWrongGuesses) {
case 0:
hangmanImageView.setImageResource(R.drawable.hangman_img00);
break;
case 1:
hangmanImageView.setImageResource(R.drawable.hangman_img01);
break;
case 2:
hangmanImageView.setImageResource(R.drawable.hangman_img02);
break;
case 3:
hangmanImageView.setImageResource(R.drawable.hangman_img03);
break;
case 4:
hangmanImageView.setImageResource(R.drawable.hangman_img04);
break;
case 5:
hangmanImageView.setImageResource(R.drawable.hangman_img05);
break;
case 6:
hangmanImageView.setImageResource(R.drawable.hangman_img06);
break;
case 7:
hangmanImageView.setImageResource(R.drawable.hangman_img07);
break;
case 8:
hangmanImageView.setImageResource(R.drawable.hangman_img08);
break;
case MAXIMUM_WRONG_GUESSES:
hangmanImageView.setImageResource(R.drawable.hangman_img09);
break;
}
}
/*
* sets the View of Mystery Word to a text view with underscores and spaces
*/
private void initMysteriousWord() {
mysteryWordTextView.setText(underscoreTheMysteryWord(mysteryWord));
mysteryWordTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openTheSoftKeyboard();
}
});
}
public void start() {
// TODO Auto-generated method stub
// TEST to see whether it is working
}
public void stop() {
this.closeTheSoftKeyboard();
}
public void pause() {
if (this.lostGame == true || this.wonGame == true) {
this.closeTheSoftKeyboard();
} else {
this.closeTheSoftKeyboard();
// Store values between instances here
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
// values to store
editor.putString(PREFERENCES_MYSTERY_WORD, mysteryWord);
editor.putString(PREFERENCES_MYSTERY_WORD_TEXT_VIEW,
mysteryWordTextView.getText().toString());
editor.putString(PREFERENCES_WRONG_LETTERS, wrongLettersTextView
.getText().toString());
editor.putInt(PREFERENCES_NUM_WRONG_GUESSES, numWrongGuesses);
// Commit to storage
editor.commit();
// give the signal that the game was saved
Hangman.savedGame = true;
}
}
public void init() {
// Initializes the screen
this.linkTheViews();
this.initTheHangmanImage();
this.initWrongGuesses();
this.initMysteriousWord();
this.openTheSoftKeyboard();
}
// called by quit button to quit the game
public void quit(View v) {
// TODO implement
}
}
|
package com.xorcode.andtweet.net;
/**
* In order to compile the application you either:
* 1. Create your own MyOAuthKeys class with your application's
* TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET
* 2. Or remove "extends MyOAuthKeys" below and un-comment the values here
* replacing values with your own token and key.
**/
public class OAuthKeys extends MyOAuthKeys {
// public static final String TWITTER_CONSUMER_KEY = "Your Twitter Application Token";
// public static final String TWITTER_CONSUMER_SECRET = "Your Twitter Application Secret";
}
|
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class CIS_Sample {
enum Sample {Hi, Lo};
Map<String, Object> map = new HashMap<String, Object>();
String val;
public void testToStringToField() {
val = Sample.Hi.toString();
}
public void testSBWithToStringToField(Date d, Integer i) {
StringBuilder s = new StringBuilder();
s.append(d);
s.append(i);
val = s.toString();
}
public Object testSBToMapField(Date d1, Date d2) {
map.put("a-v", d1 + ":" + d2);
return map.get(d1 + "-" + d2);
}
public void fpTestToStringToFieldSB(String s) {
val = s + "wow";
}
}
|
package battleships.backend;
import battleships.backend.actionhelpers.MoveStrategy;
import battleships.backend.actionhelpers.ResetHelper;
import battleships.backend.actionhelpers.TurnCounter;
import game.impl.Move;
import game.impl.Player;
public class GameActionsHandler {
private State state;
private MoveStrategy moveStrategy;
private Move firstDeployMove;
private TurnCounter turnCounter;
public GameActionsHandler(State state) {
this.state = state;
this.turnCounter = new TurnCounter(state);
this.moveStrategy = new MoveStrategy(state);
}
public Player calculateWinner() {
// TODO Auto-generated method stub
return null;
}
public boolean validateMove(Move move) {
boolean result = moveStrategy.getMoveValidator().makeMoveValidation(move, firstDeployMove);
if (!result && firstDeployMove==null)
firstDeployMove = move;
return result;
}
public void executeMove(Move move) {
moveStrategy.getMoveExecutor().executeMove(move, firstDeployMove);
turnCounter.decrementMoveCounter();
firstDeployMove = null;
}
public Boolean hasEndedCheck() {
// TODO Auto-generated method stub
return null;
}
public void reset() {
ResetHelper resetHelper = new ResetHelper(state);
resetHelper.reset();
}
}
|
package be.ibridge.kettle.job.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import be.ibridge.kettle.core.GUIResource;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.GUIResource;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.dialog.DatabaseDialog;
import be.ibridge.kettle.core.dialog.SQLEditor;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.widget.TextVar;
import be.ibridge.kettle.i18n.GlobalMessages;
import be.ibridge.kettle.job.JobEntryLoader;
import be.ibridge.kettle.job.JobMeta;
import be.ibridge.kettle.job.entry.JobEntryInterface;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.repository.RepositoryDirectory;
import be.ibridge.kettle.repository.dialog.SelectDirectoryDialog;
import be.ibridge.kettle.trans.step.BaseStepDialog;
/**
* Allows you to edit the Job settings. Just pass a JobInfo object.
*
* @author Matt
* @since 02-jul-2003
*/
public class JobDialog extends Dialog
{
private LogWriter log;
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wJobTab, wLogTab;
private Props props;
private Label wlJobname;
private Text wJobname;
private FormData fdlJobname, fdJobname;
private Label wlDirectory;
private Text wDirectory;
private Button wbDirectory;
private FormData fdlDirectory, fdbDirectory, fdDirectory;
private Label wlLogconnection;
private Button wbLogconnection;
private CCombo wLogconnection;
private FormData fdlLogconnection, fdbLogconnection, fdLogconnection;
private Label wlLogtable;
private Text wLogtable;
private FormData fdlLogtable, fdLogtable;
private Label wlBatch;
private Button wBatch;
private FormData fdlBatch, fdBatch;
private Label wlBatchTrans;
private Button wBatchTrans;
private FormData fdlBatchTrans, fdBatchTrans;
private Label wlLogfield;
private Button wLogfield;
private FormData fdlLogfield, fdLogfield;
private Button wOK, wSQL, wCancel;
private Listener lsOK, lsSQL, lsCancel;
private JobMeta jobMeta;
private Shell shell;
private Repository rep;
private SelectionAdapter lsDef;
private ModifyListener lsMod;
private boolean changed;
private TextVar wSharedObjectsFile;
private boolean sharedObjectsFileChanged;
// Job description
private Text wJobdescription;
// Extended description
private Label wlExtendeddescription;
private Text wExtendeddescription;
private FormData fdlExtendeddescription, fdExtendeddescription;
// Job Status
private Label wlJobstatus;
private CCombo wJobstatus;
private FormData fdlJobstatus, fdJobstatus;
// Job version
private Text wJobversion;
private int middle;
private int margin;
// Job creation
private Text wCreateUser;
private Text wCreateDate;
// Job modification
private Text wModUser;
private Text wModDate;
/**
* @deprecated Use version without <i>log</i> and <i>props</i> parameter
*/
public JobDialog(Shell parent, int style, LogWriter log, Props props, JobMeta jobMeta, Repository rep)
{
this(parent, style, jobMeta, rep);
//this.log = log;
//this.props = props;
}
public JobDialog(Shell parent, int style, JobMeta jobMeta, Repository rep)
{
super(parent, style);
this.log=LogWriter.getInstance();
this.jobMeta=jobMeta;
this.props=Props.getInstance();
this.rep=rep;
}
public JobMeta open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
shell.setImage((Image) GUIResource.getInstance().getImageChefGraph());
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
//changed = true;
jobMeta.setChanged();
}
};
changed = jobMeta.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("JobDialog.JobProperties.ShellText"));
middle = props.getMiddlePct();
margin = Const.MARGIN;
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
addJobTab();
addLogTab();
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
// THE BUTTONS
wOK=new Button(shell, SWT.PUSH);
wOK.setText(GlobalMessages.getSystemString("System.Button.OK"));
wSQL=new Button(shell, SWT.PUSH);
wSQL.setText(GlobalMessages.getSystemString("System.Button.SQL"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(GlobalMessages.getSystemString("System.Button.Cancel"));
//BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wSQL, wCancel }, margin, wSharedObjectsFile);
BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wSQL, wCancel }, Const.MARGIN, null);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsSQL = new Listener() { public void handleEvent(Event e) { sql(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wSQL.addListener (SWT.Selection, lsSQL );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wJobname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
wTabFolder.setSelection(0);
getData();
BaseStepDialog.setSize(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return jobMeta;
}
private void addJobTab()
{
// START OF JOB TAB///
wJobTab=new CTabItem(wTabFolder, SWT.NONE);
wJobTab.setText(Messages.getString("JobDialog.JobTab.Label")); //$NON-NLS-1$
Composite wJobComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wJobComp);
FormLayout transLayout = new FormLayout();
transLayout.marginWidth = Const.MARGIN;
transLayout.marginHeight = Const.MARGIN;
wJobComp.setLayout(transLayout);
// Job name:
wlJobname=new Label(wJobComp, SWT.RIGHT);
wlJobname.setText(Messages.getString("JobDialog.JobName.Label"));
props.setLook(wlJobname);
fdlJobname=new FormData();
fdlJobname.left = new FormAttachment(0, 0);
fdlJobname.right= new FormAttachment(middle, -margin);
fdlJobname.top = new FormAttachment(0, margin);
wlJobname.setLayoutData(fdlJobname);
wJobname=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook( wJobname);
wJobname.addModifyListener(lsMod);
fdJobname=new FormData();
fdJobname.left = new FormAttachment(middle, 0);
fdJobname.top = new FormAttachment(0, margin);
fdJobname.right= new FormAttachment(100, 0);
wJobname.setLayoutData(fdJobname);
// Job description:
Label wlJobdescription = new Label(wJobComp, SWT.RIGHT);
wlJobdescription.setText(Messages.getString("JobDialog.Jobdescription.Label")); //$NON-NLS-1$
props.setLook(wlJobdescription);
FormData fdlJobdescription = new FormData();
fdlJobdescription.left = new FormAttachment(0, 0);
fdlJobdescription.right= new FormAttachment(middle, -margin);
fdlJobdescription.top = new FormAttachment(wJobname, margin);
wlJobdescription.setLayoutData(fdlJobdescription);
wJobdescription=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wJobdescription);
wJobdescription.addModifyListener(lsMod);
FormData fdJobdescription = new FormData();
fdJobdescription.left = new FormAttachment(middle, 0);
fdJobdescription.top = new FormAttachment(wJobname, margin);
fdJobdescription.right= new FormAttachment(100, 0);
wJobdescription.setLayoutData(fdJobdescription);
// Transformation Extended description
wlExtendeddescription = new Label(wJobComp, SWT.RIGHT);
wlExtendeddescription.setText(Messages.getString("JobDialog.Extendeddescription.Label"));
props.setLook(wlExtendeddescription);
fdlExtendeddescription = new FormData();
fdlExtendeddescription.left = new FormAttachment(0, 0);
fdlExtendeddescription.top = new FormAttachment(wJobdescription, margin);
fdlExtendeddescription.right = new FormAttachment(middle, -margin);
wlExtendeddescription.setLayoutData(fdlExtendeddescription);
wExtendeddescription = new Text(wJobComp, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(wExtendeddescription,Props.WIDGET_STYLE_FIXED);
wExtendeddescription.addModifyListener(lsMod);
fdExtendeddescription = new FormData();
fdExtendeddescription.left = new FormAttachment(middle, 0);
fdExtendeddescription.top = new FormAttachment(wJobdescription, margin);
fdExtendeddescription.right = new FormAttachment(100, 0);
fdExtendeddescription.bottom =new FormAttachment(50, -margin);
wExtendeddescription.setLayoutData(fdExtendeddescription);
//Trans Status
wlJobstatus = new Label(wJobComp, SWT.RIGHT);
wlJobstatus.setText(Messages.getString("JobDialog.Jobstatus.Label"));
props.setLook(wlJobstatus);
fdlJobstatus = new FormData();
fdlJobstatus.left = new FormAttachment(0, 0);
fdlJobstatus.right = new FormAttachment(middle, 0);
fdlJobstatus.top = new FormAttachment(wExtendeddescription, margin*2);
wlJobstatus.setLayoutData(fdlJobstatus);
wJobstatus = new CCombo(wJobComp, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
wJobstatus.add(Messages.getString("JobDialog.Draft_Jobstatus.Label"));
wJobstatus.add(Messages.getString("JobDialog.Production_Jobstatus.Label"));
wJobstatus.add("");
wJobstatus.select(-1); // +1: starts at -1
props.setLook(wJobstatus);
fdJobstatus= new FormData();
fdJobstatus.left = new FormAttachment(middle, 0);
fdJobstatus.top = new FormAttachment(wExtendeddescription, margin*2);
fdJobstatus.right = new FormAttachment(100, 0);
wJobstatus.setLayoutData(fdJobstatus);
Label wlJobversion = new Label(wJobComp, SWT.RIGHT);
wlJobversion.setText(Messages.getString("JobDialog.Jobversion.Label")); //$NON-NLS-1$
props.setLook(wlJobversion);
FormData fdlJobversion = new FormData();
fdlJobversion.left = new FormAttachment(0, 0);
fdlJobversion.right= new FormAttachment(middle, -margin);
fdlJobversion.top = new FormAttachment(wJobstatus, margin);
wlJobversion.setLayoutData(fdlJobversion);
wJobversion=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wJobversion);
wJobversion.addModifyListener(lsMod);
FormData fdJobversion = new FormData();
fdJobversion.left = new FormAttachment(middle, 0);
fdJobversion.top = new FormAttachment(wJobstatus, margin);
fdJobversion.right= new FormAttachment(100, 0);
wJobversion.setLayoutData(fdJobversion);
// Directory:
wlDirectory=new Label(wJobComp, SWT.RIGHT);
wlDirectory.setText(Messages.getString("JobDialog.Directory.Label"));
props.setLook(wlDirectory);
fdlDirectory=new FormData();
fdlDirectory.left = new FormAttachment(0, 0);
fdlDirectory.right= new FormAttachment(middle, -margin);
fdlDirectory.top = new FormAttachment(wJobversion, margin);
wlDirectory.setLayoutData(fdlDirectory);
wbDirectory=new Button(wJobComp, SWT.PUSH);
wbDirectory.setText("...");
props.setLook(wbDirectory);
fdbDirectory=new FormData();
fdbDirectory.top = new FormAttachment(wJobversion, margin);
fdbDirectory.right= new FormAttachment(100, 0);
wbDirectory.setLayoutData(fdbDirectory);
wbDirectory.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
RepositoryDirectory directoryFrom = jobMeta.getDirectory();
long idDirectoryFrom = directoryFrom.getID();
SelectDirectoryDialog sdd = new SelectDirectoryDialog(shell, SWT.NONE, rep);
RepositoryDirectory rd = sdd.open();
if (rd!=null)
{
if (idDirectoryFrom!=rd.getID())
{
try
{
rep.moveJob(jobMeta.getName(), idDirectoryFrom, rd.getID() );
log.logDetailed(getClass().getName(), "Moved directory to ["+rd.getPath()+"]");
jobMeta.setDirectory( rd );
wDirectory.setText(jobMeta.getDirectory().getPath());
}
catch(KettleDatabaseException dbe)
{
jobMeta.setDirectory( directoryFrom );
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(Messages.getString("JobDialog.Dialog.ErrorChangingDirectory.Title"));
mb.setMessage(Messages.getString("JobDialog.Dialog.ErrorChangingDirectory.Message"));
mb.open();
}
}
else
{
// Same directory!
}
}
}
});
wDirectory=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDirectory);
wDirectory.setToolTipText(Messages.getString("JobDialog.Directory.Tooltip"));
wDirectory.setEditable(false);
fdDirectory=new FormData();
fdDirectory.top = new FormAttachment(wJobversion, margin);
fdDirectory.left = new FormAttachment(middle, 0);
fdDirectory.right= new FormAttachment(wbDirectory, 0);
wDirectory.setLayoutData(fdDirectory);
// Create User:
Label wlCreateUser = new Label(wJobComp, SWT.RIGHT);
wlCreateUser.setText(Messages.getString("JobDialog.CreateUser.Label")); //$NON-NLS-1$
props.setLook(wlCreateUser);
FormData fdlCreateUser = new FormData();
fdlCreateUser.left = new FormAttachment(0, 0);
fdlCreateUser.right= new FormAttachment(middle, -margin);
fdlCreateUser.top = new FormAttachment(wDirectory, margin);
wlCreateUser.setLayoutData(fdlCreateUser);
wCreateUser=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wCreateUser);
wCreateUser.setEditable(false);
wCreateUser.addModifyListener(lsMod);
FormData fdCreateUser = new FormData();
fdCreateUser.left = new FormAttachment(middle, 0);
fdCreateUser.top = new FormAttachment(wDirectory, margin);
fdCreateUser.right= new FormAttachment(100, 0);
wCreateUser.setLayoutData(fdCreateUser);
Label wlCreateDate = new Label(wJobComp, SWT.RIGHT);
wlCreateDate.setText(Messages.getString("JobDialog.CreateDate.Label")); //$NON-NLS-1$
props.setLook(wlCreateDate);
FormData fdlCreateDate = new FormData();
fdlCreateDate.left = new FormAttachment(0, 0);
fdlCreateDate.right= new FormAttachment(middle, -margin);
fdlCreateDate.top = new FormAttachment(wCreateUser, margin);
wlCreateDate.setLayoutData(fdlCreateDate);
wCreateDate=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wCreateDate);
wCreateDate.setEditable(false);
wCreateDate.addModifyListener(lsMod);
FormData fdCreateDate = new FormData();
fdCreateDate.left = new FormAttachment(middle, 0);
fdCreateDate.top = new FormAttachment(wCreateUser, margin);
fdCreateDate.right= new FormAttachment(100, 0);
wCreateDate.setLayoutData(fdCreateDate);
// Modified User:
Label wlModUser = new Label(wJobComp, SWT.RIGHT);
wlModUser.setText(Messages.getString("JobDialog.LastModifiedUser.Label")); //$NON-NLS-1$
props.setLook(wlModUser);
FormData fdlModUser = new FormData();
fdlModUser.left = new FormAttachment(0, 0);
fdlModUser.right= new FormAttachment(middle, -margin);
fdlModUser.top = new FormAttachment(wCreateDate, margin);
wlModUser.setLayoutData(fdlModUser);
wModUser=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wModUser);
wModUser.setEditable(false);
wModUser.addModifyListener(lsMod);
FormData fdModUser = new FormData();
fdModUser.left = new FormAttachment(middle, 0);
fdModUser.top = new FormAttachment(wCreateDate, margin);
fdModUser.right= new FormAttachment(100, 0);
wModUser.setLayoutData(fdModUser);
Label wlModDate = new Label(wJobComp, SWT.RIGHT);
wlModDate.setText(Messages.getString("JobDialog.LastModifiedDate.Label")); //$NON-NLS-1$
props.setLook(wlModDate);
FormData fdlModDate = new FormData();
fdlModDate.left = new FormAttachment(0, 0);
fdlModDate.right= new FormAttachment(middle, -margin);
fdlModDate.top = new FormAttachment(wModUser, margin);
wlModDate.setLayoutData(fdlModDate);
wModDate=new Text(wJobComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wModDate);
wModDate.setEditable(false);
wModDate.addModifyListener(lsMod);
FormData fdModDate = new FormData();
fdModDate.left = new FormAttachment(middle, 0);
fdModDate.top = new FormAttachment(wModUser, margin);
fdModDate.right= new FormAttachment(100, 0);
wModDate.setLayoutData(fdModDate);
FormData fdJobComp = new FormData();
fdJobComp.left = new FormAttachment(0, 0);
fdJobComp.top = new FormAttachment(0, 0);
fdJobComp.right = new FormAttachment(100, 0);
fdJobComp.bottom= new FormAttachment(100, 0);
wJobComp.setLayoutData(fdJobComp);
wJobTab.setControl(wJobComp);
/// END OF JOB TAB
}
private void addLogTab()
{
// START OF LOG TAB///
wLogTab=new CTabItem(wTabFolder, SWT.NONE);
wLogTab.setText(Messages.getString("JobDialog.LogTab.Label")); //$NON-NLS-1$
FormLayout LogLayout = new FormLayout ();
LogLayout.marginWidth = Const.MARGIN;
LogLayout.marginHeight = Const.MARGIN;
Composite wLogComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wLogComp);
wLogComp.setLayout(LogLayout);
// Log table connection...
wlLogconnection=new Label(wLogComp, SWT.RIGHT);
wlLogconnection.setText(Messages.getString("JobDialog.LogConnection.Label"));
props.setLook(wlLogconnection);
fdlLogconnection=new FormData();
fdlLogconnection.top = new FormAttachment(wDirectory, margin*4);
fdlLogconnection.left = new FormAttachment(0, 0);
fdlLogconnection.right= new FormAttachment(middle, 0);
wlLogconnection.setLayoutData(fdlLogconnection);
wbLogconnection=new Button(wLogComp, SWT.PUSH);
wbLogconnection.setText(GlobalMessages.getSystemString("System.Button.Edit"));
fdbLogconnection=new FormData();
fdbLogconnection.top = new FormAttachment(wDirectory, margin*4);
fdbLogconnection.right = new FormAttachment(100, 0);
wbLogconnection.setLayoutData(fdbLogconnection);
wbLogconnection.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
DatabaseMeta databaseMeta = jobMeta.findDatabase(wLogconnection.getText());
if (databaseMeta==null) databaseMeta=new DatabaseMeta();
DatabaseDialog cid = new DatabaseDialog(shell, databaseMeta);
if (cid.open()!=null)
{
wLogconnection.setText(databaseMeta.getName());
}
}
}
);
wLogconnection=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogconnection);
wLogconnection.setToolTipText(Messages.getString("JobDialog.LogConnection.Tooltip"));
wLogconnection.addModifyListener(lsMod);
fdLogconnection=new FormData();
fdLogconnection.top = new FormAttachment(wDirectory, margin*4);
fdLogconnection.left = new FormAttachment(middle, 0);
fdLogconnection.right= new FormAttachment(wbLogconnection, -margin);
wLogconnection.setLayoutData(fdLogconnection);
// populate the combo box...
for (int i=0;i<jobMeta.nrDatabases();i++)
{
DatabaseMeta meta = jobMeta.getDatabase(i);
wLogconnection.add(meta.getName());
}
// add a listener
wLogconnection.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { setFlags(); } } );
// Log table...:
wlLogtable=new Label(wLogComp, SWT.RIGHT);
wlLogtable.setText(Messages.getString("JobDialog.LogTable.Label"));
props.setLook(wlLogtable);
fdlLogtable=new FormData();
fdlLogtable.left = new FormAttachment(0, 0);
fdlLogtable.right= new FormAttachment(middle, 0);
fdlLogtable.top = new FormAttachment(wLogconnection, margin);
wlLogtable.setLayoutData(fdlLogtable);
wLogtable=new Text(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogtable);
wLogtable.setToolTipText(Messages.getString("JobDialog.LogTable.Tooltip"));
wLogtable.addModifyListener(lsMod);
fdLogtable=new FormData();
fdLogtable.left = new FormAttachment(middle, 0);
fdLogtable.top = new FormAttachment(wLogconnection, margin);
fdLogtable.right= new FormAttachment(100, 0);
wLogtable.setLayoutData(fdLogtable);
wlBatch=new Label(wLogComp, SWT.RIGHT);
wlBatch.setText(Messages.getString("JobDialog.UseBatchID.Label"));
props.setLook(wlBatch);
fdlBatch=new FormData();
fdlBatch.left = new FormAttachment(0, 0);
fdlBatch.top = new FormAttachment(wLogtable, margin*3);
fdlBatch.right= new FormAttachment(middle, -margin);
wlBatch.setLayoutData(fdlBatch);
wBatch=new Button(wLogComp, SWT.CHECK);
props.setLook(wBatch);
wBatch.setToolTipText(Messages.getString("JobDialog.UseBatchID.Tooltip"));
fdBatch=new FormData();
fdBatch.left = new FormAttachment(middle, 0);
fdBatch.top = new FormAttachment(wLogtable, margin*3);
fdBatch.right= new FormAttachment(100, 0);
wBatch.setLayoutData(fdBatch);
wlBatchTrans=new Label(wLogComp, SWT.RIGHT);
wlBatchTrans.setText(Messages.getString("JobDialog.PassBatchID.Label"));
props.setLook(wlBatchTrans);
fdlBatchTrans=new FormData();
fdlBatchTrans.left = new FormAttachment(0, 0);
fdlBatchTrans.top = new FormAttachment(wBatch, margin);
fdlBatchTrans.right= new FormAttachment(middle, -margin);
wlBatchTrans.setLayoutData(fdlBatchTrans);
wBatchTrans=new Button(wLogComp, SWT.CHECK);
props.setLook(wBatchTrans);
wBatchTrans.setToolTipText(Messages.getString("JobDialog.PassBatchID.Tooltip"));
fdBatchTrans=new FormData();
fdBatchTrans.left = new FormAttachment(middle, 0);
fdBatchTrans.top = new FormAttachment(wBatch, margin);
fdBatchTrans.right= new FormAttachment(100, 0);
wBatchTrans.setLayoutData(fdBatchTrans);
wlLogfield=new Label(wLogComp, SWT.RIGHT);
wlLogfield.setText(Messages.getString("JobDialog.UseLogField.Label"));
props.setLook(wlLogfield);
fdlLogfield=new FormData();
fdlLogfield.left = new FormAttachment(0, 0);
fdlLogfield.top = new FormAttachment(wBatchTrans, margin);
fdlLogfield.right= new FormAttachment(middle, -margin);
wlLogfield.setLayoutData(fdlLogfield);
wLogfield=new Button(wLogComp, SWT.CHECK);
props.setLook(wLogfield);
wLogfield.setToolTipText(Messages.getString("JobDialog.UseLogField.Tooltip"));
fdLogfield=new FormData();
fdLogfield.left = new FormAttachment(middle, 0);
fdLogfield.top = new FormAttachment(wBatchTrans, margin);
fdLogfield.right= new FormAttachment(100, 0);
wLogfield.setLayoutData(fdLogfield);
// Shared objects file
Label wlSharedObjectsFile = new Label(wLogComp, SWT.RIGHT);
wlSharedObjectsFile.setText(Messages.getString("JobDialog.SharedObjectsFile.Label"));
props.setLook(wlSharedObjectsFile);
FormData fdlSharedObjectsFile = new FormData();
fdlSharedObjectsFile.left = new FormAttachment(0, 0);
fdlSharedObjectsFile.right= new FormAttachment(middle, -margin);
fdlSharedObjectsFile.top = new FormAttachment(wLogfield, 3*margin);
wlSharedObjectsFile.setLayoutData(fdlSharedObjectsFile);
wSharedObjectsFile=new TextVar(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wlSharedObjectsFile.setToolTipText(Messages.getString("JobDialog.SharedObjectsFile.Tooltip"));
wSharedObjectsFile.setToolTipText(Messages.getString("JobDialog.SharedObjectsFile.Tooltip"));
props.setLook(wSharedObjectsFile);
FormData fdSharedObjectsFile = new FormData();
fdSharedObjectsFile.left = new FormAttachment(middle, 0);
fdSharedObjectsFile.top = new FormAttachment(wLogfield, 3*margin);
fdSharedObjectsFile.right= new FormAttachment(100, 0);
wSharedObjectsFile.setLayoutData(fdSharedObjectsFile);
wSharedObjectsFile.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent arg0)
{
sharedObjectsFileChanged = true;
}
}
);
FormData fdLogComp = new FormData();
fdLogComp.left = new FormAttachment(0, 0);
fdLogComp.top = new FormAttachment(0, 0);
fdLogComp.right = new FormAttachment(100, 0);
fdLogComp.bottom= new FormAttachment(100, 0);
wLogComp.setLayoutData(fdLogComp);
wLogComp.layout();
wLogTab.setControl(wLogComp);
/// END OF LOG TAB
}
public void dispose()
{
WindowProperty winprop = new WindowProperty(shell);
props.setScreen(winprop);
shell.dispose();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
log.logDebug(toString(), "getting transformation info...");
if (jobMeta.getName()!=null) wJobname.setText ( jobMeta.getName());
if (jobMeta.getDescription()!=null) wJobdescription.setText ( jobMeta.getDescription());
if (jobMeta.getExtendedDescription()!=null) wExtendeddescription.setText ( jobMeta.getExtendedDescription());
if (jobMeta.getJobversion()!=null) wJobversion.setText ( jobMeta.getJobversion());
wJobstatus.select( jobMeta.getJobstatus() -1);
if (jobMeta.getDirectory()!=null) wDirectory.setText ( jobMeta.getDirectory().getPath() );
if (jobMeta.getCreatedUser()!=null) wCreateUser.setText ( jobMeta.getCreatedUser() );
if (jobMeta.getCreatedDate()!=null && jobMeta.getCreatedDate().getString()!=null)
wCreateDate.setText ( jobMeta.getCreatedDate().getString() );
if (jobMeta.getModifiedUser()!=null) wModUser.setText ( jobMeta.getModifiedUser() );
if (jobMeta.getModifiedDate()!=null &&
jobMeta.getModifiedDate().getString()!=null )
wModDate.setText ( jobMeta.getModifiedDate().getString() );
if (jobMeta.getLogConnection()!=null) wLogconnection.setText( jobMeta.getLogConnection().getName());
if (jobMeta.getLogTable()!=null) wLogtable.setText ( jobMeta.getLogTable());
wBatch.setSelection(jobMeta.isBatchIdUsed());
wBatchTrans.setSelection(jobMeta.isBatchIdPassed());
wLogfield.setSelection(jobMeta.isLogfieldUsed());
wSharedObjectsFile.setText(Const.NVL(jobMeta.getSharedObjectsFile(), ""));
sharedObjectsFileChanged=false;
changed = jobMeta.hasChanged();
setFlags();
}
public void setFlags()
{
wbDirectory.setEnabled(rep!=null);
wDirectory.setEnabled(rep!=null);
wlDirectory.setEnabled(rep!=null);
DatabaseMeta dbMeta = jobMeta.findDatabase(wLogconnection.getText());
wbLogconnection.setEnabled(dbMeta!=null);
}
private void cancel()
{
props.setScreen(new WindowProperty(shell));
jobMeta.setChanged(changed);
jobMeta=null;
dispose();
}
private void ok()
{
jobMeta.setName( wJobname.getText() );
jobMeta.setDescription(wJobdescription.getText());
jobMeta.setExtendedDescription(wExtendeddescription.getText() );
jobMeta.setJobversion(wJobversion.getText() );
if ( wJobstatus.getSelectionIndex() != 2 )
{
// Saving the index as meta data is in fact pretty bad, but since
// it was already in ...
jobMeta.setJobstatus( wJobstatus.getSelectionIndex() + 1 );
}
else
{
jobMeta.setJobstatus( -1 );
}
jobMeta.setLogConnection( jobMeta.findDatabase(wLogconnection.getText()) );
jobMeta.setLogTable( wLogtable.getText() );
jobMeta.setUseBatchId( wBatch.getSelection());
jobMeta.setBatchIdPassed( wBatchTrans.getSelection());
jobMeta.setLogfieldUsed( wLogfield.getSelection());
jobMeta.setSharedObjectsFile( wSharedObjectsFile.getText() );
dispose();
}
// Generate code for create table...
// Conversions done by Database
private void sql()
{
DatabaseMeta ci = jobMeta.findDatabase(wLogconnection.getText());
if (ci!=null)
{
Row r = Database.getJobLogrecordFields(wBatch.getSelection(), wLogfield.getSelection());
if (r!=null && r.size()>0)
{
String tablename = wLogtable.getText();
if (tablename!=null && tablename.length()>0)
{
Database db = new Database(ci);
try
{
db.connect();
// Get the DDL for the specified tablename and fields...
String createTable = db.getDDL(tablename, r);
if (!Const.isEmpty(createTable))
{
log.logBasic(toString(), createTable);
SQLEditor sqledit = new SQLEditor(shell, SWT.NONE, ci, null, createTable);
sqledit.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setText(Messages.getString("JobDialog.NoSqlNedds.DialogTitle"));
mb.setMessage(Messages.getString("JobDialog.NoSqlNedds.DialogMessage"));
mb.open();
}
}
catch(KettleDatabaseException dbe)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("JobDialog.Dialog.ErrorCreatingSQL.Message")+Const.CR+dbe.getMessage());
mb.setText(Messages.getString("JobDialog.Dialog.ErrorCreatingSQL.Title"));
mb.open();
}
finally
{
db.disconnect();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("JobDialog.Dialog.PleaseEnterALogTable.Message"));
mb.setText(Messages.getString("JobDialog.Dialog.PleaseEnterALogTable.Title"));
mb.open();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("JobDialog.Dialog.CouldNotFindFieldsToCreateLogTable.Message"));
mb.setText(Messages.getString("JobDialog.Dialog.CouldNotFindFieldsToCreateLogTable.Title"));
mb.open();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("JobDialog.Dialog.SelectCreateValidLogConnection.Message"));
mb.setText(Messages.getString("JobDialog.Dialog.SelectCreateValidLogConnection.Title"));
mb.open();
}
}
public boolean isSharedObjectsFileChanged()
{
return sharedObjectsFileChanged;
}
public String toString()
{
return this.getClass().getName();
}
public static final void setShellImage(Shell shell, JobEntryInterface jobEntryInterface)
{
try
{
String id = JobEntryLoader.getInstance().getJobEntryID(jobEntryInterface);
if (id!=null)
{
shell.setImage((Image) GUIResource.getInstance().getImagesJobentries().get(id));
}
}
catch(Throwable e)
{
}
}
}
|
package bitronix.tm;
import bitronix.tm.journal.DiskJournal;
import bitronix.tm.journal.Journal;
import bitronix.tm.journal.NullJournal;
import bitronix.tm.recovery.Recoverer;
import bitronix.tm.resource.ResourceLoader;
import bitronix.tm.timer.TaskScheduler;
import bitronix.tm.twopc.executor.*;
import bitronix.tm.utils.InitializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TransactionManagerServices {
private final static Logger log = LoggerFactory.getLogger(TransactionManagerServices.class);
private static BitronixTransactionManager transactionManager;
private static Configuration configuration;
private static Journal journal;
private static TaskScheduler taskScheduler;
private static ResourceLoader resourceLoader;
private static Recoverer recoverer;
private static Executor executor;
/**
* Create an initialized transaction manager.
* @return the transaction manager.
*/
public synchronized static BitronixTransactionManager getTransactionManager() {
if (transactionManager == null)
transactionManager = new BitronixTransactionManager();
return transactionManager;
}
/**
* Create the configuration of all the components of the transaction manager.
* @return the global configuration.
*/
public synchronized static Configuration getConfiguration() {
if (configuration == null)
configuration = new Configuration();
return configuration;
}
/**
* Create the transactions journal.
* @return the transactions journal.
*/
public synchronized static Journal getJournal() {
if (journal == null) {
String configuredJounal = getConfiguration().getJournal();
if ("disk".equals(configuredJounal))
journal = new DiskJournal();
else if ("null".equals(configuredJounal))
journal = new NullJournal();
else {
try {
Class clazz = Thread.currentThread().getContextClassLoader().loadClass(configuredJounal);
journal = (Journal) clazz.newInstance();
} catch (Exception ex) {
throw new InitializationException("invalid journal implementation '" + configuredJounal + "'", ex);
}
}
if (log.isDebugEnabled()) log.debug("using journal " + configuredJounal);
}
return journal;
}
/**
* Create the task scheduler.
* @return the task scheduler.
*/
public synchronized static TaskScheduler getTaskScheduler() {
if (taskScheduler == null) {
taskScheduler = new TaskScheduler();
taskScheduler.start();
}
return taskScheduler;
}
/**
* Create the resource loader.
* @return the resource loader.
*/
public synchronized static ResourceLoader getResourceLoader() {
if (resourceLoader == null) {
resourceLoader = new ResourceLoader();
}
return resourceLoader;
}
/**
* Create the transaction recoverer.
* @return the transaction recoverer.
*/
public synchronized static Recoverer getRecoverer() {
if (recoverer == null) {
recoverer = new Recoverer();
}
return recoverer;
}
/**
* Create the 2PC executor.
* @return the 2PC executor.
*/
public synchronized static Executor getExecutor() {
if (executor == null) {
boolean async = getConfiguration().isAsynchronous2Pc();
if (async) {
if (log.isDebugEnabled()) log.debug("trying to use ConcurrentExecutor");
executor = new ConcurrentExecutor();
if (!executor.isUsable()) {
if (log.isDebugEnabled()) log.debug("trying to use BackportConcurrentExecutor");
executor = new BackportConcurrentExecutor();
}
if (!executor.isUsable()) {
if (log.isDebugEnabled()) log.debug("using SimpleAsyncExecutor");
executor = new SimpleAsyncExecutor();
}
}
else {
if (log.isDebugEnabled()) log.debug("using SyncExecutor");
executor = new SyncExecutor();
}
}
return executor;
}
/**
* Check if the transaction manager has started.
* @return true if the transaction manager has started.
*/
public synchronized static boolean isTransactionManagerRunning() {
return transactionManager != null;
}
/**
* Clear services references. Called at the end of the shutdown procedure.
*/
protected static synchronized void clear() {
transactionManager = null;
configuration = null;
journal = null;
taskScheduler = null;
resourceLoader = null;
recoverer = null;
executor = null;
}
}
|
package ca.patricklam.judodb.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedList;
import java.util.List;
import ca.patricklam.judodb.client.Constants.Division;
import ca.patricklam.judodb.client.Constants.Grade;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.NamedFrame;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.http.client.URL;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
public class ListWidget extends Composite {
interface MyUiBinder extends UiBinder<Widget, ListWidget> {}
public static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
JudoDB jdb;
private JsArray<ClientData> allClients;
private HashMap<String, ClientData> cidToCD = new HashMap<String, ClientData>();
/** A list of cours as retrieved from the server.
* Must stay in synch with the ListBox field cours. */
private List<CoursSummary> backingCours = new ArrayList<CoursSummary>();
private Set<String> clubsPresent = new HashSet<String>();
private static final String PULL_ALL_CLIENTS_URL = JudoDB.BASE_URL + "pull_all_clients.php";
private static final String PUSH_MULTI_CLIENTS_URL = JudoDB.BASE_URL + "push_multi_clients.php";
private static final String CONFIRM_PUSH_URL = JudoDB.BASE_URL + "confirm_push.php";
@UiField(provided=true) FormPanel listForm = new FormPanel(new NamedFrame("_"));
@UiField Anchor pdf;
@UiField Anchor presences;
@UiField Anchor xls;
@UiField Anchor xls2;
@UiField Hidden multi;
@UiField Hidden title;
@UiField Hidden short_title;
@UiField Hidden data;
@UiField Hidden data_full;
@UiField Hidden auxdata;
@UiField Hidden club_id;
@UiField HTMLPanel ft303_controls;
@UiField TextBox evt;
@UiField TextBox date;
@UiField Anchor createFT;
@UiField HTMLPanel impot_controls;
/*@UiField Anchor recalc;*/
@UiField CheckBox prorata;
@UiField Anchor mailmerge;
@UiField HTMLPanel edit_controls;
@UiField TextBox edit_date;
@UiField HTMLPanel filter_controls;
@UiField ListBox division;
@UiField ListBox grade_lower;
@UiField ListBox grade_upper;
@UiField ListBox cours;
@UiField Grid results;
@UiField Label nb;
@UiField Button save;
@UiField Button quit;
@UiField FormPanel listEditForm;
@UiField Hidden guid_on_form;
@UiField Hidden currentSession;
@UiField Hidden dataToSave;
private String guid;
private int pushTries;
@UiField ListBox session;
@UiField ListBox dropDownUserClubs;
private class Columns {
final static int CID = 0;
final static int VERIFICATION = 1;
final static int NOM = 2;
final static int PRENOM = 3;
final static int SEXE = 4;
final static int GRADE = 5;
final static int DATE_GRADE = 6;
final static int TEL = 7;
final static int JUDOQC = 8;
final static int DDN = 9;
final static int DIVISION = 10;
final static int COURS_DESC = 11;
final static int COURS_NUM = 12;
final static int SESSION = 13;
final static int DIVISION_SM = 14;
}
enum Mode {
NORMAL, FT, EDIT, IMPOT
};
class CoursHandler implements ChangeHandler {
public void onChange(ChangeEvent event) {
showList();
}
void generateCoursList() {
jdb.clearStatus();
int session_seqno = requestedSessionNo();
if (session_seqno == -1)
session_seqno = Constants.currentSession().seqno;
String numero_club = null;
if (jdb.getSelectedClubID() != null)
numero_club = jdb.getClubSummaryByID(jdb.getSelectedClubID()).getNumeroClub();
jdb.pleaseWait();
retrieveCours(session_seqno, numero_club);
}
}
class ClubListHandler implements ChangeHandler {
public void onChange(ChangeEvent e) {
jdb.selectedClub = dropDownUserClubs.getSelectedIndex();
coursHandler.generateCoursList();
showList();
}
}
final Widget[] allListModeWidgets;
final HashMap<Mode, Widget[]> listModeVisibility = new HashMap<Mode, Widget[]>();
private Mode mode = Mode.NORMAL;
private boolean isFiltering;
public String[] heads = new String[] {
"No", "V", "Nom", "Prenom", "Sexe", "Grade", "DateGrade", "Tel", "JudoQC", "DDN", "Cat", "Cours", "", "Saisons", "Division"
};
private boolean[] sortable = new boolean[] {
false, false, true, true, false, true, false, false, false, true, true, true, false, false, false
};
private HashMap<CheckBox, Boolean> originalVerifValues = new HashMap<CheckBox, Boolean>();
private HashMap<ListBox, Integer> originalCours = new HashMap<ListBox, Integer>();
private HashMap<TextBox, String> originalJudoQC = new HashMap<TextBox, String>();
private HashMap<TextBox, String> originalGrades = new HashMap<TextBox, String>();
private HashMap<TextBox, String> originalGradeDates = new HashMap<TextBox, String>();
private CoursHandler coursHandler = new CoursHandler();
private ClubListHandler clHandler = new ClubListHandler();
public ListWidget(JudoDB jdb) {
this.jdb = jdb;
initWidget(uiBinder.createAndBindUi(this));
listForm.addStyleName("noprint");
allListModeWidgets = new Widget[] { jdb.filtrerListes, jdb.editerListes, jdb.ftListes,
jdb.clearXListes, jdb.normalListes,
ft303_controls, edit_controls, filter_controls,
impot_controls, session, save, quit, dropDownUserClubs };
listModeVisibility.put(Mode.EDIT, new Widget[]
{ jdb.normalListes, jdb.filtrerListes,
jdb.clearXListes, session, jdb.returnToMainFromListes,
edit_controls, save, quit, dropDownUserClubs });
listModeVisibility.put(Mode.FT, new Widget[]
{ jdb.normalListes, jdb.filtrerListes, jdb.clearXListes,
ft303_controls, session, jdb.returnToMainFromListes, dropDownUserClubs } );
listModeVisibility.put(Mode.IMPOT, new Widget[]
{ jdb.normalListes, jdb.filtrerListes, jdb.clearXListes,
impot_controls, session, jdb.returnToMainFromListes, dropDownUserClubs } );
listModeVisibility.put(Mode.NORMAL, new Widget[]
{ jdb.filtrerListes, jdb.editerListes,
jdb.ftListes, jdb.impotListes, session, jdb.returnToMainFromListes, dropDownUserClubs } );
jdb.pleaseWait();
switchMode(Mode.NORMAL);
session.addItem("Tous", "-1");
for (Constants.Session s : Constants.SESSIONS) {
if (s != Constants.currentSession())
session.insertItem(s.abbrev, Integer.toString(s.seqno), 1);
}
session.insertItem(Constants.currentSession().abbrev, Integer.toString(Constants.currentSessionNo()), 0);
session.setSelectedIndex(0);
division.addItem("Tous", "-1");
for (Division c : Constants.DIVISIONS)
if (!c.noire)
division.insertItem(c.abbrev, c.abbrev, 1);
for (int i = 0; i < Constants.GRADES.length; i++) {
Grade g = Constants.GRADES[i];
grade_lower.insertItem(g.name, String.valueOf(g.order), i);
}
grade_lower.insertItem("
grade_lower.setSelectedIndex(0);
for (int i = 0; i < Constants.GRADES.length; i++) {
Grade g = Constants.GRADES[i];
grade_upper.insertItem(g.name, String.valueOf(g.order), i);
}
grade_upper.insertItem("
grade_upper.setSelectedIndex(0);
edit_date.setValue(Constants.STD_DATE_FORMAT.format(new Date()));
cours.addChangeHandler(coursHandler);
session.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent e) { showList(); } });
pdf.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) { collectDV(); clearFull(); submit("pdf"); } });
presences.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) { collectDV(); clearFull(); submit("presences"); } });
xls.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) { collectDV(); clearFull(); submit("xls"); } });
xls2.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) { collectDV(); computeFull(); submit("xlsfull"); } });
division.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent e) { showList(); } });
grade_lower.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent e) { showList(); } });
grade_upper.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent e) { showList(); } });
/* recalc.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) { recalc(); } }); */
mailmerge.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) { collectDV(); computeImpotMailMerge(); submit("impot"); } });
createFT.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) { if (makeFT()) submit("ft"); }});
save.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
save();
}
});
quit.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
reset();
ListWidget.this.switchMode(Mode.NORMAL); }
});
listEditForm.setAction(PUSH_MULTI_CLIENTS_URL);
dropDownUserClubs.addChangeHandler(clHandler);
jdb.populateClubList(true, dropDownUserClubs);
coursHandler.generateCoursList();
retrieveAllClients();
sorts.add(3); sorts.add(2);
}
private void save() {
// iterate through originalVerifValues and see which ones to generate
// create a list of tuples of the form: 163, "verification", "0"; 164, "verification", "1"
// we'll push to the server, which will update the services that match the cid and the current session.
guid = UUID.uuid();
guid_on_form.setValue(guid);
currentSession.setValue(Constants.currentSession().abbrev);
StringBuffer dv = new StringBuffer();
for (int i = 0; i < results.getRowCount(); i++) {
CheckBox cb = (CheckBox)results.getWidget(i, Columns.VERIFICATION);
if (cb != null && cb.getValue() != originalVerifValues.get(cb)) {
String cid = results.getText(i, Columns.CID);
String v = cb.getValue() ? "1" : "0";
dv.append(cid + ",Sverification,"+v+";");
}
Widget lbw = results.getWidget(i, Columns.COURS_DESC);
if (lbw != null && lbw instanceof ListBox) {
ListBox lb = (ListBox) lbw;
if (lb.getSelectedIndex() != originalCours.get(lb)) {
String cid = results.getText(i, Columns.CID);
dv.append(cid + ",Scours,"+backingCours.get(lb.getSelectedIndex()).getId()+";");
}
}
Widget jqw = results.getWidget(i, Columns.JUDOQC);
if (jqw != null && jqw instanceof TextBox) {
TextBox jq = (TextBox) jqw;
if (!jq.getValue().equals(originalJudoQC.get(jq))) {
String cid = results.getText(i, Columns.CID);
dv.append(cid + ",Caffiliation,"+jq.getValue()+";");
}
}
Widget gw = results.getWidget(i, Columns.GRADE);
if (gw != null && gw instanceof TextBox) {
TextBox g = (TextBox) gw,
gd = (TextBox)results.getWidget(i, Columns.DATE_GRADE);
boolean changed = false, deleteOld = false;
String origGrade = originalGrades.get(g), ogs;
String newGrade = g.getValue(), ngs;
if (origGrade == null) origGrade = "";
ogs = new String(origGrade); ngs = new String(newGrade);
if (ogs.length() >= 3) ogs = ogs.substring(0, 3);
if (ngs.length() >= 3) ngs = ngs.substring(0, 3);
String ogd = originalGradeDates.get(gd);
String ngd = Constants.stdToDbDate(gd.getValue());
if (!ogs.equals(ngs) && ngd.equals(ogd))
{ changed = true; deleteOld = true; }
if (ogs.equals(ngs) && !ngd.equals(ogd))
{ changed = true; ngs = origGrade; deleteOld = true; }
if (!ogs.equals(ngs) && !ngd.equals(ogd))
{ changed = true; }
// otherwise, everything is equal, no changes.
String cid = results.getText(i, Columns.CID);
if (deleteOld)
dv.append(cid + ",!,"+origGrade+"|"+ogd+";");
if (changed)
dv.append(cid + ",G,"+ngs+"|"+ngd+";");
}
}
dataToSave.setValue(dv.toString());
listEditForm.submit();
pushTries = 0;
new Timer() { public void run() {
pushChanges(guid);
} }.schedule(500);
}
private void reset() {
retrieveAllClients();
}
private void recalc() {
for (int i = 0; i < results.getRowCount(); i++) {
ClientData cd = cidToCD.get(results.getText(i, Columns.CID));
ServiceData sd = cd.getServiceFor(Constants.currentSession());
ClubSummary cs = jdb.getClubSummaryByID(sd.getClubID());
// XXX getPrix on ListWidget as well
CostCalculator.recompute(cd, sd, cs, true, null);
}
}
private void addMetaData() {
int c = cours.getSelectedIndex();
title.setValue("");
if (c > 0 || isFiltering) {
multi.setValue("0");
if (isFiltering) {
title.setValue("");
if (c != -1) {
short_title.setValue(backingCours.get(c-1).getShortDesc());
}
else {
short_title.setValue("");
}
String st = "";
// TODO: add filters to title
title.setValue(st);
} else {
short_title.setValue(backingCours.get(c-1).getShortDesc());
}
} else {
// all classes
String tt = "", shortt = "";
multi.setValue("1");
// TODO renumber the cours so as to eliminate blank spots
int maxId = -1;
for (CoursSummary cc : backingCours) {
if (Integer.parseInt(cc.getId()) > maxId)
maxId = Integer.parseInt(cc.getId());
}
if (maxId > 0) {
String[] shortDescs = new String[maxId];
for (CoursSummary cc : backingCours) {
shortDescs[Integer.parseInt(cc.getId())] = cc.getShortDesc();
}
for (int i = 0; i < maxId; i++)
shortt += shortDescs[i] + "|";
}
title.setValue(tt);
short_title.setValue(shortt);
}
}
private void collectDV() {
String dv = "|";
for (int i = 1; i < results.getRowCount(); i++) {
for (int j = 0; j < results.getColumnCount(); j++) {
if (j == Columns.VERIFICATION) continue;
dv += results.getText(i, j) + "|";
}
dv += "*|";
}
data.setValue(dv);
}
private void clearFull() {
data_full.setValue("");
}
private void computeFull() {
String dv = "";
for (int i = 0; i < allClients.length(); i++) {
ClientData cd = allClients.get(i);
if (!sessionFilter(cd)) continue;
dv += toDVFullString(cd) + "*";
}
data_full.setValue(dv);
}
private String toDVFullString(ClientData cd) {
String dv = "";
dv += cd.getID() + "|";
dv += cd.getNom() + "|";
dv += cd.getPrenom() + "|";
dv += cd.getSexe() + "|";
dv += cd.getJudoQC() + "|";
dv += cd.getDDNString() + "|";
dv += cd.getDivision(requestedSession().effective_year).abbrev + "|";
dv += cd.getCourriel() + "|";
dv += cd.getAdresse() + "|";
dv += cd.getVille() + "|";
dv += cd.getCodePostal() + "|";
dv += cd.getTel() + "|";
dv += cd.getCarteResident() + "|";
dv += cd.getTelContactUrgence() + "|";
dv += cd.getMostRecentGrade().getGrade() + "|";
dv += cd.getMostRecentGrade().getDateGrade() + "|";
ServiceData sd = cd.getServiceFor(Constants.currentSession());
ClubSummary cs = jdb.getClubSummaryByID(sd.getClubID());
// XXX getPrix on ListWidget as well
CostCalculator.recompute(cd, sd, cs, prorata.getValue(), null);
if (sd != null && !sd.getCours().equals("")) {
// XXX this is potentially slow; use a hash map instead.
for (CoursSummary cc : backingCours) {
if (cc.getId().equals(sd.getCours()))
dv += cc.getShortDesc();
}
}
dv += "|";
if (sd != null) {
dv += sd.getFrais();
}
dv += "|";
return dv;
}
private void computeImpotMailMerge() {
String dv = "";
ArrayList<ClientData> filteredClients = new ArrayList<ClientData>();
for (int i = 0; i < allClients.length(); i++) {
ClientData cd = allClients.get(i);
if (!sessionFilter(cd)) continue;
Division d = cd.getDivision(requestedSession().effective_year);
if (d.abbrev.equals("S") || d.aka.equals("S")) continue;
filteredClients.add(cd);
}
Collections.sort(filteredClients, new Comparator<ClientData>() {
public int compare(ClientData x, ClientData y) {
if (!x.getNom().equals(y.getNom()))
return x.getNom().compareTo(y.getNom());
return x.getPrenom().compareTo(y.getPrenom());
}
});
for (ClientData cd : filteredClients) {
dv += toDVImpot(cd) + "*";
}
data_full.setValue(dv);
}
private String toDVImpot(ClientData cd) {
String dv = "";
dv += cd.getID() + "|";
dv += cd.getPrenom() + " " + cd.getNom() + "|";
dv += cd.getDDNString() + "|";
ServiceData sd = cd.getServiceFor(Constants.currentSession());
ClubSummary cs = jdb.getClubSummaryByID(sd.getClubID());
// XXX clubPrix on ListWidget
CostCalculator.recompute(cd, sd, cs, prorata.getValue(), null);
if (sd != null) {
dv += Constants.currencyFormat.format(Double.parseDouble(sd.getFrais()));
}
dv += "|";
return dv;
}
private void submit(String act) {
addMetaData();
listForm.setAction(JudoDB.BASE_URL+"listes"+act+".php");
listForm.submit();
}
private boolean makeFT() {
StringBuffer dv = new StringBuffer("");
for (int i = 1; i < results.getRowCount(); i++) {
CheckBox cb = (CheckBox)results.getWidget(i, Columns.VERIFICATION);
if (cb != null && cb.getValue()) {
ClientData cd = cidToCD.get(results.getText(i, Columns.CID));
StringBuffer post = new StringBuffer();
ListBox w = (ListBox)(results.getWidget(i, Columns.DIVISION_SM));
if (w != null)
post.append(w.getValue(w.getSelectedIndex()));
post.append("|");
dv.append(toDVFullString(cd) + post + "*");
}
}
data.setValue("");
data_full.setValue(dv.toString());
if (jdb.getSelectedClubID() == null) {
jdb.setStatus("Veuillez selectionner un club.");
new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000);
return false;
}
ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID());
auxdata.setValue(cs.getNom() + "|" + cs.getNumeroClub());
return !dv.equals("");
}
public int requestedSessionNo() {
if (session == null || session.getSelectedIndex() == -1) return -1;
return Integer.parseInt(session.getValue(session.getSelectedIndex()));
}
public Constants.Session requestedSession() {
int requestedSessionNo = requestedSessionNo();
if (requestedSessionNo == -1) return null;
return Constants.SESSIONS[requestedSessionNo];
}
public void toggleFiltering()
{
this.isFiltering = !this.isFiltering;
filter_controls.setVisible(this.isFiltering);
showList();
}
private boolean clubServiceFilter(ServiceData sd) {
if (jdb.getSelectedClubID() == null) return true;
return jdb.getSelectedClubID().equals(sd.getClubID());
}
/* unlike the other filters, this one can't be disabled */
private boolean clubFilter(ClientData cd) {
Constants.Session rs = requestedSession();
if (rs == null) {
for (int i = 0; i < cd.getServices().length(); i++) {
if (clubServiceFilter(cd.getServices().get(i)))
return true;
}
return false;
}
ServiceData sd = cd.getServiceFor(rs);
return clubServiceFilter(sd);
}
private boolean sessionFilter(ClientData cd) {
Constants.Session rs = requestedSession();
if (rs == null) return true;
return cd.getServiceFor(rs) != null;
}
private boolean coursFilter(ClientData cd) {
String selectedCours = cours.getValue(cours.getSelectedIndex());
if (selectedCours.equals("-1"))
return true;
if (selectedCours.equals(cd.getServiceFor(requestedSession()).getCours()))
return true;
return false;
}
private boolean divisionFilter(ClientData cd) {
String selectedDivision = division.getValue(division.getSelectedIndex());
if (selectedDivision.equals("-1"))
return true;
Division c = cd.getDivision((requestedSession()).effective_year);
if (selectedDivision.equals(c.abbrev) || selectedDivision.equals(c.aka))
return true;
return false;
}
private boolean gradeFilter(ClientData cd) {
String lc = grade_lower.getValue(grade_lower.getSelectedIndex());
String uc = grade_upper.getValue(grade_upper.getSelectedIndex());
boolean emptyLC = lc.equals(""), emptyUC = uc.equals("");
Grade g = Constants.stringToGrade(cd.getGrade());
if (g != null) {
int lower_constraint = emptyLC ? 0 : Integer.parseInt(lc);
int upper_constraint = emptyUC ? 0 : Integer.parseInt(uc);
return (emptyLC || lower_constraint <= g.order) &&
(emptyUC || g.order <= upper_constraint);
} else {
return emptyLC && emptyUC;
}
}
public boolean filter(ClientData cd) {
if (!sessionFilter(cd))
return false;
if (!coursFilter(cd))
return false;
if (isFiltering) {
if (!divisionFilter(cd))
return false;
if (!gradeFilter(cd))
return false;
}
return true;
}
public void clearX() {
for (int i = 0; i < results.getRowCount(); i++) {
CheckBox cb = (CheckBox)results.getWidget(i, Columns.VERIFICATION);
if (cb != null && cb.getValue()) {
cb.setValue(false);
}
}
}
private ArrayList<Integer> sorts = new ArrayList<Integer>();
@SuppressWarnings("deprecation")
public void showList() {
if (cours.getItemCount() == 0) return;
boolean all = "-1".equals(cours.getValue(cours.getSelectedIndex()));
int requestedSessionNo = requestedSessionNo();
final Constants.Session rs = requestedSession();
int count = 0, curRow;
final ArrayList<ClientData> filteredClients = new ArrayList<ClientData>();
final class SortClickHandler implements ClickHandler {
int col;
SortClickHandler(int col) { this.col = col; }
public void onClick(ClickEvent e) {
if (sorts.get(sorts.size()-1).equals(col) ||
sorts.get(sorts.size()-1).equals(-col)) {
int q = sorts.get(sorts.size()-1);
sorts.remove(sorts.size()-1);
sorts.add(-q);
} else {
sorts.remove(new Integer(col));
sorts.add(col);
}
showList();
}
}
// two passes: 1) count; 2) populate the grid
if (allClients == null) return;
for (int i = 0; i < allClients.length(); i++) {
ClientData cd = allClients.get(i);
cidToCD.put(cd.getID(), cd);
if (!clubFilter(cd)) continue;
if (!filter(cd)) continue;
filteredClients.add(cd);
count++;
}
for (final Integer col : sorts) {
final int colSign = (col < 0) ? -1 : 1;
Collections.sort(filteredClients, new Comparator<ClientData>() {
public int compare(ClientData x, ClientData y) {
switch (col * colSign) {
case 2:
return colSign * x.getNom().compareToIgnoreCase(y.getNom());
case 3:
return colSign * x.getPrenom().compareToIgnoreCase(y.getPrenom());
case 5:
return colSign * x.getGrade().compareTo(y.getGrade());
case 9:
return colSign * x.getDDN().compareTo(y.getDDN());
case 10:
int xc = x.getDivision(rs.effective_year).years_ago;
int yc = y.getDivision(rs.effective_year).years_ago;
if (xc == 0) xc = Integer.MAX_VALUE;
if (yc == 0) yc = Integer.MAX_VALUE;
return colSign * (xc - yc);
case 11:
ServiceData xsd = x.getServiceFor(rs);
int xcours = xsd != null ? Integer.parseInt(xsd.getCours()) : -1;
ServiceData ysd = y.getServiceFor(rs);
int ycours = ysd != null ? Integer.parseInt(ysd.getCours()) : -1;
return colSign * (xcours - ycours);
}
return 0;
}
});
}
results.resize(count+1, 15);
if (mode==Mode.FT)
heads[Columns.VERIFICATION] = "FT";
else
heads[Columns.VERIFICATION] = "V";
boolean[] visibility = new boolean[] {
true, mode==Mode.EDIT || mode==Mode.FT, true, true, mode==Mode.EDIT || mode==Mode.FT,
true, true, true, true, true, true, mode==Mode.EDIT || all, false,
requestedSessionNo == -1, mode==Mode.FT
};
for (int i = 0; i < heads.length; i++) {
if (visibility[i]) {
if (sortable[i]) {
Anchor a = new Anchor(heads[i]);
a.addClickHandler(new SortClickHandler(i));
results.setWidget(0, i, a);
}
else
results.setText(0, i, heads[i]);
results.getCellFormatter().setStyleName(0, i, "list-th");
results.getCellFormatter().setVisible(0, i, true);
} else {
results.setText(0, i, "");
results.getCellFormatter().setVisible(0, i, false);
}
}
curRow = 1;
clubsPresent.clear();
for (ClientData cd : filteredClients) {
String grade = cd.getGrade();
if (grade != null && grade.length() >= 3) grade = grade.substring(0, 3);
ServiceData sd = cd.getServiceFor(rs);
int cours = sd != null ? Integer.parseInt(sd.getCours()) : -1;
clubsPresent.add(sd.getClubID());
Anchor nomAnchor = new Anchor(cd.getNom()), prenomAnchor = new Anchor(cd.getPrenom());
ClickHandler c = jdb.new EditClientHandler(Integer.parseInt(cd.getID()));
nomAnchor.addClickHandler(c);
prenomAnchor.addClickHandler(c);
results.setText(curRow, Columns.CID, cd.getID());
results.setWidget(curRow, Columns.NOM, nomAnchor);
results.setWidget(curRow, Columns.PRENOM, prenomAnchor);
results.setText(curRow, Columns.SEXE, cd.getSexe());
results.setText(curRow, Columns.GRADE, "");
results.setText(curRow, Columns.DATE_GRADE, "");
if (mode == Mode.EDIT) {
TextBox g = new TextBox();
final TextBox gd = new TextBox();
g.setValue(grade); g.setWidth("3em");
g.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent e) {
String gdv = gd.getValue();
if (gdv.equals("") || gdv.equals(Constants.STD_DUMMY_DATE))
gd.setValue(edit_date.getValue());
}
});
results.setWidget(curRow, Columns.GRADE, g);
originalGrades.put(g, cd.getGrade());
gd.setValue(Constants.dbToStdDate(cd.getDateGrade())); gd.setWidth("6em");
results.setWidget(curRow, Columns.DATE_GRADE, gd);
originalGradeDates.put(gd, cd.getDateGrade());
} else if (grade != null && !grade.equals("")) {
results.setText(curRow, Columns.GRADE, grade);
results.setText(curRow, Columns.DATE_GRADE, Constants.dbToStdDate(cd.getDateGrade()));
}
results.setText(curRow, Columns.TEL, cd.getTel());
if (mode == Mode.EDIT) {
TextBox jqc = new TextBox(); jqc.setValue(cd.getJudoQC()); jqc.setWidth("4em");
results.setWidget(curRow, Columns.JUDOQC, jqc);
originalJudoQC.put(jqc, cd.getJudoQC());
} else {
results.setText(curRow, Columns.JUDOQC, cd.getJudoQC());
}
Date ddns = cd.getDDN();
results.setText(curRow, Columns.DDN, ddns == null ? Constants.STD_DUMMY_DATE : Constants.STD_DATE_FORMAT.format(ddns));
results.setText(curRow, Columns.DIVISION, cd.getDivision((rs == null ? Constants.currentSession() : rs).effective_year).abbrev);
if (visibility[Columns.VERIFICATION]) {
CheckBox cb = new CheckBox();
cb.addStyleName("noprint");
results.setWidget(curRow, Columns.VERIFICATION, cb);
if (mode==Mode.EDIT) {
cb.setValue(sd.getVerification());
originalVerifValues.put(cb, sd.getVerification());
}
}
if (visibility[Columns.DIVISION_SM] && (Constants.currentSession().effective_year - (cd.getDDN().getYear() + 1900)) > Constants.VETERAN) {
ListBox d = new ListBox();
d.addItem("Senior", "S");
d.addItem("Masters", "M");
results.setWidget(curRow, Columns.DIVISION_SM, d);
} else {
results.clearCell(curRow, Columns.DIVISION_SM);
}
results.setText(curRow, Columns.COURS_DESC, "");
results.setText(curRow, Columns.COURS_NUM, "");
if (mode == Mode.EDIT) {
ListBox w = newCoursWidget(sd.getClubID(), cours);
results.setWidget(curRow, Columns.COURS_DESC, w);
results.setText(curRow, Columns.COURS_NUM, Integer.toString(cours));
originalCours.put(w, cours);
} else if (cours != -1) {
results.setText(curRow, Columns.COURS_DESC, getShortDescForCoursId(cours));
results.setText(curRow, Columns.COURS_NUM, Integer.toString(cours));
}
if (requestedSessionNo == -1) {
results.setText(curRow, Columns.SESSION, cd.getAllActiveSaisons());
} else {
results.setText(curRow, Columns.SESSION, "");
}
for (int j = 0; j < visibility.length; j++)
results.getCellFormatter().setVisible(curRow, j, visibility[j]);
if (curRow % 2 == 1)
results.getRowFormatter().setStyleName(curRow, "darkBG");
curRow++;
}
nb.setText("Nombre inscrit: "+count);
}
private ListBox newCoursWidget(String clubId, int coursId) {
ListBox lb = new ListBox();
int matching_index = -1;
int i = 0;
String ciString = Integer.toString(coursId);
for (CoursSummary cs : backingCours) {
if (clubId.equals(cs.getClubId())) {
lb.addItem(cs.getShortDesc(), cs.getId());
if (cs.getId().equals(ciString))
matching_index = i;
i++;
}
}
if (matching_index != -1)
lb.setSelectedIndex(matching_index);
return lb;
}
public void switchMode(Mode m) {
this.mode = m;
for (Widget w : allListModeWidgets)
w.setVisible(false);
for (Widget w : listModeVisibility.get(m))
w.setVisible(true);
// blow away state...
//session.setSelectedIndex(0);
originalVerifValues.clear();
if (cours.getItemCount() > 0)
showList();
}
private void loadCours(JsArray<CoursSummary> coursArray) {
backingCours.clear();
cours.setVisibleItemCount(1);
cours.clear();
cours.addItem("Tous", "-1");
for (int i = 0; i < coursArray.length(); i++) {
CoursSummary c = coursArray.get(i);
cours.addItem(c.getShortDesc(), c.getId());
backingCours.add(c);
}
}
private String getShortDescForCoursId(int coursId) {
String cidString = Integer.toString(coursId);
for (CoursSummary c : backingCours) {
if (c.getId().equals(cidString))
return c.getShortDesc();
}
return "inconnu";
}
private boolean gotCours = false;
public void retrieveCours(int session_seqno, String numero_club) {
backingCours.clear();
String url = JudoDB.PULL_CLUB_COURS_URL;
url += "?session_seqno="+session_seqno;
if (numero_club != null) url += "&numero_club="+numero_club;
RequestCallback rc =
jdb.createRequestCallback(new JudoDB.Function() {
public void eval(String s) {
gotCours = true;
loadCours(JsonUtils.<JsArray<CoursSummary>>safeEval(s));
ListWidget.this.showList();
}
});
jdb.retrieve(url, rc);
}
public void retrieveAllClients() {
String url = PULL_ALL_CLIENTS_URL;
RequestCallback rc =
jdb.createRequestCallback(new JudoDB.Function() {
public void eval(String s) {
ListWidget.this.allClients =
(JsonUtils.<JsArray<ClientData>>safeEval(s));
new Timer() {
public void run() {
if (gotCours) {
ListWidget.this.showList();
cancel();
} else {
scheduleRepeating(100);
}
} } .scheduleRepeating(10);
}
});
jdb.retrieve(url, rc);
}
public void pushChanges(final String guid) {
String url = CONFIRM_PUSH_URL + "?guid=" + guid;
RequestCallback rc =
jdb.createRequestCallback(new JudoDB.Function() {
public void eval(String s) {
ConfirmResponseObject cro =
JsonUtils.<ConfirmResponseObject>safeEval(s);
String rs = cro.getResult();
if (rs.equals("NOT_YET")) {
if (pushTries >= 3) {
jdb.displayError("le serveur n'a pas accepté les données");
return;
}
new Timer() { public void run() {
pushChanges(guid);
} }.schedule(2000);
pushTries++;
} else {
jdb.setStatus("Sauvegardé.");
}
new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000);
}
});
jdb.retrieve(url, rc);
}
}
|
package com.algorithms.map;
import java.util.NoSuchElementException;
import com.algorithms.elementary.ArrayBag;
import com.algorithms.elementary.ArrayQueue;
import com.algorithms.elementary.Bag;
import com.algorithms.elementary.Queue;
public class BinarySearchTreeMap<K extends Comparable<K>, V> implements Map<K, V>{
public static void main(String[] args) {
Map<Integer, Integer> map = new BinarySearchTreeMap<>();
map.put(10, 10);
map.put(9, 9);
map.put(15, 15);
map.put(5, 5);
map.put(12, 12);
map.put(3, 3);
map.put(7, 7);
map.put(7, 7);
System.out.println("map.isEmpty() = " + map.isEmpty());
System.out.println("map.size() = " + map.size());
System.out.println("map.size(9, 15) = " + map.size(9, 15));
System.out.println("map.ceiling(13) = " + map.ceiling(13));
System.out.println("map.floor(16) = " + map.floor(16));
System.out.println("map.get(7) = " + map.get(7));
System.out.println("map.max() = " + map.max());
System.out.println("map.min() = " + map.min());
System.out.println("map.select(2) = " + map.select(2));
System.out.println("map.contains(2) = " + map.contains(2));
System.out.println("map.rank(10) = " + map.rank(10));
System.out.print("map.keys() = ");
for (Integer i : map.keys())
System.out.print(i + " ");
System.out.print("map.keys(9, 15) = ");
for (Integer i : map.keys(9, 15))
System.out.print(i + " ");
System.out.println("******************");
System.out.println("test deleting operation");
System.out.println("map.deleteMin()");
map.deleteMin();
System.out.print("map.keys() = ");
for (Integer i : map.keys())
System.out.print(i + " ");
System.out.println("");
System.out.println("map.deleteMax()");
map.deleteMax();
System.out.print("map.keys() = ");
for (Integer i : map.keys())
System.out.print(i + " ");
System.out.println("");
System.out.println("map.delete(9)");
map.delete(9);
System.out.print("map.keys() = ");
for (Integer i : map.keys())
System.out.print(i + " ");
System.out.println(" ");
System.out.println("test again in case of some bugs in deleting operation");
System.out.println("map.isEmpty() = " + map.isEmpty());
System.out.println("map.size() = " + map.size());
System.out.println("map.size(9, 15) = " + map.size(9, 15));
System.out.println("map.ceiling(13) = " + map.ceiling(13));
System.out.println("map.floor(16) = " + map.floor(16));
System.out.println("map.get(7) = " + map.get(7));
System.out.println("map.max() = " + map.max());
System.out.println("map.min() = " + map.min());
System.out.println("map.select(2) = " + map.select(2));
System.out.println("map.contains(2) = " + map.contains(2));
System.out.println("map.rank(10) = " + map.rank(10));
System.out.print("map.keys() = ");
for (Integer i : map.keys())
System.out.print(i + " ");
System.out.print("map.keys(9, 15) = ");
for (Integer i : map.keys(9, 15))
System.out.print(i + " ");
System.out.println("******************");
}
private Node<K, V> root;
@Override
public void put(K k, V v) {
root = put(root, k, v);
}
private Node<K, V> put(Node<K, V> node, K k, V v) {
if (node == null) return new Node<>(k, v, 1);
int cmp = node.k.compareTo(k);
if (cmp > 0) {
node.left = put(node.left, k, v);
} else if (cmp < 0) {
node.right = put(node.right, k, v);
} else node.v = v;
node.size = size(node.left) + size(node.right) + 1;
return node;
}
private int size(Node<K, V> node) {
if (node == null) return 0;
return node.size;
}
@Override
public V get(K k) {
return get(root, k);
}
private V get(Node<K, V> node, K k) {
if (node == null) return null; //not find
else if (node.k.compareTo(k) > 0) {
return get(node.left, k);
} else if (node.k.compareTo(k) < 0) {
return get(node.right, k);
} else { //equal
return node.v;
}
}
@Override
public void delete(K k) {
delete(root, k);
}
//delete the k in the node tree and reset the size prorperty of this tree and subtrees to correct value
private Node<K, V> delete(Node<K, V> node, K k) {
if (node == null) return null;
int cmp = node.k.compareTo(k);
if (cmp > 0) {
node.left = delete(node.left, k);
node.size = size(node.left) + size(node.right) + 1;
return node;
} else if (cmp < 0) {
node.right = delete(node.right, k);
node.size = size(node.left) + size(node.right) + 1;
return node;
} else { //hit the key
if (node.right == null) //if the right node is null then just replace this node with left node
return node.left;
else if (node.left == null) // if the left node is null then just replace this node with right node
return node.right;
else {
return deleteMin(node.right); // if both the subnodes are not null replace this node with the smallest node in the right sub node
}
}
}
private Node<K, V> deleteMin(Node<K, V> node) {
return delete(node, min(node));
}
private Node<K, V> deleteMax(Node<K, V> node) {
return delete(node, max(node));
}
@Override
public void deleteMin() {
deleteMin(root);
}
@Override
public void deleteMax() {
deleteMax(root);
}
@Override
public boolean contains(K k) {
return get(k) != null;
}
@Override
public boolean isEmpty() {
return root == null;
}
@Override
public int size() {
return root.size;
}
@Override
public int size(K lo, K hi) {
return size(root, lo, hi);
}
private int size(Node<K, V> node, K lo, K hi) {
if (node == null) return 0;
int cmpToLow = node.k.compareTo(lo);
int cmpToHi = node.k.compareTo(hi);
if (cmpToLow < 0) { //node is less than lo
return size(node.right, lo, hi);
} else if (cmpToHi > 0) { // node is large than hi
return size(node.left, lo, hi);
} else { // node is between lo and hi, [lo, hi]
return size(node.right, lo, hi) + size(node.left, lo, hi) + 1;
}
}
@Override
public K min() {
return min(root);
}
//get the smallest node in the given node
private K min(Node<K, V> node) {
if (node == null) return null;
for (; node.left != null; node = node.left);
return node.k;
}
@Override
public K max() {
return max(root);
}
//get the most max node in the given node
private K max(Node<K, V> node) {
if (node == null) return null;
for (node = root; node.right != null; node = node.right);
return node.k;
}
//returnthe key that is less or equal to the paramter k
@Override
public K floor(K k) {
return floor(root, k);
}
private K floor(Node<K, V> node, K k) {
if (node == null) return null;
int cmp = node.k.compareTo(k);
if (cmp > 0) return floor(node.left, k); //node.k k so we need to find the k in the left tree
else if (cmp < 0) { //node.k is less then k
K returnValue = node.k; //so node.k might be the value .but iam not sure we shall see
if (floor(node.right, k) != null)
returnValue = floor(node.right, k);
return returnValue;
} else {
return node.k;
}
}
//returnthe k that is large or equal to k the paramter
@Override
public K ceiling(K k) {
return ceiling(root, k);
}
private K ceiling(Node<K, V> node, K k) {
if (node == null) return null;
int cmp = node.k.compareTo(k);
if (cmp > 0) {
K returnValue = node.k; //so node.k might be the value .but iam not sure we shall see
if (ceiling(node.left, k) != null)
returnValue = ceiling(node.left, k);
return returnValue;
}
else if (cmp < 0) { //node.k is less then k
return ceiling(node.right, k);
} else {
return node.k;
}
}
// the number of keys less than key
@Override
public int rank(K k) {
return rank(root, k);
}
private int rank(Node<K, V> node, K k) {
if (node == null) return 0;
int cmp = node.k.compareTo(k);
if (cmp > 0)
return rank(node.left, k);
else if (cmp < 0) {
return size(node.left) + rank(node.right, k) + 1;
} else
return size(node.left);
}
@Override
public K select(int k) {
if (k > root.size - 1) throw new NoSuchElementException();
return select(root, k);
}
private K select(Node<K, V> node, int k) {
if (size(node.left) > k) {
return select(node.left, k);
} else if (size(node.left) < k) {
return select(node.right, k - size(node.left) - 1);
} else
return node.k;
}
private void keys(Node<K, V> node, K lo, K hi, Queue<K> queue) {
if (node == null) return;
int cmpToLow = node.k.compareTo(lo);
int cmpToHi = node.k.compareTo(hi);
if (cmpToLow < 0) {
keys(node.left, lo, hi, queue);
} else if (cmpToHi > 0) {
keys(node.right, lo, hi, queue);
} else {
keys(node.left, lo, hi, queue);
queue.enqueue(node.k);
keys(node.right, lo, hi, queue);
}
}
// keys in [lo , hi] in sorted order
@Override
public Iterable<K> keys(K lo, K hi) {
Queue<K> queue = new ArrayQueue<>();
keys(root, lo, hi, queue);
return queue;
}
@Override
public Iterable<K> keys() {
Queue<K> queue = new ArrayQueue<>();
keys(root, min(), max(), queue);
return queue;
}
private class Node<K, V> {
private K k;
private V v;
private Node<K, V> left;
private Node<K, V> right;
private int size;
Node(K k, V v) { this.k = k; this.v = v; }
Node(K k, V v, int size) { this.k = k; this.v = v; this.size = size;}
}
}
|
package com.civica.grads.boardgames.model;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import com.civica.grads.boardgames.exceptions.NoPieceException;
import com.civica.grads.boardgames.exceptions.GameException;
import com.civica.grads.boardgames.interfaces.Describable;
import com.civica.grads.boardgames.interfaces.DeterminesNextMove;
import com.civica.grads.boardgames.interfaces.Move;
import com.civica.grads.boardgames.model.player.Player;
import com.civica.grads.boardgames.exceptions.NoPieceException;
public abstract class Game implements Describable,DeterminesNextMove {
final protected Board board ;
protected static int startingPlayerCounters ;
protected Player[] player ;
final protected ArrayList<TurnRecord> turnRecords = new ArrayList<>() ;
/**
* Constructor for game that takes in a int size and and array of player objects. Also checks for IAE exception to catch wrong board sizes
* @param size is the size of the board of type int
* @param player is an array of player objects
*/
public Game(int size, Player[] player) {
checkBoardSizeValue(size) ;
this.board = new Board(size) ;
this.player = player ;
initialiseBoardForGame() ;
}
/**
* Sets the board up for the type of game.
*/
abstract protected void initialiseBoardForGame();
public abstract void applyMove(Move move) throws GameException ;
/**
* This operation updates the board with the data from the moves;
*/
private void updateBoard()
{
throw new RuntimeException("This code is missing"); //FIXME Update the board
}
abstract public void takePiece(Position position) throws NoPieceException ;
/**
* Retrieves number of turns in a game
* @return Number of turns
*/
public int getNumberOfTurns() {
return turnRecords.size();
}
/**
* Checks if game has any turns
* @return True if turns count > 0, false otherwise
*/
public boolean hasTurns() {
return turnRecords.isEmpty();
}
/**
* Adds a turn record to list
* @param e turn record
* @return true if successful, false if failed
*/
public boolean addTurn(TurnRecord e) {
return turnRecords.add(e);
}
/**
* clears all the turns stored in the turnsRecord arraylist
*/
public void clearTurns() {
turnRecords.clear();
}
abstract protected void checkBoardSizeValue(int size) throws IllegalArgumentException ;
/**
* Retrieves board object
* @return Board object
*/
public Board getBoard() {
return board;
}
/**
* Returns the total number of counters at the start of a game
* @return Number of counters
*/
public int getStartingPlayerCounters() {
return startingPlayerCounters;
}
public Player[] getPlayer() {
return player;
}
public ArrayList<TurnRecord> getTurns() {
return turnRecords;
}
@Override
public void describe(OutputStream out) throws IOException {
out.write(this.toString().getBytes()) ;
}
@Override
public String toString() {
return "Game [board=" + board + ", player=" + Arrays.toString(player) + ", turnRecords=" + turnRecords + "]";
}
@Override
public Move evaluate(Board board) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.comandulli.data.file;
import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;
public class WriteableData extends Data {
public WriteableData(String dataPath, List<WriteableFile> files) throws IOException, DataFileException {
File dataFile = new File(dataPath);
if (dataFile.exists()) {
if (!dataFile.delete()) {
throw new DataFileException("Error cant access path: " + dataPath);
}
}
accessDataFile = new RandomAccessFile(dataFile, "rw");
int numFiles = files.size();
long dataStartPtr = indexPositionToKeyFilePosition(numFiles);
accessDataFile.setLength(dataStartPtr);
writeNumFilesHeader(numFiles);
for (int i = 0; i < numFiles; i++) {
insertFile(files.get(i), i);
}
close();
}
private synchronized void insertFile(WriteableFile fileEntry, int index) throws DataFileException, IOException {
String key = fileEntry.getKey();
FileHeader newEntry = allocateFile(key, fileEntry.getDataLength());
writeFileData(newEntry, fileEntry);
addEntryToIndex(key, newEntry, index);
}
private synchronized void close() throws IOException {
try {
accessDataFile.close();
} finally {
accessDataFile = null;
}
}
private void writeNumFilesHeader(int numRecords) throws IOException {
accessDataFile.seek(HEADER_LOCATION);
accessDataFile.writeInt(numRecords);
}
private FileHeader allocateFile(String key, int dataLength) throws IOException {
long fp = accessDataFile.length();
accessDataFile.setLength(fp + dataLength);
return new FileHeader(fp, dataLength);
}
private void writeFileData(FileHeader header, WriteableFile rw) throws IOException, DataFileException {
if (rw.getDataLength() > header.dataCapacity) {
throw new DataFileException("File data does not fit");
}
header.dataCount = rw.getDataLength();
accessDataFile.seek(header.dataPointer);
rw.writeTo((DataOutput) accessDataFile);
}
private void addEntryToIndex(String key, FileHeader newRecord, int currentIndex) throws IOException, DataFileException {
ByteArrayOutputStream temp = new ByteArrayOutputStream(MAX_KEY_LENGTH);
DataOutputStream dos = new DataOutputStream(temp);
dos.writeUTF(key);
dos.close();
if (temp.size() > MAX_KEY_LENGTH) {
throw new DataFileException("Key is larger than permitted size of " + MAX_KEY_LENGTH + " bytes");
}
accessDataFile.seek(indexPositionToKeyFilePosition(currentIndex));
byte[] data = temp.toByteArray();
accessDataFile.write(data);
accessDataFile.seek(indexPositionToRecordHeaderFilePosition(currentIndex));
newRecord.write(accessDataFile);
newRecord.setIndexPosition(currentIndex);
}
public static void GetDirectoryFiles(List<WriteableFile> writers, File directory, String parentKey) throws IOException {
if (directory.isDirectory() && directory.exists()) {
File[] children = directory.listFiles();
for (File child : children) {
if (child.isDirectory()) {
GetDirectoryFiles(writers, child, parentKey + "\\" + child.getName());
} else if (child.exists()) {
WriteableFile rw = new WriteableFile(parentKey + "\\" + child.getName());
rw.writeFile(child);
writers.add(rw);
}
}
}
}
}
|
import java.io.*;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
//For pretty colors
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
public class ftp_client {
private static Console console = System.console();
private static FTPClient ftpClient = new FTPClient();
public static void main(String[] args) {
setupFTPClient(args);
String command;
String localDir = System.getProperty("user.dir");
while(ftpClient.isConnected()) {
command = getVar("command");
switch(command) {
case "list local":
case "lsl":
listLocal(localDir);
break;
case "exit":
case "logout":
exit();
break;
case "help":
help();
break;
case "cls":
case "clear":
clear();
break;
default:
//REGEX Matching
if(command.matches("cd local (.*)") || command.matches("cdl (.*)")) {
localDir = changeDirectory(localDir, command);
}
else {
System.out.println("\tCommand not found. For help input \"help\"");
}
}
}
logout();
System.exit(0);
}
//Lists the local files/folders in the provided directory
private static boolean listLocal(String dir) {
AnsiConsole.systemInstall();
System.out.println();
try {
File folder = new File(dir);
File[] fileList = folder.listFiles();
System.out.println(ansi().fg(MAGENTA) + "Current Directory: " + ansi().fg(DEFAULT) + dir);
for (int i = 0; i < fileList.length; ++i) {
if(fileList[i].isFile()) {
System.out.println("\t" + ansi().fg(CYAN) + fileList[i].getName());
}
else if(fileList[i].isDirectory()) {
System.out.println("\t" + ansi().fg(BLUE) + fileList[i].getName());
}
}
System.out.println(ansi().fg(DEFAULT));
}
catch(Exception e) {
AnsiConsole.systemUninstall();
return false;
}
AnsiConsole.systemUninstall();
return true;
}
private static String changeDirectory(String dir, String input) {
input = input.replace("cdl","");
input = input.replace("cd local","");
input = input.trim();
File newDir = new File(dir, input);
try {
if (newDir.exists()) {
System.out.println("New Dir: " + newDir.toPath().normalize().toString());
return newDir.toPath().normalize().toString();
}
else {
System.out.println("Folder not found :(");
return dir;
}
}
catch(Exception e) {
System.out.println("Something went wrong :(");
return dir;
}
}
//Prints the help menu
private static void help() {
System.out.println("RTFM"); //fix me
System.out.println();
}
//Clears the console
private static void clear() {
AnsiConsole.systemInstall();
System.out.println(ansi().eraseScreen());
AnsiConsole.systemUninstall();
}
//Logoff and exit
private static void exit() {
logout();
}
//gets reply from the server
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
//if there are messages, display each one in order
if (replies != null && replies.length > 0)
for (String reply : replies)
System.out.println("SERVER: " + reply);
}
//Gets input from user or args and calls login
private static void setupFTPClient(String[] args) {
//shouldn't be more than 3 args - error
if(args.length > 3)
System.out.println("RTFM!"); //Yes, I know there is no manual
String server = (args.length < 1) ? getVar("Server") : args[0];
int port = 21;
String username = (args.length < 2) ? getVar("User") : args[1];
String password = (args.length < 3) ? getPrivateVar("Password") : args[2];
login(server,port,username,password);
}
private static boolean login(String server, int port, String user, String password) {
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
System.out.println("Could not connect");
return false;
}
return ftpClient.login(user, password);
}
catch(Exception ex) {
System.out.println("Something went wrong :( - couldn't connect to the server");
return false;
}
}
private static boolean logout() {
if(ftpClient.isConnected()) {
try {
System.out.println("Logging out...");
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Succesfully Disconnected");
return true;
}
catch(Exception ex) {
System.out.println("Something went wrong :( - Couldn't logout and disconnect correctly");
return false;
}
}
return false;
}
//Prompts user and returns a string
private static String getVar(String request) {
System.out.print(request + ": ");
return console.readLine();
}
//Prompts user and returns a string w/o outputing it
private static String getPrivateVar(String request) {
System.out.print(request + ": ");
return new String(console.readPassword());
}
}
|
package com.dmdirc.addons.ui_swing;
import com.dmdirc.addons.ui_swing.actions.RedoAction;
import com.dmdirc.addons.ui_swing.actions.UndoAction;
import com.dmdirc.addons.ui_swing.components.DMDircUndoableEditListener;
import com.dmdirc.ui.Colour;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.FontUIResource;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import net.miginfocom.layout.PlatformDefaults;
/**
* UI constants.
*/
@SuppressWarnings("PMD.UnusedImports")
public final class UIUtilities {
/**
* GTK LAF class name.
*/
private static final String GTKUI = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
/**
* Nimbus LAF class name.
*/
private static final String NIMBUSUI = "sun.swing.plaf.nimbus.NimbusLookAndFeel";
/**
* Windows LAF class name.
*/
private static final String WINDOWSUI = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
/**
* Windows classic LAF class name.
*/
private static final String WINDOWSCLASSICUI
= "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
/** Not intended to be instantiated. */
private UIUtilities() {
}
/**
* Adds an undo manager and associated key bindings to the specified text component.
*
* @param component component Text component to add an undo manager to
*/
public static void addUndoManager(final JTextComponent component) {
final UndoManager undoManager = new UndoManager();
// Listen for undo and redo events
component.getDocument().addUndoableEditListener(
new DMDircUndoableEditListener(undoManager));
// Create an undo action and add it to the text component
component.getActionMap().put("Undo", new UndoAction(undoManager));
// Bind the undo action to ctl-Z
component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
// Create a redo action and add it to the text component
component.getActionMap().put("Redo", new RedoAction(undoManager));
// Bind the redo action to ctl-Y
component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
}
/**
* Initialises any settings required by this UI (this is always called before any aspect of the
* UI is instantiated).
*
* @throws UnsupportedOperationException If unable to switch to the system look and feel
*/
public static void initUISettings() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException | ClassNotFoundException |
UnsupportedLookAndFeelException | IllegalAccessException ex) {
throw new UnsupportedOperationException("Unable to switch to the "
+ "system look and feel", ex);
}
UIManager.put("swing.useSystemFontSettings", true);
if (getTabbedPaneOpaque()) {
// If this is set on windows then .setOpaque seems to be ignored
// and still used as true
UIManager.put("TabbedPane.contentOpaque", false);
}
UIManager.put("swing.boldMetal", false);
UIManager.put("InternalFrame.useTaskBar", false);
UIManager.put("SplitPaneDivider.border",
BorderFactory.createEmptyBorder());
UIManager.put("Tree.scrollsOnExpand", true);
UIManager.put("Tree.scrollsHorizontallyAndVertically", true);
UIManager.put("SplitPane.border", BorderFactory.createEmptyBorder());
UIManager.put("SplitPane.dividerSize", (int) PlatformDefaults.
getPanelInsets(0).getValue());
UIManager.put("TreeUI", TreeUI.class.getName());
UIManager.put("TextField.background", new Color(255, 255, 255));
PlatformDefaults.setDefaultRowAlignmentBaseline(false);
}
/**
* Sets the font of all components in the current look and feel to the specified font, using the
* style and size from the original font.
*
* @param font New font
*/
public static void setUIFont(final Font font) {
final Enumeration<?> keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
final Object key = keys.nextElement();
final Object value = UIManager.get(key);
if (value instanceof FontUIResource) {
final FontUIResource orig = (FontUIResource) value;
UIManager.put(key, new UIDefaults.ProxyLazyValue(
"javax.swing.plaf.FontUIResource", new Object[]{
font.getFontName(), orig.getStyle(), orig.getSize()
}));
}
}
}
/**
* Returns the class name of the look and feel from its display name.
*
* @param displayName Look and feel display name
*
* @return Look and feel class name or a zero length string
*/
public static String getLookAndFeel(final String displayName) {
if (displayName == null || displayName.isEmpty() || "Native".equals(displayName)) {
return UIManager.getSystemLookAndFeelClassName();
}
final StringBuilder classNameBuilder = new StringBuilder();
for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if (laf.getName().equals(displayName)) {
classNameBuilder.append(laf.getClassName());
break;
}
}
if (classNameBuilder.length() == 0) {
classNameBuilder.append(UIManager.getSystemLookAndFeelClassName());
}
return classNameBuilder.toString();
}
/**
* Invokes and waits for the specified runnable, executed on the EDT.
*
* @param runnable Thread to be executed
*/
public static void invokeAndWait(final Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (InterruptedException ex) {
//Ignore
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
}
/**
* Invokes and waits for the specified callable, executed on the EDT.
*
* @param <T> The return type of the returnable thread
* @param returnable Thread to be executed
*
* @return Result from the completed thread or null if an exception occurred
*/
public static <T> T invokeAndWait(final Callable<T> returnable) {
try {
if (SwingUtilities.isEventDispatchThread()) {
return returnable.call();
} else {
final FutureTask<T> task = new FutureTask<>(returnable);
SwingUtilities.invokeAndWait(task);
return task.get();
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Queues the runnable to be executed on the EDT.
*
* @param runnable Runnable to be executed.
*/
public static void invokeLater(final Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
SwingUtilities.invokeLater(runnable);
}
}
/**
* Check if we are using the GTK look and feel.
*
* @return true iif the LAF is GTK
*/
public static boolean isGTKUI() {
return GTKUI.equals(UIManager.getLookAndFeel().getClass().getName());
}
/**
* Check if we are using the Nimbus look and feel.
*
* @return true iif the LAF is Nimbus
*/
public static boolean isNimbusUI() {
return NIMBUSUI.equals(UIManager.getLookAndFeel().getClass().getName());
}
/**
* Check if we are using the new Windows Look and Feel.
*
* @return true iif the current LAF is Windows
*/
public static boolean isWindowsNewUI() {
return WINDOWSUI.equals(
UIManager.getLookAndFeel().getClass().getName());
}
/**
* Check if we are using the new Windows Classic Look and Feel.
*
* @return true iif the current LAF is Windows Classic
*/
public static boolean isWindowsClassicUI() {
return WINDOWSCLASSICUI.equals(UIManager.getLookAndFeel().getClass().getName());
}
/**
* Check if we are using one of the Windows Look and Feels.
*
* @return True iff the current LAF is "Windows" or "Windows Classic"
*/
public static boolean isWindowsUI() {
return isWindowsNewUI() || isWindowsClassicUI();
}
/**
* Get the value to pass to set Opaque on items being added to a JTabbedPane. Currently they
* need to be transparent on Windows (non classic), Apple, Nimbus and GTK.
*
* @return True if tabbed panes should be opaque
*
* @since 0.6
*/
public static boolean getTabbedPaneOpaque() {
return !(isWindowsNewUI() || Apple.isAppleUI() || isNimbusUI() || isGTKUI());
}
/**
* Get the DOWN_MASK for the command/ctrl key.
*
* @return on OSX this returns META_DOWN_MASK, else CTRL_DOWN_MASK
*
* @since 0.6
*/
public static int getCtrlDownMask() {
return Apple.isAppleUI() ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK;
}
/**
* Get the MASK for the command/ctrl key.
*
* @return on OSX this returns META_MASK, else CTRL_MASK
*
* @since 0.6
*/
public static int getCtrlMask() {
return Apple.isAppleUI() ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK;
}
/**
* Check if the command/ctrl key is pressed down.
*
* @param e The KeyEvent to check
*
* @return on OSX this returns e.isMetaDown(), else e.isControlDown()
*
* @since 0.6
*/
public static boolean isCtrlDown(final KeyEvent e) {
return Apple.isAppleUI() ? e.isMetaDown() : e.isControlDown();
}
/**
* Clips a string if its longer than the specified width.
*
* @param component Component containing string
* @param string String to check
* @param avaiableWidth Available Width
*
* @return String (clipped if required)
*/
public static String clipStringifNeeded(final JComponent component,
final String string, final int avaiableWidth) {
if ((string == null) || (string.isEmpty())) {
return "";
}
final FontMetrics fm = component.getFontMetrics(component.getFont());
final int width = SwingUtilities.computeStringWidth(fm, string);
if (width > avaiableWidth) {
return clipString(component, string, avaiableWidth);
}
return string;
}
/**
* Clips the passed string .
*
* @param component Component containing string
* @param string String to check
* @param avaiableWidth Available Width
*
* @return String (clipped if required)
*/
public static String clipString(final JComponent component,
final String string, final int avaiableWidth) {
if ((string == null) || (string.isEmpty())) {
return "";
}
final FontMetrics fm = component.getFontMetrics(component.getFont());
final String clipString = "...";
int width = SwingUtilities.computeStringWidth(fm, clipString);
int nChars = 0;
for (final int max = string.length(); nChars < max; nChars++) {
width += fm.charWidth(string.charAt(nChars));
if (width > avaiableWidth) {
break;
}
}
return string.substring(0, nChars) + clipString;
}
/**
* Resets the scroll pane to 0,0.
*
* @param scrollPane Scrollpane to reset
*
* @since 0.6.3m1
*/
public static void resetScrollPane(final JScrollPane scrollPane) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
scrollPane.getHorizontalScrollBar().setValue(0);
scrollPane.getVerticalScrollBar().setValue(0);
}
});
}
/**
* Paints the background, either from the config setting or the background colour of the
* textpane.
*
* @param g Graphics object to draw onto
* @param bounds Bounds to paint within
* @param backgroundImage background image
* @param backgroundOption How to draw the background
*/
public static void paintBackground(final Graphics2D g,
final Rectangle bounds,
final Image backgroundImage,
final BackgroundOption backgroundOption) {
if (backgroundImage == null) {
paintNoBackground(g, bounds);
} else {
switch (backgroundOption) {
case TILED:
paintTiledBackground(g, bounds, backgroundImage);
break;
case SCALE:
paintStretchedBackground(g, bounds, backgroundImage);
break;
case SCALE_ASPECT_RATIO:
paintStretchedAspectRatioBackground(g, bounds, backgroundImage);
break;
case CENTER:
paintCenterBackground(g, bounds, backgroundImage);
break;
default:
break;
}
}
}
private static void paintNoBackground(final Graphics2D g, final Rectangle bounds) {
g.fill(bounds);
}
private static void paintStretchedBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
g.drawImage(backgroundImage, 0, 0, bounds.width, bounds.height, null);
}
private static void paintCenterBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
final int x = (bounds.width / 2) - (backgroundImage.getWidth(null) / 2);
final int y = (bounds.height / 2) - (backgroundImage.getHeight(null) / 2);
g.drawImage(backgroundImage, x, y, backgroundImage.getWidth(null),
backgroundImage.getHeight(null), null);
}
private static void paintStretchedAspectRatioBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
final double widthratio = bounds.width
/ (double) backgroundImage.getWidth(null);
final double heightratio = bounds.height
/ (double) backgroundImage.getHeight(null);
final double ratio = Math.min(widthratio, heightratio);
final int width = (int) (backgroundImage.getWidth(null) * ratio);
final int height = (int) (backgroundImage.getWidth(null) * ratio);
final int x = (bounds.width / 2) - (width / 2);
final int y = (bounds.height / 2) - (height / 2);
g.drawImage(backgroundImage, x, y, width, height, null);
}
private static void paintTiledBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
final int width = backgroundImage.getWidth(null);
final int height = backgroundImage.getHeight(null);
if (width <= 0 || height <= 0) {
// ARG!
return;
}
for (int x = 0; x < bounds.width; x += width) {
for (int y = 0; y < bounds.height; y += height) {
g.drawImage(backgroundImage, x, y, width, height, null);
}
}
}
/**
* Adds a popup listener which will modify the width of the combo box popup menu to be sized
* according to the preferred size of its components.
*
* @param combo Combo box to modify
*/
public static void addComboBoxWidthModifier(final JComboBox<?> combo) {
combo.addPopupMenuListener(new ComboBoxWidthModifier());
}
/**
* Converts a DMDirc {@link Colour} into an AWT-specific {@link Color} by copying the values of
* the red, green and blue channels.
*
* @param colour The colour to be converted
*
* @return A corresponding AWT colour
*/
public static Color convertColour(final Colour colour) {
return new Color(colour.getRed(), colour.getGreen(), colour.getBlue());
}
/**
* Converts the given colour into a hexadecimal string.
*
* @param colour The colour to be converted
*
* @return A corresponding 6 character hex string
*/
public static String getHex(final Color colour) {
return getHex(colour.getRed()) + getHex(colour.getGreen())
+ getHex(colour.getBlue());
}
/**
* Converts the specified integer (in the range 0-255) into a hex string.
*
* @param value The integer to convert
*
* @return A 2 char hex string representing the specified integer
*/
private static String getHex(final int value) {
final String hex = Integer.toHexString(value);
return (hex.length() < 2 ? "0" : "") + hex;
}
}
|
package com.dmdirc.parser.irc;
import java.util.List;
import java.util.LinkedList;
import java.util.Queue;
/**
* Process a List Modes.
*/
public class ProcessListModes extends IRCProcessor {
/**
* Process a ListModes.
*
* @param sParam Type of line to process
* @param token IRCTokenised line to process
*/
@SuppressWarnings("unchecked")
@Override
public void process(String sParam, String[] token) {
ChannelInfo channel = getChannelInfo(token[3]);
String thisIRCD = myParser.getIRCD(true).toLowerCase();
String item = "";
String owner = "";
byte tokenStart = 4; // Where do the relevent tokens start?
boolean isCleverMode = false;
long time = 0;
char mode = 'b';
boolean isItem = true; // true if item listing, false if "end of .." item
if (channel == null) { return; }
if (sParam.equals("367") || sParam.equals("368")) {
// Ban List/Item.
// (Also used for +d and +q on hyperion... -_-)
mode = 'b';
isItem = sParam.equals("367");
} else if (sParam.equals("348") || sParam.equals("349")) {
// Except / Exempt List etc
mode = 'e';
isItem = sParam.equals("348");
} else if (sParam.equals("346") || sParam.equals("347")) {
// Invite List
mode = 'I';
isItem = sParam.equals("346");
} else if (sParam.equals("940") || sParam.equals("941")) {
// Censored words List
mode = 'g';
isItem = sParam.equals("941");
} else if (sParam.equals("344") || sParam.equals("345")) {
// Reop List, or bad words list, or quiet list. god damn.
if (thisIRCD.equals("euircd")) {
mode = 'w';
} else if (thisIRCD.equals("oftc-hybrid")) {
mode = 'q';
} else {
mode = 'R';
}
isItem = sParam.equals("344");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("386") || sParam.equals("387"))) {
// Channel Owner list
mode = 'q';
isItem = sParam.equals("387");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("388") || sParam.equals("389"))) {
// Protected User list
mode = 'a';
isItem = sParam.equals("389");
} else if (sParam.equals(myParser.h005Info.get("LISTMODE")) || sParam.equals(myParser.h005Info.get("LISTMODEEND"))) {
// Support for potential future decent mode listing in the protocol
mode = token[4].charAt(0);
isItem = sParam.equals(myParser.h005Info.get("LISTMODE"));
tokenStart = 5;
isCleverMode = true;
}
final Queue<Character> listModeQueue = channel.getListModeQueue();
if (!isCleverMode && listModeQueue != null) {
if (sParam.equals("482")) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropped LMQ mode "+listModeQueue.poll());
return;
} else {
if (listModeQueue.peek() != null) {
Character oldMode = mode;
mode = listModeQueue.peek();
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ says this is "+mode);
boolean error = true;
// b or q are given in the same list, d is separate.
// b and q remove each other from the LMQ.
// Only raise an LMQ error if the lmqmode isn't one of bdq if the
// guess is one of bdq
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q' || mode == 'd')) {
LinkedList<Character> lmq = (LinkedList<Character>)listModeQueue;
if (mode == 'b') {
error = !(oldMode == 'q' || oldMode == 'd');
lmq.remove((Character)'q');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping q from list");
} else if (mode == 'q') {
error = !(oldMode == 'b' || oldMode == 'd');
lmq.remove((Character)'b');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping b from list");
} else if (mode == 'd') {
error = !(oldMode == 'b' || oldMode == 'q');
}
}
if (oldMode != mode && error) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode);
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
}
if (!isItem) {
listModeQueue.poll();
}
}
}
}
if (isItem) {
if ((!isCleverMode) && listModeQueue == null && (thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && token.length > 4 && mode == 'b') {
// Assume mode is a 'd' mode
mode = 'd';
// Now work out if its not (or attempt to.)
int identstart = token[tokenStart].indexOf('!');
int hoststart = token[tokenStart].indexOf('@');
// Check that ! and @ are both in the string - as required by +b and +q
if ((identstart >= 0) && (identstart < hoststart)) {
if (thisIRCD.equals("hyperion") && token[tokenStart].charAt(0) == '%') { mode = 'q'; }
else { mode = 'b'; }
}
} // End Hyperian stupidness of using the same numeric for 3 different things..
if (!channel.getAddState(mode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> list = channel.getListModeParam(mode);
if (list == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+mode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
list.clear();
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q')) {
// Also clear the other list if b or q.
final Character otherMode = (mode == 'b') ? 'q' : 'b';
if (!channel.getAddState(otherMode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> otherList = channel.getListModeParam(otherMode);
if (otherList == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+otherMode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
otherList.clear();
}
}
}
}
channel.setAddState(mode, true);
}
if (token.length > (tokenStart+2)) {
try { time = Long.parseLong(token[tokenStart+2]); } catch (NumberFormatException e) { time = 0; }
}
if (token.length > (tokenStart+1)) { owner = token[tokenStart+1]; }
if (token.length > tokenStart) { item = token[tokenStart]; }
if (!item.isEmpty()) {
ChannelListModeItem clmi = new ChannelListModeItem(item, owner, time);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s/%s/%d]",mode, item, owner, time);
channel.setListModeParam(mode, clmi, true);
}
} else {
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode Batch over");
channel.resetAddState();
if (isCleverMode || listModeQueue == null || ((LinkedList<Character>)listModeQueue).size() == 0) {
callDebugInfo(IRCParser.DEBUG_INFO, "Calling GotListModes");
channel.setHasGotListModes(true);
callChannelGotListModes(channel);
}
}
}
/**
* What does this IRCProcessor handle.
*
* @return String[] with the names of the tokens we handle.
*/
@Override
public String[] handles() {
return new String[]{"367", "368", /* Bans */
"344", "345", /* Reop list (ircnet) or bad words (euirc) */
"346", "347", /* Invite List */
"348", "349", /* Except/Exempt List */
"386", "387", /* Channel Owner List (swiftirc ) */
"388", "389", /* Protected User List (swiftirc) */
"940", "941", /* Censored words list */
"482",
"__LISTMODE__" /* Sensible List Modes */
};
}
/**
* Callback to all objects implementing the ChannelGotListModes Callback.
*
* @see IChannelGotListModes
* @param cChannel Channel which the ListModes reply is for
* @return true if a method was called, false otherwise
*/
protected boolean callChannelGotListModes(ChannelInfo cChannel) {
return getCallbackManager().getCallbackType("OnChannelGotListModes").call(cChannel);
}
/**
* Create a new instance of the IRCProcessor Object.
*
* @param parser IRCParser That owns this IRCProcessor
* @param manager ProcessingManager that is in charge of this IRCProcessor
*/
protected ProcessListModes (IRCParser parser, ProcessingManager manager) { super(parser, manager); }
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.helper.EditorData;
public class FileGroup extends AbstractActionGroup
{
public FileGroup()
{
}
/**
* Close the current editor
* @param context The data context
*/
public void closeFile(Editor editor, DataContext context)
{
Project proj = (Project)context.getData(DataConstants.PROJECT);
FileEditorManager fem = FileEditorManager.getInstance(proj);
//fem.closeFile(fem.getSelectedFile());
fem.closeFile(EditorData.getVirtualFile(fem.getSelectedTextEditor()));
/*
if (fem.getOpenFiles().length == 0)
{
exitIdea();
}
*/
}
/**
* Close all editors except for the current editor
* @param context The data context
*/
public void closeAllButCurrent(DataContext context)
{
KeyHandler.executeAction("CloseAllEditorsButCurrent", context);
}
/**
* Close all editors
* @param context The data context
*/
public void closeAllFiles(DataContext context)
{
KeyHandler.executeAction("CloseAllEditors", context);
}
/**
* Saves all files in the project
* @param context The data context
*/
public void saveFiles(DataContext context)
{
// TODO - this needs to be fixed
Project proj = (Project)context.getData(DataConstants.PROJECT);
proj.save();
FileDocumentManager.getInstance().saveAllDocuments();
}
public void closeProject(DataContext context)
{
KeyHandler.executeAction("CloseProject", context);
}
public void exitIdea()
{
ApplicationManager.getApplication().exit();
}
/**
* Selects then next or previous editor
* @param count
* @param context
*/
public boolean selectFile(int count, DataContext context)
{
Project proj = (Project)context.getData(DataConstants.PROJECT);
FileEditorManager fem = FileEditorManager.getInstance(proj);
VirtualFile[] editors = fem.getOpenFiles();
if (count == 99)
{
count = editors.length - 1;
}
if (count < 0 || count >= editors.length)
{
return false;
}
//fem.openFile(new OpenFileDescriptor(editors[count]), ScrollType.RELATIVE, true);
fem.openTextEditor(new OpenFileDescriptor(editors[count]), true);
return true;
}
/**
* Selects then next or previous editor
* @param count
* @param context
*/
public void selectNextFile(int count, DataContext context)
{
Project proj = (Project)context.getData(DataConstants.PROJECT);
FileEditorManager fem = FileEditorManager.getInstance(proj);
VirtualFile[] editors = fem.getOpenFiles();
VirtualFile current = fem.getSelectedFiles()[0];
for (int i = 0; i < editors.length; i++)
{
if (editors[i].equals(current))
{
int pos = (i + (count % editors.length) + editors.length) % editors.length;
//fem.openFile(new OpenFileDescriptor(editors[pos]), ScrollType.RELATIVE, true);
fem.openTextEditor(new OpenFileDescriptor(editors[pos]), true);
}
}
}
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.fileEditor.impl.EditorWindow;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.CommandState;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.helper.EditorHelper;
import com.maddyhome.idea.vim.helper.SearchHelper;
import com.maddyhome.idea.vim.helper.StringHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.util.HashMap;
public class FileGroup {
public FileGroup() {
}
public boolean openFile(@NotNull String filename, @NotNull DataContext context) {
if (logger.isDebugEnabled()) {
logger.debug("openFile(" + filename + ")");
}
final Project project = PlatformDataKeys.PROJECT.getData(context); // API change - don't merge
if (project == null) return false;
VirtualFile found = findFile(filename, project);
if (found != null) {
if (logger.isDebugEnabled()) {
logger.debug("found file: " + found);
}
// Can't open a file unless it has a known file type. The next call will return the known type.
// If unknown, IDEA will prompt the user to pick a type.
FileType type = FileTypeManager.getInstance().getKnownFileTypeOrAssociate(found, project);
if (type != null) {
FileEditorManager fem = FileEditorManager.getInstance(project);
fem.openFile(found, true);
return true;
}
else {
// There was no type and user didn't pick one. Don't open the file
// Return true here because we found the file but the user canceled by not picking a type.
return true;
}
}
else {
VimPlugin.showMessage("Unable to find " + filename);
return false;
}
}
@Nullable
VirtualFile findFile(@NotNull String filename, @NotNull Project project) {
VirtualFile found = null;
if (filename.length() > 2 && filename.charAt(0) == '~' && filename.charAt(1) == File.separatorChar) {
String homefile = filename.substring(2);
String dir = System.getProperty("user.home");
if (logger.isDebugEnabled()) {
logger.debug("home dir file");
logger.debug("looking for " + homefile + " in " + dir);
}
found = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(dir, homefile));
}
else {
ProjectRootManager prm = ProjectRootManager.getInstance(project);
VirtualFile[] roots = prm.getContentRoots();
for (int i = 0; i < roots.length; i++) {
if (logger.isDebugEnabled()) {
logger.debug("root[" + i + "] = " + roots[i].getPath());
}
found = findFile(roots[i], filename);
if (found != null) {
break;
}
}
if (found == null) {
found = LocalFileSystem.getInstance().findFileByIoFile(new File(filename));
}
}
return found;
}
@Nullable
private VirtualFile findFile(@NotNull VirtualFile root, @NotNull String filename) {
VirtualFile res = root.findFileByRelativePath(filename);
if (res != null) {
return res;
}
final Ref<VirtualFile> result = Ref.create();
final VirtualFileVisitor<Object> visitor = new VirtualFileVisitor<Object>() {
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (file.getName().equals(filename)) {
result.set(file);
return false;
}
return true;
}
};
VfsUtilCore.visitChildrenRecursively(root, visitor);
return result.get();
}
/**
* Closes the current editor.
*/
public void closeFile(@NotNull Editor editor, @NotNull DataContext context) {
final Project project = PlatformDataKeys.PROJECT.getData(context);
if (project != null) {
final FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project);
final EditorWindow window = fileEditorManager.getCurrentWindow();
final VirtualFile virtualFile = EditorHelper.getVirtualFile(editor);
if (virtualFile != null) {
window.closeFile(virtualFile);
}
}
}
/**
* Saves specific file in the project.
*/
public void saveFile(DataContext context) {
KeyHandler.executeAction("SaveDocument", context);
}
/**
* Saves all files in the project.
*/
public void saveFiles(DataContext context) {
KeyHandler.executeAction("SaveAll", context);
}
/**
* Selects then next or previous editor.
*/
public boolean selectFile(int count, @NotNull DataContext context) {
final Project project = PlatformDataKeys.PROJECT.getData(context);
if (project == null) return false;
FileEditorManager fem = FileEditorManager.getInstance(project); // API change - don't merge
VirtualFile[] editors = fem.getOpenFiles();
if (count == 99) {
count = editors.length - 1;
}
if (count < 0 || count >= editors.length) {
return false;
}
fem.openFile(editors[count], true);
return true;
}
/**
* Selects then next or previous editor.
*/
public void selectNextFile(int count, @NotNull DataContext context) {
Project project = PlatformDataKeys.PROJECT.getData(context);
if (project == null) return;
FileEditorManager fem = FileEditorManager.getInstance(project); // API change - don't merge
VirtualFile[] editors = fem.getOpenFiles();
VirtualFile current = fem.getSelectedFiles()[0];
for (int i = 0; i < editors.length; i++) {
if (editors[i].equals(current)) {
int pos = (i + (count % editors.length) + editors.length) % editors.length;
fem.openFile(editors[pos], true);
}
}
}
/**
* Selects previous editor tab.
*/
public void selectPreviousTab(@NotNull DataContext context) {
Project project = PlatformDataKeys.PROJECT.getData(context);
if (project == null) return;
FileEditorManager fem = FileEditorManager.getInstance(project); // API change - don't merge
VirtualFile vf = lastSelections.get(fem);
if (vf != null) {
fem.openFile(vf, true);
}
else {
VimPlugin.indicateError();
}
}
@Nullable
Editor selectEditor(Project project, @NotNull VirtualFile file) {
FileEditorManager fMgr = FileEditorManager.getInstance(project);
FileEditor[] feditors = fMgr.openFile(file, true);
if (feditors.length > 0) {
if (feditors[0] instanceof TextEditor) {
Editor editor = ((TextEditor) feditors[0]).getEditor();
if (!editor.isDisposed()) {
return editor;
}
}
}
return null;
}
public void displayAsciiInfo(@NotNull Editor editor) {
int offset = editor.getCaretModel().getOffset();
char ch = editor.getDocument().getCharsSequence().charAt(offset);
VimPlugin.showMessage("<" +
StringHelper.toKeyNotation(KeyStroke.getKeyStroke(ch)) +
"> " +
(int)ch +
", Hex " +
Long.toHexString(ch) +
", Octal " +
Long.toOctalString(ch));
}
public void displayHexInfo(@NotNull Editor editor) {
int offset = editor.getCaretModel().getOffset();
char ch = editor.getDocument().getCharsSequence().charAt(offset);
VimPlugin.showMessage(Long.toHexString(ch));
}
public void displayLocationInfo(@NotNull Editor editor) {
StringBuilder msg = new StringBuilder();
Document doc = editor.getDocument();
if (CommandState.getInstance(editor).getMode() != CommandState.Mode.VISUAL) {
LogicalPosition lp = editor.getCaretModel().getLogicalPosition();
int col = editor.getCaretModel().getOffset() - doc.getLineStartOffset(lp.line);
int endoff = doc.getLineEndOffset(lp.line);
if (doc.getCharsSequence().charAt(endoff) == '\n') {
endoff
}
int ecol = endoff - doc.getLineStartOffset(lp.line);
LogicalPosition elp = editor.offsetToLogicalPosition(endoff);
msg.append("Col ").append(col + 1);
if (col != lp.column) {
msg.append("-").append(lp.column + 1);
}
msg.append(" of ").append(ecol + 1);
if (ecol != elp.column) {
msg.append("-").append(elp.column + 1);
}
int lline = editor.getCaretModel().getLogicalPosition().line;
int total = EditorHelper.getLineCount(editor);
msg.append("; Line ").append(lline + 1).append(" of ").append(total);
SearchHelper.CountPosition cp = SearchHelper.countWords(editor);
msg.append("; Word ").append(cp.getPosition()).append(" of ").append(cp.getCount());
int offset = editor.getCaretModel().getOffset();
int size = EditorHelper.getFileSize(editor);
msg.append("; Character ").append(offset + 1).append(" of ").append(size);
}
else {
msg.append("Selected ");
TextRange vr = new TextRange(editor.getSelectionModel().getBlockSelectionStarts(), editor.getSelectionModel().getBlockSelectionEnds());
vr.normalize();
int lines;
SearchHelper.CountPosition cp = SearchHelper.countWords(editor);
int words = cp.getCount();
int word = 0;
if (vr.isMultiple()) {
lines = vr.size();
int cols = vr.getMaxLength();
msg.append(cols).append(" Cols; ");
for (int i = 0; i < vr.size(); i++) {
cp = SearchHelper.countWords(editor, vr.getStartOffsets()[i], vr.getEndOffsets()[i] - 1);
word += cp.getCount();
}
}
else {
LogicalPosition slp = editor.offsetToLogicalPosition(vr.getStartOffset());
LogicalPosition elp = editor.offsetToLogicalPosition(vr.getEndOffset());
lines = elp.line - slp.line + 1;
cp = SearchHelper.countWords(editor, vr.getStartOffset(), vr.getEndOffset() - 1);
word = cp.getCount();
}
int total = EditorHelper.getLineCount(editor);
msg.append(lines).append(" of ").append(total).append(" Lines");
msg.append("; ").append(word).append(" of ").append(words).append(" Words");
int chars = vr.getSelectionCount();
int size = EditorHelper.getFileSize(editor);
msg.append("; ").append(chars).append(" of ").append(size).append(" Characters");
}
VimPlugin.showMessage(msg.toString());
}
public void displayFileInfo(@NotNull Editor editor, boolean fullPath) {
StringBuilder msg = new StringBuilder();
VirtualFile vf = EditorHelper.getVirtualFile(editor);
if (vf != null) {
msg.append('"');
if (fullPath) {
msg.append(vf.getPath());
}
else {
Project project = editor.getProject();
if (project != null) {
VirtualFile root = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(vf);
if (root != null) {
msg.append(vf.getPath().substring(root.getPath().length() + 1));
}
else {
msg.append(vf.getPath());
}
}
}
msg.append("\" ");
}
else {
msg.append("\"[No File]\" ");
}
Document doc = editor.getDocument();
if (!doc.isWritable()) {
msg.append("[RO] ");
}
else if (FileDocumentManager.getInstance().isDocumentUnsaved(doc)) {
msg.append("[+] ");
}
int lline = editor.getCaretModel().getLogicalPosition().line;
int total = EditorHelper.getLineCount(editor);
int pct = (int)((float)lline / (float)total * 100f + 0.5);
msg.append("line ").append(lline + 1).append(" of ").append(total);
msg.append(" --").append(pct).append("%-- ");
LogicalPosition lp = editor.getCaretModel().getLogicalPosition();
int col = editor.getCaretModel().getOffset() - doc.getLineStartOffset(lline);
msg.append("col ").append(col + 1);
if (col != lp.column) {
msg.append("-").append(lp.column + 1);
}
VimPlugin.showMessage(msg.toString());
}
@NotNull private static final String disposableKey = "VimFileGroupDisposable";
@NotNull private static final HashMap<FileEditorManager, VirtualFile> lastSelections = new HashMap<>();
@NotNull private static final Logger logger = Logger.getInstance(FileGroup.class.getName());
/**
* This method listens for editor tab changes so any insert/replace modes that need to be reset can be.
*/
public static void fileEditorManagerSelectionChangedCallback(@NotNull FileEditorManagerEvent event) {
// The user has changed the editor they are working with - exit insert/replace mode, and complete any
// appropriate repeat
if (event.getOldFile() != null) {
lastSelections.put(event.getManager(), event.getOldFile());
String disposableKey = FileGroup.disposableKey + event.getManager().hashCode();
if (Disposer.get(disposableKey) == null) {
Disposer.register(event.getManager().getProject(), () -> {
lastSelections.remove(event.getManager());
}, disposableKey);
}
}
}
}
|
public class CSV2HTML
{
private String csvData;
public CSV2HTML()
{
System.out.println("CSV2HTML instantiated!!!");
csvData = "This is an empty CSV2HTML object";
}
public CSV2HTML(String csvData)
{
this.csvData = csvData;
}
public String toString()
{
return csvData;
}
}
|
package com.swabunga.spell.engine;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* This class is based on Levenshtein Distance algorithms, and it calculates how similar two words are.
* If the words are identitical, then the distance is 0. The more that the words have in common, the lower the distance value.
* The distance value is based on how many operations it takes to get from one word to the other. Possible operations are
* swapping characters, adding a character, deleting a character, and substituting a character.
* The resulting distance is the sum of these operations weighted by their cost, which can be set in the Configuration object.
* When there are multiple ways to convert one word into the other, the lowest cost distance is returned.
* <br/>
* Another way to think about this: what are the cheapest operations that would have to be done on the "original" word to end up
* with the "similar" word? Each operation has a cost, and these are added up to get the distance.
* <br/>
*
* @see com.swabunga.spell.engine.Configuration#COST_REMOVE_CHAR
* @see com.swabunga.spell.engine.Configuration#COST_INSERT_CHAR
* @see com.swabunga.spell.engine.Configuration#COST_SUBST_CHARS
* @see com.swabunga.spell.engine.Configuration#COST_SWAP_CHARS
*
*/
public class EditDistance {
/**
* JMH Again, there is no need to have a global class matrix variable
* in this class. I have removed it and made the getDistance static final
*
* DMV: I refactored this method to make it more efficient, more readable, and simpler.
* I also fixed a bug with how the distance was being calculated. You could get wrong
* distances if you compared ("abc" to "ab") depending on what you had setup your
* COST_REMOVE_CHAR and EDIT_INSERTION_COST values to - that is now fixed.
*
* WRS: I added a distance for case comparison, so a misspelling of "i" would be closer to "I" than
* to "a".
*/
public static Configuration config = Configuration.getConfiguration();
public static final int getDistance(String word, String similar) {
//get the weights for each possible operation
final int costOfDeletingSourceCharacter = config.getInteger(Configuration.COST_REMOVE_CHAR);
final int costOfInsertingSourceCharacter = config.getInteger(Configuration.COST_INSERT_CHAR);
final int costOfSubstitutingLetters = config.getInteger(Configuration.COST_SUBST_CHARS);
final int costOfSwappingLetters = config.getInteger(Configuration.COST_SWAP_CHARS);
final int costOfChangingCase = config.getInteger(Configuration.COST_CHANGE_CASE);
int a_size = word.length() + 1;
int b_size = similar.length() + 1;
int[][] matrix = new int[a_size][b_size];
matrix[0][0] = 0;
for (int i = 1; i != a_size; ++i)
matrix[i][0] = matrix[i - 1][0] + costOfInsertingSourceCharacter; //initialize the first column
for (int j = 1; j != b_size; ++j)
matrix[0][j] = matrix[0][j - 1] + costOfDeletingSourceCharacter; //initalize the first row
word = " " + word;
similar = " " + similar;
for (int i = 1; i != a_size; ++i) {
char sourceChar = word.charAt(i);
for (int j = 1; j != b_size; ++j) {
char otherChar = similar.charAt(j);
if (sourceChar == otherChar) {
matrix[i][j] = matrix[i - 1][j - 1]; //no change required, so just carry the current cost up
continue;
}
int costOfSubst = costOfSubstitutingLetters + matrix[i - 1][j - 1];
//if needed, add up the cost of doing a swap
int costOfSwap = Integer.MAX_VALUE;
boolean isSwap = (i != 1) && (j != 1) && sourceChar == similar.charAt(j - 1) && word.charAt(i - 1) == otherChar;
if (isSwap)
costOfSwap = costOfSwappingLetters + matrix[i - 2][j - 2];
int costOfDelete = costOfDeletingSourceCharacter + matrix[i][j - 1];
int costOfInsertion = costOfInsertingSourceCharacter + matrix[i - 1][j];
int costOfCaseChange = Integer.MAX_VALUE;
String strSrcChar = "" + sourceChar;
String strOtherChar = "" + otherChar;
if (strSrcChar.compareToIgnoreCase(strOtherChar) == 0)
costOfCaseChange = costOfChangingCase + matrix[i - 1][j - 1];
matrix[i][j] = minimum(costOfSubst, costOfSwap, costOfDelete, costOfInsertion, costOfCaseChange);
}
}
int cost = matrix[a_size - 1][b_size - 1];
if (false)
System.out.println(dumpMatrix(word, similar, matrix));
return cost;
}
/**
* For debugging, this creates a string that represents the matrix. To read the matrix, look at any square. That is the cost to get from
* the partial letters along the top to the partial letters along the side.
* @param src - the source string that the matrix columns are based on
* @param dest - the dest string that the matrix rows are based on
* @param matrix - a two dimensional array of costs (distances)
* @return String
*/
static private String dumpMatrix(String src, String dest, int matrix[][]) {
StringBuffer s = new StringBuffer("");
int cols = matrix.length;
int rows = matrix[0].length;
for (int i = 0; i < cols + 1; i++) {
for (int j = 0; j < rows + 1; j++) {
if (i == 0 && j == 0) {
s.append("\n ");
continue;
}
if (i == 0) {
s.append("| ");
s.append(dest.charAt(j - 1));
continue;
}
if (j == 0) {
s.append(src.charAt(i - 1));
continue;
}
String num = Integer.toString(matrix[i - 1][j - 1]);
int padding = 4 - num.length();
s.append("|");
for (int k = 0; k < padding; k++)
s.append(' ');
s.append(num);
}
s.append('\n');
}
return s.toString();
}
static private int minimum(int a, int b, int c, int d, int e) {
int mi = a;
if (b < mi)
mi = b;
if (c < mi)
mi = c;
if (d < mi)
mi = d;
if (e < mi)
mi = e;
return mi;
}
public static void main(String[] args) throws Exception {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String input1 = stdin.readLine();
if (input1 == null || input1.length() == 0)
break;
String input2 = stdin.readLine();
if (input2 == null || input2.length() == 0)
break;
System.out.println(EditDistance.getDistance(input1, input2));
}
System.out.println("done");
}
}
|
package com.wrapp.android.webimage;
import android.graphics.drawable.Drawable;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class ImageLoader {
private static final int NUM_WORKERS = 1;
private static ImageLoader staticInstance;
private final Queue<ImageRequest> pendingRequests = new LinkedList<ImageRequest>();
private final Worker[] workerPool = new Worker[NUM_WORKERS];
// TODO: This will be necessary with multiple worker threads
// private final ImageRequest[] runningRequests = new ImageRequest[NUM_WORKERS];
private static class Worker extends Thread {
private int index;
public Worker(int index) {
this.index = index;
}
@Override
public void run() {
final Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
ImageRequest request;
while(true) {
synchronized(requestQueue) {
while(requestQueue.isEmpty()) {
try {
requestQueue.wait();
}
catch(InterruptedException e) {
// Log, but otherwise ignore. Not a big deal.
LogWrapper.logException(e);
}
}
request = requestQueue.poll();
Iterator requestIterator = requestQueue.iterator();
while(requestIterator.hasNext()) {
ImageRequest checkRequest = (ImageRequest)requestIterator.next();
if(request.listener.equals(checkRequest.listener)) {
if(request.imageUrl.equals(checkRequest.imageUrl)) {
// Ignore duplicate requests. This is common when doing view recycling in list adapters.
requestIterator.remove();
}
else {
// If this request in the queue was made by the same listener but is for a new URL,
// then use that request instead and remove it from the queue.
request = checkRequest;
requestIterator.remove();
}
}
}
}
processRequest(request);
}
}
private void processRequest(ImageRequest request) {
Drawable drawable = ImageCache.loadImage(request);
request.listener.onDrawableLoaded(drawable);
// TODO: Handle running requests queue
/*
final ImageRequest[] runningRequests = getInstance().runningRequests;
synchronized(runningRequests) {
runningRequests[index] = request;
drawable = ImageCache.loadImage(request);
}
synchronized(runningRequests) {
if(request != null) {
request.listener.onDrawableLoaded(drawable);
runningRequests[index] = null;
}
else {
LogWrapper.logMessage("Interrupted, returning");
}
}
*/
}
}
private static ImageLoader getInstance() {
if(staticInstance == null) {
staticInstance = new ImageLoader();
}
return staticInstance;
}
private ImageLoader() {
for(int i = 0; i < NUM_WORKERS; i++) {
workerPool[i] = new Worker(i);
workerPool[i].start();
}
}
public static void load(URL imageUrl, ImageRequest.Listener listener, boolean cacheInMemory) {
// TODO: This might be too much work in the GUI thread. Move to a worker?
Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
/*
synchronized(requestQueue) {
Iterator requestIterator = requestQueue.iterator();
while(requestIterator.hasNext()) {
ImageRequest request = (ImageRequest)requestIterator.next();
if(request.listener.equals(listener)) {
if(request.imageUrl.equals(imageUrl)) {
// Ignore duplicate requests. This is common when doing view recycling in list adapters
return;
}
else {
// If the listener is the same but the request is for a new URL, remove the previous
// request from the pending queue
requestIterator.remove();
}
}
}
*/
/*
final ImageRequest[] runningRequests = getInstance().runningRequests;
synchronized(runningRequests) {
for(int i = 0; i < runningRequests.length; i++) {
ImageRequest request = runningRequests[i];
if(request != null) {
if(request.listener.equals(listener)) {
if(request.imageUrl.equals(imageUrl)) {
// Ignore duplicate requests. This is common when doing view recycling in list adapters
return;
}
else {
// Null out the running request in this index. The job will continue running, but when
// it returns it will skip notifying the listener and start processing the next job in
// the pending request queue.
runningRequests[i] = null;
}
}
}
}
}
}
*/
synchronized(requestQueue) {
requestQueue.add(new ImageRequest(imageUrl, listener, cacheInMemory));
// TODO: Use notifyAll() instead?
requestQueue.notify();
}
}
public static void enableLogging(String tag, int level) {
LogWrapper.tag = tag;
LogWrapper.level = level;
}
}
|
package nallar.patched.world;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.ImmutableSetMultimap;
import nallar.collections.SynchronizedSet;
import nallar.tickthreading.Log;
import nallar.tickthreading.minecraft.TickThreading;
import nallar.tickthreading.minecraft.entitylist.EntityList;
import nallar.tickthreading.minecraft.entitylist.LoadedTileEntityList;
import nallar.tickthreading.patcher.Declare;
import net.minecraft.block.Block;
import net.minecraft.command.IEntitySelector;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.profiler.Profiler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ReportedException;
import net.minecraft.util.Vec3;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import org.cliffc.high_scale_lib.NonBlockingHashMapLong;
@SuppressWarnings ("unchecked")
public abstract class PatchWorld extends World {
private static final double COLLISION_RANGE = 2D;
private int forcedUpdateCount;
@Declare
public ThreadLocal<Boolean> inPlaceEvent_;
@Declare
public org.cliffc.high_scale_lib.NonBlockingHashMapLong<Integer> redstoneBurnoutMap_;
@Declare
public nallar.collections.SynchronizedSet<Entity> unloadedEntitySet_;
@Declare
public nallar.collections.SynchronizedSet<TileEntity> tileEntityRemovalSet_;
@Declare
public com.google.common.collect.ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> forcedChunks_;
@Declare
public int tickCount_;
private boolean warnedWrongList;
@Declare
public int dimensionId_;
private String cachedName;
@Declare
public boolean multiverseWorld_;
@Declare
public int originalDimension_;
@Declare
public boolean unloaded_;
@Declare
public Chunk emptyChunk_;
@Declare
public boolean loadEventFired_;
@Declare
public boolean forcedChunksInited_;
public Object auraLock;
public void construct() {
auraLock = new Object();
tickCount = rand.nextInt(240); // So when different worlds do every N tick actions,
// they won't all happen at the same time even if the worlds loaded at the same time
tileEntityRemovalSet = new SynchronizedSet<TileEntity>();
unloadedEntitySet = new SynchronizedSet<Entity>();
redstoneBurnoutMap = new NonBlockingHashMapLong<Integer>();
if (dimensionId == 0) {
dimensionId = provider.dimensionId;
}
}
public PatchWorld(ISaveHandler par1ISaveHandler, String par2Str, WorldProvider par3WorldProvider, WorldSettings par4WorldSettings, Profiler par5Profiler) {
super(par1ISaveHandler, par2Str, par3WorldProvider, par4WorldSettings, par5Profiler);
}
@Override
@Declare
public boolean onClient() {
return isRemote;
}
@Override
@Declare
public void setDimension(int dimensionId) {
WorldProvider provider = this.provider;
this.dimensionId = dimensionId;
if (provider.dimensionId != dimensionId) {
try {
DimensionManager.registerDimension(dimensionId, provider.dimensionId);
} catch (Throwable t) {
Log.warning("Failed to register corrected dimension ID with DimensionManager", t);
}
originalDimension = provider.dimensionId;
multiverseWorld = true;
provider.dimensionId = dimensionId;
}
cachedName = null;
Log.fine("Set dimension ID for " + this.getName());
if (TickThreading.instance.getManager(this) != null) {
Log.severe("Set corrected dimension too late!");
}
}
@Override
@Declare
public int getDimension() {
return dimensionId;
}
@Override
@Declare
public String getName() {
String name = cachedName;
if (name != null) {
return name;
}
int dimensionId = getDimension();
name = worldInfo.getWorldName();
if (name.equals("DIM" + dimensionId) || "world".equals(name)) {
name = provider.getDimensionName();
}
if (name.startsWith("world_") && name.length() != 6) {
name = name.substring(6);
}
cachedName = name = (name + '/' + dimensionId + (isRemote ? "-r" : ""));
return name;
}
@Override
public boolean isBlockNormalCube(int x, int y, int z) {
int id = getBlockId(x, y, z);
Block block = Block.blocksList[id];
return block != null && block.isBlockNormalCube(this, x, y, z);
}
@Override
public void removeEntity(Entity entity) {
if (entity == null) {
return;
}
try {
if (entity.riddenByEntity != null) {
entity.riddenByEntity.mountEntity(null);
}
if (entity.ridingEntity != null) {
entity.mountEntity(null);
}
entity.setDead();
if (entity instanceof EntityPlayer) {
if (playerEntities == null) {
// The world has been unloaded and cleaned already, so we can't remove the player entity.
return;
}
this.playerEntities.remove(entity);
this.updateAllPlayersSleepingFlag();
}
} catch (Exception e) {
Log.severe("Exception removing an entity", e);
}
}
@Override
public int getBlockId(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y >= 0 && y < 256) {
try {
return getChunkFromChunkCoords(x >> 4, z >> 4).getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.pos(this, x, y, z), t);
}
}
return 0;
}
@Override
@Declare
public int getBlockIdWithoutLoad(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y >= 0 && y < 256) {
try {
Chunk chunk = getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? -1 : chunk.getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.pos(this, x, y, z), t);
}
}
return 0;
}
@Override
public Chunk getChunkFromChunkCoords(int x, int z) {
return chunkProvider.provideChunk(x, z);
}
@Override
@Declare
public Chunk getChunkFromChunkCoordsWithLoad(int x, int z) {
return chunkProvider.loadChunk(x, z);
}
@Override
@Declare
public int getBlockIdWithLoad(int x, int y, int z) {
if (y >= 256) {
return 0;
} else {
return chunkProvider.loadChunk(x >> 4, z >> 4).getBlockID(x & 15, y, z & 15);
}
}
@Override
public EntityPlayer getClosestPlayer(double x, double y, double z, double maxRange) {
double closestRange = Double.MAX_VALUE;
EntityPlayer target = null;
for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) {
double distanceSq = playerEntity.getDistanceSq(x, y, z);
if ((maxRange < 0.0D || distanceSq < (maxRange * maxRange)) && (distanceSq < closestRange)) {
closestRange = distanceSq;
target = playerEntity;
}
}
return target;
}
@SuppressWarnings ("ConstantConditions")
@Override
public EntityPlayer getClosestVulnerablePlayer(double x, double y, double z, double maxRange) {
double closestRange = Double.MAX_VALUE;
EntityPlayer target = null;
for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) {
if (!playerEntity.capabilities.disableDamage && playerEntity.isEntityAlive()) {
double distanceSq = playerEntity.getDistanceSq(x, y, z);
double effectiveMaxRange = maxRange;
if (playerEntity.isSneaking()) {
effectiveMaxRange = maxRange * 0.800000011920929D;
}
if (playerEntity.getHasActivePotion()) {
float var18 = playerEntity.func_82243_bO();
if (var18 < 0.1F) {
var18 = 0.1F;
}
effectiveMaxRange *= (double) (0.7F * var18);
}
if ((maxRange < 0.0D || distanceSq < (effectiveMaxRange * effectiveMaxRange)) && (distanceSq < closestRange)) {
closestRange = distanceSq;
target = playerEntity;
}
}
}
return target;
}
@Override
public EntityPlayer getPlayerEntityByName(String name) {
for (EntityPlayer player : (Iterable<EntityPlayer>) playerEntities) {
if (name.equals(player.username)) {
return player;
}
}
return null;
}
@Override
protected void notifyBlockOfNeighborChange(int x, int y, int z, int par4) {
if (!this.editingBlocks && !this.isRemote) {
int var5 = this.getBlockIdWithoutLoad(x, y, z);
Block var6 = var5 < 1 ? null : Block.blocksList[var5];
if (var6 != null) {
try {
var6.onNeighborBlockChange(this, x, y, z, par4);
} catch (Throwable t) {
Log.severe("Exception while updating block neighbours " + Log.pos(this, x, y, z), t);
}
}
}
}
@Override
public ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> getPersistentChunks() {
ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> forcedChunks = this.forcedChunks;
return forcedChunks == null ? ImmutableSetMultimap.<ChunkCoordIntPair, ForgeChunkManager.Ticket>of() : forcedChunks;
}
@Override
public TileEntity getBlockTileEntity(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
@Declare
public TileEntity getTEWithoutLoad(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = ((ChunkProviderServer) this.chunkProvider).getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
@Declare
public TileEntity getTEWithLoad(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
return chunkProvider.loadChunk(x >> 4, z >> 4).getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
public void updateEntityWithOptionalForce(Entity entity, boolean notForced) {
Chunk chunk = entity.chunk;
if (notForced && chunk != null) {
if (chunk.partiallyUnloaded) {
chunk.removeEntity(entity);
entity.addedToChunk = false;
return;
} else if (chunk.queuedUnload) {
return;
}
}
int x = MathHelper.floor_double(entity.posX);
int z = MathHelper.floor_double(entity.posZ);
boolean periodicUpdate = forcedUpdateCount++ % 19 == 0;
Boolean isForced_ = entity.isForced;
if (isForced_ == null || periodicUpdate) {
entity.isForced = isForced_ = getPersistentChunks().containsKey(new ChunkCoordIntPair(x >> 4, z >> 4));
}
boolean isForced = isForced_;
Boolean canUpdate_ = entity.canUpdate;
if (canUpdate_ == null || periodicUpdate) {
byte range = isForced ? (byte) 0 : 48;
entity.canUpdate = canUpdate_ = !notForced || this.checkChunksExist(x - range, 0, z - range, x + range, 0, z + range);
} else if (canUpdate_) {
entity.canUpdate = canUpdate_ = !notForced || chunk != null || chunkExists(x >> 4, z >> 4);
}
boolean canUpdate = canUpdate_;
if (canUpdate) {
entity.lastTickPosX = entity.posX;
entity.lastTickPosY = entity.posY;
entity.lastTickPosZ = entity.posZ;
entity.prevRotationYaw = entity.rotationYaw;
entity.prevRotationPitch = entity.rotationPitch;
if (notForced && entity.addedToChunk) {
if (entity.ridingEntity != null) {
entity.updateRidden();
} else {
++entity.ticksExisted;
entity.onUpdate();
}
}
this.theProfiler.startSection("chunkCheck");
if (Double.isNaN(entity.posX) || Double.isInfinite(entity.posX)) {
entity.posX = entity.lastTickPosX;
}
if (Double.isNaN(entity.posY) || Double.isInfinite(entity.posY)) {
entity.posY = entity.lastTickPosY;
}
if (Double.isNaN(entity.posZ) || Double.isInfinite(entity.posZ)) {
entity.posZ = entity.lastTickPosZ;
}
if (Double.isNaN((double) entity.rotationPitch) || Double.isInfinite((double) entity.rotationPitch)) {
entity.rotationPitch = entity.prevRotationPitch;
}
if (Double.isNaN((double) entity.rotationYaw) || Double.isInfinite((double) entity.rotationYaw)) {
entity.rotationYaw = entity.prevRotationYaw;
}
int cX = MathHelper.floor_double(entity.posX / 16.0D);
int cY = MathHelper.floor_double(entity.posY / 16.0D);
int cZ = MathHelper.floor_double(entity.posZ / 16.0D);
if (!entity.addedToChunk || entity.chunkCoordX != cX || entity.chunkCoordY != cY || entity.chunkCoordZ != cZ) {
synchronized (entity) {
if (entity.addedToChunk) {
if (chunk == null) {
chunk = getChunkIfExists(entity.chunkCoordX, entity.chunkCoordZ);
}
if (chunk != null) {
chunk.removeEntityAtIndex(entity, entity.chunkCoordY);
}
}
chunk = getChunkIfExists(cX, cZ);
if (chunk != null) {
entity.addedToChunk = true;
chunk.addEntity(entity);
} else {
entity.addedToChunk = false;
}
entity.chunk = chunk;
}
}
this.theProfiler.endSection();
if (notForced && entity.addedToChunk && entity.riddenByEntity != null) {
if (!entity.riddenByEntity.isDead && entity.riddenByEntity.ridingEntity == entity) {
this.updateEntity(entity.riddenByEntity);
} else {
entity.riddenByEntity.ridingEntity = null;
entity.riddenByEntity = null;
}
}
}
}
@Override
public void addLoadedEntities(List par1List) {
EntityTracker entityTracker = null;
//noinspection RedundantCast
if (((Object) this instanceof WorldServer)) {
entityTracker = ((WorldServer) (Object) this).getEntityTracker();
}
for (int var2 = 0; var2 < par1List.size(); ++var2) {
Entity entity = (Entity) par1List.get(var2);
if (entity == null) {
Log.warning("Null entity in chunk during world load", new Throwable());
par1List.remove(var2
} else if (MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(entity, this))) {
par1List.remove(var2
} else if (entityTracker == null || !entityTracker.isTracking(entity.entityId)) {
loadedEntityList.add(entity);
this.obtainEntitySkin(entity);
}
}
}
@Override
@Declare
public boolean hasCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
ArrayList collidingBoundingBoxes = new ArrayList();
int minX = MathHelper.floor_double(par2AxisAlignedBB.minX);
int maxX = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D);
int minY = MathHelper.floor_double(par2AxisAlignedBB.minY);
int maxY = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D);
int minZ = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int maxZ = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D);
int ystart = ((minY - 1) < 0) ? 0 : (minY - 1);
for (int chunkx = (minX >> 4); chunkx <= ((maxX - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (minZ >> 4); chunkz <= ((maxZ - 1) >> 4); chunkz++) {
Chunk chunk = this.getChunkIfExists(chunkx, chunkz);
if (chunk == null) {
continue;
}
// Compute ranges within chunk
int cz = chunkz << 4;
int xstart = (minX < cx) ? cx : minX;
int xend = (maxX < (cx + 16)) ? maxX : (cx + 16);
int zstart = (minZ < cz) ? cz : minZ;
int zend = (maxZ < (cz + 16)) ? maxZ : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < maxY; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
if (!collidingBoundingBoxes.isEmpty()) {
return true;
}
}
}
}
}
}
}
double var14 = 0.25D;
List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), 100);
for (Entity aVar16 : var16) {
AxisAlignedBB var13 = aVar16.getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
var13 = par1Entity.getCollisionBox(aVar16);
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
}
return false;
}
@Override
@Declare
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
ArrayList collidingBoundingBoxes = new ArrayList();
int minX = MathHelper.floor_double(par2AxisAlignedBB.minX);
int maxX = MathHelper.floor_double(par2AxisAlignedBB.maxX) + 1;
int minY = MathHelper.floor_double(par2AxisAlignedBB.minY);
int maxY = MathHelper.floor_double(par2AxisAlignedBB.maxY) + 1;
int minZ = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int maxZ = MathHelper.floor_double(par2AxisAlignedBB.maxZ) + 1;
if (minX >= maxX || minY >= maxY || minZ >= maxZ) {
return collidingBoundingBoxes;
}
int ystart = ((minY - 1) < 0) ? 0 : (minY - 1);
for (int chunkx = (minX >> 4); chunkx <= ((maxX - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (minZ >> 4); chunkz <= ((maxZ - 1) >> 4); chunkz++) {
Chunk chunk = this.getChunkIfExists(chunkx, chunkz);
if (chunk == null) {
continue;
}
// Compute ranges within chunk
int cz = chunkz << 4;
// Compute ranges within chunk
int xstart = (minX < cx) ? cx : minX;
int xend = (maxX < (cx + 16)) ? maxX : (cx + 16);
int zstart = (minZ < cz) ? cz : minZ;
int zend = (maxZ < (cz + 16)) ? maxZ : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < maxY; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
}
}
}
}
if (collidingBoundingBoxes.size() >= limit) {
return collidingBoundingBoxes;
}
}
}
double var14 = 0.25D;
List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), limit);
for (Entity aVar16 : var16) {
AxisAlignedBB var13 = aVar16.getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
var13 = par1Entity.getCollisionBox(aVar16);
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
}
return collidingBoundingBoxes;
}
@Override
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
return getCollidingBoundingBoxes(par1Entity, par2AxisAlignedBB, 2000);
}
@Override
public void addTileEntity(Collection tileEntities) {
List dest = scanningTileEntities ? addedTileEntityList : loadedTileEntityList;
for (TileEntity tileEntity : (Iterable<TileEntity>) tileEntities) {
try {
tileEntity.validate();
} catch (Throwable t) {
Log.severe("Tile Entity " + tileEntity + " failed to validate, it will be ignored.", t);
}
if (tileEntity.canUpdate()) {
dest.add(tileEntity);
}
}
}
@Override
@Declare
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
ArrayList entitiesWithinAABBExcludingEntity = new ArrayList();
int minX = MathHelper.floor_double((par2AxisAlignedBB.minX - COLLISION_RANGE) / 16.0D);
int maxX = MathHelper.floor_double((par2AxisAlignedBB.maxX + COLLISION_RANGE) / 16.0D);
int minZ = MathHelper.floor_double((par2AxisAlignedBB.minZ - COLLISION_RANGE) / 16.0D);
int maxZ = MathHelper.floor_double((par2AxisAlignedBB.maxZ + COLLISION_RANGE) / 16.0D);
for (int x = minX; x <= maxX; ++x) {
for (int z = minZ; z <= maxZ; ++z) {
Chunk chunk = getChunkIfExists(x, z);
if (chunk != null) {
limit = chunk.getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity, limit);
}
}
}
return entitiesWithinAABBExcludingEntity;
}
@Override
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
return getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB, 1000);
}
@Override
public int countEntities(Class entityType) {
if (loadedEntityList instanceof EntityList) {
return ((EntityList) this.loadedEntityList).manager.getEntityCount(entityType);
}
int count = 0;
for (Entity e : (Iterable<Entity>) this.loadedEntityList) {
if (entityType.isAssignableFrom(e.getClass())) {
++count;
}
}
return count;
}
@Override
public boolean checkChunksExist(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
return minY <= 255 && maxY >= 0 && ((ChunkProviderServer) chunkProvider).chunksExist(minX >> 4, minZ >> 4, maxX >> 4, maxZ >> 4);
}
@Override
public void unloadEntities(List entitiesToUnload) {
for (Entity entity : (Iterable<Entity>) entitiesToUnload) {
if (entity == null) {
Log.warning("Tried to unload null entity", new Throwable());
}
if (!(entity instanceof EntityPlayerMP)) {
unloadedEntitySet.add(entity);
}
}
}
@Override
public void updateEntities() {
final Profiler theProfiler = this.theProfiler;
theProfiler.startSection("updateEntities");
int var1;
Entity var2;
CrashReport var4;
CrashReportCategory var5;
theProfiler.startSection("global");
final List weatherEffects = this.weatherEffects;
for (var1 = 0; var1 < weatherEffects.size(); ++var1) {
var2 = (Entity) weatherEffects.get(var1);
try {
++var2.ticksExisted;
var2.onUpdate();
} catch (Throwable var6) {
var4 = CrashReport.makeCrashReport(var6, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
if (var2 != null) {
var2.func_85029_a(var5);
}
throw new ReportedException(var4);
}
if (var2 == null || var2.isDead) {
weatherEffects.remove(var1
}
}
theProfiler.endStartSection("remove");
int var3;
int var13;
final List loadedEntityList = this.loadedEntityList;
boolean tickTT = loadedEntityList instanceof EntityList;
if (tickTT) {
((EntityList) loadedEntityList).manager.batchRemoveEntities(unloadedEntitySet);
((EntityList) loadedEntityList).manager.doTick();
} else {
loadedEntityList.removeAll(unloadedEntitySet);
for (Entity entity : unloadedEntitySet) {
var3 = entity.chunkCoordX;
var13 = entity.chunkCoordZ;
if (entity.addedToChunk) {
Chunk chunk = getChunkIfExists(var3, var13);
if (chunk != null) {
chunk.removeEntity(entity);
}
}
releaseEntitySkin(entity);
}
unloadedEntitySet.clear();
theProfiler.endStartSection("entities");
for (var1 = 0; var1 < loadedEntityList.size(); ++var1) {
var2 = (Entity) loadedEntityList.get(var1);
if (var2.ridingEntity != null) {
if (!var2.ridingEntity.isDead && var2.ridingEntity.riddenByEntity == var2) {
continue;
}
var2.ridingEntity.riddenByEntity = null;
var2.ridingEntity = null;
}
theProfiler.startSection("tick");
if (!var2.isDead) {
try {
updateEntity(var2);
} catch (Throwable var7) {
var4 = CrashReport.makeCrashReport(var7, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
var2.func_85029_a(var5);
throw new ReportedException(var4);
}
}
theProfiler.endSection();
theProfiler.startSection("remove");
if (var2.isDead) {
var3 = var2.chunkCoordX;
var13 = var2.chunkCoordZ;
if (var2.addedToChunk) {
Chunk chunk = getChunkIfExists(var3, var13);
if (chunk != null) {
chunk.removeEntity(var2);
}
}
loadedEntityList.remove(var1
releaseEntitySkin(var2);
}
theProfiler.endSection();
}
theProfiler.endStartSection("tileEntities");
scanningTileEntities = true;
Iterator var14 = loadedTileEntityList.iterator();
while (var14.hasNext()) {
TileEntity var9 = (TileEntity) var14.next();
if (!var9.isInvalid() && var9.func_70309_m() && blockExists(var9.xCoord, var9.yCoord, var9.zCoord)) {
try {
var9.updateEntity();
} catch (Throwable var8) {
var4 = CrashReport.makeCrashReport(var8, "Ticking tile entity");
var5 = var4.makeCategory("Tile entity being ticked");
var9.func_85027_a(var5);
throw new ReportedException(var4);
}
}
if (var9.isInvalid()) {
var14.remove();
Chunk var11 = getChunkIfExists(var9.xCoord >> 4, var9.zCoord >> 4);
if (var11 != null) {
var11.cleanChunkBlockTileEntity(var9.xCoord & 15, var9.yCoord, var9.zCoord & 15);
}
}
}
}
theProfiler.endStartSection("removingTileEntities");
final List loadedTileEntityList = this.loadedTileEntityList;
if (loadedTileEntityList instanceof LoadedTileEntityList) {
((LoadedTileEntityList) loadedTileEntityList).manager.batchRemoveTileEntities(tileEntityRemovalSet);
} else {
if (!warnedWrongList && loadedTileEntityList.getClass() != ArrayList.class) {
Log.severe("TickThreading's replacement loaded tile entity list has been replaced by one from another mod!\n" +
"Class: " + loadedTileEntityList.getClass() + ", toString(): " + loadedTileEntityList);
warnedWrongList = true;
}
for (TileEntity tile : tileEntityRemovalSet) {
tile.onChunkUnload();
}
loadedTileEntityList.removeAll(tileEntityRemovalSet);
tileEntityRemovalSet.clear();
}
scanningTileEntities = false;
theProfiler.endStartSection("pendingTileEntities");
if (!addedTileEntityList.isEmpty()) {
for (TileEntity te : (Iterable<TileEntity>) addedTileEntityList) {
if (te.isInvalid()) {
Chunk var15 = getChunkIfExists(te.xCoord >> 4, te.zCoord >> 4);
if (var15 != null) {
var15.cleanChunkBlockTileEntity(te.xCoord & 15, te.yCoord, te.zCoord & 15);
}
} else {
if (!loadedTileEntityList.contains(te)) {
loadedTileEntityList.add(te);
}
}
}
addedTileEntityList.clear();
}
theProfiler.endSection();
theProfiler.endSection();
}
@Override
public boolean isBlockProvidingPowerTo(int par1, int par2, int par3, int par4) {
int id = getBlockIdWithoutLoad(par1, par2, par3);
return id > 0 && Block.blocksList[id].isProvidingStrongPower(this, par1, par2, par3, par4);
}
@Override
public boolean isBlockIndirectlyProvidingPowerTo(int x, int y, int z, int direction) {
int id = getBlockIdWithoutLoad(x, y, z);
if (id < 1) {
return false;
}
Block block = Block.blocksList[id];
return block != null && ((block.isBlockNormalCube(this, x, y, z) && isBlockGettingPowered(x, y, z)) || block.isProvidingWeakPower(this, x, y, z, direction));
}
@Override
@Declare
public Chunk getChunkIfExists(int x, int z) {
Chunk chunk = chunkProvider.provideChunk(x, z);
return chunk == emptyChunk ? null : chunk;
}
@Override
@Declare
public Chunk getChunkFromBlockCoordsIfExists(int x, int z) {
return getChunkIfExists(x >> 4, z >> 4);
}
@Override
public void markTileEntityForDespawn(TileEntity tileEntity) {
tileEntityRemovalSet.add(tileEntity);
}
@Override
@Declare
public void setBlockTileEntityWithoutValidate(int x, int y, int z, TileEntity tileEntity) {
if (tileEntity == null || tileEntity.isInvalid()) {
return;
}
if (tileEntity.canUpdate()) {
(scanningTileEntities ? addedTileEntityList : loadedTileEntityList).add(tileEntity);
}
Chunk chunk = getChunkFromChunkCoords(x >> 4, z >> 4);
if (chunk != null) {
chunk.setChunkBlockTileEntityWithoutValidate(x & 15, y, z & 15, tileEntity);
}
}
@Override
@Declare
public boolean setBlockAndMetadataWithUpdateWithoutValidate(int x, int y, int z, int id, int meta, boolean update) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y >= 0 && y < 256) {
Chunk chunk = getChunkFromChunkCoords(x >> 4, z >> 4);
if (!chunk.setBlockIDWithMetadataWithoutValidate(x & 15, y, z & 15, id, meta)) {
return false;
}
theProfiler.startSection("checkLight");
updateAllLightTypes(x, y, z);
theProfiler.endSection();
if (update) {
markBlockForUpdate(x, y, z);
}
return true;
}
return false;
}
@Override
@Declare
public boolean isChunkSavedPopulated(int x, int z) {
return ((AnvilChunkLoader) ((WorldServer) (Object) this).theChunkProviderServer.currentChunkLoader).isChunkSavedPopulated(x, z);
}
@Override
public List selectEntitiesWithinAABB(Class par1Class, AxisAlignedBB par2AxisAlignedBB, IEntitySelector par3IEntitySelector) {
int var4 = MathHelper.floor_double((par2AxisAlignedBB.minX - COLLISION_RANGE) / 16.0D);
int var5 = MathHelper.floor_double((par2AxisAlignedBB.maxX + COLLISION_RANGE) / 16.0D);
int var6 = MathHelper.floor_double((par2AxisAlignedBB.minZ - COLLISION_RANGE) / 16.0D);
int var7 = MathHelper.floor_double((par2AxisAlignedBB.maxZ + COLLISION_RANGE) / 16.0D);
ArrayList entities = new ArrayList();
if (var5 < var4 || var7 < var6) {
return entities;
}
for (int cX = var4; cX <= var5; ++cX) {
for (int cZ = var6; cZ <= var7; ++cZ) {
Chunk chunk = getChunkIfExists(cX, cZ);
if (chunk != null) {
chunk.getEntitiesOfTypeWithinAAAB(par1Class, par2AxisAlignedBB, entities, par3IEntitySelector);
}
}
}
return entities;
}
@Override
@Declare
public List selectEntitiesWithinAABB(Class par1Class, AxisAlignedBB par2AxisAlignedBB, IEntitySelector par3IEntitySelector, double COLLISION_RANGE) {
int var4 = MathHelper.floor_double((par2AxisAlignedBB.minX - COLLISION_RANGE) / 16.0D);
int var5 = MathHelper.floor_double((par2AxisAlignedBB.maxX + COLLISION_RANGE) / 16.0D);
int var6 = MathHelper.floor_double((par2AxisAlignedBB.minZ - COLLISION_RANGE) / 16.0D);
int var7 = MathHelper.floor_double((par2AxisAlignedBB.maxZ + COLLISION_RANGE) / 16.0D);
ArrayList entities = new ArrayList();
if (var5 < var4 || var7 < var6) {
return entities;
}
for (int cX = var4; cX <= var5; ++cX) {
for (int cZ = var6; cZ <= var7; ++cZ) {
Chunk chunk = getChunkIfExists(cX, cZ);
if (chunk != null) {
chunk.getEntitiesOfTypeWithinAAAB(par1Class, par2AxisAlignedBB, entities, par3IEntitySelector);
}
}
}
return entities;
}
private static double center(double a, double b) {
return ((a - b) / 2) + b;
}
private static boolean isBroken(double a) {
return Double.isNaN(a) || Double.isInfinite(a);
}
@Override
public float getBlockDensity(Vec3 start, AxisAlignedBB target) {
if (isBroken(target.minX) || isBroken(target.maxX) ||
isBroken(target.minY) || isBroken(target.maxY) ||
isBroken(target.minZ) || isBroken(target.maxZ) ||
isBroken(start.xCoord) || isBroken(start.yCoord) || isBroken(start.zCoord) ||
target.getAverageEdgeLength() > 10) {
return 0.5f;
}
Vec3 center = getWorldVec3Pool().getVecFromPool(center(target.maxX, target.minX), center(target.maxY, target.minY), center(target.maxZ, target.minZ));
if (start.squareDistanceTo(center) > 1000 || !chunkExists(((int) center.xCoord) >> 4, ((int) center.zCoord) >> 4)) {
return 0.5f;
}
double dX = 1.0D / ((target.maxX - target.minX) * 2.0D + 1.0D);
double dY = 1.0D / ((target.maxY - target.minY) * 2.0D + 1.0D);
double dZ = 1.0D / ((target.maxZ - target.minZ) * 2.0D + 1.0D);
dX = dX > 0.02 ? dX : 0.02;
dY = dY > 0.02 ? dY : 0.02;
dZ = dZ > 0.02 ? dZ : 0.02;
int hit = 0;
int noHit = 0;
for (float var11 = 0.0F; var11 <= 1.0F; var11 = (float) ((double) var11 + dX)) {
for (float var12 = 0.0F; var12 <= 1.0F; var12 = (float) ((double) var12 + dY)) {
for (float var13 = 0.0F; var13 <= 1.0F; var13 = (float) ((double) var13 + dZ)) {
double x = target.minX + (target.maxX - target.minX) * (double) var11;
double y = target.minY + (target.maxY - target.minY) * (double) var12;
double z = target.minZ + (target.maxZ - target.minZ) * (double) var13;
if (rayTraceBlocks(center.setComponents(x, y, z), start) == null) {
++hit;
}
++noHit;
}
}
}
return (float) hit / (float) noHit;
}
@Override
@Declare
public boolean preHandleSpawn(Entity e) {
if (e == null) {
return true;
}
if (e instanceof EntityPlayer) {
return false;
}
if (e.isDead) {
return true;
}
Chunk chunk = getChunkIfExists(((int) e.posX) >> 4, ((int) e.posZ) >> 4);
if (chunk == null) {
e.setDead();
return true;
}
if (e instanceof EntityItem) {
int recentSpawnedItems = TickThreading.recentSpawnedItems++;
if (recentSpawnedItems > 100000) {
e.setDead();
return true;
}
if (!TickThreading.instance.removeIfOverMaxItems((EntityItem) e, chunk) && recentSpawnedItems > 200) {
if (((EntityItem) e).aggressiveCombine()) {
return true;
}
}
} else if (e instanceof EntityXPOrb) {
EntityXPOrb thisXP = (EntityXPOrb) e;
final double mergeRadius = 1d;
for (EntityXPOrb otherXP : (Iterable<EntityXPOrb>) selectEntitiesWithinAABB(EntityXPOrb.class, thisXP.boundingBox.expand(mergeRadius, mergeRadius, mergeRadius), null, 0.3D)) {
if (!otherXP.isDead) {
otherXP.addXPFrom(thisXP);
}
if (thisXP.isDead) {
break;
}
}
}
return e.isDead;
}
@Declare
public Entity getEntity(int id) {
return ((WorldServer) (Object) this).getEntityTracker().getEntity(id);
}
}
|
package de.lmu.ifi.dbs.elki.algorithm.outlier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import de.lmu.ifi.dbs.elki.algorithm.DistanceBasedAlgorithm;
import de.lmu.ifi.dbs.elki.data.RealVector;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.DistanceResultPair;
import de.lmu.ifi.dbs.elki.distance.DoubleDistance;
import de.lmu.ifi.dbs.elki.distance.similarityfunction.kernel.KernelFunction;
import de.lmu.ifi.dbs.elki.distance.similarityfunction.kernel.KernelMatrix;
import de.lmu.ifi.dbs.elki.distance.similarityfunction.kernel.PolynomialKernelFunction;
import de.lmu.ifi.dbs.elki.math.MeanVariance;
import de.lmu.ifi.dbs.elki.result.AnnotationFromHashMap;
import de.lmu.ifi.dbs.elki.result.MultiResult;
import de.lmu.ifi.dbs.elki.result.OrderingFromHashMap;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.utilities.Description;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ClassParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.UnspecifiedParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GlobalParameterConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterEqualConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.ParameterFlagGlobalConstraint;
import de.lmu.ifi.dbs.elki.utilities.pairs.FCPair;
/**
* Angle-Based Outlier Detection
*
* Outlier detection using variance analysis on angles, especially for high
* dimensional data sets.
*
* H.-P. Kriegel, M. Schubert, and A. Zimek: Angle-Based Outlier Detection in
* High-dimensional Data. In: Proc. 14th ACM SIGKDD Int. Conf. on Knowledge
* Discovery and Data Mining (KDD '08), Las Vegas, NV, 2008.
*
* @author Matthias Schubert (Original Code)
* @author Erich Schubert (ELKIfication)
*
* @param <V> Vector type
*/
public class ABOD<V extends RealVector<V, ?>> extends DistanceBasedAlgorithm<V, DoubleDistance, MultiResult> {
/**
* OptionID for {@link #K_PARAM}
*/
public static final OptionID K_ID = OptionID.getOrCreateOptionID("abod.k", "Parameter k for kNN queries.");
/**
* Parameter for k, the number of neighbors used in kNN queries.
*
* Key: {@code -abod.k}
*
* Default value: 30
*/
private final IntParameter K_PARAM = new IntParameter(K_ID, new GreaterEqualConstraint(1), 30);
/**
* k parameter
*/
private int k;
/**
* OptionID for {@link #FAST_FLAG}
*/
public static final OptionID FAST_ID = OptionID.getOrCreateOptionID("abod.fast", "Flag to indicate that the algorithm should run the fast/approximative version.");
/**
* Flag for fast mode.
*
* Key: {@code -abod.fast}
*/
private final Flag FAST_FLAG = new Flag(FAST_ID);
/**
* Variable to store fast mode flag.
*/
boolean fast = false;
/**
* OptionID for {@link #FAST_SAMPLE_PARAM}
*/
public static final OptionID FAST_SAMPLE_ID = OptionID.getOrCreateOptionID("abod.samplesize", "Sample size to use in fast mode.");
/**
* Parameter for sample size to be used in fast mode.
*
* Key: {@code -abod.samplesize}
*/
private final IntParameter FAST_SAMPLE_PARAM = new IntParameter(FAST_SAMPLE_ID, new GreaterEqualConstraint(1), true);
/**
* Variable to store fast mode flag.
*/
int sampleSize;
/**
* OptionID for {@link #KERNEL_FUNCTION_PARAM}
*/
public static final OptionID KERNEL_FUNCTION_ID = OptionID.getOrCreateOptionID("abod.kernelfunction", "Kernel function to use.");
/**
* Parameter for Kernel function.
*
* Key: {@code -abod.kernelfunction}
*
* Default: {@link PolynomialKernelFunction}
*/
// TODO: is a Polynomial Kernel the best default?
private final ClassParameter<KernelFunction<V, DoubleDistance>> KERNEL_FUNCTION_PARAM = new ClassParameter<KernelFunction<V, DoubleDistance>>(KERNEL_FUNCTION_ID, KernelFunction.class, PolynomialKernelFunction.class.getCanonicalName());
/**
* Association ID for ABOD.
*/
public static final AssociationID<Double> ABOD_SCORE = AssociationID.getOrCreateAssociationID("ABOD", Double.class);
/**
* Association ID for ABOD Normalization value.
*/
public static final AssociationID<Double> ABOD_NORM = AssociationID.getOrCreateAssociationID("ABOD normalization", Double.class);
/**
* Store the configured Kernel version
*/
KernelFunction<V, DoubleDistance> kernelFunction;
/**
* Result storage.
*/
MultiResult result = null;
public ABOD() {
addOption(K_PARAM);
addOption(FAST_FLAG);
addOption(FAST_SAMPLE_PARAM);
addOption(KERNEL_FUNCTION_PARAM);
GlobalParameterConstraint gpc = new ParameterFlagGlobalConstraint<Number, Integer>(FAST_SAMPLE_PARAM, null, FAST_FLAG, true);
optionHandler.setGlobalParameterConstraint(gpc);
}
/**
* Main part of the algorithm. Exact version.
*
* @param database Database to use
* @param k k for kNN queries
* @return result
*/
public MultiResult getRanking(Database<V> database, int k) {
KernelMatrix<V> kernelMatrix = new KernelMatrix<V>(kernelFunction, database);
PriorityQueue<FCPair<Double, Integer>> pq = new PriorityQueue<FCPair<Double, Integer>>(database.size(), Collections.reverseOrder());
for(Integer objKey : database) {
MeanVariance s = new MeanVariance();
// System.out.println("Processing: " +objKey);
List<DistanceResultPair<DoubleDistance>> neighbors = database.kNNQueryForID(objKey, k, getDistanceFunction());
Iterator<DistanceResultPair<DoubleDistance>> iter = neighbors.iterator();
while(iter.hasNext()) {
Integer key1 = iter.next().getID();
// Iterator iter2 = data.keyIterator();
Iterator<DistanceResultPair<DoubleDistance>> iter2 = neighbors.iterator();
// PriorityQueue best = new PriorityQueue(false, k);
while(iter2.hasNext()) {
Integer key2 = iter2.next().getID();
if(key2.equals(key1) || key1.equals(objKey) || key2.equals(objKey)) {
continue;
}
double nenner = calcDenominator(kernelMatrix, objKey, key1, key2);
if(nenner != 0) {
double sqrtnenner = Math.sqrt(nenner);
double tmp = calcNumerator(kernelMatrix, objKey, key1, key2) / nenner;
s.addData(tmp, 1 / sqrtnenner);
}
}
}
pq.add(new FCPair<Double, Integer>(s.getVariance(), objKey));
}
Double maxabod = Double.MIN_VALUE;
HashMap<Integer, Double> abodvalues = new HashMap<Integer, Double>();
for(FCPair<Double, Integer> pair : pq) {
abodvalues.put(pair.getSecond(), pair.getFirst());
maxabod = Math.max(maxabod, pair.getFirst());
}
// combine results.
result = new MultiResult();
result.addResult(new AnnotationFromHashMap<Double>(ABOD_SCORE, abodvalues));
result.addResult(new OrderingFromHashMap<Double>(abodvalues, true));
// store normalization information.
ResultUtil.setGlobalAssociation(result, ABOD_NORM, maxabod);
return result;
}
/**
* Main part of the algorithm. Fast version.
*
* @param database Database to use
* @param k k for kNN queries
* @param sampleSize Sample size
* @return result
*/
public MultiResult getFastRanking(Database<V> database, int k, int sampleSize) {
KernelMatrix<V> kernelMatrix = new KernelMatrix<V>(kernelFunction, database);
PriorityQueue<FCPair<Double, Integer>> pq = new PriorityQueue<FCPair<Double, Integer>>(database.size(), Collections.reverseOrder());
// get Candidate Ranking
for(Integer aKey : database) {
HashMap<Integer, Double> dists = new HashMap<Integer, Double>(database.size());
// determine kNearestNeighbors and pairwise distances
PriorityQueue<FCPair<Double, Integer>> nn = calcDistsandNN(database, kernelMatrix, sampleSize, aKey, dists);
if(false) {
// alternative:
PriorityQueue<FCPair<Double, Integer>> nn2 = calcDistsandRNDSample(database, kernelMatrix, sampleSize, aKey, dists);
}
// get normalization
double[] counter = calcFastNormalization(aKey, dists);
// System.out.println(counter[0] + " " + counter2[0] + " " + counter[1] +
// " " + counter2[1]);
// umsetzen von Pq zu list
List<Integer> neighbors = new ArrayList<Integer>(nn.size());
while(!nn.isEmpty()) {
neighbors.add(nn.remove().getSecond());
}
// getFilter
double var = getAbofFilter(kernelMatrix, aKey, dists, counter[1], counter[0], neighbors);
pq.add(new FCPair<Double, Integer>(var, aKey));
// System.out.println("prog "+(prog++));
}
// refine Candidates
PriorityQueue<FCPair<Double, Integer>> resqueue = new PriorityQueue<FCPair<Double, Integer>>(k);
System.out.println(pq.size() + " objects ordered into candidate list.");
int v = 0;
while(!pq.isEmpty()) {
if(resqueue.size() == k && pq.peek().getFirst() > resqueue.peek().getFirst()) {
break;
}
// double approx = pq.peek().getFirst();
Integer aKey = pq.remove().getSecond();
// if(!result.isEmpty()) {
// System.out.println("Best Candidate " + aKey+" : " + pq.firstPriority()
// + " worst result: " + result.firstPriority());
// } else {
// System.out.println("Best Candidate " + aKey+" : " + pq.firstPriority()
// + " worst result: " + Double.MAX_VALUE);
v++;
MeanVariance s = new MeanVariance();
for(Integer bKey : database) {
if(bKey.equals(aKey)) {
continue;
}
for(Integer cKey : database) {
if(cKey.equals(aKey)) {
continue;
}
// double nenner = dists[y]*dists[z];
double nenner = calcDenominator(kernelMatrix, aKey, bKey, cKey);
if(nenner != 0) {
double tmp = calcNumerator(kernelMatrix, aKey, bKey, cKey) / nenner;
double sqrtNenner = Math.sqrt(nenner);
s.addData(tmp, 1 / sqrtNenner);
}
}
}
// System.out.println( aKey + "Sum " + sum + " SQRSum " +sqrSum +
// " Counter " + counter);
double var = s.getVariance();
// System.out.println(aKey+ " : " + approx +" " + var);
if(resqueue.size() < k) {
resqueue.add(new FCPair<Double, Integer>(var, aKey));
}
else {
if(resqueue.peek().getFirst() > var) {
resqueue.remove();
resqueue.add(new FCPair<Double, Integer>(var, aKey));
}
}
}
// System.out.println(v + " Punkte von " + data.size() + " verfeinert !!");
Double maxabod = Double.MIN_VALUE;
HashMap<Integer, Double> abodvalues = new HashMap<Integer, Double>();
for(FCPair<Double, Integer> pair : pq) {
abodvalues.put(pair.getSecond(), pair.getFirst());
maxabod = Math.max(maxabod, pair.getFirst());
}
// ABOD values as result
result = new MultiResult();
result.addResult(new AnnotationFromHashMap<Double>(ABOD_SCORE, abodvalues));
result.addResult(new OrderingFromHashMap<Double>(abodvalues, true));
// store normalization information.
ResultUtil.setGlobalAssociation(result, ABOD_NORM, maxabod);
return result;
}
// TODO: remove?
@SuppressWarnings("unused")
private double[] calcNormalization(Integer xKey, HashMap<Integer, Double> dists) {
double[] result = new double[2];
for(Integer yKey : dists.keySet()) {
if(yKey.equals(xKey)) {
continue;
}
for(Integer zKey : dists.keySet()) {
if(zKey <= yKey) {
continue;
}
if(zKey.equals(xKey)) {
continue;
}
if(dists.get(yKey) != 0 && dists.get(zKey) != 0) {
double sqr = Math.sqrt(dists.get(yKey) * dists.get(zKey));
result[0] += 1 / sqr;
result[1] += 1 / (dists.get(yKey) * dists.get(zKey) * sqr);
}
}
}
return result;
}
private double[] calcFastNormalization(@SuppressWarnings("unused") Integer x, HashMap<Integer, Double> dists) {
double[] result = new double[2];
double sum = 0;
double sumF = 0;
for(Integer yKey : dists.keySet()) {
if(dists.get(yKey) != 0) {
double tmp = 1 / Math.sqrt(dists.get(yKey));
sum += tmp;
sumF += (1 / dists.get(yKey)) * tmp;
}
}
double sofar = 0;
double sofarF = 0;
for(Integer zKey : dists.keySet()) {
if(dists.get(zKey) != 0) {
double tmp = 1 / Math.sqrt(dists.get(zKey));
sofar += tmp;
double rest = sum - sofar;
result[0] += tmp * rest;
sofarF += (1 / dists.get(zKey)) * tmp;
double restF = sumF - sofarF;
result[1] += (1 / dists.get(zKey)) * tmp * restF;
}
}
return result;
}
// TODO: sum, sqrSum were always set to 0 on invocation.
private double getAbofFilter(KernelMatrix<V> kernelMatrix, Integer aKey, HashMap<Integer, Double> dists, double fulCounter, double counter, List<Integer> neighbors) {
MeanVariance s = new MeanVariance();
double partCounter = 0;
Iterator<Integer> iter = neighbors.iterator();
while(iter.hasNext()) {
Integer bKey = iter.next();
if(bKey.equals(aKey)) {
continue;
}
Iterator<Integer> iter2 = neighbors.iterator();
while(iter2.hasNext()) {
Integer cKey = iter2.next();
if(cKey.equals(aKey)) {
continue;
}
if(cKey > bKey) {
double nenner = dists.get(bKey).doubleValue() * dists.get(cKey).doubleValue();
if(nenner != 0) {
double tmp = calcNumerator(kernelMatrix, aKey, bKey, cKey) / nenner;
double sqrtNenner = Math.sqrt(nenner);
s.addData(tmp, 1 / sqrtNenner);
partCounter += (1 / (sqrtNenner * nenner));
}
}
}
}
// TODO: Document the meaning / use of fulCounter, partCounter.
double mu = (s.sum + (fulCounter - partCounter)) / counter;
return (s.sqrSum / counter) - (mu * mu);
}
/**
* Compute the cosinus value between vectors aKey and bKey.
*
* @param kernelMatrix
* @param aKey
* @param bKey
* @return cosinus value
*/
private double calcCos(KernelMatrix<V> kernelMatrix, Integer aKey, Integer bKey) {
return kernelMatrix.getDistance(aKey, aKey) + kernelMatrix.getDistance(bKey, bKey) - 2 * kernelMatrix.getDistance(aKey, bKey);
}
private double calcDenominator(KernelMatrix<V> kernelMatrix, Integer aKey, Integer bKey, Integer cKey) {
return calcCos(kernelMatrix, aKey, bKey) * calcCos(kernelMatrix, aKey, cKey);
}
private double calcNumerator(KernelMatrix<V> kernelMatrix, Integer aKey, Integer bKey, Integer cKey) {
return (kernelMatrix.getDistance(aKey, aKey) + kernelMatrix.getDistance(bKey, cKey) - kernelMatrix.getDistance(aKey, cKey) - kernelMatrix.getDistance(aKey, bKey));
}
private PriorityQueue<FCPair<Double, Integer>> calcDistsandNN(Database<V> data, KernelMatrix<V> kernelMatrix, int sampleSize, Integer aKey, HashMap<Integer, Double> dists) {
PriorityQueue<FCPair<Double, Integer>> nn = new PriorityQueue<FCPair<Double, Integer>>(sampleSize);
for(Integer bKey : data) {
double val = calcCos(kernelMatrix, aKey, bKey);
dists.put(bKey, val);
if(nn.size() < sampleSize) {
nn.add(new FCPair<Double, Integer>(val, bKey));
}
else {
if(val < nn.peek().getFirst()) {
nn.remove();
nn.add(new FCPair<Double, Integer>(val, bKey));
}
}
}
return nn;
}
private PriorityQueue<FCPair<Double, Integer>> calcDistsandRNDSample(Database<V> data, KernelMatrix<V> kernelMatrix, int sampleSize, Integer aKey, HashMap<Integer, Double> dists) {
PriorityQueue<FCPair<Double, Integer>> nn = new PriorityQueue<FCPair<Double, Integer>>(sampleSize);
int step = (int) ((double) data.size() / (double) sampleSize);
int counter = 0;
for(Integer bKey : data) {
double val = calcCos(kernelMatrix, aKey, bKey);
dists.put(bKey, val);
if(counter % step == 0) {
nn.add(new FCPair<Double, Integer>(val, bKey));
}
counter++;
}
return nn;
}
/**
* @param data
*/
// TODO: this should be done by the result classes.
public void getExplanations(Database<V> data) {
KernelMatrix<V> kernelMatrix = new KernelMatrix<V>(kernelFunction, data);
// PQ for Outlier Ranking
PriorityQueue<FCPair<Double, Integer>> pq = new PriorityQueue<FCPair<Double, Integer>>(data.size(), Collections.reverseOrder());
HashMap<Integer, LinkedList<Integer>> explaintab = new HashMap<Integer, LinkedList<Integer>>();
// test all objects
for(Integer objKey : data) {
MeanVariance s = new MeanVariance();
// Queue for the best explanation
PriorityQueue<FCPair<Double, Integer>> explain = new PriorityQueue<FCPair<Double, Integer>>();
// determine Object
// for each pair of other objects
Iterator<Integer> iter = data.iterator();
// Collect Explanation Vectors
while(iter.hasNext()) {
MeanVariance s2 = new MeanVariance();
Integer key1 = iter.next();
Iterator<Integer> iter2 = data.iterator();
if(objKey.equals(key1)) {
continue;
}
while(iter2.hasNext()) {
Integer key2 = iter2.next();
if(key2.equals(key1) || objKey.equals(key2)) {
continue;
}
double nenner = calcDenominator(kernelMatrix, objKey, key1, key2);
if(nenner != 0) {
double tmp = calcNumerator(kernelMatrix, objKey, key1, key2) / nenner;
double sqr = Math.sqrt(nenner);
s2.addData(tmp, 1 / sqr);
}
}
explain.add(new FCPair<Double, Integer>(s2.getVariance(), key1));
s.addData(s2);
}
// build variance of the observed vectors
pq.add(new FCPair<Double, Integer>(s.getVariance(), objKey));
LinkedList<Integer> expList = new LinkedList<Integer>();
expList.add(explain.remove().getSecond());
while(!explain.isEmpty()) {
Integer nextKey = explain.remove().getSecond();
if(nextKey.equals(objKey)) {
continue;
}
double max = Double.MIN_VALUE;
for(Integer exp : expList) {
if(exp.equals(objKey) || nextKey.equals(exp)) {
continue;
}
double nenner = Math.sqrt(calcCos(kernelMatrix, objKey, nextKey)) * Math.sqrt(calcCos(kernelMatrix, objKey, exp));
double angle = calcNumerator(kernelMatrix, objKey, nextKey, exp) / nenner;
max = Math.max(angle, max);
}
if(max < 0.5) {
expList.add(nextKey);
}
}
explaintab.put(objKey, expList);
}
System.out.println("
System.out.println("Result: ABOD");
int count = 0;
while(!pq.isEmpty()) {
if(count > 10) {
break;
}
double factor = pq.peek().getFirst();
Integer key = pq.remove().getSecond();
System.out.print(data.get(key) + " ");
System.out.println(count + " Factor=" + factor + " " + key);
LinkedList<Integer> expList = explaintab.get(key);
generateExplanation(data, key, expList);
count++;
}
System.out.println("
}
private void generateExplanation(Database<V> data, Integer key, LinkedList<Integer> expList) {
V vect1 = data.get(key);
Iterator<Integer> iter = expList.iterator();
while(iter.hasNext()) {
System.out.println("Outlier: " + vect1);
V exp = data.get(iter.next());
System.out.println("Most common neighbor: " + exp);
// determine difference Vector
V vals = exp.plus(vect1.negativeVector());
System.out.println(vals);
// System.out.println(new FeatureVector(
// "Diff-"+vect1.getPrimaryKey(),vals ));
}
System.out.println();
}
@Override
protected MultiResult runInTime(Database<V> database) throws IllegalStateException {
this.kernelFunction.setDatabase(database, false, false);
if(fast) {
return getFastRanking(database, k, sampleSize);
}
else {
return getRanking(database, k);
}
}
/**
* Return a description of the algorithm.
*/
@Override
public Description getDescription() {
return new Description("ABOD", "Angle-Based Outlier Detection", "Outlier detection using variance analysis on angles, especially for high dimensional data sets.", "H.-P. Kriegel, M. Schubert, and A. Zimek: " + "Angle-Based Outlier Detection in High-dimensional Data. " + "In: Proc. 14th ACM SIGKDD Int. Conf. on Knowledge Discovery and Data Mining (KDD '08), Las Vegas, NV, 2008.");
}
/**
* Return the results of the last run.
*/
@Override
public MultiResult getResult() {
return result;
}
/**
* Calls the super method and sets parameters {@link #FAST_FLAG},
* {@link #FAST_SAMPLE_PARAM} and {@link #KERNEL_FUNCTION_PARAM}. The
* remaining parameters are then passed to the {@link #kernelFunction}.
*/
@Override
public String[] setParameters(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
k = K_PARAM.getValue();
fast = FAST_FLAG.getValue();
if(fast) {
if(!FAST_SAMPLE_PARAM.isSet()) {
throw new UnspecifiedParameterException("If you set a fast mode, you also need to set a sample size.");
}
sampleSize = FAST_SAMPLE_PARAM.getValue();
}
kernelFunction = KERNEL_FUNCTION_PARAM.instantiateClass();
remainingParameters = kernelFunction.setParameters(remainingParameters);
addParameterizable(kernelFunction);
rememberParametersExcept(args, remainingParameters);
return remainingParameters;
}
}
|
package de.lmu.ifi.dbs.utilities.heap;
/**
* Defines the requiremnts for objects that are identifiable, i.e. objects which have an unique id.
*
* @author Elke Achtert (<a href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>)
*/
public interface Identifiable extends Comparable<Identifiable> {
/**
* Returns the unique id of this object.
*
* @return the unique id of this object
*/
Integer getID();
}
|
package de.mrapp.android.preference;
import android.app.Fragment;
/**
* Defines the interface a class, which should be notified when the user
* navigates within a {@link PreferenceActivity}, which is used as wizard, by
* using its next-, back- and finish-button. The return values of the
* interface's methods allow to take influence on the navigation, e.g. if the
* currently shown preferences should be validated.
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public interface WizardListener {
/**
* The method, which is invoked, when the user wants to navigate to the next
* step of the wizard.
*
* @param position
* The position of the currently selected preference header as an
* {@link Integer} value
* @param preferenceHeader
* The currently selected preference header as an instance of the
* class {@link PreferenceHeader}
* @param fragment
* The currently shown fragment as an instance of the class
* {@link Fragment}
* @return True, if navigating to the next step of the wizard should be
* allowed, false otherwise
*/
boolean onNextStep(int position, PreferenceHeader preferenceHeader,
Fragment fragment);
/**
* The method, which is invoked, when the user wants to navigate to the
* previous step of the wizard.
*
* @param position
* The position of the currently selected preference header as an
* {@link Integer} value
* @param preferenceHeader
* The currently selected preference header as an instance of the
* class {@link PreferenceHeader}
* @param fragment
* The currently shown fragment as an instance of the class
* {@link Fragment}
* @return True, if navigating to the previous step of the wizard should be
* allowed, false otherwise
*/
boolean onPreviousStep(int position, PreferenceHeader preferenceHeader,
Fragment fragment);
/**
* The method, which is invoked, when the user wants to finish the last step
* of the wizard.
*
* @param position
* The position of the currently selected preference header as an
* {@link Integer} value
* @param preferenceHeader
* The currently selected preference header as an instance of the
* class {@link PreferenceHeader}
* @param fragment
* The currently shown fragment as an instance of the class
* {@link Fragment}
* @return True, if finishing the wizard should be allowed, false otherwise
*/
boolean onFinish(int position, PreferenceHeader preferenceHeader,
Fragment fragment);
/**
* The method, which is invoked, when the user wants to skip the wizard.
*
* @param position
* The position of the currently selected preference header as an
* {@link Integer} value
* @param preferenceHeader
* The currently selected preference header as an instance of the
* class {@link PreferenceHeader}
* @param fragment
* The currently shown fragment as an instance of the class
* {@link Fragment}
* @return True, if skipping the wizard should be allowed, false otherwise
*/
boolean onSkip(int position, PreferenceHeader preferenceHeader,
Fragment fragment);
}
|
package edu.gatech.nutrack.database;
import java.util.ArrayList;
import java.util.List;
import team.cs6365.payfive.database.MenuItemDatabaseHelper;
import edu.gatech.nutrack.model.User;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class UserDataSource
{
private SQLiteDatabase db;
private UserDatabaseHelper dbHelper;
private String[] columns = {UserDatabaseContract.COLUMN_NAME_USERNAME,
UserDatabaseContract.COLUMN_NAME_PASSWORD,
UserDatabaseContract.COLUMN_NAME_EMAIL,
UserDatabaseContract.COLUMN_NAME_TYPE};
public UserDataSource(Context context)
{
dbHelper = new UserDatabaseHelper(context);
}
public void open() throws SQLException
{
db = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public void drop() {
db.execSQL(UserDatabaseHelper.SQL_DROP_USER_TABLE);
}
public void create() {
db.execSQL(UserDatabaseHelper.SQL_CREATE_USER_TABLE);
}
public void addUser(String username, String password, String email, int type)
{
ContentValues row = new ContentValues();
row.put(columns[0], username);
row.put(columns[1], password);
row.put(columns[2], email);
row.put(columns[3], type);
db.insert(UserDatabaseContract.TABLE_NAME, null, row);
}
public void addUser(User u) {
addUser(u.getUsername(), u.getPassword(), u.getEmail(), u.getType());
}
public void deleteUser(User u)
{
db.delete(UserDatabaseContract.TABLE_NAME,
UserDatabaseContract.COLUMN_NAME_USERNAME + "='" + u.getUsername() + "' AND " +
UserDatabaseContract.COLUMN_NAME_PASSWORD + "='" + u.getPassword() + "' AND " +
UserDatabaseContract.COLUMN_NAME_EMAIL + "='" + u.getEmail() + "' AND " +
UserDatabaseContract.COLUMN_NAME_TYPE + "=" + u.getType(),
null);
}
public User getUser(String username, String password, String email, int type)
{
User u = null;
Cursor cur = db.query(UserDatabaseContract.TABLE_NAME,
columns,
UserDatabaseContract.COLUMN_NAME_USERNAME + "='" + username + "' AND " +
UserDatabaseContract.COLUMN_NAME_PASSWORD + "='" + password + "' AND " +
UserDatabaseContract.COLUMN_NAME_EMAIL + "='" + email + "' AND " +
UserDatabaseContract.COLUMN_NAME_TYPE + "=" + type,
null, null, null, null);
if(cur != null && cur.getCount() > 0)
{
cur.moveToFirst();
u = cursorToUser(cur);
}
cur.close();
return u;
}
public List<User> getAllUsers()
{
List<User> list = null;
Cursor cur = db.query(UserDatabaseContract.TABLE_NAME,
columns, null, null, null, null, null);
if(cur != null && cur.getCount() > 0)
{
list = new ArrayList<User>();
cur.moveToFirst();
while(!cur.isAfterLast())
{
list.add(cursorToUser(cur));
cur.moveToNext();
}
}
cur.close();
return list;
}
public User cursorToUser(Cursor cur)
{
return new User(cur.getString(0),
cur.getString(1),
cur.getString(2),
cur.getInt(3));
}
}
|
package foam.nanos.session.cron;
import foam.core.ContextAgent;
import foam.core.X;
import foam.dao.ArraySink;
import foam.dao.DAO;
import java.util.List;
import java.util.Date;
import foam.nanos.session.Session;
import static foam.mlang.MLang.*;
public class ExpireSessionsCron implements ContextAgent {
private DAO localSessionDAO;
@Override
public void execute(X x) {
localSessionDAO = (DAO) x.get("localSessionDAO");
List<Session> expiredSessions = ((ArraySink) localSessionDAO.where(GT(Session.TTL, 0)).select(new ArraySink())).getArray();
for ( Session session : expiredSessions ) {
if ( session.getLastUsed().getTime() + session.getTtl() > (new Date()).getTime() ) {
System.out.println("Destroyed expired session : " + (String) session.getId());
localSessionDAO.remove(session);
}
}
}
}
|
package edu.utexas.jdumper.writer;
import edu.utexas.jdumper.soot.*;
import soot.*;
import soot.jimple.*;
import soot.jimple.internal.JimpleLocal;
import soot.shimple.PhiExpr;
import soot.shimple.Shimple;
import soot.tagkit.LineNumberTag;
import java.sql.*;
import java.util.*;
/**
* Serialize JIMPLE to disk
*/
public final class JimpleWriter
{
private static class IfInfo
{
int stmtId;
int conditionId;
public IfInfo(int stmtId, int conditionId)
{
this.stmtId = stmtId;
this.conditionId = conditionId;
}
}
DatabaseWriter dbWriter;
private IndexMap<Type> typeMap = new IndexMap<>();
private IndexMap<SootField> fieldMap = new IndexMap<>();
private IndexMap<SootMethod> methodMap = new IndexMap<>();
private IndexMap<SootVariable> varMap = new IndexMap<>();
private IndexMap<Constant> constMap = new IndexMap<>();
private IndexMap<Stmt> stmtMap = new IndexMap<>();
private Map<IfStmt, IfInfo> ifMap = new HashMap<>();
private Map<LookupSwitchStmt, Integer> lookupSwitchMap = new HashMap<>();
private Map<TableSwitchStmt, Integer> tableSwitchMap = new HashMap<>();
private IndexMap<Trap> trapMap = new IndexMap<>();
private JimpleWriter(Connection connection) throws SQLException
{
dbWriter = new DatabaseWriter(connection);
}
private int getTypeId(Type type) throws SQLException
{
// Array type requires special handling here since their table are not populated at the beginning of the dump process
if (type instanceof ArrayType)
{
ArrayType aType = (ArrayType) type;
if (!typeMap.exist(aType))
{
int elemId = getTypeId(aType.getElementType());
int id = typeMap.getIndex(aType);
dbWriter.writeArrayType(id, elemId);
return id;
}
}
return typeMap.getIndexOrFail(type);
}
private int getConstantId(Constant constant) throws SQLException
{
if (!constMap.exist(constant))
{
int id = constMap.getIndex(constant);
if (constant instanceof IntConstant)
{
IntConstant intConst = (IntConstant) constant;
dbWriter.writeIntConstant(id, intConst.value);
}
else if (constant instanceof LongConstant)
{
LongConstant longConst = (LongConstant) constant;
dbWriter.writeLongConstant(id, longConst.value);
}
else if (constant instanceof FloatConstant)
{
FloatConstant floatConst = (FloatConstant) constant;
dbWriter.writeFloatConstant(id, floatConst.value);
}
else if (constant instanceof DoubleConstant)
{
DoubleConstant doubleConst = (DoubleConstant) constant;
dbWriter.writeDoubleConstant(id, doubleConst.value);
}
else if (constant instanceof NullConstant)
{
dbWriter.writeNullConstant(id);
}
else if (constant instanceof StringConstant)
{
StringConstant strConst = (StringConstant) constant;
dbWriter.writeStringConstant(id, strConst.value);
}
else if (constant instanceof ClassConstant)
{
ClassConstant classConst = (ClassConstant) constant;
dbWriter.writeClassConstant(id, classConst.value);
}
else
throw new RuntimeException("Unsupported constant: " + constant);
return id;
}
return constMap.getIndexOrFail(constant);
}
private void writeNullType() throws SQLException
{
int id = typeMap.getIndex(soot.NullType.v());
dbWriter.writeNullType(id);
}
private void writePrimitiveTypes() throws SQLException
{
dbWriter.writePrimitiveType(typeMap.getIndex(soot.BooleanType.v()), "boolean");
dbWriter.writePrimitiveType(typeMap.getIndex(soot.ByteType.v()), "byte");
dbWriter.writePrimitiveType(typeMap.getIndex(soot.CharType.v()), "char");
dbWriter.writePrimitiveType(typeMap.getIndex(soot.ShortType.v()), "short");
dbWriter.writePrimitiveType(typeMap.getIndex(soot.IntType.v()), "int");
dbWriter.writePrimitiveType(typeMap.getIndex(soot.LongType.v()), "long");
dbWriter.writePrimitiveType(typeMap.getIndex(soot.FloatType.v()), "float");
dbWriter.writePrimitiveType(typeMap.getIndex(soot.DoubleType.v()), "double");
}
private void writeFields(SootClass cl) throws SQLException
{
for (SootField field: cl.getFields())
{
int fid = fieldMap.getIndex(field);
String name = field.getName();
int tid = getTypeId(field.getType());
int parentId = getTypeId(cl.getType());
int modifier = field.getModifiers();
dbWriter.writeField(fid, name, tid, parentId, modifier);
}
}
private int writeLocal(int mid, Local local) throws SQLException
{
SootVariable var = new LocalVariable(local);
int vid = varMap.getIndex(var);
int tid = getTypeId(local.getType());
dbWriter.writeVariable(vid, var.getName(), tid, mid);
return vid;
}
private void writeLocals(int mid, Body body) throws SQLException
{
for (Local local: body.getLocals())
writeLocal(mid, local);
}
private void writeAssignToLocal(int mid, AssignStmt stmt, int lhsId) throws SQLException
{
int id = stmtMap.getIndex(stmt);
Value rhs = stmt.getRightOp();
if (rhs instanceof Local)
{
Local local = (Local) rhs;
int rhsId = varMap.getIndex(new LocalVariable(local));
dbWriter.writeAssignVariableInstruction(id, lhsId, rhsId, mid);
}
else if (rhs instanceof InvokeExpr)
{
InvokeExpr expr = (InvokeExpr) rhs;
LineNumberTag tag = (LineNumberTag) stmt.getTag("LineNumberTag");
writeInvokeExpr(id, expr, mid, tag == null ? null : tag.getLineNumber(), lhsId);
}
else if (rhs instanceof CastExpr)
{
CastExpr cast = (CastExpr) rhs;
Value op = cast.getOp();
if (op instanceof Local)
{
int rhsId = varMap.getIndex(new LocalVariable((Local) op));
int typeId = getTypeId(cast.getCastType());
dbWriter.writeAssignCastInstruction(id, lhsId, rhsId, typeId, mid);
}
else if (op instanceof Constant)
{
int cid = getConstantId((Constant) op);
dbWriter.writeAssignConstInstruction(id, lhsId, cid, mid);
}
else
throw new RuntimeException("Unsupported assign cast stmt: " + stmt);
}
else if (rhs instanceof NewExpr)
{
NewExpr newExpr = (NewExpr) rhs;
int tid = typeMap.getIndexOrFail(newExpr.getType());
dbWriter.writeAssignAllocInstruction(id, lhsId, tid, mid);
}
else if (rhs instanceof NewArrayExpr)
{
NewArrayExpr newExpr = (NewArrayExpr) rhs;
int tid = getTypeId(newExpr.getType());
Value sizeVal = newExpr.getSize();
int vid;
if (sizeVal instanceof Local)
{
Local local = (Local) sizeVal;
vid = varMap.getIndex(new LocalVariable(local));
}
else if (sizeVal instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) sizeVal;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
vid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, vid, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported alloc size value: " + sizeVal);
dbWriter.writeAllocSize(vid, 0, id);
dbWriter.writeAssignAllocInstruction(id, lhsId, tid, mid);
}
else if (rhs instanceof NewMultiArrayExpr)
{
NewMultiArrayExpr newExpr = (NewMultiArrayExpr) rhs;
int tid = getTypeId(newExpr.getType());
ArrayList<Integer> sizeList = new ArrayList<>();
for (int i = 0, e = newExpr.getSizeCount(); i < e; ++i) {
Value sizeVal = newExpr.getSize(i);
int vid;
if (sizeVal instanceof Local)
{
Local local = (Local) sizeVal;
vid = varMap.getIndex(new LocalVariable(local));
}
else if (sizeVal instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) sizeVal;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
vid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, vid, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported alloc size value: " + sizeVal);
sizeList.add(vid);
}
dbWriter.writeAssignAllocInstruction(id, lhsId, tid, mid);
for (int i = 0, e = sizeList.size(); i < e; ++i) {
Integer vid = sizeList.get(i);
dbWriter.writeAllocSize(vid, i, id);
}
}
else if (rhs instanceof Constant)
{
int cid = getConstantId((Constant) rhs);
dbWriter.writeAssignConstInstruction(id, lhsId, cid, mid);
}
else if (rhs instanceof InstanceFieldRef)
{
InstanceFieldRef iFieldRef = (InstanceFieldRef) rhs;
Local local = (Local) iFieldRef.getBase();
int fieldId = fieldMap.getIndexOrFail(iFieldRef.getField());
int rhsId = varMap.getIndex(new LocalVariable(local));
dbWriter.writeLoadInstanceFieldInstruction(id, lhsId, rhsId, fieldId, mid);
}
else if (rhs instanceof StaticFieldRef)
{
StaticFieldRef sFieldRef = (StaticFieldRef) rhs;
int fieldId = fieldMap.getIndexOrFail(sFieldRef.getField());
dbWriter.writeLoadStaticFieldInstruction(id, lhsId, fieldId, mid);
}
else if (rhs instanceof ArrayRef)
{
ArrayRef arrayRef = (ArrayRef) rhs;
Local base = (Local) arrayRef.getBase();
int baseId = varMap.getIndex(new LocalVariable(base));
Value index = arrayRef.getIndex();
int iid;
if (index instanceof Local)
{
Local local = (Local) index;
iid = varMap.getIndex(new LocalVariable(local));
}
else if (index instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) index;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
iid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, iid, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported operand: " + index);
dbWriter.writeLoadArrayInstruction(id, lhsId, baseId, iid, mid);
}
else if (rhs instanceof BinopExpr)
{
BinopExpr expr = (BinopExpr) rhs;
BinOpKind kind = BinOpKind.getOpKind(expr);
Value op0 = expr.getOp1();
int op0Id;
if (op0 instanceof Local)
{
Local local = (Local) op0;
op0Id = varMap.getIndex(new LocalVariable(local));
}
else if (op0 instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) op0;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
op0Id = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, op0Id, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported operand: " + op0);
Value op1 = expr.getOp2();
int op1Id;
if (op1 instanceof Local)
{
Local local = (Local) op1;
op1Id = varMap.getIndex(new LocalVariable(local));
}
else if (op1 instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) op1;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
op1Id = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, op1Id, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported operand: " + op1);
dbWriter.writeBinaryOpInstruction(id, kind, lhsId, op0Id, op1Id, mid);
}
else if (rhs instanceof NegExpr || rhs instanceof LengthExpr || rhs instanceof InstanceOfExpr)
{
Value op = null;
UnOpKind kind;
if (rhs instanceof NegExpr) {
kind = UnOpKind.NEG;
op = ((NegExpr) rhs).getOp();
}
else if (rhs instanceof LengthExpr) {
kind = UnOpKind.LENGTH;
op = ((LengthExpr) rhs).getOp();
}
else if (rhs instanceof InstanceOfExpr) {
kind = UnOpKind.INSTANCEOF;
op = ((InstanceOfExpr) rhs).getOp();
} else {
throw new RuntimeException("Not an unary exp: " + rhs);
}
int opId;
if (op instanceof Local)
{
Local local = (Local) op;
opId = varMap.getIndex(new LocalVariable(local));
}
else if (op instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) op;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
opId = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, opId, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported operand: " + op);
dbWriter.writeUnaryOpInstruction(id, kind, lhsId, opId, mid);
}
else if (rhs instanceof PhiExpr)
{
PhiExpr rhsPhi = (PhiExpr) rhs;
// ShimpleBody sometimes gives me phiexpr with duplicated rhs.
// This is annoying, but we have to deal with it.
Set<Integer> rhsIds = new TreeSet<>();
for (Value rhsVal: rhsPhi.getValues())
{
if (rhsVal instanceof Local)
{
Local rhsLocal = (Local) rhsVal;
int rhsId = varMap.getIndex(new LocalVariable(rhsLocal));
rhsIds.add(rhsId);
}
else
throw new RuntimeException("Unsupported PHI rhs: " + rhsVal);
}
dbWriter.writeAssignPhiInstruction(id, lhsId, new ArrayList<>(rhsIds), mid);
}
else
{
throw new RuntimeException("Unsupported assignment stmt: " + stmt);
}
}
private void writeAssignToNonLocal(int mid, AssignStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
Value lhs = stmt.getLeftOp();
Value rhs = stmt.getRightOp();
int rhsId;
if (rhs instanceof Local)
{
Local local = (Local) rhs;
rhsId = varMap.getIndex(new LocalVariable(local));
}
else if (rhs instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) rhs;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
rhsId = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, rhsId, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported assignment rhs: " + rhs);
if (lhs instanceof InstanceFieldRef)
{
InstanceFieldRef iFieldRef = (InstanceFieldRef) lhs;
Local base = (Local) iFieldRef.getBase();
int fieldId = fieldMap.getIndexOrFail(iFieldRef.getField());
int baseId = varMap.getIndex(new LocalVariable(base));
dbWriter.writeStoreInstanceFieldInstruction(id, baseId, fieldId, rhsId, mid);
}
else if (lhs instanceof StaticFieldRef)
{
StaticFieldRef sFieldRef = (StaticFieldRef) lhs;
int fieldId = fieldMap.getIndexOrFail(sFieldRef.getField());
dbWriter.writeStoreStaticFieldInstruction(id, fieldId, rhsId, mid);
}
else if (lhs instanceof ArrayRef)
{
ArrayRef arrayRef = (ArrayRef) lhs;
Local base = (Local) arrayRef.getBase();
int baseId = varMap.getIndex(new LocalVariable(base));
Value index = arrayRef.getIndex();
int iid;
if (index instanceof Local)
{
Local local = (Local) index;
iid = varMap.getIndex(new LocalVariable(local));
}
else if (index instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) index;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
iid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, iid, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported operand: " + index);
dbWriter.writeStoreArrayInstruction(id, baseId, iid, rhsId, mid);
}
else
throw new RuntimeException("Unsupported assignment lhs: " + lhs);
}
private void writeAssignStmt(int mid, AssignStmt stmt) throws SQLException
{
Value lhs = stmt.getLeftOp();
if (lhs instanceof Local)
{
Local local = (Local) lhs;
int vid = varMap.getIndex(new LocalVariable(local));
writeAssignToLocal(mid, stmt, vid);
}
else
writeAssignToNonLocal(mid, stmt);
}
private void writeIdentityStmt(int mid, SootMethod method, IdentityStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
Value lhs = stmt.getLeftOp();
Value rhs = stmt.getRightOp();
if(rhs instanceof CaughtExceptionRef) {
// The case is handled by ExceptionHandler writer
// Pretend that stmt is an no-op here
dbWriter.writeNopInstruction(id, mid);
}
else if(lhs instanceof Local && rhs instanceof ThisRef)
{
Local local = (Local) lhs;
int lhsId = varMap.getIndex(new LocalVariable(local));
int rhsId = varMap.getIndex(new ThisVariable(method));
dbWriter.writeAssignVariableInstruction(id, lhsId, rhsId, mid);
}
else if(lhs instanceof Local && rhs instanceof ParameterRef)
{
Local local = (Local) lhs;
ParameterRef parameterRef = (ParameterRef) rhs;
int lhsId = varMap.getIndex(new LocalVariable(local));
int rhsId = varMap.getIndex(new ParamVariable(method, parameterRef.getIndex()));
dbWriter.writeAssignVariableInstruction(id, lhsId, rhsId, mid);
}
else
{
throw new RuntimeException("Unsupported identity statement: " + stmt);
}
}
private void writeInvokeExpr(int id, InvokeExpr expr, int mid, Integer lineno, Integer retId) throws SQLException
{
// Write actual arguments
ArrayList<Integer> argIdList = new ArrayList<>();
for (int i = 0; i < expr.getArgCount(); ++i)
{
Value v = expr.getArg(i);
if (v instanceof Local)
{
Local local = (Local) v;
int vid = varMap.getIndexOrFail(new LocalVariable(local));
argIdList.add(vid);
}
else if (v instanceof Constant)
{
Constant c = (Constant) v;
int cid = getConstantId(c);
// Fabricate an ASSIGN_CONST instruction here
Local l = new JimpleLocal("const" + id, c.getType());
int vid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, vid, cid, mid);
id = stmtMap.getNextIndex();
argIdList.add(vid);
}
else
throw new RuntimeException("Unsupported actual argument: " + v);
}
for (int i = 0; i < argIdList.size(); ++i)
dbWriter.writeArgument(argIdList.get(i), i, id);
// Write 'this' argument
Integer baseId = null;
if (expr instanceof InstanceInvokeExpr)
{
InstanceInvokeExpr iExpr = (InstanceInvokeExpr) expr;
Local base = (Local) iExpr.getBase();
baseId = varMap.getIndex(new LocalVariable(base));
}
InvokeKind kind;
if (expr instanceof StaticInvokeExpr)
kind = InvokeKind.STATIC;
else if (expr instanceof VirtualInvokeExpr)
kind = InvokeKind.VIRTUAL;
else if (expr instanceof InterfaceInvokeExpr)
kind = InvokeKind.INTERFACE;
else if (expr instanceof SpecialInvokeExpr)
kind = InvokeKind.SPECIAL;
else
throw new RuntimeException("Unsupported invoke expr: " + expr);
int targetId = methodMap.getIndexOrFail(expr.getMethod());
dbWriter.writeInvokeInstruction(id, kind, targetId, baseId, lineno, retId, mid);
}
private void writeInvokeStmt(int mid, InvokeStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
InvokeExpr expr = stmt.getInvokeExpr();
LineNumberTag tag = (LineNumberTag) stmt.getTag("LineNumberTag");
writeInvokeExpr(id, expr, mid, tag == null ? null : tag.getLineNumber(), null);
}
private void writeReturnStmt(int mid, ReturnStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
Value v = stmt.getOp();
if(v instanceof Local)
{
Local local = (Local) v;
int vid = varMap.getIndexOrFail(new LocalVariable(local));
dbWriter.writeReturnInstruction(id, vid, mid);
}
else if (v instanceof Constant)
{
Constant c = (Constant) v;
int cid = getConstantId(c);
// Fabricate an ASSIGN_CONST instruction here
Local l = new JimpleLocal("const" + id, c.getType());
int vid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, vid, cid, mid);
id = stmtMap.getNextIndex();
dbWriter.writeReturnInstruction(id, vid, mid);
}
else
{
throw new RuntimeException("Unsupported throw stmt: " + stmt);
}
}
private void writeReturnVoidStmt(int mid, ReturnVoidStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
dbWriter.writeReturnVoidInstruction(id, mid);
}
private void writeThrowStmt(int mid, ThrowStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
Value v = stmt.getOp();
if(v instanceof Local)
{
Local local = (Local) v;
int vid = varMap.getIndexOrFail(new LocalVariable(local));
dbWriter.writeThrowInstruction(id, vid, mid);
}
else
{
throw new RuntimeException("Unsupported throw stmt: " + stmt);
}
}
private void writeEnterMonitorStmt(int mid, EnterMonitorStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
Value v = stmt.getOp();
if(v instanceof Local)
{
Local local = (Local) v;
int vid = varMap.getIndexOrFail(new LocalVariable(local));
dbWriter.writeEnterMonitorInstruction(id, vid, mid);
}
else if (v instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) v;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
int vid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, vid, cid, mid);
id = stmtMap.getNextIndex();
dbWriter.writeEnterMonitorInstruction(id, vid, mid);
}
else
{
throw new RuntimeException("Unsupported entermonitor stmt: " + stmt);
}
}
private void writeExitMonitorStmt(int mid, ExitMonitorStmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
Value v = stmt.getOp();
if(v instanceof Local)
{
Local local = (Local) v;
int vid = varMap.getIndexOrFail(new LocalVariable(local));
dbWriter.writeExitMonitorInstruction(id, vid, mid);
}
else if (v instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) v;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
int vid = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, vid, cid, mid);
id = stmtMap.getNextIndex();
dbWriter.writeExitMonitorInstruction(id, vid, mid);
}
else
{
throw new RuntimeException("Unsupported exitmonitor stmt: " + stmt);
}
}
private void writeGotoStmt(int mid, GotoStmt stmt) throws SQLException
{
int id = stmtMap.getIndexOrFail(stmt);
int target = stmtMap.getIndexOrFail((Stmt) stmt.getTarget());
dbWriter.writeGotoInstruction(id, target, mid);
}
private void writeIfStmt(int mid, IfStmt stmt) throws SQLException
{
ConditionExpr expr = (ConditionExpr) stmt.getCondition();
Stmt targetStmt = stmt.getTarget();
int targetId = stmtMap.getIndexOrFail(targetStmt);
IfInfo info = ifMap.get(stmt);
dbWriter.writeIfInstruction(info.stmtId, info.conditionId, targetId, mid);
}
private void writeTableSwitchStmt(int mid, TableSwitchStmt stmt) throws SQLException
{
int id = tableSwitchMap.get(stmt);
int indexCounter = 0;
for (int tgtIndex = stmt.getLowIndex(); tgtIndex <= stmt.getHighIndex(); ++tgtIndex)
{
int targetId = stmtMap.getIndexOrFail((Stmt) stmt.getTarget(indexCounter));
dbWriter.writeSwitchTarget(id, tgtIndex, targetId);
++indexCounter;
}
int defaultId = stmtMap.getIndexOrFail((Stmt) stmt.getDefaultTarget());
dbWriter.writeDefaultSwitchTarget(id, defaultId);
}
private void writeLookupSwitchStmt(int mid, LookupSwitchStmt stmt) throws SQLException
{
int id = lookupSwitchMap.get(stmt);
for (int i = 0; i < stmt.getTargetCount(); ++i)
{
int tgtIndex = stmt.getLookupValue(i);
int targetId = stmtMap.getIndexOrFail((Stmt) stmt.getTarget(i));
dbWriter.writeSwitchTarget(id, tgtIndex, targetId);
}
int defaultId = stmtMap.getIndexOrFail((Stmt) stmt.getDefaultTarget());
dbWriter.writeDefaultSwitchTarget(id, defaultId);
}
private void writeNopStmt(int mid, Stmt stmt) throws SQLException
{
int id = stmtMap.getIndex(stmt);
dbWriter.writeNopInstruction(id, mid);
}
private void writeTraps(int mid, Body body) throws SQLException
{
for (Trap trap: body.getTraps())
{
int trapid = trapMap.getIndex(trap);
assert(!trap.getException().isInterface());
int typeid = typeMap.getIndexOrFail(trap.getException().getType());
int startid = stmtMap.getIndexOrFail((Stmt) trap.getBeginUnit());
int endid = stmtMap.getIndexOrFail((Stmt) trap.getEndUnit());
IdentityStmt idStmt = (IdentityStmt) trap.getHandlerUnit();
int hid = stmtMap.getIndexOrFail(idStmt);
Local lhs = (Local) idStmt.getLeftOp();
if (!(idStmt.getRightOp() instanceof CaughtExceptionRef))
throw new RuntimeException("Trap not supported: " + idStmt.getRightOp());
int vid = varMap.getIndex(new LocalVariable(lhs));
dbWriter.writeExceptionHandler(trapid, mid, typeid, vid, startid, endid, hid + 1);
}
}
private void writeStmts(int mid, Body body) throws SQLException
{
for (Unit unit: body.getUnits())
{
Stmt stmt = (Stmt) unit;
if(stmt instanceof AssignStmt)
{
writeAssignStmt(mid, (AssignStmt) stmt);
}
else if(stmt instanceof IdentityStmt)
{
writeIdentityStmt(mid, body.getMethod(), (IdentityStmt) stmt);
}
else if(stmt instanceof InvokeStmt)
{
writeInvokeStmt(mid, (InvokeStmt) stmt);
}
else if(stmt instanceof ReturnStmt)
{
writeReturnStmt(mid, (ReturnStmt) stmt);
}
else if(stmt instanceof ReturnVoidStmt)
{
writeReturnVoidStmt(mid, (ReturnVoidStmt)stmt);
}
else if(stmt instanceof ThrowStmt)
{
writeThrowStmt(mid, (ThrowStmt) stmt);
}
else if(stmt instanceof EnterMonitorStmt)
{
writeEnterMonitorStmt(mid, (EnterMonitorStmt) stmt);
}
else if(stmt instanceof ExitMonitorStmt)
{
writeExitMonitorStmt(mid, (ExitMonitorStmt) stmt);
}
else if(stmt instanceof GotoStmt)
{
stmtMap.getIndex(stmt);
}
else if(stmt instanceof IfStmt)
{
// We need to prepare for the if condition first
int id = stmtMap.getIndex(stmt);
IfStmt ifStmt = (IfStmt) stmt;
ConditionExpr expr = (ConditionExpr) ifStmt.getCondition();
BinOpKind kind = BinOpKind.getOpKind(expr);
Value op0 = expr.getOp1();
int op0Id;
if (op0 instanceof Local)
{
Local local = (Local) op0;
op0Id = varMap.getIndex(new LocalVariable(local));
}
else if (op0 instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) op0;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
op0Id = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, op0Id, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported operand: " + op0);
Value op1 = expr.getOp2();
int op1Id;
if (op1 instanceof Local)
{
Local local = (Local) op1;
op1Id = varMap.getIndex(new LocalVariable(local));
}
else if (op1 instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) op1;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
op1Id = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, op1Id, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported operand: " + op1);
// Fabricate a BINARY_OPERATION instruction here
Local condLocal = new JimpleLocal("if_cond" + id, expr.getType());
int condId = writeLocal(mid, condLocal);
dbWriter.writeBinaryOpInstruction(id, kind, condId, op0Id, op1Id, mid);
id = stmtMap.getNextIndex();
ifMap.put(ifStmt, new IfInfo(id, condId));
}
else if(stmt instanceof TableSwitchStmt)
{
int id = stmtMap.getIndex(stmt);
TableSwitchStmt switchStmt = (TableSwitchStmt) stmt;
Value key = switchStmt.getKey();
int keyId;
if (key instanceof Local)
{
Local local = (Local) key;
keyId = varMap.getIndex(new LocalVariable(local));
}
else if (key instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) key;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
keyId = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, keyId, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported switch key: " + key);
dbWriter.writeTableSwitchInstruction(id, keyId, mid);
tableSwitchMap.put(switchStmt, id);
}
else if(stmt instanceof LookupSwitchStmt)
{
int id = stmtMap.getIndex(stmt);
LookupSwitchStmt switchStmt = (LookupSwitchStmt) stmt;
Value key = switchStmt.getKey();
int keyId;
if (key instanceof Local)
{
Local local = (Local) key;
keyId = varMap.getIndex(new LocalVariable(local));
}
else if (key instanceof Constant)
{
// Fabricate an ASSIGN_CONST instruction here
Constant c = (Constant) key;
int cid = getConstantId(c);
Local l = new JimpleLocal("const" + id, c.getType());
keyId = writeLocal(mid, l);
dbWriter.writeAssignConstInstruction(id, keyId, cid, mid);
id = stmtMap.getNextIndex();
}
else
throw new RuntimeException("Unsupported switch key: " + key);
dbWriter.writeLookupSwitchInstruction(id, keyId, mid);
lookupSwitchMap.put(switchStmt, id);
}
else
{
writeNopStmt(mid, stmt);
}
}
}
private void writeJumpStmts(int mid, Body body) throws SQLException
{
for (Unit unit: body.getUnits())
{
Stmt stmt = (Stmt) unit;
if(stmt instanceof GotoStmt)
{
writeGotoStmt(mid, (GotoStmt) stmt);
}
else if(stmt instanceof IfStmt)
{
writeIfStmt(mid, (IfStmt) stmt);
}
else if(stmt instanceof TableSwitchStmt)
{
writeTableSwitchStmt(mid, (TableSwitchStmt) stmt);
}
else if(stmt instanceof LookupSwitchStmt)
{
writeLookupSwitchStmt(mid, (LookupSwitchStmt) stmt);
}
}
}
private void writeBody(int mid, Body body) throws SQLException
{
writeLocals(mid, body);
writeStmts(mid, body);
writeJumpStmts(mid, body);
writeTraps(mid, body);
}
private void writeMethodDecls(SootClass cl) throws SQLException {
for (SootMethod method: cl.getMethods())
{
int mid = methodMap.getIndex(method);
String name = method.getName();
String sig = method.getSignature();
int parentId = getTypeId(cl.getType());
int modifier = method.getModifiers();
dbWriter.writeMethod(mid, name, sig, parentId, modifier);
if (!(method.getReturnType() instanceof VoidType))
{
int tid = getTypeId(method.getReturnType());
dbWriter.writeMethodReturnType(mid, tid);
}
if (!method.isStatic())
{
SootVariable var = new ThisVariable(method);
int vid = varMap.getIndex(var);
dbWriter.writeVariable(vid, var.getName(), parentId, mid);
dbWriter.writeMethodThisParam(mid, vid);
}
for(int i = 0 ; i < method.getParameterCount(); i++)
{
SootVariable var = new ParamVariable(method, i);
int vid = varMap.getIndex(var);
int tid = getTypeId(method.getParameterType(i));
dbWriter.writeMethodParam(mid, i, vid);
dbWriter.writeVariable(vid, var.getName(), tid, mid);
}
for (SootClass exceptClass: method.getExceptions())
{
assert(!exceptClass.isInterface());
int eid = typeMap.getIndexOrFail(exceptClass.getType());
dbWriter.writeExceptionDeclaration(mid, eid);
}
}
}
private void writeMethodBodys(SootClass cl, boolean ssa) throws SQLException
{
for (SootMethod method: cl.getMethods())
{
int mid = methodMap.getIndexOrFail(method);
if (!method.isAbstract() && !method.isNative() && !method.isPhantom())
{
// This is an EXTREMELY slow operation
if (!method.hasActiveBody())
method.retrieveActiveBody();
// Transform to SSA
Body body = method.getActiveBody();
if (ssa) {
body = Shimple.v().newBody(body);
method.setActiveBody(body);
}
writeBody(mid, body);
method.releaseActiveBody();
}
}
}
private void writeClass(SootClass cl) throws SQLException
{
String name = cl.getName();
int id = typeMap.getIndex(cl.getType());
if (cl.isInterface())
{
dbWriter.writeInterfaceType(id, name);
}
else
{
dbWriter.writeClassType(id, name);
if (cl.hasSuperclass())
{
int sid = typeMap.getIndex(cl.getSuperclass().getType());
dbWriter.writeSuperclass(id, sid);
}
}
for (SootClass iface: cl.getInterfaces())
{
int sid = typeMap.getIndex(iface.getType());
dbWriter.writeSuperinterface(id, sid);
}
}
private void writeClasses(List<SootClass> classes, boolean ssa) throws SQLException
{
writeNullType();
writePrimitiveTypes();
for (SootClass cl: classes)
writeClass(cl);
for (SootClass cl: classes)
writeFields(cl);
for (SootClass cl: classes) {
writeMethodDecls(cl);
}
for (SootClass cl: classes) {
writeMethodBodys(cl, ssa);
}
}
public static void writeJimple(String outfile, List<SootClass> classes, boolean ssa)
{
Connection connection = null;
try
{
connection = DriverManager.getConnection("jdbc:sqlite:" + outfile);
// We really don't care about transaction semantics: if something went wrong, just restart the entire process.
connection.setAutoCommit(false);
JimpleWriter writer = new JimpleWriter(connection);
System.out.println("[JimpleDumper] Database connection established");
long startTime = System.currentTimeMillis();
writer.writeClasses(classes, ssa);
connection.commit();
double elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
System.out.println("[JimpleDumper] Database transaction takes " + elapsedTime + " seconds to finish");
System.out.println("[JimpleDumper] Program serialization succeeded");
} catch (SQLException e)
{
System.err.println("[JimpleDumper] Jimple serialization failed: " + e.getMessage());
} finally
{
try
{
if (connection != null)
connection.close();
} catch (SQLException e)
{
System.err.println("[JimpleDumper] Jimple serialization failed: " + e.getMessage());
}
}
}
}
|
package edu.wustl.xipHost.avt2ext;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.io.DicomOutputStream;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.nema.dicom.wg23.ObjectDescriptor;
import org.nema.dicom.wg23.ObjectLocator;
import org.nema.dicom.wg23.Uuid;
import com.siemens.scr.avt.ad.annotation.ImageAnnotation;
import com.siemens.scr.avt.ad.api.ADFacade;
import edu.wustl.xipHost.dataAccess.DataAccessListener;
import edu.wustl.xipHost.dataAccess.Retrieve;
import edu.wustl.xipHost.dataAccess.RetrieveEvent;
import edu.wustl.xipHost.dataModel.Item;
import edu.wustl.xipHost.dataModel.Patient;
import edu.wustl.xipHost.dataModel.SearchResult;
import edu.wustl.xipHost.dataModel.Series;
import edu.wustl.xipHost.dataModel.Study;
import edu.wustl.xipHost.iterator.Criteria;
import edu.wustl.xipHost.iterator.RetrieveTarget;
import edu.wustl.xipHost.iterator.TargetElement;
public class AVTRetrieve2 implements Retrieve {
final static Logger logger = Logger.getLogger(AVTRetrieve2.class);
ADFacade adService = AVTFactory.getADServiceInstance();
TargetElement targetElement;
RetrieveTarget retrieveTarget;
File importDir;
public AVTRetrieve2(File importDir){
this.importDir = importDir;
}
public AVTRetrieve2(TargetElement targetElement, RetrieveTarget retrieveTarget, File importDir) throws IOException{
this.targetElement = targetElement;
this.retrieveTarget = retrieveTarget;
this.importDir = importDir;
}
@Override
public void setRetrieve(TargetElement targetElement, RetrieveTarget retrieveTarget) {
this.targetElement = targetElement;
this.retrieveTarget = retrieveTarget;
}
public void run() {
try {
logger.info("Executing AVT retrieve.");
retrieve(targetElement, retrieveTarget);
fireResultsAvailable(targetElement.getId());
} catch (IOException e) {
logger.error(e, e);
return;
}
}
SAXBuilder builder = new SAXBuilder();
Document document;
Map<String, ObjectLocator> objectLocators;
XMLOutputter outToXMLFile = new XMLOutputter();
void retrieve(TargetElement targetElement, RetrieveTarget retrieveTarget) throws IOException {
objectLocators = new HashMap<String, ObjectLocator>();
SearchResult subSearchResult = targetElement.getSubSearchResult();
Criteria originalCriteria = subSearchResult.getOriginalCriteria();
Map<Integer, Object> dicomCriteria = originalCriteria.getDICOMCriteria();
Map<String, Object> aimCriteria = originalCriteria.getAIMCriteria();
List<Patient> patients = subSearchResult.getPatients();
for(Patient patient : patients){
dicomCriteria.put(Tag.PatientName, patient.getPatientName());
dicomCriteria.put(Tag.PatientID, patient.getPatientID());
List<Study> studies = patient.getStudies();
for(Study study : studies){
dicomCriteria.put(Tag.StudyInstanceUID, study.getStudyInstanceUID());
List<Series> series = study.getSeries();
for(Series oneSeries : series){
dicomCriteria.put(Tag.SeriesInstanceUID, oneSeries.getSeriesInstanceUID());
if(aimCriteria == null){
logger.debug("AD AIM criteria: " + aimCriteria);
}else{
logger.debug("AD AIM retrieve criteria:");
Set<String> keys = aimCriteria.keySet();
Iterator<String> iter = keys.iterator();
while(iter.hasNext()){
String key = iter.next();
String value = (String) aimCriteria.get(key);
if(!value.isEmpty()){
logger.debug("Key: " + key + " Value: " + value);
}
}
}
File dirPath = importDir.getAbsoluteFile();
List<ObjectDescriptor> objectDescriptors = new ArrayList<ObjectDescriptor>();
List<Item> items = oneSeries.getItems();
for(Item item : items){
objectDescriptors.add(item.getObjectDescriptor());
}
if(retrieveTarget == RetrieveTarget.DICOM_AND_AIM){
//Retrieve DICOM
//If oneSeries contains subset of items, narrow dicomCriteria to individual SOPInstanceUIDs
//Then retrieve data item by item
if(oneSeries.containsSubsetOfItems()){
for(Item item : items){
String itemSOPInstanceUID = item.getItemID();
dicomCriteria.put(Tag.SOPInstanceUID, itemSOPInstanceUID);
List<DicomObject> retrievedDICOM = adService.retrieveDicomObjs(dicomCriteria, aimCriteria);
int i = 0;
for(i = 0; i < retrievedDICOM.size(); i++){
DicomObject dicom = retrievedDICOM.get(i);
String filePrefix = dicom.getString(Tag.SOPInstanceUID);
try {
File file = new File(importDir.getAbsolutePath() + File.separatorChar + filePrefix);
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicom);
dout.close();
ObjectLocator objLoc = new ObjectLocator();
Uuid itemUUID = item.getObjectDescriptor().getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(file.getAbsolutePath());
item.setObjectLocator(objLoc);
objectLocators.put(itemUUID.getUuid(), objLoc);
} catch (IOException e) {
logger.error(e, e);
}
}
//Retrieve AIM
List<String> annotationUIDs = adService.findAnnotations(dicomCriteria, aimCriteria);
Set<String> uniqueAnnotUIDs = new HashSet<String>(annotationUIDs);
Iterator<String> iter = uniqueAnnotUIDs.iterator();
while(iter.hasNext()){
String uid = iter.next();
ImageAnnotation loadedAnnot = adService.getAnnotation(uid);
String strXML = loadedAnnot.getAIM();
byte[] source = strXML.getBytes();
InputStream is = new ByteArrayInputStream(source);
try {
document = builder.build(is);
} catch (JDOMException e) {
logger.error(e, e);
}
//Ensure dirPath is correctly assign. There are references below of this variable
File outFile = new File(dirPath + File.separator + uid);
FileOutputStream outStream = new FileOutputStream(outFile);
outToXMLFile.output(document, outStream);
outStream.flush();
outStream.close();
//retrievedFiles.add(outFile);
ObjectLocator objLoc = new ObjectLocator();
Uuid itemUUID = item.getObjectDescriptor().getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(outFile.getAbsolutePath());
item.setObjectLocator(objLoc);
objectLocators.put(itemUUID.getUuid(), objLoc);
//Retrieve DICOM SEG
//temporarily voided. AVTQuery needs to be modified to query for DICOM SEG objects
Set<String> dicomSegSOPInstanceUIDs = new HashSet<String>();
List<DicomObject> segObjects = adService.retrieveSegmentationObjects(uid);
for(int j = 0; j < segObjects.size(); j++){
DicomObject dicom = segObjects.get(j);
String sopInstanceUID = dicom.getString(Tag.SOPInstanceUID);
//Check if DICOM SEG was not serialized in reference to another AIM
if(!dicomSegSOPInstanceUIDs.contains(sopInstanceUID)){
dicomSegSOPInstanceUIDs.add(sopInstanceUID);
DicomObject dicomSeg = adService.getDicomObject(sopInstanceUID);
String message = "DICOM SEG " + sopInstanceUID + " cannot be loaded from file system!";
if(dicomSeg == null){
throw new FileNotFoundException(message);
} else {
//TODO DICOM SEG tmp file not found e.g. DICOM SEG belongs to not specified Study for which TargetIteratorRunner was not requested
File outDicomSegFile = new File(dirPath + File.separator + sopInstanceUID);
FileOutputStream fos = new FileOutputStream(outDicomSegFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicomSeg);
dout.close();
//retrievedFiles.add(outDicomSegFile);
ObjectLocator dicomSegObjLoc = new ObjectLocator();
Item itemDicomSeg = items.get(i);
Uuid dicomSegItemUUID = itemDicomSeg.getObjectDescriptor().getUuid();
dicomSegObjLoc.setUuid(dicomSegItemUUID);
dicomSegObjLoc.setUri(outDicomSegFile.getAbsolutePath());
item.setObjectLocator(dicomSegObjLoc);
objectLocators.put(dicomSegItemUUID.getUuid(), dicomSegObjLoc);
}
}
}
}
}
//Reset value of SOPInstanceUID in dicomCriteria
dicomCriteria.remove(Tag.SOPInstanceUID);
} else {
List<DicomObject> retrievedDICOM = adService.retrieveDicomObjs(dicomCriteria, aimCriteria);
int i = 0;
for(i = 0; i < retrievedDICOM.size(); i++){
DicomObject dicom = retrievedDICOM.get(i);
String filePrefix = dicom.getString(Tag.SOPInstanceUID);
try {
File file = new File(importDir.getAbsolutePath() + File.separatorChar + filePrefix);
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicom);
dout.close();
ObjectLocator objLoc = new ObjectLocator();
Item item = items.get(i);
Uuid itemUUID = item.getObjectDescriptor().getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(file.getAbsolutePath());
item.setObjectLocator(objLoc);
objectLocators.put(itemUUID.getUuid(), objLoc);
} catch (IOException e) {
logger.error(e, e);
}
}
//Retrieve AIM
List<String> annotationUIDs = adService.findAnnotations(dicomCriteria, aimCriteria);
Set<String> uniqueAnnotUIDs = new HashSet<String>(annotationUIDs);
Iterator<String> iter = uniqueAnnotUIDs.iterator();
while(iter.hasNext()){
String uid = iter.next();
ImageAnnotation loadedAnnot = adService.getAnnotation(uid);
String strXML = loadedAnnot.getAIM();
byte[] source = strXML.getBytes();
InputStream is = new ByteArrayInputStream(source);
try {
document = builder.build(is);
} catch (JDOMException e) {
logger.error(e, e);
}
//Ensure dirPath is correctly assign. There are references below of this variable
File outFile = new File(dirPath + File.separator + uid);
FileOutputStream outStream = new FileOutputStream(outFile);
outToXMLFile.output(document, outStream);
outStream.flush();
outStream.close();
//retrievedFiles.add(outFile);
ObjectLocator objLoc = new ObjectLocator();
Item item = items.get(i);
Uuid itemUUID = item.getObjectDescriptor().getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(outFile.getAbsolutePath());
item.setObjectLocator(objLoc);
objectLocators.put(itemUUID.getUuid(), objLoc);
//Retrieve DICOM SEG
//temporarily voided. AVTQuery needs to be modified to query for DICOM SEG objects
Set<String> dicomSegSOPInstanceUIDs = new HashSet<String>();
List<DicomObject> segObjects = adService.retrieveSegmentationObjects(uid);
for(int j = 0; j < segObjects.size(); j++){
DicomObject dicom = segObjects.get(j);
String sopInstanceUID = dicom.getString(Tag.SOPInstanceUID);
//Check if DICOM SEG was not serialized in reference to another AIM
if(!dicomSegSOPInstanceUIDs.contains(sopInstanceUID)){
dicomSegSOPInstanceUIDs.add(sopInstanceUID);
DicomObject dicomSeg = adService.getDicomObject(sopInstanceUID);
String message = "DICOM SEG " + sopInstanceUID + " cannot be loaded from file system!";
if(dicomSeg == null){
throw new FileNotFoundException(message);
} else {
//TODO DICOM SEG tmp file not found e.g. DICOM SEG belongs to not specified Study for which TargetIteratorRunner was not requested
File outDicomSegFile = new File(dirPath + File.separator + sopInstanceUID);
FileOutputStream fos = new FileOutputStream(outDicomSegFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicomSeg);
dout.close();
//retrievedFiles.add(outDicomSegFile);
ObjectLocator dicomSegObjLoc = new ObjectLocator();
Item itemDicomSeg = items.get(i);
Uuid dicomSegItemUUID = itemDicomSeg.getObjectDescriptor().getUuid();
dicomSegObjLoc.setUuid(dicomSegItemUUID);
dicomSegObjLoc.setUri(outDicomSegFile.getAbsolutePath());
item.setObjectLocator(dicomSegObjLoc);
objectLocators.put(dicomSegItemUUID.getUuid(), dicomSegObjLoc);
}
}
}
}
}
}
//Reset Series level dicomCriteria
dicomCriteria.remove(Tag.SeriesInstanceUID);
}
//Reset Study level dicomCriteria
dicomCriteria.remove(Tag.StudyInstanceUID);
}
//Reset Patient level dicomCriteria
dicomCriteria.remove(Tag.PatientName);
dicomCriteria.remove(Tag.PatientID);
}
}
void fireResultsAvailable(String targetElementID){
RetrieveEvent event = new RetrieveEvent(targetElementID);
listener.retrieveResultsAvailable(event);
}
DataAccessListener listener;
@Override
public void addDataAccessListener(DataAccessListener l) {
listener = l;
}
public Map<String, ObjectLocator> getObjectLocators(){
return objectLocators;
}
}
|
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.CharacterizationFileBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
import gov.nih.nci.calab.dto.inventory.AliquotBean;
import gov.nih.nci.calab.dto.inventory.ContainerBean;
import gov.nih.nci.calab.dto.inventory.ContainerInfoBean;
import gov.nih.nci.calab.dto.inventory.SampleBean;
import gov.nih.nci.calab.dto.workflow.AssayBean;
import gov.nih.nci.calab.dto.workflow.RunBean;
import gov.nih.nci.calab.exception.InvalidSessionException;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CalabComparators;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.CananoConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import gov.nih.nci.security.exceptions.CSException;
import gov.nih.nci.calab.dto.LabFileBean;
import gov.nih.nci.common.util.StringHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* This class sets up session level or servlet context level variables to be
* used in various actions during the setup of query forms.
*
* @author pansu
*
*/
public class InitSessionSetup {
private static LookupService lookupService;
private static UserService userService;
private InitSessionSetup() throws Exception {
lookupService = new LookupService();
userService = new UserService(CalabConstants.CSM_APP_NAME);
}
public static InitSessionSetup getInstance() throws Exception {
return new InitSessionSetup();
}
public void setCurrentRun(HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
String runId = (String) request.getParameter("runId");
if (runId == null && session.getAttribute("currentRun") == null) {
throw new InvalidSessionException(
"The session containing a run doesn't exists.");
} else if (runId == null && session.getAttribute("currentRun") != null) {
RunBean currentRun = (RunBean) session.getAttribute("currentRun");
runId = currentRun.getId();
}
if (session.getAttribute("currentRun") == null
|| session.getAttribute("newRunCreated") != null) {
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
RunBean runBean = executeWorkflowService.getCurrentRun(runId);
session.setAttribute("currentRun", runBean);
}
session.removeAttribute("newRunCreated");
}
public void clearRunSession(HttpSession session) {
session.removeAttribute("currentRun");
}
public void setAllUsers(HttpSession session) throws Exception {
if ((session.getAttribute("newUserCreated") != null)
|| (session.getServletContext().getAttribute("allUsers") == null)) {
List allUsers = userService.getAllUsers();
session.getServletContext().setAttribute("allUsers", allUsers);
}
session.removeAttribute("newUserCreated");
}
public void setSampleSourceUnmaskedAliquots(HttpSession session)
throws Exception {
// set map between sample source and samples that have unmasked aliquots
if (session.getAttribute("sampleSourceSamplesWithUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
Map<String, SortedSet<SampleBean>> sampleSourceSamples = lookupService
.getSampleSourceSamplesWithUnmaskedAliquots();
session.setAttribute("sampleSourceSamplesWithUnmaskedAliquots",
sampleSourceSamples);
List<String> sources = new ArrayList<String>(sampleSourceSamples
.keySet());
session.setAttribute("allSampleSourcesWithUnmaskedAliquots",
sources);
}
setAllSampleUnmaskedAliquots(session);
session.removeAttribute("newAliquotCreated");
}
public void clearSampleSourcesWithUnmaskedAliquotsSession(
HttpSession session) {
session.removeAttribute("allSampleSourcesWithUnmaskedAliquots");
}
public void setAllSampleUnmaskedAliquots(HttpSession session)
throws Exception {
// set map between samples and unmasked aliquots
if (session.getAttribute("allUnmaskedSampleAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
Map<String, SortedSet<AliquotBean>> sampleAliquots = lookupService
.getUnmaskedSampleAliquots();
List<String> sampleNames = new ArrayList<String>(sampleAliquots
.keySet());
Collections.sort(sampleNames,
new CalabComparators.SortableNameComparator());
session.setAttribute("allUnmaskedSampleAliquots", sampleAliquots);
session.setAttribute("allSampleNamesWithAliquots", sampleNames);
}
session.removeAttribute("newAliquotCreated");
}
public void clearSampleUnmaskedAliquotsSession(HttpSession session) {
session.removeAttribute("allUnmaskedSampleAliquots");
session.removeAttribute("allSampleNamesWithAliquots");
}
public void setAllAssayTypeAssays(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.getServletContext().setAttribute("allAssayTypes",
assayTypes);
}
if (session.getServletContext().getAttribute("allAssayTypeAssays") == null) {
Map<String, SortedSet<AssayBean>> assayTypeAssays = lookupService
.getAllAssayTypeAssays();
List<String> assayTypes = new ArrayList<String>(assayTypeAssays
.keySet());
session.getServletContext().setAttribute("allAssayTypeAssays",
assayTypeAssays);
session.getServletContext().setAttribute("allAvailableAssayTypes",
assayTypes);
}
}
public void setAllSampleSources(HttpSession session) throws Exception {
if (session.getAttribute("allSampleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSources = lookupService.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleSourcesSession(HttpSession session) {
session.removeAttribute("allSampleSources");
}
public void setAllSampleContainerTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allSampleContainerTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List containerTypes = lookupService.getAllSampleContainerTypes();
session.setAttribute("allSampleContainerTypes", containerTypes);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleContainerTypesSession(HttpSession session) {
session.removeAttribute("allSampleContainerTypes");
}
public void setAllSampleTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.getServletContext().setAttribute("allSampleTypes",
sampleTypes);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleTypesSession(HttpSession session) {
session.removeAttribute("allSampleTypes");
}
public void setAllSampleSOPs(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSampleSOPs") == null) {
List sampleSOPs = lookupService.getAllSampleSOPs();
session.getServletContext().setAttribute("allSampleSOPs",
sampleSOPs);
}
}
public void setAllSampleContainerInfo(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("sampleContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.getServletContext().setAttribute("sampleContainerInfo",
containerInfo);
}
}
public void setCurrentUser(HttpSession session) throws Exception {
// get user and date information
String creator = "";
if (session.getAttribute("user") != null) {
UserBean user = (UserBean) session.getAttribute("user");
creator = user.getLoginName();
}
String creationDate = StringUtils.convertDateToString(new Date(),
CalabConstants.DATE_FORMAT);
session.setAttribute("creator", creator);
session.setAttribute("creationDate", creationDate);
}
public void setAllAliquotContainerTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allAliquotContainerTypes") == null
|| session.getAttribute("newAliquotCreated") != null) {
List containerTypes = lookupService.getAllAliquotContainerTypes();
session.setAttribute("allAliquotContainerTypes", containerTypes);
}
}
public void clearAliquotContainerTypesSession(HttpSession session) {
session.removeAttribute("allAliquotContainerTypes");
}
public void setAllAliquotContainerInfo(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("aliquotContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.getServletContext().setAttribute("aliquotContainerInfo",
containerInfo);
}
}
public void setAllAliquotCreateMethods(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("aliquotCreateMethods") == null) {
List methods = lookupService.getAliquotCreateMethods();
session.getServletContext().setAttribute("aliquotCreateMethods",
methods);
}
}
public void setAllSampleContainers(HttpSession session) throws Exception {
if (session.getAttribute("allSampleContainers") == null
|| session.getAttribute("newSampleCreated") != null) {
Map<String, SortedSet<ContainerBean>> sampleContainers = lookupService
.getAllSampleContainers();
List<String> sampleNames = new ArrayList<String>(sampleContainers
.keySet());
Collections.sort(sampleNames,
new CalabComparators.SortableNameComparator());
session.setAttribute("allSampleContainers", sampleContainers);
session.setAttribute("allSampleNames", sampleNames);
}
session.removeAttribute("newSampleCreated");
}
public void clearSampleContainersSession(HttpSession session) {
session.removeAttribute("allSampleContainers");
session.removeAttribute("allSampleNames");
}
public void setAllSourceSampleIds(HttpSession session) throws Exception {
if (session.getAttribute("allSourceSampleIds") == null
|| session.getAttribute("newSampleCreated") != null) {
List sourceSampleIds = lookupService.getAllSourceSampleIds();
session.setAttribute("allSourceSampleIds", sourceSampleIds);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSourceSampleIdsSession(HttpSession session) {
session.removeAttribute("allSourceSampleIds");
}
public void clearWorkflowSession(HttpSession session) {
clearRunSession(session);
clearSampleSourcesWithUnmaskedAliquotsSession(session);
clearSampleUnmaskedAliquotsSession(session);
session.removeAttribute("httpFileUploadSessionData");
}
public void clearSearchSession(HttpSession session) {
clearSampleTypesSession(session);
clearSampleContainerTypesSession(session);
clearAliquotContainerTypesSession(session);
clearSourceSampleIdsSession(session);
clearSampleSourcesSession(session);
session.removeAttribute("aliquots");
session.removeAttribute("sampleContainers");
}
public void clearInventorySession(HttpSession session) {
clearSampleTypesSession(session);
clearSampleContainersSession(session);
clearSampleContainerTypesSession(session);
clearSampleUnmaskedAliquotsSession(session);
clearAliquotContainerTypesSession(session);
session.removeAttribute("createSampleForm");
session.removeAttribute("createAliquotForm");
session.removeAttribute("aliquotMatrix");
}
public static LookupService getLookupService() {
return lookupService;
}
public static UserService getUserService() {
return userService;
}
public boolean canUserExecuteClass(HttpSession session, Class classObj)
throws CSException {
UserBean user = (UserBean) session.getAttribute("user");
// assume the part of the package name containing the function domain
// is the same as the protection element defined in CSM
String[] nameStrs = classObj.getName().split("\\.");
String domain = nameStrs[nameStrs.length - 2];
return userService.checkExecutePermission(user, domain);
}
public void setAllParticleTypeParticles(HttpSession session)
throws Exception {
if (session.getAttribute("allParticleTypeParticles") == null
|| session.getAttribute("newSampleCreated") != null) {
Map<String, SortedSet<String>> particleTypeParticles = lookupService
.getAllParticleTypeParticles();
List<String> particleTypes = new ArrayList<String>(
particleTypeParticles.keySet());
Collections.sort(particleTypes);
session.setAttribute("allParticleTypeParticles",
particleTypeParticles);
session.setAttribute("allParticleTypes", particleTypes);
}
session.removeAttribute("newParticleCreated");
}
public void setAllVisibilityGroups(HttpSession session) throws Exception {
if (session.getAttribute("allVisibilityGroups") == null
|| session.getAttribute("newSampleCreated") != null) {
List<String> groupNames = userService.getAllVisibilityGroups();
session.setAttribute("allVisibilityGroups", groupNames);
}
}
public void setAllDendrimerCores(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allDendrimerCores") == null) {
String[] dendrimerCores = lookupService.getAllDendrimerCores();
session.getServletContext().setAttribute("allDendrimerCores",
dendrimerCores);
}
}
public void setAllDendrimerSurfaceGroupNames(HttpSession session)
throws Exception {
System.out.println("sesion attribute = "
+ session.getAttribute("newCharacterizationCreated"));
System.out.println("allDendrimerSurfaceGroupNames = "
+ session.getServletContext().getAttribute(
"allDendrimerSurfaceGroupNames"));
if (session.getServletContext().getAttribute(
"allDendrimerSurfaceGroupNames") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] surfaceGroupNames = lookupService
.getAllDendrimerSurfaceGroupNames();
session.getServletContext().setAttribute(
"allDendrimerSurfaceGroupNames", surfaceGroupNames);
}
}
public void setAllDendrimerBranches(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allDendrimerBranches") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] branches = lookupService.getAllDendrimerBranches();
session.getServletContext().setAttribute("allDendrimerBranches",
branches);
}
}
public void setAllDendrimerGenerations(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("allDendrimerGenerations") == null) {
String[] generations = lookupService.getAllDendrimerGenerations();
session.getServletContext().setAttribute("allDendrimerGenerations",
generations);
}
}
public void addSessionAttributeElement(HttpSession session,
String attributeName, String newElement) throws Exception {
String[] attributeValues = (String[]) session.getServletContext()
.getAttribute(attributeName);
if (!StringHelper.contains(attributeValues, newElement, true)) {
session.getServletContext().setAttribute(attributeName,
StringHelper.add(attributeValues, newElement));
}
}
public void setAllMetalCompositions(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allMetalCompositions") == null) {
String[] compositions = lookupService.getAllMetalCompositions();
session.getServletContext().setAttribute("allMetalCompositions",
compositions);
}
}
public void setAllPolymerInitiators(HttpSession session) throws Exception {
if ((session.getServletContext().getAttribute("allPolymerInitiators") == null)
|| (session.getAttribute("newCharacterizationCreated") != null)) {
String[] initiators = lookupService.getAllPolymerInitiators();
session.getServletContext().setAttribute("allPolymerInitiators",
initiators);
}
}
public void setAllParticleFunctionTypes(HttpSession session)
throws Exception {
if (session.getServletContext()
.getAttribute("allParticleFunctionTypes") == null) {
String[] functions = lookupService.getAllParticleFunctions();
session.getServletContext().setAttribute(
"allParticleFunctionTypes", functions);
}
}
public void setAllParticleSources(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allParticleSources") == null) {
List<String> sources = lookupService.getAllParticleSources();
session.getServletContext().setAttribute("allParticleSources",
sources);
}
}
public void setAllParticleCharacterizationTypes(HttpSession session)
throws Exception {
if (session.getServletContext()
.getAttribute("allCharacterizationTypes") == null) {
String[] charTypes = lookupService.getAllCharacterizationTypes();
session.getServletContext().setAttribute(
"allCharacterizationTypes", charTypes);
}
}
public void setSideParticleMenu(HttpServletRequest request,
String particleName, String particleType) throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute("charTypeChars") == null
|| session.getAttribute("newCharacterizationCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
SearchNanoparticleService service = new SearchNanoparticleService();
List<CharacterizationBean> charBeans = service
.getCharacterizationInfo(particleName, particleType);
Map<String, List<CharacterizationBean>> existingCharTypeChars = new HashMap<String, List<CharacterizationBean>>();
if (!charBeans.isEmpty()) {
Map<String, String[]> charTypeChars = lookupService
.getCharacterizationTypeCharacterizations();
for (String charType : charTypeChars.keySet()) {
List<CharacterizationBean> newCharBeans = new ArrayList<CharacterizationBean>();
List<String> charList = Arrays.asList(charTypeChars
.get(charType));
for (CharacterizationBean charBean : charBeans) {
if (charList.contains(charBean.getName())) {
newCharBeans.add(charBean);
}
}
if (!newCharBeans.isEmpty()) {
existingCharTypeChars.put(charType, newCharBeans);
}
}
}
session.setAttribute("charTypeChars", existingCharTypeChars);
List<LabFileBean> reportBeans = service.getReportInfo(particleName,
particleType);
session.setAttribute("charTypeReports", reportBeans);
}
session.removeAttribute("newCharacterizationCreated");
if (session.getAttribute("funcTypeFuncs") == null
|| session.getAttribute("newFunctionCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
SearchNanoparticleService service = new SearchNanoparticleService();
Map<String, List<FunctionBean>> funcTypeFuncs = service
.getFunctionInfo(particleName, particleType);
session.setAttribute("funcTypeFuncs", funcTypeFuncs);
}
session.removeAttribute("newFunctionCreated");
session.removeAttribute("newParticleCreated");
session.removeAttribute("detailPage");
setStaticDropdowns(session);
}
public void setCharacterizationTypeCharacterizations(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allCharacterizationTypeCharacterizations") == null) {
Map<String, String[]> charTypeChars = lookupService
.getCharacterizationTypeCharacterizations();
session.getServletContext().setAttribute(
"allCharacterizationTypeCharacterizations", charTypeChars);
}
}
public String setAllInstrumentTypes(HttpSession session) throws Exception {
String rv = "";
if (session.getServletContext().getAttribute("allInstrumentTypes") == null) {
String[] instrumentTypes = lookupService.getAllInstrumentTypes();
session.getServletContext().setAttribute("allInstrumentTypes",
instrumentTypes);
if (instrumentTypes != null && instrumentTypes.length > 0)
rv = instrumentTypes[0];
}
return rv;
}
public void setManufacturerPerType(HttpSession session,
String instrumentType) throws Exception {
/*
* if (session.getServletContext().getAttribute("manufacturerPerType") ==
* null) { String[] manufacturerPerType = new String[]
* {"Manufacturer#1",
* "Manufacturer#2"};//lookupService.getAllInstrumentTypes();
* session.getServletContext().setAttribute("manufacturerPerType",
* manufacturerPerType); }
*/
if (session.getServletContext().getAttribute("manufacturerPerType") != null) {
session.getServletContext().removeAttribute("manufacturerPerType");
}
String[] manufacturerPerType = lookupService
.getManufacturers(instrumentType);
session.getServletContext().setAttribute("manufacturerPerType",
manufacturerPerType);
}
public void setAllSizeDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allSizeDistributionGraphTypes") == null) {
String[] graphTypes = lookupService.getSizeDistributionGraphTypes();
session.getServletContext().setAttribute(
"allSizeDistributionGraphTypes", graphTypes);
}
}
public void setAllMolecularWeightDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allMolecularWeightDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getMolecularWeightDistributionGraphTypes();
session.getServletContext().setAttribute(
"allMolecularWeightDistributionGraphTypes", graphTypes);
}
}
public void setAllMorphologyDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allMorphologyDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getMorphologyDistributionGraphTypes();
session.getServletContext().setAttribute(
"allMorphologyDistributionGraphTypes", graphTypes);
}
}
public void setAllShapeDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allShapeDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getShapeDistributionGraphTypes();
session.getServletContext().setAttribute(
"allShapeDistributionGraphTypes", graphTypes);
}
}
public void setAllStabilityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allStabilityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getStabilityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allStabilityDistributionGraphTypes", graphTypes);
}
}
public void setAllPurityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allPurityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getPurityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allPurityDistributionGraphTypes", graphTypes);
}
}
public void setAllSolubilityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allSolubilityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getSolubilityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allSolubilityDistributionGraphTypes", graphTypes);
}
}
public void setAllMorphologyTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allMorphologyTypes") == null) {
String[] morphologyTypes = lookupService.getAllMorphologyTypes();
session.getServletContext().setAttribute("allMorphologyTypes",
morphologyTypes);
}
}
public void setAllShapeTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allShapeTypes") == null) {
String[] shapeTypes = lookupService.getAllShapeTypes();
session.getServletContext().setAttribute("allShapeTypes",
shapeTypes);
}
}
public void setAllStressorTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allStessorTypes") == null) {
String[] stressorTypes = lookupService.getAllStressorTypes();
session.getServletContext().setAttribute("allStressorTypes",
stressorTypes);
}
}
public void setStaticDropdowns(HttpSession session) {
// set static boolean yes or no and characterization source choices
session.setAttribute("booleanChoices", CananoConstants.BOOLEAN_CHOICES);
session.setAttribute("characterizationSources",
CananoConstants.CHARACTERIZATION_SOURCES);
session.setAttribute("allCarbonNanotubeWallTypes",
CananoConstants.CARBON_NANOTUBE_WALLTYPES);
session.setAttribute("allReportTypes", CananoConstants.REPORT_TYPES);
}
public void setAllRunFiles(HttpSession session, String particleName)
throws Exception {
if (session.getAttribute("allRunFiles") == null
|| session.getAttribute("newParticleCreated") != null
|| session.getAttribute("newRunCreated") != null) {
SubmitNanoparticleService service = new SubmitNanoparticleService();
List<CharacterizationFileBean> runFileBeans = service
.getAllRunFiles(particleName);
session.setAttribute("allRunFiles", runFileBeans);
}
session.removeAttribute("newParticleCreated");
session.removeAttribute("newRunCreated");
}
public void setAllAreaMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAreaMeasureUnits") == null) {
String[] areaUnits = lookupService.getAllAreaMeasureUnits();
session.getServletContext().setAttribute("allAreaMeasureUnits",
areaUnits);
}
}
public void setAllChargeMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allChargeMeasureUnits") == null) {
String[] chargeUnits = lookupService.getAllChargeMeasureUnits();
session.getServletContext().setAttribute("allChargeMeasureUnits",
chargeUnits);
}
}
public void setAllControlTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allControlTypes") == null) {
String[] controlTypes = lookupService.getAllControlTypes();
session.getServletContext().setAttribute("allControlTypes",
controlTypes);
}
}
public void setAllConditionTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypes") == null) {
String[] conditionTypes = lookupService.getAllConditionTypes();
session.getServletContext().setAttribute("allConditionTypes",
conditionTypes);
}
}
public void setAllConditionUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypeUnits") == null) {
Map<String, SortedSet<String>> conditionTypeUnits = lookupService
.getAllConditionUnits();
List<String> conditionUnits = new ArrayList<String>(
conditionTypeUnits.keySet());
Collections.sort(conditionUnits);
session.getServletContext().setAttribute("allConditionTypeUnits",
conditionTypeUnits);
session.getServletContext().setAttribute("allConditionUnits",
conditionUnits);
}
}
public void setAllAgentTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTypes") == null) {
Map<String, String[]> agentTypes = lookupService.getAllAgentTypes();
session.getServletContext().setAttribute("allAgentTypes",
agentTypes);
}
}
public void setAllAgentTargetTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTargetTypes") == null) {
Map<String, String[]> agentTargetTypes = lookupService
.getAllAgentTargetTypes();
session.getServletContext().setAttribute("allAgentTargetTypes",
agentTargetTypes);
}
}
public void setAllTimeUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allTimeUnits") == null) {
String[] timeUnits = lookupService.getAllTimeUnits();
session.getServletContext().setAttribute("allTimeUnits", timeUnits);
}
}
public void setAllConcentrationUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConcentrationUnits") == null) {
String[] concentrationUnits = lookupService
.getAllConcentrationUnits();
session.getServletContext().setAttribute("allConcentrationUnits",
concentrationUnits);
}
}
public void setAllCellLines(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allCellLines") == null) {
String[] cellLines = lookupService.getAllCellLines();
session.getServletContext().setAttribute("allCellLines", cellLines);
}
}
public void setAllActivationMethods(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allActivationMethods") == null) {
String[] activationMethods = lookupService.getAllActivationMethods();
session.getServletContext().setAttribute("allActivationMethods", activationMethods);
}
}
// public void addCellLine(HttpSession session, String option) throws
// Exception {
// String[] cellLines = (String[])
// session.getServletContext().getAttribute("allCellLines");
// if (!StringHelper.contains(cellLines, option, true)) {
// session.getServletContext().setAttribute("allCellLines",
// StringHelper.add(cellLines, option));
}
|
package dr.app.beauti.options;
import dr.app.beauti.traitspanel.GuessTraitException;
import dr.evolution.util.TaxonList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Andrew Rambaut
* @author Walter Xie
*/
public class TraitGuesser {
private final TraitData traitData;
public TraitGuesser(TraitData traitData) {
this.traitData = traitData;
}
public static enum GuessType {
DELIMITER,
REGEX
}
private GuessType guessType = GuessType.DELIMITER;
private int order = 0;
private String delimiter;
private String regex;
public TraitData getTraitData() {
return traitData;
}
public GuessType getGuessType() {
return guessType;
}
public void setGuessType(GuessType guessType) {
this.guessType = guessType;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getDelimiter() {
return delimiter;
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public String getRegex() {
return regex;
}
public void setRegex(String regex) {
this.regex = regex;
}
public void guessTrait(TaxonList taxa) {
for (int i = 0; i < taxa.getTaxonCount(); i++) {
String value = null;
try {
switch (guessType) {
case DELIMITER:
value = guessTraitByDelimiter(taxa.getTaxonId(i), delimiter);
break;
case REGEX:
value = guessTraitFromRegex(taxa.getTaxonId(i), regex);
break;
default:
throw new IllegalArgumentException("unknown GuessType");
}
} catch (GuessTraitException gfe) {
}
taxa.getTaxon(i).setAttribute(traitData.getName(), value);
}
}
private String guessTraitByDelimiter(String label, String delimiter) throws GuessTraitException {
if (delimiter.length() < 1) {
throw new IllegalArgumentException("No delimiter");
}
String[] tokens = label.split(delimiter);
if (tokens.length < 2) {
throw new IllegalArgumentException("Can not find delimiter in taxon label (" + label + ")\n or invalid delimiter (" + delimiter + ").");
}
if (order >= 0) {
if (order >= tokens.length) {
throw new IllegalArgumentException("Insufficent delimiters in taxon lable (" + label + ")\n to find requested field.");
}
return tokens[order];
} else {
if (tokens.length + order < 0) {
throw new IllegalArgumentException("Insufficent delimiters in taxon lable (" + label + ")\n to find requested field.");
}
return tokens[tokens.length + order];
}
}
private String guessTraitFromRegex(String label, String regex) throws GuessTraitException {
String t;
if (!regex.contains("(")) {
// if user hasn't specified a replace element, assume the whole regex should match
regex = "(" + regex + ")";
}
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(label);
if (!matcher.find()) {
throw new GuessTraitException("Regular expression doesn't find a match in taxon label, " + label);
}
if (matcher.groupCount() < 1) {
throw new GuessTraitException("Trait value group not defined in regular expression");
}
t = matcher.group(1); // TODO: not working?
} catch (NumberFormatException nfe) {
throw new GuessTraitException("Badly formatted trait value in taxon label, " + label);
}
return t;
}
}
|
package eu.visualize.ini.convnet;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.TreeMap;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUquadric;
import com.jogamp.opengl.util.awt.TextRenderer;
import eu.seebetter.ini.chips.DavisChip;
import java.io.LineNumberReader;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventio.AEFileInputStream;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Labels location of target using mouse GUI in recorded data for later
* supervised learning.
*
* @author tobi
*/
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
@Description("Labels location of target using mouse GUI in recorded data for later supervised learning.")
public class TargetLabeler extends EventFilter2DMouseAdaptor implements PropertyChangeListener, KeyListener {
private boolean mousePressed = false;
private boolean shiftPressed = false;
private boolean ctlPressed = false;
private Point mousePoint = null;
final float labelRadius = 5f;
private GLUquadric mouseQuad = null;
private TreeMap<Integer, SimultaneouTargetLocations> targetLocations = new TreeMap();
private TargetLocation targetLocation = null;
private DavisChip apsDvsChip = null;
private int lastFrameNumber = -1;
private int lastTimestamp = Integer.MIN_VALUE;
private int currentFrameNumber = -1;
private final String LAST_FOLDER_KEY = "lastFolder";
TextRenderer textRenderer = null;
private int minTargetPointIntervalUs = getInt("minTargetPointIntervalUs", 2000);
private int targetRadius = getInt("targetRadius", 10);
private int maxTimeLastTargetLocationValidUs = getInt("maxTimeLastTargetLocationValidUs", 50000);
private int minSampleTimestamp = Integer.MAX_VALUE, maxSampleTimestamp = Integer.MIN_VALUE;
private final int N_FRACTIONS = 1000;
private boolean[] labeledFractions = new boolean[N_FRACTIONS]; // to annotate graphically what has been labeled so far in event stream
private boolean[] targetPresentInFractions = new boolean[N_FRACTIONS]; // to annotate graphically what has been labeled so far in event stream
private boolean showLabeledFraction = getBoolean("showLabeledFraction", true);
private boolean showHelpText = getBoolean("showHelpText", true);
// protected int maxTargets = getInt("maxTargets", 8);
protected int currentTargetTypeID = getInt("currentTargetTypeID", 0);
private ArrayList<TargetLocation> currentTargets = new ArrayList(10); // currently valid targets
protected boolean eraseSamplesEnabled = false;
private HashMap<String, String> mapDataFilenameToTargetFilename = new HashMap();
private boolean propertyChangeListenerAdded = false;
private String DEFAULT_FILENAME = "locations.txt";
private String lastFileName = getString("lastFileName", DEFAULT_FILENAME);
protected boolean showStatistics = getBoolean("showStatistics", true);
private String lastDataFilename = null;
private boolean locationsLoadedFromFile = false;
// file statistics
private long firstInputStreamTimestamp = 0, lastInputStreamTimestamp = 0, inputStreamDuration = 0;
private long filePositionEvents = 0, fileLengthEvents = 0;
private int filePositionTimestamp = 0;
private boolean warnSave = true;
public TargetLabeler(AEChip chip) {
super(chip);
if (chip instanceof DavisChip) {
apsDvsChip = ((DavisChip) chip);
}
setPropertyTooltip("minTargetPointIntervalUs", "minimum interval between target positions in the database in us");
setPropertyTooltip("targetRadius", "drawn radius of target in pixels");
setPropertyTooltip("maxTimeLastTargetLocationValidUs", "this time after last sample, the data is shown as not yet been labeled. This time specifies how long a specified target location is valid after its last specified location.");
setPropertyTooltip("saveLocations", "saves target locations");
setPropertyTooltip("saveLocationsAs", "show file dialog to save target locations to a new file");
setPropertyTooltip("loadLocations", "loads locations from a file");
setPropertyTooltip("clearLocations", "clears all existing targets");
setPropertyTooltip("resampleLabeling", "resamples the existing labeling to fill in null locations for unlabeled parts and fills in copies of latest location between samples, to specified minTargetPointIntervalUs");
setPropertyTooltip("showLabeledFraction", "shows labeled part of input by a bar with red=unlabeled, green=labeled, blue=current position");
setPropertyTooltip("showHelpText", "shows help text on screen. Uncheck to hide");
setPropertyTooltip("showStatistics", "shows statistics");
// setPropertyTooltip("maxTargets", "maximum number of simultaneous targets to label");
setPropertyTooltip("currentTargetTypeID", "ID code of current target to be labeled, e.g., 0=dog, 1=cat, etc. User must keep track of the mapping from ID codes to target classes.");
setPropertyTooltip("eraseSamplesEnabled", "Use this mode erase all samples up to minTargetPointIntervalUs before current time.");
Arrays.fill(labeledFractions, false);
Arrays.fill(targetPresentInFractions, false);
try {
byte[] bytes = getPrefs().getByteArray("TargetLabeler.hashmap", null);
if (bytes != null) {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
mapDataFilenameToTargetFilename = (HashMap<String, String>) in.readObject();
in.close();
log.info("loaded mapDataFilenameToTargetFilename: " + mapDataFilenameToTargetFilename.size() + " entries");
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void mouseDragged(MouseEvent e) {
Point p = (getMousePixel(e));
if (p != null) {
if (mousePoint != null) {
mousePoint.setLocation(p);
} else {
mousePoint = new Point(p);
}
} else {
mousePoint = null;
}
}
@Override
public void mouseReleased(MouseEvent e) {
mousePressed = false;
}
@Override
public void mousePressed(MouseEvent e) {
mouseMoved(e);
}
@Override
public void mouseMoved(MouseEvent e) {
Point p = (getMousePixel(e));
if (p != null) {
if (mousePoint != null) {
mousePoint.setLocation(p);
} else {
mousePoint = new Point(p);
}
} else {
mousePoint = null;
}
}
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
if (chip.getAeViewer().getPlayMode() != AEViewer.PlayMode.PLAYBACK) {
return;
}
GL2 gl = drawable.getGL().getGL2();
chipCanvas = chip.getCanvas();
if (chipCanvas == null) {
return;
}
glCanvas = (GLCanvas) chipCanvas.getCanvas();
if (glCanvas == null) {
return;
}
glu = GLU.createGLU(gl); // TODO check if this solves problem of bad GL context in file preview
if (isSelected()) {
Point mp = glCanvas.getMousePosition();
Point p = chipCanvas.getPixelFromPoint(mp);
if (p == null) {
return;
}
checkBlend(gl);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[currentTargetTypeID % targetTypeColors.length].getColorComponents(compArray), 0);
gl.glLineWidth(3f);
gl.glPushMatrix();
gl.glTranslatef(p.x, p.y, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glTranslatef(.5f, -.5f, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
// if (quad == null) {
// quad = glu.gluNewQuadric();
// glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL);
// glu.gluDisk(quad, 0, 3, 32, 1);
gl.glPopMatrix();
}
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 36));
textRenderer.setColor(1, 1, 1, 1);
}
MultilineAnnotationTextRenderer.setColor(Color.CYAN);
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .9f);
MultilineAnnotationTextRenderer.setScale(.3f);
StringBuilder sb = new StringBuilder();
if (showHelpText) {
sb.append("Shift + !Ctrl + mouse position: Specify no target present\n i.e. mark data as looked at\nClt + Shift + mouse position: Specify currentTargetTypeID is present at mouse location\n");
MultilineAnnotationTextRenderer.renderMultilineString(sb.toString());
}
if (showStatistics) {
MultilineAnnotationTextRenderer.renderMultilineString(String.format("%d TargetLocation labels specified\nFirst label time: %.1fs, Last label time: %.1fs\nCurrent frame number: %d\nCurrent # labels within maxTimeLastTargetLocationValidUs: %d",
targetLocations.size(),
minSampleTimestamp * 1e-6f,
maxSampleTimestamp * 1e-6f, getCurrentFrameNumber(),
currentTargets.size()));
if (shiftPressed && !ctlPressed) {
MultilineAnnotationTextRenderer.renderMultilineString("Specifying no target");
} else if (shiftPressed && ctlPressed) {
MultilineAnnotationTextRenderer.renderMultilineString("Specifying target location");
} else {
MultilineAnnotationTextRenderer.renderMultilineString("Playing recorded target locations");
}
}
for (TargetLocation t : currentTargets) {
if (t.location != null) {
t.draw(drawable, gl);
}
}
// show labeled parts
if (showLabeledFraction && (inputStreamDuration > 0)) {
float dx = chip.getSizeX() / (float) N_FRACTIONS;
float y = chip.getSizeY() / 5;
float dy = chip.getSizeY() / 50;
float x = 0;
for (int i = 0; i < N_FRACTIONS; i++) {
boolean b = labeledFractions[i];
if (b) {
gl.glColor3f(0, 1, 0);
} else {
gl.glColor3f(1, 0, 0);
}
gl.glRectf(x - (dx / 2), y, x + (dx / 2), y + (dy * (1 + (targetPresentInFractions[i] ? 1 : 0))));
// gl.glRectf(x-dx/2, y, x + dx/2, y + dy * (1 + (currentTargets.size())));
x += dx;
}
float curPosFrac = ((float) (filePositionTimestamp - firstInputStreamTimestamp) / inputStreamDuration);
x = curPosFrac * chip.getSizeX();
y = y + dy;
gl.glColor3f(1, 1, 1);
gl.glRectf(x - (dx * 6), y - (dy * 2), x, y + dy * 2);
}
}
synchronized public void doClearLocations() {
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
Arrays.fill(labeledFractions, false);
Arrays.fill(targetPresentInFractions, false);
currentTargets.clear();
locationsLoadedFromFile = false;
}
synchronized public void doSaveLocationsAs() {
String fn = mapDataFilenameToTargetFilename.get(lastDataFilename);
if (fn == null) {
fn = lastFileName == null ? DEFAULT_FILENAME : lastFileName;
}
JFileChooser c = new JFileChooser(fn);
c.setSelectedFile(new File(fn));
int ret = c.showSaveDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
// end filename with -targets.txt
File f = c.getSelectedFile();
String s = f.getPath();
if (!s.endsWith("-targets.txt")) {
int idxdot = s.lastIndexOf('.');
if (idxdot > 0) {
s = s.substring(0, idxdot);
}
s = s + "-targets.txt";
f = new File(s);
}
if (f.exists()) {
int r = JOptionPane.showConfirmDialog(glCanvas, "File " + f.toString() + " already exists, overwrite it?");
if (r != JOptionPane.OK_OPTION) {
return;
}
}
lastFileName = f.toString();
putString("lastFileName", lastFileName);
saveLocations(f);
warnSave = false;
}
public void doResampleLabeling() {
if (targetLocations == null) {
log.warning("null targetLocations - nothing to resample");
return;
}
if (chip.getAeViewer().getAePlayer().getAEInputStream() == null) {
log.warning("cannot label unless a file is being played back");
return;
}
if (targetLocations.size() == 0) {
log.warning("no locations labeled - will label entire recording with no visible targets");
}
Map.Entry<Integer, SimultaneouTargetLocations> prevTargets = targetLocations.firstEntry();
TreeMap<Integer, SimultaneouTargetLocations> newTargets = new TreeMap();
if (prevTargets != null) {
for (Map.Entry<Integer, SimultaneouTargetLocations> nextTargets : targetLocations.entrySet()) { // for each existing set of targets by timestamp key list
// if no label at all for minTargetPointIntervalUs, then add copy of last labels up to maxTimeLastTargetLocationValidUs,
// then add null labels after that
if ((nextTargets.getKey() - prevTargets.getKey()) > minTargetPointIntervalUs) {
int n = (nextTargets.getKey() - prevTargets.getKey()) / minTargetPointIntervalUs; // add this many total
int tCopy = prevTargets.getKey() + maxTimeLastTargetLocationValidUs; // add this many total
for (int i = 0; i < n; i++) {
int ts = prevTargets.getKey() + ((i + 1) * minTargetPointIntervalUs);
newTargets.put(ts, copyLocationsToNewTs(prevTargets.getValue(), ts, ts <= tCopy));
}
}
prevTargets = nextTargets;
}
}
// handle time after last label
AEFileInputStream fileInputStream = chip.getAeViewer().getAePlayer().getAEInputStream();
int tFirstLabel = prevTargets != null ? prevTargets.getKey() : fileInputStream.getFirstTimestamp();
int tLastLabel = fileInputStream.getLastTimestamp(); // TODO handle wrapped timestamp during recording
int frameNumber = prevTargets != null ? prevTargets.getValue().get(0).frameNumber : -1;
int n = (tLastLabel - tFirstLabel) / minTargetPointIntervalUs; // add this many total
for (int i = 0; i < n; i++) {
SimultaneouTargetLocations s = new SimultaneouTargetLocations();
int ts = tFirstLabel + ((i + 1) * minTargetPointIntervalUs);
TargetLocation addedNullLabel = new TargetLocation(frameNumber, ts, null, targetRadius, -1, -1);
s.add(addedNullLabel);
newTargets.put(ts, s);
}
targetLocations.putAll(newTargets);
fixLabeledFraction();
}
private SimultaneouTargetLocations copyLocationsToNewTs(SimultaneouTargetLocations src, int ts, boolean useOriginalLocation) {
SimultaneouTargetLocations s = new SimultaneouTargetLocations();
for (TargetLocation t : src) {
TargetLocation tNew = new TargetLocation(t.frameNumber, ts, useOriginalLocation ? t.location : null, targetRadius, t.dimx, t.dimy);
s.add(tNew);
}
return s;
}
synchronized public void doSaveLocations() {
if (warnSave) {
int ret = JOptionPane.showConfirmDialog(chip.getAeViewer().getFilterFrame(), "Really overwrite " + lastFileName + " ?", "Overwrite warning", JOptionPane.WARNING_MESSAGE);
if (ret != JOptionPane.YES_OPTION) {
log.info("save canceled");
return;
}
}
File f = new File(lastFileName);
saveLocations(new File(lastFileName));
}
synchronized public void doLoadLocations() {
if (lastFileName == null) {
lastFileName = mapDataFilenameToTargetFilename.get(lastDataFilename);
}
if (lastFileName == null) {
lastFileName = DEFAULT_FILENAME;
}
if ((lastFileName != null) && lastFileName.equals(DEFAULT_FILENAME)) {
File f = chip.getAeViewer().getRecentFiles().getMostRecentFile();
if (f == null) {
lastFileName = DEFAULT_FILENAME;
} else {
lastFileName = f.getPath();
}
}
JFileChooser c = new JFileChooser(lastFileName);
c.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
@Override
public String getDescription() {
return "Text target label files";
}
});
c.setMultiSelectionEnabled(false);
c.setSelectedFile(new File(lastFileName));
int ret = c.showOpenDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
putString("lastFileName", lastFileName);
loadLocations(new File(lastFileName));
}
private TargetLocation lastAddedSample = null;
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
if (chip.getAeViewer().getPlayMode() != AEViewer.PlayMode.PLAYBACK) {
return in;
}
if (!propertyChangeListenerAdded) {
if (chip.getAeViewer() != null) {
chip.getAeViewer().addPropertyChangeListener(this);
propertyChangeListenerAdded = true;
}
}
int nCurrentTargets = currentTargets.size();
// currentTargets.clear();
for (BasicEvent e : in) {
if (e.isSpecial()) {
continue;
}
if (apsDvsChip != null) {
// update actual frame number, starting from 0 at start of recording (for playback or after rewind)
// this can be messed up by jumping in the file using slider
int newFrameNumber = apsDvsChip.getFrameCount();
if (newFrameNumber != lastFrameNumber) {
if (newFrameNumber > lastFrameNumber) {
currentFrameNumber++;
} else if (newFrameNumber < lastFrameNumber) {
currentFrameNumber
}
lastFrameNumber = newFrameNumber;
}
if (((long) e.timestamp - (long) lastTimestamp) >= minTargetPointIntervalUs) {
updateCurrentlyDisplayedTargets(e);
lastTimestamp = e.timestamp;
// find next saved target location that is just before this time (lowerEntry)
if (shiftPressed && ctlPressed && (mousePoint != null)) { // specify (additional) target present
// add a labeled location sample
addSample(getCurrentFrameNumber(), e.timestamp, mousePoint, false);
} else if (shiftPressed && !ctlPressed) { // specify no target present now but mark recording as reviewed
addSample(getCurrentFrameNumber(), e.timestamp, null, false);
}
}
if (e.timestamp < lastTimestamp) {
lastTimestamp = e.timestamp;
}
}
}
//prune list of current targets to their valid lifetime, and remove leftover targets in the future
ArrayList<TargetLocation> removeList = new ArrayList();
for (TargetLocation t : currentTargets) {
if (((t.timestamp + maxTimeLastTargetLocationValidUs) < in.getLastTimestamp()) || (t.timestamp > in.getLastTimestamp())) {
removeList.add(t);
}
}
currentTargets.removeAll(removeList);
if (currentTargets.size() != nCurrentTargets) {
fixLabeledFraction();
}
return in;
}
private void updateCurrentlyDisplayedTargets(BasicEvent e) {
// if at least minTargetPointIntervalUs has passed by maybe add new labels
Map.Entry<Integer, SimultaneouTargetLocations> mostRecentTargetsBeforeThisEvent = targetLocations.lowerEntry(e.timestamp);
if (mostRecentTargetsBeforeThisEvent != null) {
for (TargetLocation t : mostRecentTargetsBeforeThisEvent.getValue()) {
if ((t == null) || ((t != null) && ((e.timestamp - t.timestamp) > maxTimeLastTargetLocationValidUs))) {
targetLocation = null;
} else if (targetLocation != t) {
targetLocation = t;
currentTargets.add(targetLocation);
markDataHasTarget(targetLocation.timestamp, targetLocation.location != null);
}
}
}
}
private void maybeEraseSamplesBefore(int timestamp) {
if (!isEraseSamplesEnabled()) {
return;
}
Map.Entry<Integer, SimultaneouTargetLocations> nextBack = targetLocations.floorEntry(timestamp);
while (nextBack != null && nextBack.getKey() > timestamp - minTargetPointIntervalUs) {
if (lastAddedSample != null && lastAddedSample.timestamp == nextBack.getKey()) {
log.info("not erasing " + nextBack.getKey() + " because we just added it");
return;
}
targetLocations.remove(nextBack.getKey());
// log.info("removed " + nextBack.getKey());
nextBack = targetLocations.lowerEntry(nextBack.getKey());
}
fixLabeledFraction();
}
@Override
public void setSelected(boolean yes) {
super.setSelected(yes); // register/deregister mouse listeners
if (yes) {
glCanvas.removeKeyListener(this); // only add ourselves once in case we were added on startup
glCanvas.addKeyListener(this);
} else {
glCanvas.removeKeyListener(this);
}
}
@Override
public void resetFilter() {
}
@Override
public void initFilter() {
}
/**
* @return the minTargetPointIntervalUs
*/
public int getMinTargetPointIntervalUs() {
return minTargetPointIntervalUs;
}
/**
* @param minTargetPointIntervalUs the minTargetPointIntervalUs to set
*/
public void setMinTargetPointIntervalUs(int minTargetPointIntervalUs) {
this.minTargetPointIntervalUs = minTargetPointIntervalUs;
putInt("minTargetPointIntervalUs", minTargetPointIntervalUs);
}
@Override
public void keyTyped(KeyEvent ke) {
// forward space and b (toggle direction of playback) to AEPlayer
int k = ke.getKeyChar();
// log.info("keyChar=" + k + " keyEvent=" + ke.toString());
if (shiftPressed || ctlPressed) { // only forward to AEViewer if we are blocking ordinary input to AEViewer by labeling
switch (k) {
case KeyEvent.VK_SPACE:
chip.getAeViewer().setPaused(!chip.getAeViewer().isPaused());
break;
case KeyEvent.VK_B:
case 2:
chip.getAeViewer().getAePlayer().toggleDirection();
break;
case 'F':
case 6:
chip.getAeViewer().getAePlayer().speedUp();
break;
case 'S':
case 19:
chip.getAeViewer().getAePlayer().slowDown();
break;
}
}
}
@Override
public void keyPressed(KeyEvent ke) {
int k = ke.getKeyCode();
if (k == KeyEvent.VK_SHIFT) {
shiftPressed = true;
} else if (k == KeyEvent.VK_CONTROL) {
ctlPressed = true;
} else if (k == KeyEvent.VK_E) {
setEraseSamplesEnabled(true);
}
}
@Override
public void keyReleased(KeyEvent ke) {
int k = ke.getKeyCode();
if (k == KeyEvent.VK_SHIFT) {
shiftPressed = false;
} else if (k == KeyEvent.VK_CONTROL) {
ctlPressed = false;
} else if (k == KeyEvent.VK_E) {
setEraseSamplesEnabled(false);
}
}
/**
* @return the targetRadius
*/
public int getTargetRadius() {
return targetRadius;
}
/**
* @param targetRadius the targetRadius to set
*/
public void setTargetRadius(int targetRadius) {
this.targetRadius = targetRadius;
putInt("targetRadius", targetRadius);
}
/**
* @return the maxTimeLastTargetLocationValidUs
*/
public int getMaxTimeLastTargetLocationValidUs() {
return maxTimeLastTargetLocationValidUs;
}
/**
* @param maxTimeLastTargetLocationValidUs the
* maxTimeLastTargetLocationValidUs to set
*/
public void setMaxTimeLastTargetLocationValidUs(int maxTimeLastTargetLocationValidUs) {
if (maxTimeLastTargetLocationValidUs < minTargetPointIntervalUs) {
maxTimeLastTargetLocationValidUs = minTargetPointIntervalUs;
}
this.maxTimeLastTargetLocationValidUs = maxTimeLastTargetLocationValidUs;
putInt("maxTimeLastTargetLocationValidUs", maxTimeLastTargetLocationValidUs);
}
/**
* Returns true if any locations are specified already. However if there are
* no targets at all visible then also returns false.
*
*
* @return true if there are locations specified
* @see #isLocationsLoadedFromFile()
*/
public boolean hasLocations() {
return !targetLocations.isEmpty();
}
/**
* Returns the last target location
*
* @return the targetLocation
*/
public TargetLocation getTargetLocation() {
return targetLocation;
}
/** Add a new label
*
* @param timestamp
* @param point null to label target not visible
* @param fastAdd true during file read, to speed up and avoid memory thrashing
*/
private void addSample(int frame, int timestamp, Point point, boolean fastAdd) {
if (!fastAdd) {
maybeEraseSamplesBefore(timestamp);
}
TargetLocation newTargetLocation = new TargetLocation(getCurrentFrameNumber(), timestamp, point, currentTargetTypeID, targetRadius, targetRadius);
SimultaneouTargetLocations s = targetLocations.get(timestamp);
if (s == null) {
s = new SimultaneouTargetLocations();
targetLocations.put(timestamp, s);
}
s.add(newTargetLocation);
if (!fastAdd) {
currentTargets.add(newTargetLocation);
}
if (newTargetLocation != null) {
if (newTargetLocation.timestamp > maxSampleTimestamp) {
maxSampleTimestamp = newTargetLocation.timestamp;
}
if (newTargetLocation.timestamp < minSampleTimestamp) {
minSampleTimestamp = newTargetLocation.timestamp;
}
}
lastAddedSample = newTargetLocation;
if (!fastAdd) {
markDataHasTarget(timestamp, point != null);
}
// log.info("added " + timestamp);
}
private int getFractionOfFileDuration(int timestamp) {
if (inputStreamDuration == 0) {
return 0;
}
return (int) Math.floor((N_FRACTIONS * ((float) (timestamp - firstInputStreamTimestamp))) / inputStreamDuration);
}
private class TargetLocationComparator implements Comparator<TargetLocation> {
@Override
public int compare(TargetLocation o1, TargetLocation o2) {
return Integer.valueOf(o1.frameNumber).compareTo(Integer.valueOf(o2.frameNumber));
}
}
private final Color[] targetTypeColors = {Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED};
/**
* List of targets simultaneously present at a particular timestamp
*/
private class SimultaneouTargetLocations extends ArrayList<TargetLocation> {
boolean hasTargetWithLocation() {
for (TargetLocation t : this) {
if (t.location != null) {
return true;
}
}
return false;
}
}
class TargetLocation {
int timestamp;
int frameNumber;
Point location; // center of target location
int targetClassID; // class of target, i.e. car, person
int dimx; // dimension of target x
int dimy;
public TargetLocation(int frameNumber, int timestamp, Point location, int targetTypeID, int dimx, int dimy) {
this.frameNumber = frameNumber;
this.timestamp = timestamp;
this.location = location != null ? new Point(location) : null;
this.targetClassID = targetTypeID;
this.dimx = dimx;
this.dimy = dimy;
}
private void draw(GLAutoDrawable drawable, GL2 gl) {
// if (getTargetLocation() != null && getTargetLocation().location == null) {
// textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
// textRenderer.draw("Target not visible", chip.getSizeX() / 2, chip.getSizeY() / 2);
// textRenderer.endRendering();
// return;
gl.glPushMatrix();
gl.glTranslatef(location.x, location.y, 0f);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[targetClassID % targetTypeColors.length].getColorComponents(compArray), 0);
// gl.glColor4f(0, 1, 0, .5f);
if (mouseQuad == null) {
mouseQuad = glu.gluNewQuadric();
}
glu.gluQuadricDrawStyle(mouseQuad, GLU.GLU_LINE);
//glu.gluDisk(mouseQuad, getTargetRadius(), getTargetRadius(), 32, 1);
int maxDim = Math.max(dimx, dimy);
glu.gluDisk(mouseQuad, maxDim / 2, (maxDim / 2) + 0.1, 32, 1);
//getTargetRadius(), getTargetRadius() + 1, 32, 1);
gl.glPopMatrix();
}
@Override
public String toString() {
return String.format("TargetLocation frameNumber=%d timestamp=%d location=%s", frameNumber, timestamp, location == null ? "null" : location.toString());
}
}
private void saveLocations(File f) {
try {
FileWriter writer = new FileWriter(f);
writer.write(String.format("# target locations\n"));
writer.write(String.format("# written %s\n", new Date().toString()));
// writer.write("# maxTargets=" + maxTargets+"\n");
writer.write(String.format("# frameNumber timestamp x y targetTypeID\n"));
for (Map.Entry<Integer, SimultaneouTargetLocations> entry : targetLocations.entrySet()) {
for (TargetLocation l : entry.getValue()) {
if (l.location != null) {
writer.write(String.format("%d %d %d %d %d\n", l.frameNumber, l.timestamp, l.location.x, l.location.y, l.targetClassID, l.dimx, l.dimy));
} else {
writer.write(String.format("%d %d -1 -1 -1\n", l.frameNumber, l.timestamp));
}
}
}
writer.close();
log.info("wrote locations to file " + f.getAbsolutePath());
if (f.getPath() != null) {
mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath());
}
try {
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput oos = new ObjectOutputStream(bos);
oos.writeObject(mapDataFilenameToTargetFilename);
oos.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
getPrefs().putByteArray("TargetLabeler.hashmap", buf);
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't save locations", JOptionPane.WARNING_MESSAGE, null);
return;
}
}
/**
* Loads last locations. Note that this is a lengthy operation
*/
synchronized public void loadLastLocations() {
if (lastFileName == null) {
return;
}
File f = new File(lastFileName);
if (!f.exists() || !f.isFile()) {
return;
}
loadLocations(f);
}
synchronized private void loadLocations(File f) {
long startMs = System.currentTimeMillis();
log.info("loading " + f);
boolean oldEraseSamples = this.eraseSamplesEnabled;
doClearLocations();
TargetLocation tmpTargetLocation = null;
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
try {
LineNumberReader reader = new LineNumberReader(new FileReader(f));
String s = reader.readLine();
StringBuilder sb = new StringBuilder();
while ((s != null) && s.startsWith("
sb.append(s + "\n");
s = reader.readLine();
}
log.info("header lines on " + f.getAbsolutePath() + " are\n" + sb.toString());
Scanner scanner = new Scanner(reader);
while (scanner.hasNext()) {
try {
int frame = scanner.nextInt();
int ts = scanner.nextInt();
int x = scanner.nextInt();
int y = scanner.nextInt();
int targetTypeID = 0;
int targetdimx = targetRadius;
int targetdimy = targetRadius;
// see if more tokens in this line
String mt = scanner.findInLine("\\d+");
if (mt != null) {
targetTypeID = Integer.parseInt(scanner.match().group());
}
mt = scanner.findInLine("\\d+");
if (mt != null) {
targetdimx = Integer.parseInt(scanner.match().group());
}
mt = scanner.findInLine("\\d+");
if (mt != null) {
targetdimy = Integer.parseInt(scanner.match().group());
}
Point p = null;
if ((x != -1) && (y != -1)) {
p = new Point(x, y);
}
addSample(frame, ts, p, true);
} catch (NoSuchElementException ex2) {
String l=("couldn't parse file " + f) == null ? "null" : f.toString() + ", got InputMismatchException on line: " + reader.getLineNumber();
log.warning(l);
throw new IOException(l);
}
}
long endMs = System.currentTimeMillis();
log.info("Took " + (endMs - startMs) + " ms to load " + f + " with " + targetLocations.size() + " SimultaneouTargetLocations entries");
if (lastDataFilename != null) {
mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath());
}
this.targetLocation = null; // null out current location
locationsLoadedFromFile = true;
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null);
} catch (IOException ex) {
JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null);
}
} finally {
setCursor(Cursor.getDefaultCursor());
this.eraseSamplesEnabled = oldEraseSamples;
}
fixLabeledFraction();
}
int maxDataHasTargetWarningCount = 10;
/**
* marks this point in time as reviewed already
*
* @param timestamp
*/
private void markDataReviewedButNoTargetPresent(int timestamp) {
if (inputStreamDuration == 0) {
return;
}
int frac = getFractionOfFileDuration(timestamp);
labeledFractions[frac] = true;
targetPresentInFractions[frac] = false;
}
private void markDataHasTarget(int timestamp, boolean visible) {
if (inputStreamDuration == 0) {
return;
}
int frac = getFractionOfFileDuration(timestamp);
if ((frac < 0) || (frac >= labeledFractions.length)) {
if (maxDataHasTargetWarningCount
log.warning("fraction " + frac + " is out of range " + labeledFractions.length + ", something is wrong");
}
if (maxDataHasTargetWarningCount == 0) {
log.warning("suppressing futher warnings");
}
return;
}
labeledFractions[frac] = true;
targetPresentInFractions[frac] = visible;
}
private void fixLabeledFraction() {
if (chip.getAeInputStream() != null) {
firstInputStreamTimestamp = chip.getAeInputStream().getFirstTimestamp();
lastTimestamp = chip.getAeInputStream().getLastTimestamp();
inputStreamDuration = chip.getAeInputStream().getDurationUs();
fileLengthEvents = chip.getAeInputStream().size();
if (inputStreamDuration > 0) {
if ((targetLocations == null) || targetLocations.isEmpty()) {
Arrays.fill(labeledFractions, false);
return;
}
for (Map.Entry<Integer, SimultaneouTargetLocations> t : targetLocations.entrySet()) {
markDataHasTarget(t.getKey(), t.getValue().hasTargetWithLocation());
}
}
}
}
/**
* @return the showLabeledFraction
*/
public boolean isShowLabeledFraction() {
return showLabeledFraction;
}
/**
* @param showLabeledFraction the showLabeledFraction to set
*/
public void setShowLabeledFraction(boolean showLabeledFraction) {
this.showLabeledFraction = showLabeledFraction;
putBoolean("showLabeledFraction", showLabeledFraction);
}
/**
* @return the showHelpText
*/
public boolean isShowHelpText() {
return showHelpText;
}
/**
* @param showHelpText the showHelpText to set
*/
public void setShowHelpText(boolean showHelpText) {
this.showHelpText = showHelpText;
putBoolean("showHelpText", showHelpText);
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
super.setFilterEnabled(yes); //To change body of generated methods, choose Tools | Templates.
fixLabeledFraction();
}
// /**
// * @return the maxTargets
// */
// public int getMaxTargets() {
// return maxTargets;
// /**
// * @param maxTargets the maxTargets to set
// */
// public void setMaxTargets(int maxTargets) {
// this.maxTargets = maxTargets;
/**
* @return the currentTargetTypeID
*/
public int getCurrentTargetTypeID() {
return currentTargetTypeID;
}
/**
* @param currentTargetTypeID the currentTargetTypeID to set
*/
public void setCurrentTargetTypeID(int currentTargetTypeID) {
// if (currentTargetTypeID >= maxTargets) {
// currentTargetTypeID = maxTargets;
this.currentTargetTypeID = currentTargetTypeID;
putInt("currentTargetTypeID", currentTargetTypeID);
}
/**
* @return the eraseSamplesEnabled
*/
public boolean isEraseSamplesEnabled() {
return eraseSamplesEnabled;
}
/**
* @param eraseSamplesEnabled the eraseSamplesEnabled to set
*/
public void setEraseSamplesEnabled(boolean eraseSamplesEnabled) {
boolean old = this.eraseSamplesEnabled;
this.eraseSamplesEnabled = eraseSamplesEnabled;
getSupport().firePropertyChange("eraseSamplesEnabled", old, this.eraseSamplesEnabled);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(!isFilterEnabled()) return;
switch (evt.getPropertyName()) {
case AEInputStream.EVENT_POSITION:
filePositionEvents = (long) evt.getNewValue();
if ((chip.getAeViewer().getAePlayer() == null) || (chip.getAeViewer().getAePlayer().getAEInputStream() == null)) {
log.warning("null input stream, cannot get most recent timestamp");
return;
}
filePositionTimestamp = chip.getAeViewer().getAePlayer().getAEInputStream().getMostRecentTimestamp();
break;
case AEInputStream.EVENT_REWIND:
case AEInputStream.EVENT_REPOSITIONED:
// log.info("rewind to start or mark position or reposition event " + evt.toString());
if (evt.getNewValue() instanceof Long) {
long position = (long) evt.getNewValue();
if (chip.getAeInputStream() == null) {
log.warning("AE input stream is null, cannot determine timestamp after rewind");
return;
}
int timestamp = chip.getAeInputStream().getMostRecentTimestamp();
Map.Entry<Integer, SimultaneouTargetLocations> targetsBeforeRewind = targetLocations.lowerEntry(timestamp);
if (targetsBeforeRewind != null) {
currentFrameNumber = targetsBeforeRewind.getValue().get(0).frameNumber;
lastFrameNumber = getCurrentFrameNumber() - 1;
lastTimestamp = targetsBeforeRewind.getValue().get(0).timestamp;
} else {
currentFrameNumber = 0;
lastFrameNumber = getCurrentFrameNumber() - 1;
lastInputStreamTimestamp = Integer.MIN_VALUE;
}
} else {
log.warning("couldn't determine stream position after rewind from PropertyChangeEvent " + evt.toString());
}
shiftPressed = false;
ctlPressed = false; // disable labeling on rewind to prevent bad labels at start
if (evt.getPropertyName() == AEInputStream.EVENT_REWIND) {
try {
Thread.currentThread().sleep(1000);// time for preparing label
} catch (InterruptedException e) {
}
}
break;
case AEInputStream.EVENT_INIT:
fixLabeledFraction();
warnSave = true;
if (evt.getNewValue() instanceof AEFileInputStream) {
File f = ((AEFileInputStream) evt.getNewValue()).getFile();
lastDataFilename = f.getPath();
}
break;
}
}
/**
* @return the showStatistics
*/
public boolean isShowStatistics() {
return showStatistics;
}
/**
* @param showStatistics the showStatistics to set
*/
public void setShowStatistics(boolean showStatistics) {
this.showStatistics = showStatistics;
putBoolean("showStatistics", showStatistics);
}
/**
* @return the currentFrameNumber
*/
public int getCurrentFrameNumber() {
return currentFrameNumber;
}
/**
* False until locations are loaded from a file. Reset by clearLocations.
*
* @return the locationsLoadedFromFile true if data was loaded from a file
* successfully
*/
public boolean isLocationsLoadedFromFile() {
return locationsLoadedFromFile;
}
}
|
package gov.nih.nci.cananolab.ui.core;
import gov.nih.nci.cananolab.ui.particle.InitNanoparticleSetup;
import gov.nih.nci.cananolab.ui.security.InitSecuritySetup;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import javax.servlet.ServletException;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
/**
* Creates default CSM groups and sample types and initialize Hibernate
* configurations as soon as server starts up.
*
* @author pansu
*
*/
public class CustomPlugIn implements PlugIn {
Logger logger = Logger.getLogger(CustomPlugIn.class);
// This method will be called at application startup time
public void init(ActionServlet actionServlet, ModuleConfig config)
throws ServletException {
System.out.println("Entering CustomPlugIn.init()");
try {
// set servlet context variables
InitSetup.getInstance().getDisplayNameLookup(
actionServlet.getServletContext());
InitNanoparticleSetup.getInstance().getDefaultFunctionTypes(
actionServlet.getServletContext());
InitNanoparticleSetup.getInstance()
.getDefaultNanoparticleEntityTypes(
actionServlet.getServletContext());
InitNanoparticleSetup.getInstance()
.getDefaultFunctionalizingEntityTypes(
actionServlet.getServletContext());
actionServlet.getServletContext().setAttribute("applicationOwner",
CaNanoLabConstants.APP_OWNER);
InitNanoparticleSetup.getInstance()
.getDefaultCharacterizationTypes(
actionServlet.getServletContext());
// InitSecuritySetup.getInstance().createDefaultCSMGroups();
} catch (Exception e) {
this.logger.error("Servlet initialization error", e);
}
System.out.println("Exiting CustomPlugIn.init()");
}
// This method will be called at application shutdown time
public void destroy() {
System.out.println("Entering CustomPlugIn.destroy()");
System.out.println("Exiting CustomPlugIn.destroy()");
}
}
|
package dr.evomodelxml;
import dr.xml.*;
import dr.evolution.datatype.Microsatellite;
import dr.evomodel.substmodel.*;
import dr.inference.model.Parameter;
import dr.app.beauti.options.MicrosatelliteModelType;
import java.util.logging.Logger;
public class AsymQuadModelParser extends AbstractXMLObjectParser{
public static final String EXPANSION_CONSTANT = "ExpansionConstant";
public static final String CONTRACTION_CONSTANT = "ContractionConstant";
public static final String EXPANSION_LIN = "ExpansionLinear";
public static final String CONTRACTION_LIN = "ContractionLinear";
public static final String EXPANSION_QUAD = "ExpansionQuad";
public static final String CONTRACTION_QUAD = "ContractionQuad";
public static final String ESTIMATE = "estimate";
public String getParserName() {
return MicrosatelliteModelType.ASYMQUAD.getXMLName();
}
//AbstractXMLObjectParser implementation
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Microsatellite microsatellite = (Microsatellite) xo.getChild(Microsatellite.class);
Parameter expanConst = processModelParameter(xo, EXPANSION_CONSTANT);
Parameter expanLin = processModelParameter(xo, EXPANSION_LIN);
Parameter expanQuad = processModelParameter(xo, EXPANSION_QUAD);
Parameter contractConst = processModelParameter(xo, CONTRACTION_CONSTANT);
Parameter contractLin = processModelParameter(xo, CONTRACTION_LIN);
Parameter contractQuad = processModelParameter(xo, CONTRACTION_QUAD);
//get FrequencyModel
FrequencyModel freqModel = null;
if(xo.hasChildNamed(FrequencyModel.FREQUENCIES)){
freqModel = (FrequencyModel)xo.getElementFirstChild(FrequencyModel.FREQUENCIES);
}
return new AsymmetricQuadraticModel(microsatellite, freqModel,
expanConst, expanLin, expanQuad, contractConst, contractLin, contractQuad);
}
private Parameter processModelParameter(XMLObject xo,
String parameterName)throws XMLParseException{
Parameter param = null;
if(xo.hasChildNamed(parameterName)){
XMLObject paramXO = xo.getChild(parameterName);
param =(Parameter) paramXO.getChild(Parameter.class);
Logger.getLogger("dr.evoxml").info(
"\nUser has specified the parameter: "+ parameterName + " " + param.toString());
}else{
Logger.getLogger("dr.evoxml").info(
"\nUser has not specified the parameter:"+ parameterName+", default value will be used");
}
return param;
}
public String getParserDescription() {
return "This element represents an instance of the stepwise mutation model of microsatellite evolution.";
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
new ElementRule(Microsatellite.class),
new ElementRule(FrequencyModel.class,true),
new ElementRule(EXPANSION_CONSTANT,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true),
new ElementRule(CONTRACTION_CONSTANT,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true),
new ElementRule(EXPANSION_LIN,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true),
new ElementRule(CONTRACTION_LIN,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true),
new ElementRule(EXPANSION_QUAD,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true),
new ElementRule(CONTRACTION_QUAD,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true)
};
public Class getReturnType() {
return AsymmetricQuadraticModel.class;
}
public static boolean requirePattern(){
return true;
}
}
|
package edu.ntnu.idi.goldfish;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.stat.correlation.*;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FullRunningAverage;
import org.apache.mahout.cf.taste.model.Preference;
import edu.ntnu.idi.goldfish.mahout.SMPreference;
import edu.ntnu.idi.goldfish.mahout.SMPreferenceArray;
public class Preprocessor {
private final int THRESHOLD = 2;
private Map<Integer, List<Preprocessor.Pref>> prefByUser = new HashMap<Integer, List<Preprocessor.Pref>>();
private Map<Integer, List<Preprocessor.Pref>> prefByItem = new HashMap<Integer, List<Preprocessor.Pref>>();
private List<Pref> prefs = new ArrayList<Pref>();
public static void main(String[] args) {
Preprocessor pre = new Preprocessor();
pre.readFile("datasets/yow-userstudy/ratings-and-timings.csv");
pre.calculateRMSE();
// pre.writeToCsv("datasets/yow-userstudy/processed.csv");
}
public void calculateRMSE() {
FullRunningAverage average = new FullRunningAverage();
for (Pref p : prefs) {
boolean hasExplicit = p.expl >= 1;
boolean hasImplicit = p.impl > 0;
if (hasExplicit && hasImplicit) {
// have implicit
// find out if we have enough explicit-implicit rating pars
List<Pref> ps = get(p.itemId);
if (ps.size() >= THRESHOLD) {
// check if abs(correlation) > 0.5
double correlation = getCorrelation(ps);
if (Math.abs(correlation) > 0.5) {
// calculate pseudorating, and store as explicit rating
double diff = p.expl - getPseudoRating(p, correlation, ps);
average.addDatum(Math.abs(diff));
}
}
}
}
System.out.println(Math.sqrt(average.getAverage()));
}
public void writeToCsv(String name) {
for (Pref p : prefs) {
boolean hasExplicit = p.expl >= 1;
boolean hasImplicit = p.impl > 0;
if (!hasExplicit && hasImplicit) {
// have implicit
// find out if we have enough explicit-implicit rating pars
List<Pref> ps = get(p.itemId);
if (ps.size() >= THRESHOLD) {
// check if abs(correlation) > 0.5
double correlation = getCorrelation(ps);
if (Math.abs(correlation) > 0.5) {
// calculate pseudorating, and store as explicit rating
// win
p.expl = getPseudoRating(p, correlation, ps);
}
}
}
}
try {
FileWriter writer = new FileWriter(name);
for (Pref p : prefs) {
writer.write(String.format("%d,%d,%d\n", p.userId, p.itemId, p.expl));
}
writer.close();
} catch (IOException e) {
}
}
private int getPseudoRating(Pref p, double correlation, List<Pref> ps) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int pseudoRating = 5;
for (Pref pref : ps) {
if (pref.impl < min) {
min = pref.impl;
}
if (pref.impl > max) {
max = pref.impl;
}
}
if (min == max) {
return 3;
}
if (p.impl < max) {
pseudoRating = (int) (1 + Math.floor((5 * (p.impl / max))));
}
if (correlation < 0) {
pseudoRating = 6 - pseudoRating;
}
return pseudoRating;
}
private List<Pref> get(int itemId) {
List<Pref> prefs = new ArrayList<Pref>();
for (Pref pref : prefByItem.get(itemId)) {
if (pref.expl > 0 && pref.impl > 0) {
prefs.add(pref);
}
}
return prefs;
}
public void readFile(String csvFile) {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
br.readLine();
while ((line = br.readLine()) != null) {
// use comma as separator
String[] row = line.split(cvsSplitBy);
// need 4 values
if (row.length != 4) {
continue;
}
int userId = Integer.parseInt(row[0]);
int articleId = Integer.parseInt(row[1]);
int expl = Integer.parseInt(row[2]);
int impl = Integer.parseInt(row[3]);
Pref p = new Pref(userId, articleId, impl, expl);
if (prefByItem.containsKey(articleId)) {
List<Preprocessor.Pref> prefs = prefByItem.get(articleId);
prefs.add(p);
} else {
List<Preprocessor.Pref> prefs = new ArrayList<Preprocessor.Pref>();
prefs.add(p);
prefByItem.put(articleId, prefs);
}
if (prefByUser.containsKey(userId)) {
List<Preprocessor.Pref> prefs = prefByUser.get(userId);
prefs.add(p);
} else {
List<Preprocessor.Pref> prefs = new ArrayList<Preprocessor.Pref>();
prefs.add(p);
prefByUser.put(userId, prefs);
}
prefs.add(p);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public double getCorrelation(List<Pref> prefs) {
PearsonsCorrelation pc = new PearsonsCorrelation();
double[] expl = new double[prefs.size()];
double[] impl = new double[prefs.size()];
for (int i = 0; i < prefs.size(); i++) {
Pref p = prefs.get(i);
expl[i] = p.expl;
impl[i] = p.impl;
}
return pc.correlation(expl, impl);
}
public class Pref {
int userId;
int itemId;
public int impl;
public int expl;
public Pref(int userId, int itemId, int impl, int expl) {
this.userId = userId;
this.itemId = itemId;
this.impl = impl;
this.expl = expl;
}
}
}
|
package experimentalcode.erich.minigui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.logging.ErrorManager;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import de.lmu.ifi.dbs.elki.KDDTask;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.elki.logging.MessageFormatter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Option;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionUtil;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable;
import de.lmu.ifi.dbs.elki.utilities.output.FormatUtil;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
import de.lmu.ifi.dbs.elki.utilities.pairs.Triple;
public class MiniGUI extends JPanel {
/**
* Serial version
*/
private static final long serialVersionUID = 1L;
public static final int BIT_INCOMPLETE = 0;
public static final int BIT_NO_DASH = 1;
public static final int BIT_NO_NAME_BUT_VALUE = 2;
static final String[] columns = { "Parameter", "Value" };
private static final String NEWLINE = System.getProperty("line.separator");
protected Logging logger = Logging.getLogger(MiniGUI.class);
protected JTextArea outputArea;
protected ArrayList<Triple<String, String, BitSet>> parameters;
public MiniGUI() {
super();
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
parameters = new ArrayList<Triple<String, String, BitSet>>();
parameters.add(new Triple<String, String, BitSet>("-algorithm", "clustering.DBSCAN", new BitSet()));
parameters.add(new Triple<String, String, BitSet>("-dbscan.minpts", "10", new BitSet()));
parameters.add(new Triple<String, String, BitSet>("-dbscan.epsilon", "0.3", new BitSet()));
parameters.add(new Triple<String, String, BitSet>("-dbc.in", "data/testdata/unittests/hierarchical-3d2d1d.csv", new BitSet()));
parameters.add(new Triple<String, String, BitSet>("-resulthandler", "experimentalcode.erich.ResultVisualizeScatterplot", new BitSet()));
final JTable table = new JTable(new ParametersModel(parameters));
table.setPreferredScrollableViewportSize(new Dimension(600, 200));
table.setFillsViewportHeight(true);
table.setDefaultRenderer(String.class, new HighlightingRenderer(parameters));
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
// Add the scroll pane to this panel.
add(scrollPane);
// Button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
// button to evaluate settings
JButton setButton = new JButton("Test Settings");
setButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
runSetParameters(false);
}
});
buttonPanel.add(setButton);
// button to evaluate settings
JButton helpButton = new JButton("Request usage help");
helpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
runSetParameters(true);
}
});
buttonPanel.add(helpButton);
// button to launch the task
JButton runButton = new JButton("Run Task");
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
runTask();
}
});
buttonPanel.add(runButton);
add(buttonPanel);
// setup text output area
outputArea = new JTextArea();
// Create the scroll pane and add the table to it.
JScrollPane outputPane = new JScrollPane(outputArea);
outputPane.setPreferredSize(new Dimension(600, 200));
// Add the output pane to the bottom
add(outputPane);
// reconfigure logging
LogHandler.setReceiver(this);
LoggingConfiguration.reconfigureLogging(MiniGUI.class.getPackage().getName(), "logging-minigui.properties");
}
protected void runSetParameters(boolean help) {
ArrayList<String> params = serializeParameters();
if(!help) {
outputArea.setText("Testing parameters: " + FormatUtil.format(params, " ") + NEWLINE);
}
else {
outputArea.setText("");
}
KDDTask<DatabaseObject> task = new KDDTask<DatabaseObject>();
try {
task.setParameters(params);
if(!help) {
outputArea.append("Test ok." + NEWLINE);
}
}
catch(ParameterException e) {
outputArea.append("Parameter Error: " + e.getMessage() + NEWLINE);
}
catch(Exception e) {
logger.exception(e);
}
if(help) {
// Collect options
List<Pair<Parameterizable, Option<?>>> options = new ArrayList<Pair<Parameterizable, Option<?>>>();
task.collectOptions(options);
StringBuffer buf = new StringBuffer();
buf.append("Parameters:").append(NEWLINE);
OptionUtil.formatForConsole(buf, 100, " ", options);
// TODO: global parameter constraints
outputArea.append(buf.toString());
}
}
private ArrayList<String> serializeParameters() {
ArrayList<String> p = new ArrayList<String>(2 * parameters.size());
for(Triple<String, String, BitSet> t : parameters) {
if(t.getFirst() != null && t.getFirst().length() > 0) {
p.add(t.getFirst());
}
if(t.getSecond() != null && t.getSecond().length() > 0) {
p.add(t.getSecond());
}
}
return p;
}
protected void runTask() {
ArrayList<String> params = serializeParameters();
outputArea.setText("Running: " + FormatUtil.format(params, " ") + NEWLINE);
KDDTask<DatabaseObject> task = new KDDTask<DatabaseObject>();
try {
task.setParameters(params);
task.run();
}
catch(ParameterException e) {
outputArea.setText(e.getMessage());
}
catch(Exception e) {
logger.exception(e);
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
protected static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("ELKI MiniGUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Create and set up the content pane.
MiniGUI newContentPane = new MiniGUI();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
class ParametersModel extends AbstractTableModel {
/**
* Serial version
*/
private static final long serialVersionUID = 1L;
private ArrayList<Triple<String, String, BitSet>> parameters;
public ParametersModel(ArrayList<Triple<String, String, BitSet>> parameters) {
super();
this.parameters = parameters;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public int getRowCount() {
return parameters.size() + 1;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(rowIndex < parameters.size()) {
Triple<String, String, BitSet> p = parameters.get(rowIndex);
if(columnIndex == 0) {
return p.getFirst();
}
else if(columnIndex == 1) {
return p.getSecond();
}
return null;
}
else {
return "";
}
}
@Override
public String getColumnName(int column) {
return columns[column];
}
@Override
public Class<?> getColumnClass(@SuppressWarnings("unused") int columnIndex) {
return String.class;
}
@Override
public boolean isCellEditable(@SuppressWarnings("unused") int rowIndex, @SuppressWarnings("unused") int columnIndex) {
return true;
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if(value instanceof String) {
String s = (String) value;
Triple<String, String, BitSet> p;
if(rowIndex < parameters.size()) {
p = parameters.get(rowIndex);
}
else {
BitSet flags = new BitSet();
// flags.set(BIT_INCOMPLETE);
p = new Triple<String, String, BitSet>("", "", flags);
parameters.add(p);
}
BitSet flags = p.getThird();
if(columnIndex == 0) {
p.setFirst(s);
if(s.length() <= 0 || s.charAt(0) != '-') {
flags.set(BIT_NO_DASH);
}
else {
flags.clear(BIT_NO_DASH);
}
}
else if(columnIndex == 1) {
p.setSecond(s);
}
// set flag when we have a key but no value
flags.set(BIT_NO_NAME_BUT_VALUE, (p.getFirst().length() == 0 && p.getSecond().length() > 0));
// no data at all?
if(p.getFirst() == null || p.getFirst() == "") {
if(p.getSecond() == null || p.getSecond() == "") {
flags.clear();
}
}
p.setThird(flags);
}
else {
logger.warning("Edited value is not a String!");
}
}
}
protected static class HighlightingRenderer extends DefaultTableCellRenderer {
/**
* Serial Version
*/
private static final long serialVersionUID = 1L;
private ArrayList<Triple<String, String, BitSet>> parameters;
private static final Color COLOR_INCOMPLETE = new Color(0x7F7FFF);
private static final Color COLOR_SYNTAX_ERROR = new Color(0xFF7F7F);
public HighlightingRenderer(ArrayList<Triple<String, String, BitSet>> parameters) {
super();
this.parameters = parameters;
}
@Override
public void setValue(Object value) {
if(value instanceof String) {
setText((value == null) ? "" : (String) value);
}
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(row < parameters.size()) {
Triple<String, String, BitSet> p = parameters.get(row);
if((p.getThird().get(BIT_NO_DASH))) {
c.setBackground(COLOR_SYNTAX_ERROR);
}
else if((p.getThird().get(BIT_NO_NAME_BUT_VALUE))) {
c.setBackground(COLOR_SYNTAX_ERROR);
}
else if((p.getThird().get(BIT_INCOMPLETE))) {
c.setBackground(COLOR_INCOMPLETE);
}
else {
c.setBackground(null);
}
}
return c;
}
}
public static class LogHandler extends Handler {
private static MiniGUI logReceiver = null;
/**
* Formatter for regular messages (informational records)
*/
private Formatter msgformat = new MessageFormatter();
/**
* Formatter for debugging messages
*/
private Formatter debugformat = new SimpleFormatter();
/**
* Formatter for error messages
*/
private Formatter errformat = new SimpleFormatter();
@Override
public void close() throws SecurityException {
// Do nothing
}
@Override
public void flush() {
// Do nothing
}
@Override
public void publish(LogRecord record) {
// choose an appropriate formatter
final Formatter fmt;
// always format progress messages using the progress formatter.
if(record.getLevel().intValue() >= Level.WARNING.intValue()) {
// format errors using the error formatter
fmt = errformat;
}
else if(record.getLevel().intValue() <= Level.FINE.intValue()) {
// format debug statements using the debug formatter.
fmt = debugformat;
}
else {
// default to the message formatter.
fmt = msgformat;
}
// format
final String m;
try {
m = fmt.format(record);
}
catch(Exception ex) {
reportError(null, ex, ErrorManager.FORMAT_FAILURE);
return;
}
if(logReceiver != null) {
logReceiver.publish(m, record.getLevel());
}
else {
// fall back to standard error.
System.err.println(m);
}
}
protected static void setReceiver(MiniGUI receiver) {
logReceiver = receiver;
}
}
/**
* @param record log message.
* @param level unused for now
*/
protected void publish(String record, Level level) {
outputArea.append(record);
}
}
|
package edu.nyu.cs.omnidroid.util;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import android.content.Context;
public class UGParser
{
/**
* deletes the entire userConfig Except the Enabled Field.
*
* @param Context
* Application Context
*/
public void delete_all(Context context)
{
try
{
String Enabled=readLine(context,"Enabled");
if(Enabled.equals(null)) Enabled="True";
String LineString = new String("Enabled"+":"+Enabled+"\n");
FileOutputStream fOut = context.openFileOutput("UserConfig.txt",2);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(LineString);
osw.flush();
osw.close();
}
catch(Exception e)
{
OmLogger.write(context,"Could not delete Instances");
}
}
/**
* deletes the Record from userConfig.
*
* @param Context
* Application Context
* @param HM
* HashMap of the record to be deleted.
*/
public int deleteRecord(Context context,HashMap<String,String> HM)
{
try
{
ArrayList<HashMap <String,String>> UCRecords=readRecords(context);
ArrayList<HashMap <String,String>> UCRecords_New=readRecords(context);
Iterator<HashMap<String,String>> i=UCRecords.iterator();
while(i.hasNext())
{
HashMap<String,String> HM1=i.next();
if(HM1.equals(HM))
continue;
UCRecords_New.add(HM1);
}
delete_all(context);
Iterator<HashMap<String,String>> i1=UCRecords_New.iterator();
while(i1.hasNext())
{
HashMap<String,String> HM1=i.next();
writeRecord(context, HM1);
}
return 1;
}
catch(Exception e)
{
OmLogger.write(context,"Could not delete Instance Record");
return 0;
}
}
/**
* Writes a Key Value into the UserConfig as Key:Value
*
* @param Context
* Application Context
* @param Key
* Specify the Key to be written
* @param Value
* Specify the Value to be written
* @return Returns 1 if successful
*/
public int write(Context context,String key,String val)
{
try
{
final String LineString = new String(key+":"+val+"\n");
FileOutputStream fOut = context.openFileOutput("UserConfig.txt",32768);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(LineString);
osw.flush();
osw.close();
return 1;
}catch(Exception e)
{
OmLogger.write(context, "Unable to write line in User Config");
return 0;
}
}
public String readLine(Context context,String key)
{
String col2="";
try{
FileInputStream FIn = context.openFileInput("UserConfig.txt");
BufferedInputStream bis = new BufferedInputStream(FIn);
DataInputStream dis = new DataInputStream(bis);
String line;
while((line=dis.readLine())!=null)
{
String[] parts=line.split(":");
if(parts[0].toString().equalsIgnoreCase(key))
{
col2=parts[1].toString();
break;
}
}
return col2;
}catch(Exception e)
{
OmLogger.write(context,"Unable to read Line from User Config");
return col2;
}
}
/**
* Reads values from the UserConfig based on the Key
*
* @param Context
* Application Context
* @param Key
* Specify the Key to be read. example ActionName, EventName
* @return Returns values as ArrayList of Strings
*/
public ArrayList<String> readLines(Context context,String key)
{
ArrayList<String> cols2=new ArrayList<String>();
String val;
try{
FileInputStream FIn = context.openFileInput("UserConfig.txt");
BufferedInputStream bis = new BufferedInputStream(FIn);
DataInputStream dis = new DataInputStream(bis);
String line;
while((line=dis.readLine())!=null)
{
String[] parts=line.split(":");
if(parts[0].toString().equalsIgnoreCase(key))
{
val=parts[1].toString();
cols2.add(val);
}
}
return cols2;
}catch(Exception e)
{
OmLogger.write(context,"Unable to read Line from User Config");
return cols2;
}
}
/**
* Reads Instance Records from the UserConfig
*
* @param Context
* Application Context
* @return Returns Array List of HashMaps. HashMaps have the keys as EventName, EventApp, FilterType, FilterData, ActionName, ActionApp, AppData,EnableInstance
*/
public ArrayList<HashMap<String,String>> readRecords(Context context)
{
ArrayList<HashMap<String,String>> UCRecords=new ArrayList<HashMap<String,String>>();
try{
FileInputStream FIn = context.openFileInput("UserConfig.txt");
BufferedInputStream bis = new BufferedInputStream(FIn);
DataInputStream dis = new DataInputStream(bis);
String line="";
while((line=dis.readLine())!=null)
{
HashMap<String,String> HM=new HashMap<String,String>();
String[] parts=line.split(":");
if(parts[0].toString().equalsIgnoreCase("InstanceName"))
{
HM.put("InstanceName",line.split(":")[1].toString());
line=dis.readLine();
HM.put("EventName",line.split(":")[1].toString());
line=dis.readLine();
HM.put("EventApp",line.split(":")[1].toString());
line=dis.readLine();
HM.put("FilterType",line.split(":")[1].toString());
line=dis.readLine();
HM.put("FilterData",line.split(":")[1].toString());
line=dis.readLine();
HM.put("ActionName",line.split(":")[1].toString());
line=dis.readLine();
HM.put("ActionApp",line.split(":")[1].toString());
line=dis.readLine();
HM.put("ActionData",line.split(":")[1].toString());
line=dis.readLine();
HM.put("EnableInstance",line.split(":")[1].toString());
line=dis.readLine();
}
UCRecords.add(HM);
}
return UCRecords;
}catch(Exception e)
{
OmLogger.write(context,"Unable to read Line from User Config");
return UCRecords;
}
}
/**
* Reads Instance Records from the UserConfig based on the InstanceName passed
*
* @param Context
* Application Context
* @param Key
* InstanceName to be passed.
* @return Returns HashMap.
* */
public HashMap<String,String> readRecord(Context context,String Key)
{
HashMap<String,String> HM=new HashMap<String,String>();
try{
FileInputStream FIn = context.openFileInput("UserConfig.txt");
BufferedInputStream bis = new BufferedInputStream(FIn);
DataInputStream dis = new DataInputStream(bis);
String line="";
while((line=dis.readLine())!=null)
{
String[] parts=line.split(":");
if(parts[0].toString().equalsIgnoreCase("InstanceName") && parts[1].toString().equalsIgnoreCase(Key) )
{
HM.put("InstanceName",line.split(":")[1].toString());
line=dis.readLine();
HM.put("EventName",line.split(":")[1].toString());
line=dis.readLine();
HM.put("EventApp",line.split(":")[1].toString());
line=dis.readLine();
HM.put("FilterType",line.split(":")[1].toString());
line=dis.readLine();
HM.put("FilterData",line.split(":")[1].toString());
line=dis.readLine();
HM.put("ActionName",line.split(":")[1].toString());
line=dis.readLine();
HM.put("ActionApp",line.split(":")[1].toString());
line=dis.readLine();
HM.put("ActionData",line.split(":")[1].toString());
line=dis.readLine();
HM.put("EnableInstance",line.split(":")[1].toString());
line=dis.readLine();
break;
}
}
return HM;
}catch(Exception e)
{
OmLogger.write(context,"Unable to read record from User Config");
return HM;
}
}
/**
* Writes an Instance in the UserConfig File
*
* @param Context
* Application Context
* @param HM
* HashMap containing EventName, EventApp, FilterType, FilterData, ActionName, ActionApp, AppData,EnableInstance
* @return Returns 1 if successful else 0.
*/
public int writeRecord(Context context,HashMap<String,String> HM)
{
try{
write(context,"InstanceName",HM.get("InstanceName").toString());
write(context,"EventName",HM.get("EventName").toString());
write(context,"EventApp",HM.get("EventApp").toString());
write(context,"FilterType",HM.get("FilterType").toString());
write(context,"FilterData",HM.get("FilterData").toString());
write(context,"ActionName",HM.get("ActionName").toString());
write(context,"ActionApp",HM.get("ActionApp").toString());
write(context,"ActionData",HM.get("ActionData").toString());
write(context,"EnableInstance",HM.get("EnableInstance").toString());
return 1;
}catch(Exception e)
{
OmLogger.write(context,"Unable to write record from User Config");
return 0;
}
}
public int updateRecord(Context context,HashMap<String,String> HM)
{
try{
deleteRecord(context, HM);
write(context,"InstanceName",HM.get("InstanceName").toString());
write(context,"EventName",HM.get("EventName").toString());
write(context,"EventApp",HM.get("EventApp").toString());
write(context,"FilterType",HM.get("FilterType").toString());
write(context,"FilterData",HM.get("FilterData").toString());
write(context,"ActionName",HM.get("ActionName").toString());
write(context,"ActionApp",HM.get("ActionApp").toString());
write(context,"ActionData",HM.get("ActionData").toString());
write(context,"EnableInstance",HM.get("EnableInstance").toString());
return 1;
}catch(Exception e)
{
OmLogger.write(context,"Unable to write record from User Config");
return 0;
}
}
}
|
package edu.toronto.bb.core;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import org.biojava3.core.sequence.AccessionID;
import org.biojava3.core.sequence.DNASequence;
import org.biojava3.core.sequence.compound.DNACompoundSet;
import org.biojava3.core.sequence.compound.NucleotideCompound;
import org.biojava3.core.sequence.io.FastaReader;
import org.biojava3.core.sequence.io.FastaReaderHelper;
import org.biojava3.core.sequence.io.FastaWriter;
import org.biojava3.core.sequence.io.FastaWriterHelper;
import org.biojava3.core.sequence.io.FileProxyDNASequenceCreator;
import org.biojava3.core.sequence.io.GenericFastaHeaderFormat;
import org.biojava3.core.sequence.io.GenericFastaHeaderParser;
import org.biojava3.core.sequence.io.template.FastaHeaderFormatInterface;
import org.biojava3.core.sequence.io.template.SequenceCreatorInterface;
import edu.toronto.bb.core.phred.PhredReader;
import edu.toronto.bb.core.phred.PhredScore;
import edu.toronto.bb.core.phred.PhredScoreSequence;
import edu.toronto.bb.core.phred.PhredWriter;
public class BarcodeBooster {
private File fnaIn;
private File fnaOut;
private File qualIn;
private File qualOut;
private InputStream fnaInputStream;
private InputStream qualInputStream;
private FileOutputStream fnaOutputStream;
private FileOutputStream qualOutputStream;
private BufferedOutputStream fnaBO;
private BufferedOutputStream qualBO;
private FastaWriter<DNASequence, NucleotideCompound> fastaWriter;
private PhredReader phredReader;
private PhredWriter phredWriter;
private LinkedHashMap<String,DNASequence> dnaSequences;
private LinkedHashMap<String,PhredScoreSequence> qualSequences;
private String barcodes; // contains the CSV formats of all the barcodes
private final String pathToBarcodes = "config/barcodes";
private final int barcodeLength = 10;
private String marker = ""; // key to be inserted
public BarcodeBooster(File fnaIn, File fnaOut, File qualIn, File qualOut) throws FileNotFoundException {
this.fnaIn = fnaIn;
this.fnaOut = fnaOut;
this.qualIn = qualIn;
this.qualOut = qualOut;
}
public void process() throws Throwable {
if (marker.length() != 1) {
throw new IllegalArgumentException("marker has to be exactly one character");
}
barcodes = loadBarcodes();
initInputIO();
dnaSequences = FastaReaderHelper.readFastaDNASequence(fnaIn);
qualSequences = phredReader.process();
searchForBarcodeAndInsertMarkerToSequence();
initOutputIO();
FastaWriterHelper.writeNucleotideSequence(fnaBO, dnaSequences.values());
phredWriter.process();
closeIO();
}
public String getMarker() {
return marker;
}
public void setMarker(String key) {
this.marker = key;
}
private void searchForBarcodeAndInsertMarkerToSequence() {
DNASequence newDNASequence;
DNASequence currDNASequence;
PhredScoreSequence currPhredScoreSequence;
String currKey;
for(Entry<String, DNASequence> entry : dnaSequences.entrySet() ) {
currDNASequence = entry.getValue();
currKey = entry.getKey();
if (containsBarcode(currDNASequence.toString(), barcodes)) {
newDNASequence = new DNASequence(marker + currDNASequence.toString());
newDNASequence.setAccession(currDNASequence.getAccession());
dnaSequences.put(entry.getKey(), newDNASequence);
currPhredScoreSequence = qualSequences.get(currKey);
if (currPhredScoreSequence == null) {
throw new IllegalArgumentException("No matching PhredScore Sequence with header " + entry.getKey());
} else {
currPhredScoreSequence.pushScore(new PhredScore(PhredScore.MAX_SCORE));
}
}
}
}
private boolean containsBarcode(String sequenceData, String barcodes) {
return barcodes.indexOf(sequenceData.substring(0, barcodeLength)) > -1;
}
private void initInputIO() throws FileNotFoundException {
fnaInputStream = new FileInputStream(fnaIn);
qualInputStream = new FileInputStream(qualIn);
phredReader = new PhredReader(qualInputStream);
}
private void initOutputIO() throws FileNotFoundException {
fnaOutputStream = new FileOutputStream(fnaOut);
qualOutputStream = new FileOutputStream(qualOut);
fnaBO = new BufferedOutputStream(fnaOutputStream);
qualBO = new BufferedOutputStream(qualOutputStream);
phredWriter = new PhredWriter(qualBO, qualSequences.values());
}
private void closeIO() throws IOException {
fnaInputStream.close();
qualInputStream.close();
fnaBO.close();
fnaOutputStream.close();
qualBO.close();
qualOutputStream.close();
}
private String loadBarcodes() throws IOException {
FileInputStream barcodeFile = new FileInputStream(pathToBarcodes);
InputStreamReader reader = new InputStreamReader(barcodeFile);
BufferedReader br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String delimiter =",";
String line = br.readLine();
while (line != null ) {
sb.append(line);
sb.append(delimiter);
line = br.readLine();
}
br.close();
reader.close();
barcodeFile.close();
return sb.toString();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package flowreader.view.diveview;
import flowreader.model.Document;
import flowreader.model.Page;
import flowreader.model.WordCloud;
import java.util.ArrayList;
import javafx.animation.ParallelTransition;
import javafx.animation.TranslateTransition;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.input.ZoomEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;
/**
*
* @author D-Day
*/
public class DiveViewScene extends StackPane {
private ArrayList<DiveRibbonPane> levels;
private int currentLevel;
private BorderPane bp;
private StackPane contentPane;
private LiftPane lp;
private boolean otherTransitionsFinished = true;
public DiveViewScene(Document document) {
bp = new BorderPane();
this.contentPane = new StackPane();
ArrayList<ArrayList<WordCloud>> wordClouds = document.getWordClouds();
ArrayList<Page> pages = document.getPages();
lp = new LiftPane(wordClouds.size() + 1);
double x = 0, y = 0;
this.levels = new ArrayList<>();
// Creation of the pages
DiveRibbonPane pagesLevel = new DivePagesRibbonPane(pages, x, y);
this.levels.add(pagesLevel);
// Creation of the word clouds
for (int i = 0; i < wordClouds.size(); i++) {
DiveRibbonPane wcp = new DiveWcRibbonPane(wordClouds.get(i), x, y);
x = x + (wcp.getRibbonWidth() / 4);
this.levels.add(wcp);
}
this.currentLevel = this.levels.size() - 1;
ArrayList<Integer> ali = new ArrayList<>();
ali.add(0);
this.levels.get(this.currentLevel).createRibbon(ali);
this.contentPane.getChildren().add(this.levels.get(this.currentLevel));
bp.setCenter(this.contentPane);
this.lp.setHighLight(currentLevel);
bp.setRight(lp);
this.getChildren().add(bp);
//this.swipe();
this.diveIn();
this.diveOut();
}
private void swipe() {
EventHandler<MouseEvent> swipeHandler = new EventHandler<MouseEvent>() {
MouseEvent previousEvent;
@Override
public void handle(MouseEvent event) {
if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
previousEvent = event;
// System.out.println("PRESSED");
} else if (event.getEventType().equals(MouseEvent.MOUSE_DRAGGED)) {
// System.out.println("DRAGGED");
double dx = event.getX() - previousEvent.getX();
double dy = event.getY() - previousEvent.getY();
for (DiveRibbonPane rp : DiveViewScene.this.levels) {
rp.move(dx, dy);
}
TranslateTransition tt = new TranslateTransition(Duration.millis(100), DiveViewScene.this);
tt.setByX(dx);
tt.setByY(dy);
tt.setCycleCount(0);
tt.setAutoReverse(true);
tt.play();
} else if (event.getEventType().equals(MouseEvent.MOUSE_CLICKED)) {
if (event.getClickCount() == 2) {
if (event.getButton().equals(MouseButton.PRIMARY) && DiveViewScene.this.currentLevel != 0) {
DiveViewScene.this.currentLevel -= 1;
DiveViewScene.this.getChildren().clear();
DiveViewScene.this.getChildren().add(DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel));
} else if (event.getButton().equals(MouseButton.SECONDARY) && DiveViewScene.this.currentLevel != DiveViewScene.this.levels.size() - 1) {
DiveViewScene.this.currentLevel += 1;
DiveViewScene.this.getChildren().clear();
DiveViewScene.this.getChildren().add(DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel));
}
}
}
previousEvent = event;
event.consume();
}
};
this.addEventHandler(MouseEvent.MOUSE_DRAGGED, swipeHandler);
this.addEventHandler(MouseEvent.MOUSE_PRESSED, swipeHandler);
this.addEventHandler(MouseEvent.MOUSE_RELEASED, swipeHandler);
}
private void diveIn() {
EventHandler<ScrollEvent> diveInScrollHandler = new EventHandler<ScrollEvent>() {
@Override
public void handle(ScrollEvent event) {
if (event.getDeltaY() > 0 && DiveViewScene.this.otherTransitionsFinished) { // Scroll forward
if (DiveViewScene.this.currentLevel != 0 && DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel).getSelectedIndexes().size()>0) {
DiveViewScene.this.otherTransitionsFinished = false;
//Collect data from the previous level
DiveRibbonPane previous = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
double previousFocusPoint = previous.getFocusPoint();
int previousSelectedIndex = previous.getSelectedIndexes().get(0);
// Set up current level
DiveViewScene.this.currentLevel -= 1;
DiveViewScene.this.lp.setHighLight(currentLevel);
DiveRibbonPane current = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
if (DiveViewScene.this.currentLevel == 0) {
ArrayList<Integer> ali = new ArrayList<>();
ali.add(previousSelectedIndex);
current.createRibbon(ali);
} else {
current.createRibbon(getIndexesCurrentLevelDiveIn(previousSelectedIndex, DiveViewScene.this.currentLevel));
}
double focusPoint = current.getFocusPoint();
double x = 0 + (previousFocusPoint - focusPoint);
current.setNewPosition(x, 0);
//We add the current level in the scene
DiveViewScene.this.contentPane.getChildren().add(current);
ParallelTransition at = current.appearTransitionDiveIn();
ParallelTransition dt = previous.disappearTransitionDiveIn();
at.play();
dt.play();
dt.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DiveViewScene.this.contentPane.getChildren().remove(DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel+1));
DiveViewScene.this.otherTransitionsFinished = true;
}
});
//DiveViewScene.this.contentPane.getChildren().remove(previous);
}
}
event.consume();
}
};
this.addEventHandler(ScrollEvent.SCROLL, diveInScrollHandler);
EventHandler<ZoomEvent> diveInZoomHandler = new EventHandler<ZoomEvent>() {
@Override
public void handle(ZoomEvent event) {
double delta = event.getZoomFactor() - 1;
if (delta > 0 && DiveViewScene.this.otherTransitionsFinished) { // Scroll forward
if (DiveViewScene.this.currentLevel != 0 && DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel).getSelectedIndexes().size()>0) {
DiveViewScene.this.otherTransitionsFinished = false;
//Collect data from the previous level
DiveRibbonPane previous = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
double previousFocusPoint = previous.getFocusPoint();
int previousSelectedIndex = previous.getSelectedIndexes().get(0);
// Set up current level
DiveViewScene.this.currentLevel -= 1;
DiveViewScene.this.lp.setHighLight(currentLevel);
DiveRibbonPane current = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
if (DiveViewScene.this.currentLevel == 0) {
ArrayList<Integer> ali = new ArrayList<>();
ali.add(previousSelectedIndex);
current.createRibbon(ali);
} else {
current.createRibbon(getIndexesCurrentLevelDiveIn(previousSelectedIndex, DiveViewScene.this.currentLevel));
}
double focusPoint = current.getFocusPoint();
double x = 0 + (previousFocusPoint - focusPoint);
current.setNewPosition(x, 0);
//We add the current level in the scene
DiveViewScene.this.contentPane.getChildren().add(current);
ParallelTransition at = current.appearTransitionDiveIn();
ParallelTransition dt = previous.disappearTransitionDiveIn();
at.play();
dt.play();
dt.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DiveViewScene.this.contentPane.getChildren().remove(DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel+1));
DiveViewScene.this.otherTransitionsFinished = true;
}
});
//DiveViewScene.this.contentPane.getChildren().remove(previous);
}
}
event.consume();
}
};
this.addEventHandler(ZoomEvent.ZOOM, diveInZoomHandler);
}
private void diveOut() {
EventHandler<ScrollEvent> diveOutHandler = new EventHandler<ScrollEvent>() {
@Override
public void handle(ScrollEvent event) {
if (event.getDeltaY() < 0 && DiveViewScene.this.otherTransitionsFinished) {
if (DiveViewScene.this.currentLevel != DiveViewScene.this.levels.size() - 1 && DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel).getSelectedIndexes().size()>0) {
DiveViewScene.this.otherTransitionsFinished = false;
//Collect data from the previous level
DiveRibbonPane previous = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
double previousFocusPoint = previous.getFocusPoint();
int previousSelectedIndex = previous.getSelectedIndexes().get(0);
// Set up current level
DiveViewScene.this.currentLevel += 1;
DiveViewScene.this.lp.setHighLight(currentLevel);
DiveRibbonPane current = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
if (DiveViewScene.this.currentLevel == 0) {
ArrayList<Integer> ali = new ArrayList<>();
ali.add(previousSelectedIndex);
current.createRibbon(ali);
} else {
current.createRibbon(getIndexesCurrentLevelDiveOut(previousSelectedIndex, DiveViewScene.this.currentLevel));
}
double focusPoint = current.getFocusPoint();
double x = 0 + (previousFocusPoint - focusPoint);
current.setNewPosition(x, 0);
DiveViewScene.this.contentPane.getChildren().add(current);
ParallelTransition at = current.appearTransitionDiveOut();
ParallelTransition dt = previous.disappearTransitionDiveOut();
at.play();
dt.play();
dt.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DiveViewScene.this.contentPane.getChildren().remove(DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel-1));
DiveViewScene.this.otherTransitionsFinished = true;
}
});
}
}
event.consume();
}
};
this.addEventHandler(ScrollEvent.SCROLL, diveOutHandler);
EventHandler<ZoomEvent> diveOutZoomHandler = new EventHandler<ZoomEvent>() {
@Override
public void handle(ZoomEvent event) {
double delta = event.getZoomFactor() - 1;
if (delta < 0 && DiveViewScene.this.otherTransitionsFinished) {
if (DiveViewScene.this.currentLevel != DiveViewScene.this.levels.size() - 1 && DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel).getSelectedIndexes().size()>0) {
DiveViewScene.this.otherTransitionsFinished = false;
DiveRibbonPane current = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
DiveViewScene.this.currentLevel += 1;
DiveViewScene.this.lp.setHighLight(currentLevel);
DiveRibbonPane next = DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel);
DiveViewScene.this.contentPane.getChildren().add(next);
ParallelTransition at = next.appearTransitionDiveOut();
ParallelTransition dt = current.disappearTransitionDiveOut();
at.play();
dt.play();
dt.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DiveViewScene.this.contentPane.getChildren().remove(DiveViewScene.this.levels.get(DiveViewScene.this.currentLevel-1));
DiveViewScene.this.otherTransitionsFinished = true;
}
});
}
}
event.consume();
}
};
this.addEventHandler(ZoomEvent.ZOOM, diveOutZoomHandler);
}
private ArrayList<Integer> getIndexesCurrentLevelDiveIn(int previousSelectedIndex, int level) {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(previousSelectedIndex * 2);
temp.add((previousSelectedIndex * 2) + 1);
if ((this.levels.get(level).getNumberOfElements() % 2 == 1) && (this.levels.get(level + 1).getNumberOfElements() - 1 == previousSelectedIndex)) {
temp.add((previousSelectedIndex * 2) + 2);
}
/*String s = "previous " + previousSelectedIndex + " current ";
for (Integer i : temp) {
s += i + " ";
}
System.out.println(s);*/
return temp;
}
private ArrayList<Integer> getIndexesCurrentLevelDiveOut(int previousSelectedIndex, int level) {
ArrayList<Integer> temp = new ArrayList<>();
if(level == this.levels.size()-1){
temp.add(0);
}
else {
if ((this.levels.get(level-1).getNumberOfElements() % 2 == 1) && (this.levels.get(level - 1).getNumberOfElements() - 1 == previousSelectedIndex)) {
previousSelectedIndex -= 1;
}
temp = getIndexesCurrentLevelDiveIn(previousSelectedIndex/4, level-1);
}
/*String s = "Curent Level "+ level+" previous index " + previousSelectedIndex + " current ";
for (Integer i : temp) {
s += i + " ";
}
System.out.println(s);*/
return temp;
}
}
|
package io.miti.codeman.actions;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import io.miti.codeman.managers.TabViewManager;
import io.miti.codeman.managers.ZipManager;
import io.miti.codeman.model.FileListModel;
import io.miti.codeman.util.Utility;
public final class MousePopupListener extends MouseAdapter
{
private JList<String> tableList = null;
private JPopupMenu menu = new JPopupMenu();
private Point point = null;
private static final String eoln = "\r\n";
/**
* Default constructor.
*/
public MousePopupListener()
{
super();
}
/**
* Standard constructor for this class.
*
* @param tableData whether we're showing table or column data
* @param dataList the JList for this popup menu
*/
public MousePopupListener(final JList<String> dataList)
{
tableList = dataList;
buildPopup();
}
/**
* Build the popup menu.
*/
private void buildPopup()
{
JMenuItem m1 = new JMenuItem("Open this file");
m1.addActionListener(new PopupAction(0));
JMenuItem m2 = new JMenuItem("Copy this file");
m2.addActionListener(new PopupAction(1));
JMenuItem m3 = new JMenuItem("Copy selected files");
m3.addActionListener(new PopupAction(2));
JMenuItem m4 = new JMenuItem("Copy all files");
m4.addActionListener(new PopupAction(3));
menu.add(m1);
menu.add(m2);
menu.add(m3);
menu.add(m4);
}
@Override
public void mouseClicked(final MouseEvent e)
{
checkPopup(e);
}
@Override
public void mousePressed(final MouseEvent e)
{
checkPopup(e);
}
@Override
public void mouseReleased(final MouseEvent e)
{
checkPopup(e);
}
/**
* If the user invoked the popup trigger (right-click), show the popup menu.
*
* @param e the mouse event
*/
private void checkPopup(final MouseEvent e)
{
if (e.isPopupTrigger())
{
point = new Point(e.getX(), e.getY());
updatePopupItems();
menu.show(tableList, e.getX(), e.getY());
}
}
/**
* Enable and disable items in the popup menu as needed.
*/
private void updatePopupItems()
{
// See if the list has any items
final int len = ((FileListModel) tableList.getModel()).getSize();
if (len < 1)
{
// No items in the list, so disable all menu items
enableMenuItems(false, new int[] {0, 1, 2, 3});
return;
}
else
{
// Enable the "all tables" menu items
enableMenuItems(true, new int[] {3});
// Check if there's an item near the mouse click
final int currItem = tableList.locationToIndex(point);
enableMenuItems((currItem >= 0), new int[] {0, 1});
// Check if any rows are selected
final int[] sel = tableList.getSelectedIndices();
enableMenuItems((sel.length > 0), new int[] {2});
}
}
/**
* Enable or disable menu items in the popup menu.
*
* @param enable whether to enable the items referenced by the list in ind
* @param ind the list of indices of popup menu items to enable or disable
*/
private void enableMenuItems(final boolean enable, final int[] ind)
{
final int num = ind.length;
for (int i = 0; i < num; ++i)
{
menu.getComponent(ind[i]).setEnabled(enable);
}
}
/**
* The action listener for the items in the popup menu.
*/
class PopupAction implements ActionListener
{
/** The mode for this action - copy one row, selected rows, or all rows. */
private int mode = 0;
/**
* Constructor.
*
* @param nMode the mode for this instance
*/
public PopupAction(final int nMode)
{
mode = nMode;
}
/**
* Handle the action.
*
* @param evt the action event
*/
@Override
public void actionPerformed(final ActionEvent evt)
{
switch (mode)
{
case 0:
openFile(evt);
break;
case 1:
copyFileName(evt);
break;
case 2:
copySelectedFileNames(evt);
break;
case 3:
copyAllFileNames(evt);
break;
}
}
/**
* Open the current file.
*
* @param evt the action event
*/
private void openFile(final ActionEvent evt)
{
final int currItem = tableList.locationToIndex(point);
if (currItem >= 0)
{
String item = (String) ((FileListModel)
tableList.getModel()).getElementAt(currItem);
String text = ZipManager.getInstance().getFileText(item);
if (text != null)
{
TabViewManager.getInstance().addFileFromZip(item, text);
}
}
}
/**
* Copy the current object.
*
* @param evt the action event
*/
private void copyFileName(final ActionEvent evt)
{
final int currItem = tableList.locationToIndex(point);
if (currItem >= 0)
{
String item = (String) ((FileListModel)
tableList.getModel()).getElementAt(currItem);
if (item != null)
{
Utility.copyToClipboard(item);
}
}
}
/**
* Copy the current object.
*
* @param evt the action event
*/
private void copySelectedFileNames(final ActionEvent evt)
{
final int[] sel = tableList.getSelectedIndices();
if ((sel == null) || (sel.length < 1))
{
return;
}
final int len = sel.length;
StringBuilder sb = new StringBuilder(100);
String name = (String) ((FileListModel)
tableList.getModel()).getElementAt(sel[0]);
sb.append(name);
for (int i = 1; i < len; ++i)
{
name = (String) ((FileListModel)
tableList.getModel()).getElementAt(sel[i]);
sb.append(eoln).append(name);
}
Utility.copyToClipboard(sb.toString());
}
/**
* Copy the current objects.
*
* @param evt the action event
*/
private void copyAllFileNames(final ActionEvent evt)
{
final int len = ((FileListModel) tableList.getModel()).getSize();
if (len < 1)
{
return;
}
StringBuilder sb = new StringBuilder(100);
String name = (String) ((FileListModel)
tableList.getModel()).getElementAt(0);
sb.append(name);
for (int i = 1; i < len; ++i)
{
name = (String) ((FileListModel)
tableList.getModel()).getElementAt(i);
sb.append(eoln).append(name);
}
Utility.copyToClipboard(sb.toString());
}
}
}
|
package it.unitn.disi.annotation;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import it.unitn.disi.annotation.data.INLPContext;
import it.unitn.disi.annotation.data.INLPNode;
import it.unitn.disi.annotation.loaders.context.INLPContextLoader;
import it.unitn.disi.annotation.renderers.context.INLPContextRenderer;
import it.unitn.disi.common.components.Configurable;
import it.unitn.disi.common.components.ConfigurableException;
import it.unitn.disi.common.utils.MiscUtils;
import it.unitn.disi.nlptools.NLPToolsConstants;
import it.unitn.disi.nlptools.NLPToolsException;
import it.unitn.disi.nlptools.components.PipelineComponentException;
import it.unitn.disi.nlptools.data.ILabel;
import it.unitn.disi.nlptools.data.IToken;
import it.unitn.disi.nlptools.data.Label;
import it.unitn.disi.nlptools.data.Token;
import it.unitn.disi.nlptools.pipelines.ILabelPipelineComponent;
import it.unitn.disi.smatch.loaders.context.ContextLoaderException;
import it.unitn.disi.smatch.renderers.context.ContextRendererException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.*;
import java.util.List;
public class POSAnnotationTool extends Configurable {
private static Logger log;
static {
MiscUtils.configureLog4J();
log = Logger.getLogger(POSAnnotationTool.class);
}
private static final String CONF_FILE = ".." + File.separator + "conf" + File.separator + "annotation.properties";
private static final String LOOK_AND_FEEL_KEY = "LookAndFeel";
private String lookAndFeel = null;
private static final String TAG_ORDER = "tagOrder";
List<String> tagOrder = Arrays.asList(NLPToolsConstants.ARR_POS_ALL);
private static final String CONTEXT_LOADER_KEY = "contextLoader";
private INLPContextLoader contextLoader;
private static final String CONTEXT_RENDERER_KEY = "contextRenderer";
private INLPContextRenderer contextRenderer;
private static final String TOKENIZER_KEY = "tokenizer";
private ILabelPipelineComponent tokenizer;
private static final String POS_TAGGER_KEY = "postagger";
private ILabelPipelineComponent postagger;
private String inputFileName = null;
//allows loading other datasets to be used as label dictionaries. semicolon-separated list
private static final String loadAlsoCmdLineToken = "-loadAlso=";
private INLPContext context;
private java.util.List<INLPNode> data;
private boolean dataModified = false;
private int curIndex = -1;
//panels with interface for phrases to avoid flicker when going force-n-back
private final ArrayList<JPanel> phrasePanels = new ArrayList<JPanel>();
private JPanel curPhrasePanel = null;
private String datasetSizeString = "";
private Action prevAction = new PrevAction("Prev", "Go to previous item", KeyEvent.VK_P);
private Action nextAction = new NextAction("Next", "Go to next item", KeyEvent.VK_N);
private Action nextNNPAction = new NextNNPAction("NNP && Next", "Mark all NNP and go to next item", KeyEvent.VK_X);
private Action prevTagsAction = new PrevTagsAction("Prev Tags", "Load tags from previous item", KeyEvent.VK_T);
//magics used in binding components for data elements
//ILabel, binds phrase objects to interface objects
private static final String MAGIC_LABEL = "LABEL";
//IToken, binds token to panel
private static final String MAGIC_TOKEN = "TOKEN";
//panel -> token pos list
private static final String MAGIC_TOKEN_POS_LIST = "TOKENPOS_";
private static JPanel mainPanel;
private static JButton btNext;
private static JButton btNextNNP;
private static JButton btPrevTags;
private static JTextField lbLabel;
private static JTextField lbPath;
private static JScrollPane tokensScroll;
private static JProgressBar progressBar;
//label -> tagged label: token \t tag \t\t ...
private static final HashMap<String, String> taggedPOS = new HashMap<String, String>();
class NavAction extends AbstractAction {
public NavAction(String text, String desc, Integer mnemonic) {
super(text);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
loadLabelAndPath();
updateActions();
loadPanel();
updateProgressBar();
}
public void actionPerforming(ActionEvent e) {
}
}
class PrevAction extends NavAction {
public PrevAction(String text, String desc, Integer mnemonic) {
super(text, desc, mnemonic);
}
public void actionPerformed(ActionEvent e) {
super.actionPerforming(e);
curIndex
super.actionPerformed(e);
}
}
class NextAction extends NavAction {
public NextAction(String text, String desc, Integer mnemonic) {
super(text, desc, mnemonic);
}
public void actionPerformed(ActionEvent e) {
super.actionPerforming(e);
//next
curIndex++;
ILabel curLabel = data.get(curIndex).getNodeData().getLabel();
if (null == curLabel) {
//create label
curLabel = new Label(data.get(curIndex).getNodeData().getName());
data.get(curIndex).getNodeData().setLabel(curLabel);
//process label
try {
tokenizer.process(curLabel);
postagger.process(curLabel);
} catch (PipelineComponentException exc) {
log.error(exc.getMessage(), exc);
}
}
//load annotation from cache into a new label
String label = curLabel.getText();
String tabText = taggedPOS.get(label);
while (null != tabText && curIndex < (data.size() - 1)) {
fromTabText(data.get(curIndex).getNodeData().getLabel(), tabText);
log.info("Skipping: " + label);
super.actionPerformed(e);
curIndex++;
curLabel = data.get(curIndex).getNodeData().getLabel();
if (null == curLabel) {
//create label
curLabel = new Label(data.get(curIndex).getNodeData().getName());
data.get(curIndex).getNodeData().setLabel(curLabel);
//process label
try {
tokenizer.process(curLabel);
postagger.process(curLabel);
} catch (PipelineComponentException exc) {
log.error(exc.getMessage(), exc);
}
}
label = data.get(curIndex).getNodeData().getLabel().getText();
tabText = taggedPOS.get(label);
}
super.actionPerformed(e);
}
}
/**
* Tab text format: token \t pos \t\t token \t pos \t\t ...
*
* @param label label instance
* @return tab text
*/
private String toTabText(ILabel label) {
StringBuilder result = new StringBuilder();
if (0 < label.getTokens().size()) {
for (IToken token : label.getTokens()) {
result.append(token.getText()).append("\t").append(token.getPOSTag()).append("\t\t");
}
}
return result.substring(0, result.length() - 2);
}
private void fromTabText(ILabel label, String tabText) {
String[] tokens = tabText.split("\t\t");
label.setTokens(new ArrayList<IToken>(tokens.length));
for (String token : tokens) {
String[] tt = token.split("\t");
IToken t = new Token(tt[0]);
t.setPOSTag(tt[1]);
label.getTokens().add(t);
}
}
class NextNNPAction extends NextAction {
public NextNNPAction(String text, String desc, Integer mnemonic) {
super(text, desc, mnemonic);
}
public void actionPerformed(ActionEvent e) {
super.actionPerforming(e);
//set NNP
ILabel curLabel = data.get(curIndex).getNodeData().getLabel();
if (null != curLabel) {
for (IToken token : curLabel.getTokens()) {
token.setPOSTag(NLPToolsConstants.PROPER_NOUN_SING);
}
modify();
loadLabelAndPath();
}
super.actionPerformed(e);
}
}
private void modify() {
dataModified = true;
updateActions();
}
class PrevTagsAction extends AbstractAction {
public PrevTagsAction(String text, String desc, Integer mnemonic) {
super(text);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
//set prev tags
copyTags(data.get(curIndex - 1).getNodeData().getLabel(), data.get(curIndex).getNodeData().getLabel());
loadLabelAndPath();
loadPanel();
}
public void actionPerforming(ActionEvent e) {
}
}
private void copyTags(ILabel source, ILabel target) {
if (null != source && null != target) {
if (source.getTokens().size() == target.getTokens().size()) {
for (int i = 0; i < source.getTokens().size(); i++) {
target.getTokens().get(i).setPOSTag(source.getTokens().get(i).getPOSTag());
}
}
}
}
private void loadPanel() {
curPhrasePanel = null;
//get new one if there is one
if ((-1 < curIndex) && (curIndex < phrasePanels.size())) {
curPhrasePanel = phrasePanels.get(curIndex);
}
//or create new one
if (null == curPhrasePanel) {
createCurrentPhrasePanel();
}
//update
if (null != curPhrasePanel) {
//update token pos
updateTokenPOS(curPhrasePanel, data.get(curIndex).getNodeData().getLabel());
tokensScroll.setViewportView(curPhrasePanel);
tokensScroll.repaint();
}
}
private void updateTokenPOS(JPanel curPhrasePanel, ILabel phrase) {
java.util.List<IToken> tokens;
tokens = phrase.getTokens();
for (int i = 0; i < tokens.size(); i++) {
IToken token = tokens.get(i);
Object obj = curPhrasePanel.getClientProperty(MAGIC_TOKEN_POS_LIST + Integer.toString(i));
if (null != obj && obj instanceof JList) {
JList list = (JList) obj;
//select current POS tag
list.setSelectedValue(token.getPOSTag(), true);
updatePOSListToolTip(list, token);
}
}
}
@Override
public boolean setProperties(Properties newProperties) throws ConfigurableException {
if (log.isEnabledFor(Level.INFO)) {
log.info("Loading configuration...");
}
Properties oldProperties = new Properties();
oldProperties.putAll(properties);
boolean result = super.setProperties(newProperties);
if (result) {
if (newProperties.containsKey(LOOK_AND_FEEL_KEY)) {
lookAndFeel = newProperties.getProperty(LOOK_AND_FEEL_KEY);
}
if (newProperties.containsKey(TAG_ORDER)) {
String order = newProperties.getProperty(TAG_ORDER);
String[] tags = order.split("\t");
tagOrder = new ArrayList<String>(Arrays.asList(tags));
for (String t : NLPToolsConstants.ARR_POS_ALL) {
if (!tagOrder.contains(t)) {
tagOrder.add(t);
}
}
}
contextLoader = (INLPContextLoader) configureComponent(contextLoader, oldProperties, newProperties, "context loader", CONTEXT_LOADER_KEY, INLPContextLoader.class);
contextRenderer = (INLPContextRenderer) configureComponent(contextRenderer, oldProperties, newProperties, "context renderer", CONTEXT_RENDERER_KEY, INLPContextRenderer.class);
tokenizer = (ILabelPipelineComponent) configureComponent(tokenizer, oldProperties, newProperties, "tokenizer", TOKENIZER_KEY, ILabelPipelineComponent.class);
postagger = (ILabelPipelineComponent) configureComponent(postagger, oldProperties, newProperties, "POS tagger", POS_TAGGER_KEY, ILabelPipelineComponent.class);
}
return result;
}
private void createCurrentPhrasePanel() {
try {
curPhrasePanel = buildPhrasePanel(data.get(curIndex).getNodeData().getLabel());
} catch (NLPToolsException e) {
if (log.isEnabledFor(Level.ERROR)) {
log.error("NLPToolsException: ", e);
}
curPhrasePanel = null;
} catch (RemoteException e) {
if (log.isEnabledFor(Level.ERROR)) {
log.error("RemoteException: ", e);
}
curPhrasePanel = null;
}
if ((-1 < curIndex) && (curIndex < phrasePanels.size())) {
phrasePanels.set(curIndex, curPhrasePanel);
} else {
phrasePanels.add(curIndex, curPhrasePanel);
}
//update
tokensScroll.setViewportView(curPhrasePanel);
tokensScroll.repaint();
}
private JPanel buildPhrasePanel(ILabel curPhrase) throws NLPToolsException, RemoteException {
JPanel result = null;
//TODO: hotkey for each token: 1,2,3,4...9,0 ?A,B,C?
String layoutRows = "default, 4dlu, fill:min:grow";//row for tokens, row for POS tags
String layoutColumns = "";
//create a column for each token
java.util.List<IToken> tokens = curPhrase.getTokens();
if (0 < tokens.size()) {
for (IToken token : tokens) {
layoutColumns = layoutColumns + "fill:default, 4dlu, ";
}
layoutColumns = layoutColumns.substring(0, layoutColumns.length() - 2);
FormLayout layout = new FormLayout(layoutColumns, layoutRows);
//PanelBuilder builder = new PanelBuilder(layout, new FormDebugPanel());
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
//later bind components via putClientProperty
for (int i = 0; i < tokens.size(); i++) {
builder.add(buildTokenTextField(curPhrase, tokens.get(i)), cc.xy(1 + 2 * i, 1, CellConstraints.FILL, CellConstraints.DEFAULT));
JScrollPane listScroll = new JScrollPane();
listScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JList list = buildTokenPOSList(curPhrase, tokens.get(i));
builder.getPanel().putClientProperty(MAGIC_TOKEN_POS_LIST + Integer.toString(i), list);
listScroll.setViewportView(list);
builder.add(listScroll, cc.xy(1 + 2 * i, 3, CellConstraints.FILL, CellConstraints.DEFAULT));
}
//FormDebugUtils.dumpAll(builder.getPanel());
result = builder.getPanel();
}
return result;
}
private JTextField buildTokenTextField(ILabel phrase, IToken token) {
JTextField textField = new JTextField();
textField.setHorizontalAlignment(JTextField.TRAILING);
textField.setText(token.getText());
//for listeners
//split on space and on dblclick
textField.putClientProperty(MAGIC_TOKEN, token);
textField.putClientProperty(MAGIC_LABEL, phrase);
//splits token on space typed
textField.addKeyListener(tokenTextFieldKeyTyped);
//updates token on enter typed
textField.addKeyListener(tokenTextFieldKeyReleased);
//splits token on dbl click
//does not work - work selectAll
//textField.addMouseListener(tokenTextFieldMouseClick);
return textField;
}
private final KeyAdapter tokenTextFieldKeyTyped = new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (' ' == e.getKeyChar()) {
super.keyTyped(e);
processTokenSplittingKeyEvent(e);
} else {
if ('+' == e.getKeyChar()) {
super.keyTyped(e);
processTokenJoinKeyEvent(e);
}
//now we allow token editing...
//e.consume();
super.keyTyped(e);
}
}
};
private final KeyAdapter tokenTextFieldKeyReleased = new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyCode()) {
super.keyTyped(e);
processTokenUpdateKeyEvent(e);
} else {
//now we allow token editing...
//e.consume();
super.keyTyped(e);
}
}
};
private void processTokenUpdateKeyEvent(KeyEvent e) {
Object mayBeTextField = e.getSource();
if (mayBeTextField instanceof JTextField) {
JTextField textField = (JTextField) mayBeTextField;
Object mayBeNLToken = textField.getClientProperty(MAGIC_TOKEN);
if (mayBeNLToken instanceof IToken) {
Object mayBeNLPhrase = textField.getClientProperty(MAGIC_LABEL);
if (mayBeNLPhrase instanceof ILabel) {
updateToken((ILabel) mayBeNLPhrase, (IToken) mayBeNLToken, textField.getText());
}
}
}
}
private void processTokenSplittingKeyEvent(KeyEvent e) {
Object mayBeTextField = e.getSource();
if (mayBeTextField instanceof JTextField) {
JTextField textField = (JTextField) mayBeTextField;
Object mayBeNLToken = textField.getClientProperty(MAGIC_TOKEN);
if (mayBeNLToken instanceof IToken) {
Object mayBeNLPhrase = textField.getClientProperty(MAGIC_LABEL);
if (mayBeNLPhrase instanceof ILabel) {
splitToken((ILabel) mayBeNLPhrase, (IToken) mayBeNLToken, textField.getCaretPosition());
}
}
}
}
private void processTokenJoinKeyEvent(KeyEvent e) {
Object mayBeTextField = e.getSource();
if (mayBeTextField instanceof JTextField) {
JTextField textField = (JTextField) mayBeTextField;
Object mayBeNLToken = textField.getClientProperty(MAGIC_TOKEN);
if (mayBeNLToken instanceof IToken) {
Object mayBeNLPhrase = textField.getClientProperty(MAGIC_LABEL);
if (mayBeNLPhrase instanceof ILabel) {
joinToken((ILabel) mayBeNLPhrase, (IToken) mayBeNLToken, textField.getText());
}
}
}
}
private void splitToken(ILabel label, IToken token, int position) {
String stringToken = token.getText();
if (0 < position && position < stringToken.length()) {
//will insert new tokens here
int tokenIndex = label.getTokens().indexOf(token);
IToken firstToken = new Token(stringToken.substring(0, position).trim());
IToken secondToken = new Token(stringToken.substring(position, stringToken.length()).trim());
//bye bye
label.getTokens().remove(token);
label.getTokens().add(tokenIndex, secondToken);
label.getTokens().add(tokenIndex, firstToken);
try {
postagger.process(label);
} catch (PipelineComponentException e) {
log.error(e.getMessage(), e);
}
//updates current panel to make controls for new tokens
createCurrentPhrasePanel();
loadLabelAndPath();
modify();
}
}
private void joinToken(ILabel label, IToken token, String updatedTokenText) {
int tokenIndex = label.getTokens().indexOf(token);
java.util.List<IToken> tokens = label.getTokens();
if (tokenIndex < tokens.size() - 1) {
String newTokenText = updatedTokenText + tokens.get(tokenIndex + 1).getText();
//current one
label.getTokens().remove(token);
//next one
label.getTokens().remove(tokens.get(tokenIndex));
//add new one in place of original
label.getTokens().add(tokenIndex, new Token(newTokenText));
try {
postagger.process(label);
} catch (PipelineComponentException e) {
log.error(e.getMessage(), e);
}
//updates current panel to make controls for new tokens
createCurrentPhrasePanel();
loadLabelAndPath();
modify();
}
}
private void updateToken(ILabel label, IToken token, String updatedTokenText) {
int tokenIndex = label.getTokens().indexOf(token);
//current one
label.getTokens().remove(token);
//add new one in place of original
label.getTokens().add(tokenIndex, new Token(updatedTokenText));
try {
postagger.process(label);
} catch (PipelineComponentException e) {
log.error(e.getMessage(), e);
}
//updates current panel to make controls for new tokens
createCurrentPhrasePanel();
loadLabelAndPath();
modify();
}
private JList buildTokenPOSList(ILabel label, IToken token) {
JList posList = new JList();
posList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
DefaultListModel model = new DefaultListModel();
for (String pos : tagOrder) {
model.addElement(pos);
}
//for empty tags. should be encountered rarely
model.addElement("");
posList.setModel(model);
//select current POS tag
int idx = model.indexOf(token.getPOSTag());
if (-1 != idx) {
posList.setSelectedIndex(idx);
posList.ensureIndexIsVisible(idx);
} else {
if (log.isEnabledFor(Level.WARN)) {
log.warn("buildTokenPOSList(ILabel label, IToken token): POS tag not found. Token: " + token.getText() + ". POS: " + token.getPOSTag());
}
}
updatePOSListToolTip(posList, token);
//token and label for future reference in listener
posList.putClientProperty(MAGIC_TOKEN, token);
posList.putClientProperty(MAGIC_LABEL, label);
//hook listener
posList.addListSelectionListener(tokenPOSListSelectionListener);
posList.addMouseListener(tokenPOSListMouseListener);
posList.addMouseWheelListener(tokenPOSListMouseWheelListener);
return posList;
}
private static void updatePOSListToolTip(JList posCombo, IToken nlToken) {
String hint = NLPToolsConstants.posDescriptions.get(nlToken.getPOSTag());
posCombo.setToolTipText(hint);
}
//listener for token pos combobox
private ListSelectionListener tokenPOSListSelectionListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getSource() instanceof JList) {
JList source = (JList) e.getSource();
IToken token = (IToken) source.getClientProperty(MAGIC_TOKEN);
if (source.getSelectedValue() instanceof String) {
String tag = (String) source.getSelectedValue();
token.setPOSTag(tag);
updatePOSListToolTip(source, token);
//update cache, useful on correction
ILabel label = (ILabel) source.getClientProperty(MAGIC_LABEL);
taggedPOS.remove(label.getText());
taggedPOS.put(label.getText(), toTabText(label));
modify();
}
}
}
};
private static final MouseListener tokenPOSListMouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (2 == e.getClickCount()) {
btNext.doClick();
}
}
};
private static final MouseWheelListener tokenPOSListMouseWheelListener = new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getSource() instanceof JList) {
JList source = (JList) e.getSource();
int idx = source.getSelectedIndex();
idx = idx + e.getWheelRotation();
if (-1 < idx && idx < source.getModel().getSize()) {
source.setSelectedIndex(idx);
source.ensureIndexIsVisible(idx);
}
}
}
};
private void updateProgressBar() {
if (-1 < curIndex) {
progressBar.setValue(curIndex);
progressBar.setToolTipText("Item " + Integer.toString(curIndex) + " of " + datasetSizeString);
}
}
public POSAnnotationTool(String inputFile) {
inputFileName = inputFile;
}
private void loadLabelAndPath() {
String label = "";
String path = "";
if (-1 != curIndex) {
//label = curDataItem.getLabel();
path = getPathToRoot(data.get(curIndex));
label = data.get(curIndex).getNodeData().getLabel().getText();
}
lbLabel.setText(label);
lbLabel.setToolTipText(label);
lbPath.setText(path);
lbPath.setToolTipText(path);
}
private String getPathToRoot(INLPNode node) {
StringBuilder result = new StringBuilder();
java.util.List<INLPNode> ancestors = node.getAncestorsList();
for (int i = ancestors.size() - 1; i >= 0; i
result.append(ancestors.get(i).getNodeData().getLabel().getText()).append("/");
}
return result.toString();
}
private void updateActions() {
prevAction.setEnabled(0 < curIndex);
prevTagsAction.setEnabled(0 < curIndex);
nextAction.setEnabled(curIndex < data.size() - 1);
nextNNPAction.setEnabled(curIndex < data.size() - 1);
}
private void prepareData() throws ContextLoaderException {
context = contextLoader.loadContext(inputFileName);
data = context.getNodesList();
progressBar.setMaximum(data.size());
datasetSizeString = Integer.toString(data.size());
curIndex = -1;
while (null != data.get(curIndex + 1).getNodeData().getLabel() && (curIndex < (data.size() - 2))) {
curIndex++;
}
//in case we load partially marked-up dataset
while (phrasePanels.size() <= curIndex) {
phrasePanels.add(null);
}
int oldIndex = curIndex;
while (-1 < curIndex) {
//put all already tagged labels for future reuse
ILabel label = data.get(curIndex).getNodeData().getLabel();
taggedPOS.put(label.getText(), toTabText(label));
curIndex
}
//restore index
curIndex = oldIndex;
}
private void loadAlso(String loadAlsoFileNames) throws ContextLoaderException {
String[] files = loadAlsoFileNames.split(";");
for (String file : files) {
log.info("Loading: " + file);
int oldSize = taggedPOS.size();
HashSet<String> conflicts = new HashSet<String>();
INLPContext c = contextLoader.loadContext(file);
for (Iterator<INLPNode> i = c.getNodes(); i.hasNext(); ) {
ILabel label = i.next().getNodeData().getLabel();
String annotation = toTabText(label);
if (!conflicts.contains(label.getText())) {
if (taggedPOS.containsKey(label.getText())) {
if (!taggedPOS.get(label.getText()).equals(annotation)) {
log.warn("Conflict in " + file + ": " + label.getText());
taggedPOS.remove(label.getText());
conflicts.add(label.getText());
}
} else {
//put all already tagged labels for future reuse
taggedPOS.put(label.getText(), annotation);
}
}
}
log.info("Loaded " + (taggedPOS.size() - oldSize) + " items from " + file);
}
}
private void applyLookAndFeel() {
if (null != lookAndFeel) {
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (ClassNotFoundException e) {
if (log.isEnabledFor(Level.ERROR)) {
log.error("ClassNotFoundException", e);
}
} catch (InstantiationException e) {
if (log.isEnabledFor(Level.ERROR)) {
log.error("InstantiationException", e);
}
} catch (IllegalAccessException e) {
if (log.isEnabledFor(Level.ERROR)) {
log.error("IllegalAccessException", e);
}
} catch (UnsupportedLookAndFeelException e) {
if (log.isEnabledFor(Level.ERROR)) {
log.error("UnsupportedLookAndFeelException", e);
}
}
}
}
private void showLFIs() {
System.out.println("Available LookAndFeels:");
for (UIManager.LookAndFeelInfo lfi : UIManager.getInstalledLookAndFeels()) {
System.out.println(lfi.getName() + "=" + lfi.getClassName());
}
}
private void buildStaticGUI() {
String layoutColumns = "right:pref, 4dlu, fill:max(p;400px):grow";
String layoutRows = "center:default, 4dlu, center:default, 4dlu, center:default:grow, 4dlu, center:default";
FormLayout layout = new FormLayout(layoutColumns, layoutRows);
//PanelBuilder builder = new PanelBuilder(layout, new FormDebugPanel());
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addLabel("Path:", cc.xy(1, 1));
lbPath = new JTextField("/Some/Example/Path");
lbPath.setEditable(false);
builder.add(lbPath, cc.xy(3, 1));
final JToolBar toolBar1 = new JToolBar();
toolBar1.setFloatable(false);
JButton btPrev = new JButton(prevAction);
toolBar1.add(btPrev);
btNext = new JButton(nextAction);
toolBar1.add(btNext);
btNextNNP = new JButton(nextNNPAction);
toolBar1.add(btNextNNP);
btPrevTags = new JButton(prevTagsAction);
toolBar1.add(btPrevTags);
builder.add(toolBar1, cc.xy(1, 3, CellConstraints.FILL, CellConstraints.DEFAULT));
lbLabel = new JTextField("Loading data...");
//big font for label
lbLabel.setFont(new Font(lbLabel.getFont().getName(), lbLabel.getFont().getStyle(), 22));
lbLabel.setEditable(false);
builder.add(lbLabel, cc.xy(3, 3));
tokensScroll = new JScrollPane();
tokensScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
tokensScroll.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Tokens"));
builder.add(tokensScroll, cc.xyw(1, 5, 3, CellConstraints.FILL, CellConstraints.FILL));
progressBar = new JProgressBar(0, 100);
builder.add(progressBar, cc.xyw(1, 7, 3, CellConstraints.FILL, CellConstraints.BOTTOM));
//FormDebugUtils.dumpAll(builder.getPanel());
mainPanel = builder.getPanel();
}
public void startup() throws ContextLoaderException {
showLFIs();
applyLookAndFeel();
buildStaticGUI();
prepareData();
updateProgressBar();
File inputFile = new File(inputFileName);
JFrame frame = new JFrame(inputFile.getName() + " - POS tag annotation tool");
frame.setMinimumSize(new Dimension(1000, 800));
frame.setLocation(200, 200);
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.addWindowListener(windowListener);
updateActions();
//initiate, load first item
btNext.doClick();
}
private final WindowListener windowListener = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (dataModified) {
lbLabel.setText("Saving data...");
try {
contextRenderer.render(context, inputFileName);
} catch (ContextRendererException exc) {
log.error(exc.getMessage(), exc);
}
}
e.getWindow().dispose();
}
};
public static void main(String[] args) throws ConfigurableException, ClassNotFoundException, IOException {
//analyze args
if (0 > args.length) {
System.out.println("Usage: POSAnnotationTool datasetFileName [" + loadAlsoCmdLineToken + "file1;file2;...;fileN]");
} else {
POSAnnotationTool tool = new POSAnnotationTool(args[0]);
tool.setProperties(CONF_FILE);
if (2 == args.length && args[1].startsWith(loadAlsoCmdLineToken)) {
String loadAlsoFileNames = args[1].substring(loadAlsoCmdLineToken.length(), args[1].length());
tool.loadAlso(loadAlsoFileNames);
}
tool.startup();
}
}
}
|
package fr.utc.assos.uvweb.util;
/**
* A helper class containing a few parameters for the application's animations.
*/
public class AnimationUtils {
public static final long CARD_ANIMATION_DELAY_MILLIS = 100;
public static final long CARD_ANIMATION_DURATION_MILLIS = 800;
}
|
package org.xins.logdoc;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.WeakHashMap;
/**
* Utility functions related to exceptions.
*
* @version $Revision$ $Date$
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
*
* @since XINS 1.2.0
*/
public final class ExceptionUtils {
// Class fields
/**
* Reference to the <code>getCause()</code> method in class
* <code>Throwable</code>. This reference will be <code>null</code> on Java
* 1.3.
*/
private static Method GET_CAUSE;
/**
* Reference to the <code>initCause()</code> method in class
* <code>Throwable</code>. This reference will be <code>null</code> on Java
* 1.3.
*/
private static Method SET_CAUSE;
/**
* Table that maps from exception to cause. This table will only be used on
* Java 1.3. On Java 1.4 and up it will be <code>null</code>.
*/
private static WeakHashMap CAUSE_TABLE;
/**
* Placeholder for the <code>null</code> object. This object will be stored
* in the {@link #CAUSE_TABLE} on Java 1.3 if the cause for an exception is
* set to <code>null</code>.
*/
private static final Object NULL = new Object();
// Class functions
/**
* Initializes this class.
*/
static {
Class[] args = new Class[] { Throwable.class };
try {
GET_CAUSE = Throwable.class.getDeclaredMethod("getCause", null);
SET_CAUSE = Throwable.class.getDeclaredMethod("initCause", args);
CAUSE_TABLE = null;
// Method does not exist, this is not Java 1.4
} catch (NoSuchMethodException exception) {
GET_CAUSE = null;
SET_CAUSE = null;
CAUSE_TABLE = new WeakHashMap();
// Access denied
} catch (SecurityException exception) {
throw new RuntimeException("Unable to get getCause() method of class Throwable: Access denied by security manager.");
}
}
public static Throwable getRootCause(Throwable exception)
throws IllegalArgumentException {
// Check preconditions
if (exception == null) {
throw new IllegalArgumentException("exception == null");
}
// Get the root cause of the exception
Throwable cause = getCause(exception);
while (cause != null) {
exception = cause;
cause = getCause(exception);
}
return exception;
}
public static Throwable getCause(Throwable exception)
throws IllegalArgumentException {
// Check preconditions
if (exception == null) {
throw new IllegalArgumentException("exception == null");
}
// On Java 1.4 (and up) use the Throwable.getCause() method
if (GET_CAUSE != null) {
try {
return (Throwable) GET_CAUSE.invoke(exception, null);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to invoke Throwable.getCause() method. Caught IllegalAccessException.");
} catch (IllegalArgumentException e) {
throw new RuntimeException("Unable to invoke Throwable.getCause() method. Caught IllegalArgumentException");
} catch (InvocationTargetException e) {
throw new RuntimeException("Unable to invoke Throwable.getCause() method. Caught InvocationTargetException");
}
// On Java 1.3 use the static table
} else {
Object cause = CAUSE_TABLE.get(exception);
return (cause == NULL) ? null : (Throwable) cause;
}
}
public static void setCause(Throwable exception, Throwable cause)
throws IllegalArgumentException, IllegalStateException {
// Check preconditions
if (exception == null) {
throw new IllegalArgumentException("exception == null");
}
if (exception == cause) {
throw new IllegalArgumentException("exception == cause");
}
// On Java 1.4 (and up) use the Throwable.initCause() method
if (SET_CAUSE != null) {
try {
Object args[] = { cause };
SET_CAUSE.invoke(exception, args);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to invoke Throwable.initCause() method. Caught IllegalAccessException.");
} catch (IllegalArgumentException e) {
throw new RuntimeException("Unable to invoke Throwable.initCause() method. Caught IllegalArgumentException");
} catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
} else if (targetException instanceof Error) {
throw (Error) targetException;
} else {
throw new RuntimeException("Unable to invoke Throwable.initCause() method. Throwable.initCause() has thrown an unexpected exception. Exception class is " + targetException.getClass().getName() + ". Message is: " + targetException.getMessage() + '.');
}
}
// On Java 1.3 use the static table
} else {
if (CAUSE_TABLE.get(exception) != null) {
throw new IllegalStateException("Cause for exception already set.");
}
Object value = (cause == null) ? NULL : cause;
CAUSE_TABLE.put(exception, value);
}
}
// Constructors
/**
* Constructs a new <code>ExceptionUtils</code> object.
*/
private ExceptionUtils() {
// empty
}
// Methods
}
|
package com.jaeksoft.searchlib.util;
import java.net.MalformedURLException;
import java.net.URL;
import com.jaeksoft.searchlib.Logging;
import com.jaeksoft.searchlib.crawler.web.database.UrlFilterItem;
public class LinkUtils {
private static String changePathUrl(URL url, String newPath,
String additionnal) {
StringBuffer newUri = new StringBuffer();
newUri.append(url.getProtocol());
newUri.append(":
newUri.append(url.getHost());
if (url.getPort() != -1) {
newUri.append(":");
newUri.append(url.getPort());
}
if (newPath != null && newPath.length() > 0) {
if (newPath.charAt(0) != '/')
newUri.append('/');
newUri.append(newPath);
}
if (additionnal != null && additionnal.length() > 0)
newUri.append(additionnal);
return newUri.toString();
}
private static String resolveDotSlash(String path) {
// "/./" means nothing
path = path.replaceAll("/\\./", "/");
// "///" multiple slashes
path = path.replaceAll("/{2,}", "/");
// "/../" means one directory up
String newPath = path;
do {
path = newPath;
newPath = path.replaceFirst("/[^\\./]*/\\.\\./", "/");
} while (!newPath.equals(path));
return path;
}
public final static URL getLink(URL currentURL, String uri, boolean follow,
boolean allowRefAnchor, boolean resolveDotSlash,
UrlFilterItem[] urlFilterList) {
if (uri == null)
return null;
uri = uri.trim();
if (uri.length() == 0)
return null;
char startChar = uri.charAt(0);
// Relative URI starting with slash
if (startChar == '/') {
if (resolveDotSlash)
uri = resolveDotSlash(uri);
uri = changePathUrl(currentURL, null, uri);
} else if (startChar == '#' || startChar == '?')
uri = changePathUrl(currentURL, currentURL.getPath(), uri);
// Relative URI not starting with slash
else if (!uri.contains(":")) {
String path = currentURL.getPath();
// Search the last slash
int i = path.lastIndexOf('/');
if (i != -1)
path = path.substring(0, i + 1);
if (resolveDotSlash)
path = resolveDotSlash(path + uri);
uri = changePathUrl(currentURL, path, null);
}
// Do we have to remove anchor ?
if (!allowRefAnchor) {
int p = uri.indexOf('
if (p != -1)
uri = uri.substring(0, p);
}
int i = uri.indexOf('?');
if (i != -1 && urlFilterList != null) {
StringBuffer newUrl = new StringBuffer(uri.substring(0, i++));
String queryString = uri.substring(i);
String[] queryParts = queryString.split("\\&");
if (queryParts != null && queryParts.length > 0) {
for (UrlFilterItem urlFilter : urlFilterList)
urlFilter.doReplace(queryParts);
boolean first = true;
for (String queryPart : queryParts) {
if (queryPart != null) {
if (first) {
newUrl.append('?');
first = false;
} else
newUrl.append('&');
newUrl.append(queryPart);
}
}
uri = newUrl.toString();
}
}
try {
return new URL(uri);
} catch (MalformedURLException e) {
Logging.logger.warn(e.getMessage(), e);
return null;
}
}
}
|
package org.voltdb.client;
import java.util.Date;
import java.util.Iterator;
import org.voltdb.LatencyBucketSet;
public class ClientStats {
String m_procName;
long m_since; // java.util.Date compatible microseconds since epoch
long m_connectionId;
String m_hostname;
int m_port;
long m_invocationsCompleted;
long m_invocationAborts;
long m_invocationErrors;
// cumulative latency measured by client, used to calculate avg. lat.
long m_roundTripTime; // microsecs
// cumulative latency measured by the cluster, used to calculate avg lat.
long m_clusterRoundTripTime; // microsecs
final public static int ONE_MS_BUCKET_COUNT = 50;
final public static int TEN_MS_BUCKET_COUNT = 20;
final public static int HUNDRED_MS_BUCKET_COUNT = 10;
LatencyBucketSet m_latencyBy1ms;
LatencyBucketSet m_latencyBy10ms;
LatencyBucketSet m_latencyBy100ms;
long m_bytesSent;
long m_bytesReceived;
ClientStats() {
m_procName = "";
m_connectionId = -1;
m_hostname = "";
m_port = -1;
m_since = Long.MAX_VALUE;
m_invocationsCompleted = m_invocationAborts = m_invocationErrors = 0;
m_roundTripTime = m_clusterRoundTripTime = 0;
m_latencyBy1ms = new LatencyBucketSet(1, ONE_MS_BUCKET_COUNT);
m_latencyBy10ms = new LatencyBucketSet(10, TEN_MS_BUCKET_COUNT);
m_latencyBy100ms = new LatencyBucketSet(100, HUNDRED_MS_BUCKET_COUNT);
m_bytesSent = m_bytesReceived = 0;
}
ClientStats(ClientStats other) {
m_procName = other.m_procName;
m_connectionId = other.m_connectionId;
m_hostname = other.m_hostname;
m_port = other.m_port;
m_since = other.m_since;
m_invocationsCompleted = other.m_invocationsCompleted;
m_invocationAborts = other.m_invocationAborts;
m_invocationErrors = other.m_invocationErrors;
m_roundTripTime = other.m_roundTripTime;
m_clusterRoundTripTime = other.m_clusterRoundTripTime;
m_latencyBy1ms = (LatencyBucketSet) other.m_latencyBy1ms.clone();
m_latencyBy10ms = (LatencyBucketSet) other.m_latencyBy10ms.clone();
m_latencyBy100ms = (LatencyBucketSet) other.m_latencyBy100ms.clone();
m_bytesSent = other.m_bytesSent;
m_bytesReceived = other.m_bytesReceived;
}
public static ClientStats diff(ClientStats newer, ClientStats older) {
if ((newer.m_procName != older.m_procName) || (newer.m_connectionId != older.m_connectionId)) {
throw new IllegalArgumentException("Can't diff these ClientStats instances.");
}
ClientStats retval = new ClientStats();
retval.m_procName = older.m_procName;
retval.m_connectionId = older.m_connectionId;
retval.m_hostname = older.m_hostname;
retval.m_port = older.m_port;
retval.m_since = older.m_since;
retval.m_invocationsCompleted = newer.m_invocationsCompleted - older.m_invocationsCompleted;
retval.m_invocationAborts = newer.m_invocationAborts - older.m_invocationAborts;
retval.m_invocationErrors = newer.m_invocationErrors - older.m_invocationErrors;
retval.m_roundTripTime = newer.m_roundTripTime - older.m_roundTripTime;
retval.m_clusterRoundTripTime = newer.m_clusterRoundTripTime - older.m_clusterRoundTripTime;
retval.m_latencyBy1ms = LatencyBucketSet.diff(newer.m_latencyBy1ms, older.m_latencyBy1ms);
retval.m_latencyBy10ms = LatencyBucketSet.diff(newer.m_latencyBy10ms, older.m_latencyBy10ms);
retval.m_latencyBy100ms = LatencyBucketSet.diff(newer.m_latencyBy100ms, older.m_latencyBy100ms);
retval.m_bytesSent = newer.m_bytesSent - older.m_bytesSent;
retval.m_bytesReceived = newer.m_bytesReceived - older.m_bytesReceived;
return retval;
}
static ClientStats merge(Iterable<ClientStats> statsIterable) {
return merge(statsIterable.iterator());
}
static ClientStats merge(Iterator<ClientStats> statsIter) {
// empty set
if (!statsIter.hasNext()) {
return new ClientStats();
}
// seed the grouping by the first element
ClientStats seed = statsIter.next();
assert(seed != null);
// non-destructive
seed = (ClientStats) seed.clone();
// add in all the other elements
while (statsIter.hasNext()) {
seed.add(statsIter.next());
}
return seed;
}
void add(ClientStats other) {
if (m_procName.equals(other.m_procName) == false) m_procName = "";
if (m_connectionId != other.m_connectionId) m_connectionId = -1;
if (m_hostname.equals(other.m_hostname) == false) m_hostname = "";
if (m_port != other.m_port) m_port = -1;
m_since = Math.min(other.m_since, m_since);
m_invocationsCompleted = other.m_invocationsCompleted;
m_invocationAborts = other.m_invocationAborts;
m_invocationErrors = other.m_invocationErrors;
m_roundTripTime += other.m_roundTripTime;
m_clusterRoundTripTime += other.m_clusterRoundTripTime;
m_latencyBy1ms.add(other.m_latencyBy1ms);
m_latencyBy10ms.add(other.m_latencyBy10ms);
m_latencyBy100ms.add(other.m_latencyBy100ms);
m_bytesSent += other.m_bytesSent;
m_bytesReceived += other.m_bytesReceived;
}
void update(int roundTripTime, int clusterRoundTripTime, boolean abort, boolean error) {
m_invocationsCompleted++;
if (abort) m_invocationAborts++;
if (error) m_invocationErrors++;
m_roundTripTime += roundTripTime;
m_clusterRoundTripTime += clusterRoundTripTime;
// calculate the latency buckets to increment and increment.
m_latencyBy1ms.update(roundTripTime);
m_latencyBy10ms.update(roundTripTime);
m_latencyBy100ms.update(roundTripTime);
}
public String getProcedureName() {
return m_procName;
}
public long getStartTimestamp() {
return m_since;
}
public long getConnectionId() {
return m_connectionId;
}
public String getHostname() {
return m_hostname;
}
public int getPort() {
return m_port;
}
public long getInvocationsCompleted() {
return m_invocationsCompleted;
}
public long getInvocationAborts() {
return m_invocationAborts;
}
public long getInvocationErrors() {
return m_invocationErrors;
}
public long getAverageLatency() {
if (m_invocationsCompleted == 0) return 0;
return m_roundTripTime / m_invocationsCompleted;
}
public long getAverageInternalLatency() {
if (m_invocationsCompleted == 0) return 0;
return m_clusterRoundTripTime / m_invocationsCompleted;
}
public long[] getLatencyBucketsBy1ms() {
return m_latencyBy1ms.buckets.clone();
}
public long[] getLatencyBucketsBy10ms() {
return m_latencyBy10ms.buckets.clone();
}
public long[] getLatencyBucketsBy100ms() {
return m_latencyBy100ms.buckets.clone();
}
public long getBytesWritten() {
return m_bytesSent;
}
public long getBytesRead() {
return m_bytesReceived;
}
public int kPercentileLatency(double percentile) {
int kpl;
kpl = m_latencyBy1ms.kPercentileLatency(percentile);
if (kpl != Integer.MAX_VALUE) {
return kpl;
}
kpl = m_latencyBy10ms.kPercentileLatency(percentile);
if (kpl != Integer.MAX_VALUE) {
return kpl;
}
kpl = m_latencyBy100ms.kPercentileLatency(percentile);
if (kpl != Integer.MAX_VALUE) {
return kpl;
}
return m_latencyBy100ms.msPerBucket * m_latencyBy100ms.numberOfBuckets * 2;
}
public long getTxnThroughput(long now) {
if (m_invocationsCompleted == 0) return 0;
if (now < m_since) {
now = m_since + 1; // 1 ms duration is sorta cheatin'
}
long durationMs = now - m_since;
return (long) (m_invocationsCompleted / (durationMs / 1000.0));
}
public long getIOWriteThroughput(long now) {
long durationMs = now - m_since;
return (long) (m_bytesSent / (durationMs / 1000.0));
}
public long getIOReadThroughput(long now) {
long durationMs = now - m_since;
return (long) (m_bytesReceived / (durationMs / 1000.0));
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("Since %s - Procedure: %s - ConnectionId: %d {\n",
new Date(m_since).toString(), m_procName, m_connectionId));
sb.append(String.format(" hostname: %s:%d\n",
m_hostname, m_port));
sb.append(String.format(" invocations completed/aborted/errors: %d/%d/%d\n",
m_invocationsCompleted, m_invocationAborts, m_invocationErrors));
if (m_invocationsCompleted > 0) {
sb.append(String.format(" avg latency client/internal: %d/%d\n",
m_roundTripTime / m_invocationsCompleted, m_clusterRoundTripTime / m_invocationsCompleted));
sb.append(m_latencyBy1ms).append("\n");
sb.append(m_latencyBy10ms).append("\n");
sb.append(m_latencyBy100ms).append("\n");
}
return sb.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
protected Object clone() {
return new ClientStats(this);
}
}
|
// Narya library - tools for developing networked games
// 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.threerings.presents.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.samskivert.util.StringUtil;
/**
* Utility methods used by our various source code generating tasks.
*/
public class GenUtil
{
/** A regular expression for matching the package declaration. */
public static final Pattern PACKAGE_PATTERN =
Pattern.compile("^\\s*package\\s+(\\S+)\\W");
/** A regular expression for matching the class or interface
* declaration. */
public static final Pattern NAME_PATTERN =
Pattern.compile("^\\s*public\\s+(?:abstract\\s+)?" +
"(interface|class)\\s+(\\S+)(\\W|$)");
/**
* Returns the name of the supplied class as it would likely appear in code
* using the class (no package prefix, arrays specified as
* <code>type[]</code>).
*/
public static String simpleName (Field field)
{
String cname;
Class<?> clazz = field.getType();
if (clazz.isArray()) {
if (field.getGenericType() instanceof GenericArrayType) {
GenericArrayType atype = (GenericArrayType)
field.getGenericType();
cname = atype.getGenericComponentType().toString();
} else {
return simpleName(clazz.getComponentType(),
field.getGenericType()) + "[]";
}
} else if (field.getGenericType() instanceof ParameterizedType) {
cname = field.getGenericType().toString();
} else {
cname = clazz.getName();
}
Package pkg = clazz.getPackage();
int offset = (pkg == null) ? 0 : pkg.getName().length()+1;
return StringUtil.replace(cname.substring(offset), "$", ".");
}
/**
* Returns the name of the supplied class as it would likely appear in code
* using the class (no package prefix, arrays specified as
* <code>type[]</code>).
*/
public static String simpleName (Class<?> clazz, Type type)
{
if (clazz.isArray()) {
return simpleName(clazz.getComponentType(), type) + "[]";
} else {
String cname = clazz.getName();
if (type instanceof ParameterizedType) {
cname = type.toString();
}
Package pkg = clazz.getPackage();
int offset = (pkg == null) ? 0 : pkg.getName().length()+1;
String name = cname.substring(offset);
return StringUtil.replace(name, "$", ".");
}
}
/**
* Returns the name of the supplied class as it would appear in
* ActionScript code using the class (no package prefix, arrays specified
* as Array<code>Array</code>).
*/
public static String simpleASName (Class<?> clazz)
{
if (clazz.isArray()) {
return "Array";
} else if (clazz == Boolean.TYPE) {
return "Boolean";
} else if (clazz == Byte.TYPE || clazz == Character.TYPE ||
clazz == Short.TYPE || clazz == Integer.TYPE) {
return "int";
} else if (clazz == Long.TYPE) {
return "Long";
} else if (clazz == Float.TYPE || clazz == Double.TYPE) {
return "Number";
} else {
String cname = clazz.getName();
Package pkg = clazz.getPackage();
int offset = (pkg == null) ? 0 : pkg.getName().length()+1;
String name = cname.substring(offset);
return StringUtil.replace(name, "$", "_");
}
}
/**
* "Boxes" the supplied argument, ie. turning an <code>int</code> into
* an <code>Integer</code> object.
*/
public static String boxArgument (Class<?> clazz, String name)
{
if (clazz == Boolean.TYPE) {
return "Boolean.valueOf(" + name + ")";
} else if (clazz == Byte.TYPE) {
return "Byte.valueOf(" + name + ")";
} else if (clazz == Character.TYPE) {
return "Character.valueOf(" + name + ")";
} else if (clazz == Short.TYPE) {
return "Short.valueOf(" + name + ")";
} else if (clazz == Integer.TYPE) {
return "Integer.valueOf(" + name + ")";
} else if (clazz == Long.TYPE) {
return "Long.valueOf(" + name + ")";
} else if (clazz == Float.TYPE) {
return "Float.valueOf(" + name + ")";
} else if (clazz == Double.TYPE) {
return "Double.valueOf(" + name + ")";
} else {
return name;
}
}
/**
* "Unboxes" the supplied argument, ie. turning an <code>Integer</code>
* object into an <code>int</code>.
*/
public static String unboxArgument (Class<?> clazz, Type type, String name)
{
if (clazz == Boolean.TYPE) {
return "((Boolean)" + name + ").booleanValue()";
} else if (clazz == Byte.TYPE) {
return "((Byte)" + name + ").byteValue()";
} else if (clazz == Character.TYPE) {
return "((Character)" + name + ").charValue()";
} else if (clazz == Short.TYPE) {
return "((Short)" + name + ").shortValue()";
} else if (clazz == Integer.TYPE) {
return "((Integer)" + name + ").intValue()";
} else if (clazz == Long.TYPE) {
return "((Long)" + name + ").longValue()";
} else if (clazz == Float.TYPE) {
return "((Float)" + name + ").floatValue()";
} else if (clazz == Double.TYPE) {
return "((Double)" + name + ").doubleValue()";
} else {
return "(" + simpleName(clazz, type) + ")" + name + "";
}
}
/**
* "Boxes" the supplied argument, ie. turning an <code>int</code> into
* an <code>Integer</code> object.
*/
public static String boxASArgument (Class<?> clazz, String name)
{
if (clazz == Boolean.TYPE) {
return "langBoolean.valueOf(" + name + ")";
} else if (clazz == Byte.TYPE) {
return "Byte.valueOf(" + name + ")";
} else if (clazz == Character.TYPE) {
return "Character.valueOf(" + name + ")";
} else if (clazz == Short.TYPE) {
return "Short.valueOf(" + name + ")";
} else if (clazz == Integer.TYPE) {
return "Integer.valueOf(" + name + ")";
} else if (clazz == Long.TYPE) {
return name; // Long is left as is
} else if (clazz == Float.TYPE) {
return "Float.valueOf(" + name + ")";
} else if (clazz == Double.TYPE) {
return "Double.valueOf(" + name + ")";
} else {
return name;
}
}
/**
* "Unboxes" the supplied argument, ie. turning an <code>Integer</code>
* object into an <code>int</code>.
*/
public static String unboxASArgument (Class<?> clazz, String name)
{
if (clazz == Boolean.TYPE) {
return "(" + name + " as langBoolean).value";
} else if (clazz == Byte.TYPE) {
return "(" + name + " as Byte).value";
} else if (clazz == Character.TYPE) {
return "(" + name + " as Character).value";
} else if (clazz == Short.TYPE) {
return "(" + name + " as Short).value";
} else if (clazz == Integer.TYPE) {
return "(" + name + " as Integer).value";
} else if (clazz == Long.TYPE) {
return "(" + name + " as Long)";
} else if (clazz == Float.TYPE) {
return "(" + name + " as Float).value";
} else if (clazz == Double.TYPE) {
return "(" + name + " as Double).value";
} else {
return "(" + name + " as " + simpleASName(clazz) + ")";
}
}
/**
* Potentially clones the supplied argument if it is the type that
* needs such treatment.
*/
public static String cloneArgument (Class<?> dsclazz, Field f, String name)
{
Class<?> clazz = f.getType();
if (dsclazz.equals(clazz)) {
return "(" + name + " == null) ? null : " + name + ".typedClone()";
} else if (clazz.isArray() || dsclazz.isAssignableFrom(clazz)) {
return "(" + name + " == null) ? null : " +
"(" + simpleName(f) + ")" + name + ".clone()";
} else {
return name;
}
}
/**
* Reads in the supplied source file and locates the package and class
* or interface name and returns a fully qualified class name.
*/
public static String readClassName (File source)
throws IOException
{
// load up the file and determine it's package and classname
String pkgname = null, name = null;
BufferedReader bin = new BufferedReader(new FileReader(source));
String line;
while ((line = bin.readLine()) != null) {
Matcher pm = PACKAGE_PATTERN.matcher(line);
if (pm.find()) {
pkgname = pm.group(1);
}
Matcher nm = NAME_PATTERN.matcher(line);
if (nm.find()) {
name = nm.group(2);
break;
}
}
bin.close();
// make sure we found something
if (name == null) {
throw new IOException(
"Unable to locate class or interface name in " + source + ".");
}
// prepend the package name to get a name we can Class.forName()
if (pkgname != null) {
name = pkgname + "." + name;
}
return name;
}
}
|
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//This library is distributed in the hope that it will be useful,
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//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 opennlp.tools.lang.english;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import opennlp.maxent.MaxentModel;
import opennlp.maxent.io.PooledGISModelReader;
import opennlp.tools.namefind.NameFinderEventStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.parser.Parse;
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.util.Span;
/**
* Class is used to create a name finder for English.
*/
public class NameFinder {
public static String[] NAME_TYPES = {"person", "organization", "location", "date", "time", "percentage", "money"};
private NameFinderME nameFinder;
/** Creates an English name finder using the specified model.
* @param mod The model used for finding names.
*/
public NameFinder(MaxentModel mod) {
nameFinder = new NameFinderME(mod);
}
private static void addNames(String tag, Span[] names, Parse[] tokens) {
for (int ni=0,nn=names.length;ni<nn;ni++) {
Span nameTokenSpan = names[ni];
Parse startToken = tokens[nameTokenSpan.getStart()];
Parse endToken = tokens[nameTokenSpan.getEnd()];
Parse commonParent = startToken.getCommonParent(endToken);
//System.err.println("addNames: "+startToken+" .. "+endToken+" commonParent = "+commonParent);
if (commonParent != null) {
Span nameSpan = new Span(startToken.getSpan().getStart(),endToken.getSpan().getEnd());
if (nameSpan.equals(commonParent.getSpan())) {
commonParent.insert(new Parse(commonParent.getText(),nameSpan,tag,1.0,endToken.getHeadIndex()));
}
else {
Parse[] kids = commonParent.getChildren();
boolean crossingKids = false;
for (int ki=0,kn=kids.length;ki<kn;ki++) {
if (nameSpan.crosses(kids[ki].getSpan())){
crossingKids = true;
}
}
if (!crossingKids) {
commonParent.insert(new Parse(commonParent.getText(),nameSpan,tag,1.0,endToken.getHeadIndex()));
}
else {
if (commonParent.getType().equals("NP")) {
Parse[] grandKids = kids[0].getChildren();
if (grandKids.length > 1 && nameSpan.contains(grandKids[grandKids.length-1].getSpan())) {
commonParent.insert(new Parse(commonParent.getText(),commonParent.getSpan(),tag,1.0,commonParent.getHeadIndex()));
}
}
}
}
}
}
}
private static Map[] createPrevTokenMaps(NameFinder[] finders){
Map[] prevTokenMaps = new HashMap[finders.length];
for (int fi = 0, fl = finders.length; fi < fl; fi++) {
prevTokenMaps[fi]=new HashMap();
}
return prevTokenMaps;
}
private static void clearPrevTokenMaps(Map[] prevTokenMaps) {
for (int mi = 0, ml = prevTokenMaps.length; mi < ml; mi++) {
prevTokenMaps[mi].clear();
}
}
private static void updatePrevTokenMaps(Map[] prevTokenMaps, String[] tokens, Span[][] nameSpans) {
for (int mi = 0, ml = prevTokenMaps.length; mi < ml; mi++) {
NameFinderEventStream.updatePrevMap(tokens, nameSpans[mi], prevTokenMaps[mi]);
}
}
private static void processParse(NameFinder[] finders, String[] tags, BufferedReader input) throws IOException {
Span[][] nameSpans = new Span[finders.length][];
Map[] prevTokenMaps = createPrevTokenMaps(finders);
for (String line = input.readLine(); null != line; line = input.readLine()) {
if (line.equals("")) {
System.out.println();
clearPrevTokenMaps(prevTokenMaps);
continue;
}
Parse p = Parse.parseParse(line);
Parse[] tagNodes = p.getTagNodes();
String[] tokens = new String[tagNodes.length];
for (int ti=0;ti<tagNodes.length;ti++){
tokens[ti] = tagNodes.toString();
}
//System.err.println(java.util.Arrays.asList(tokens));
for (int fi = 0, fl = finders.length; fi < fl; fi++) {
nameSpans[fi] = finders[fi].nameFinder.find(tokens, NameFinderEventStream.additionalContext(tokens,prevTokenMaps[fi]));
//System.err.println("EnglishNameFinder.processParse: "+tags[fi] + " " + java.util.Arrays.asList(finderTags[fi]));
}
updatePrevTokenMaps(prevTokenMaps,tokens,nameSpans);
for (int fi = 0, fl = finders.length; fi < fl; fi++) {
addNames(tags[fi],nameSpans[fi],tagNodes);
}
p.show();
}
}
/**
* Adds sgml style name tags to the specified input buffer and outputs this information to stdout.
* @param finders The name finders to be used.
* @param tags The tag names for the coresponding name finder.
* @param input The input reader.
* @throws IOException
*/
private static void processText(NameFinder[] finders, String[] tags, BufferedReader input) throws IOException {
Span[][] nameSpans = new Span[finders.length][];
String[][] nameOutcomes = new String[finders.length][];
Map[] prevTokenMaps = createPrevTokenMaps(finders);
opennlp.tools.tokenize.Tokenizer tokenizer = new SimpleTokenizer();
for (String line = input.readLine(); null != line; line = input.readLine()) {
if (line.equals("")) {
clearPrevTokenMaps(prevTokenMaps);
System.out.println();
continue;
}
Span[] spans = tokenizer.tokenizePos(line);
String[] tokens = Span.spansToStrings(spans,line);
for (int fi = 0, fl = finders.length; fi < fl; fi++) {
nameSpans[fi] = finders[fi].nameFinder.find(tokens,NameFinderEventStream.additionalContext(tokens,prevTokenMaps[fi]));
//System.err.println("EnglighNameFinder.processText: "+tags[fi] + " " + java.util.Arrays.asList(finderTags[fi]));
nameOutcomes[fi] = NameFinderEventStream.generateOutcomes(nameSpans[fi], tokens.length);
}
updatePrevTokenMaps(prevTokenMaps,tokens,nameSpans);
for (int ti = 0, tl = tokens.length; ti < tl; ti++) {
for (int fi = 0, fl = finders.length; fi < fl; fi++) {
//check for end tags
if (ti != 0) {
if ((nameOutcomes[fi][ti].equals(NameFinderME.START) || nameOutcomes[fi][ti].equals(NameFinderME.OTHER)) &&
(nameOutcomes[fi][ti - 1].equals(NameFinderME.START) || nameOutcomes[fi][ti - 1].equals(NameFinderME.CONTINUE))) {
System.out.print("</" + tags[fi] + ">");
}
}
}
if (ti > 0 && spans[ti - 1].getEnd() < spans[ti].getStart()) {
System.out.print(line.substring(spans[ti - 1].getEnd(), spans[ti].getStart()));
}
//check for start tags
for (int fi = 0, fl = finders.length; fi < fl; fi++) {
if (nameOutcomes[fi][ti].equals(NameFinderME.START)) {
System.out.print("<" + tags[fi] + ">");
}
}
System.out.print(tokens[ti]);
}
//final end tags
if (tokens.length != 0) {
for (int fi = 0, fl = finders.length; fi < fl; fi++) {
if (nameOutcomes[fi][tokens.length - 1].equals(NameFinderME.START) || nameOutcomes[fi][tokens.length - 1].equals(NameFinderME.CONTINUE)) {
System.out.print("</" + tags[fi] + ">");
}
}
}
if (tokens.length != 0) {
if (spans[tokens.length - 1].getEnd() < line.length()) {
System.out.print(line.substring(spans[tokens.length - 1].getEnd()));
}
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Usage NameFinder -[parse] model1 model2 ... modelN < sentences");
System.err.println(" -parse: Use this option to find names on parsed input. Un-tokenized sentence text is the default.");
System.exit(1);
}
int ai = 0;
boolean parsedInput = false;
while (args[ai].startsWith("-") && ai < args.length) {
if (args[ai].equals("-parse")) {
parsedInput = true;
}
else {
System.err.println("Ignoring unknown option "+args[ai]);
}
ai++;
}
NameFinder[] finders = new NameFinder[args.length-ai];
String[] names = new String[args.length-ai];
for (int fi=0; ai < args.length; ai++,fi++) {
String modelName = args[ai];
finders[fi] = new NameFinder(new PooledGISModelReader(new File(modelName)).getModel());
int nameStart = modelName.lastIndexOf(System.getProperty("file.separator")) + 1;
int nameEnd = modelName.indexOf('.', nameStart);
if (nameEnd == -1) {
nameEnd = modelName.length();
}
names[fi] = modelName.substring(nameStart, nameEnd);
}
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
if (parsedInput) {
processParse(finders,names,in);
}
else {
processText(finders,names,in);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.