diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/mediastore/src/mediastore/ManagerCLITestDriver.java b/mediastore/src/mediastore/ManagerCLITestDriver.java
index a11189a..973a278 100644
--- a/mediastore/src/mediastore/ManagerCLITestDriver.java
+++ b/mediastore/src/mediastore/ManagerCLITestDriver.java
@@ -1,52 +1,50 @@
package mediastore;
import java.io.File;
-import java.util.LinkedList;
/**
* Name: Milton John
* Section: 1
* Program: Manager CLI Test Driver
* Date: Feb 7, 2013
*/
/**
* A class that tests the functionality of the Manager class via a text-based
* interface.
*
* @author Milton John, Ryan Smith and Cole Arnold
* @version 1.0 Feb 7, 2013
*
*/
public class ManagerCLITestDriver {
public static void main( String[] args ) {
System.out.println( "test" );
TextDatabase db = null;
try {
db = new TextDatabase( System.getProperty( "user.dir" ).concat( File.separator + ".." + File.separator + ".." + File.separator + "db" + File.separator ) );
} catch ( Exception e ) {
System.out.println( "An exception occured while parsing the database. (" + e.toString() + ")" );
e.printStackTrace(); // this is what the @SupressWarnings is for
}
try {
Customer c = db.getCustomerFromID( 1 );
// c.listText();
//db.manager.addContent();
c.listText();
- // db.manager.getCustomerInfo( 1);
+ System.out.println("Customer 1 info: \n" + db.manager.getCustomerInfo( 1));
c.buy( 1 );
- System.out.println("Item sales for media id: 1 is " + db.manager.checkItemSales( 2 ));
- System.exit( 0);
+ System.out.println("Item sales for media id: 1 is " + db.manager.checkItemSales( 1 ));
} catch ( Exception e ) {
System.out.println( "An exception occured testing the Manager class. (" + e.toString() + ")" );
e.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/java/javaProjectFiles/web_TreeViewInitializator/src/Web_TreeViewInitializator.java b/java/javaProjectFiles/web_TreeViewInitializator/src/Web_TreeViewInitializator.java
index 70b9d984..a5b55639 100644
--- a/java/javaProjectFiles/web_TreeViewInitializator/src/Web_TreeViewInitializator.java
+++ b/java/javaProjectFiles/web_TreeViewInitializator/src/Web_TreeViewInitializator.java
@@ -1,372 +1,373 @@
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import tcwi.xml.*;
import tcwi.exception.Exceptions;
import tcwi.fileHandler.*;
import tcwi.TCWIFile.CompareFile;
import tcwi.TCWIFile.ErrorFile;
import tcwi.TCWIFile.TCWIFile;
public class Web_TreeViewInitializator {
- private static final String VERSION = "0.2.0.3";
+ private static final String VERSION = "0.2.0.4";
private static final String AUTHORS = "EifX & hulllemann";
private static ArrayList<TCWIFile> files;
private static Check check = new Check();
private static Exceptions exception;
/**
* Read the file-list generated by web_ProjectInitializator
* @param projectName
* @param settingsFile
*/
private static void getAllFiles(String projectName, String settingsFile, String projectType, String project_settings_path){
try{
if(projectType.equals("normal")){
files = TCWIFile.createTCWIFileArrayFromErrorFile(project_settings_path);
}else if(projectType.equals("compare")){
files = TCWIFile.createTCWIFileArrayFromCompareFile(project_settings_path);
}else{
exception.throwException(12, null, true, "");
}
}catch(IOException e){
exception.throwException(1, e, true, "");
}
}
/**
* Check a given folder for failure dbg-files.
* @param path
* @return
*/
private static boolean isAFailFolder(String path, String projectType){
ArrayList<TCWIFile> filesNew = new ArrayList<TCWIFile>();
for(int i=0;i<files.size();i++){
if(projectType.equals("normal")){
if(((ErrorFile) files.get(i)).getPath().contains(path)){
filesNew.add((ErrorFile) files.get(i));
}
}else if(projectType.equals("compare")){
if(((CompareFile) files.get(i)).getPath().contains(path)){
filesNew.add((CompareFile) files.get(i));
}
}else{
exception.throwException(12, null, true, "");
}
}
for(int i=0;i<filesNew.size();i++){
if(projectType.equals("normal")){
if(((ErrorFile) filesNew.get(i)).haveErrors()){
if(((ErrorFile) filesNew.get(i)).isHaveNoDBG()){
return false;
}else{
return true;
}
}
}else if(projectType.equals("compare")){
return ((CompareFile) filesNew.get(i)).haveChanges();
}else{
exception.throwException(12, null, true, "");
}
}
return false;
}
/**
* Write the output filefalse
* @param path
* @param prettyOutput
*/
private static void writeTxt(String path, String txt){
try{
File f = new File(path);
f.delete();
RandomAccessFile file = new RandomAccessFile(path,"rw");
file.writeBytes(txt);
file.close();
}catch (IOException e){
exception.throwException(3, e, true, path);
}
}
/**
* Get the right icon for the treeview
* @param path
* @param projectType
* @return
*/
private static String getIcon(String path, String projectType){
if(projectType.equals("normal")){
if(!isAFailFolder(path,projectType)){
return "folderok";
}else{
return "folderfail";
}
}else if(projectType.equals("compare")){
if(!isAFailFolder(path,projectType)){
return "folderidentical";
}else{
return "folderdifference";
}
}else{
exception.throwException(12, null, true, "");
return "";
}
}
/**
* Get the right icon for the treeview
* @param file
* @param projectType
* @return
*/
private static String getIcon(TCWIFile file, String projectType){
if(projectType.equals("normal")){
if(!((ErrorFile) file).haveErrors()){
return "fileok";
}else{
if(((ErrorFile) file).isHaveNoDBG()){
return "fileempty";
}else{
return "filefail";
}
}
}else if(projectType.equals("compare")){
if(!((CompareFile) file).haveChanges()){
return "fileidentical";
}else{
return "filedifference";
}
}else{
exception.throwException(12, null, true, "");
return "";
}
}
/**
* Count how many "}]" needed to close an dir
* @param pathOld
* @param pathNew
* @return
*/
public static int getFolderDifference(String[] pathOld, String[] pathNew){
int diff = 0;
int maxLen = 0;
if(pathOld.length>pathNew.length){
maxLen = pathNew.length-1;
diff = pathOld.length-pathNew.length;
}else{
maxLen = pathOld.length-1;
}
for(int i=0;i<pathOld.length-1;i++){
if(i>pathNew.length-1){
return diff;
}
if(!pathOld[i].equals(pathNew[i])){
return maxLen-i+diff;
}
}
return 0;
}
/**
* Look, if a path change is a "DirChange"<br>
* Ex:<br>
* /foo/bar/bar.c<br>
* /foo/ber.c<br>
* This is not an dir change, because you go from a higher level dir to a lower level dir
*
* @param oldArr
* @param newArr
* @return
*/
private static boolean isADirChange(String[] oldArr, String[] newArr){
if(oldArr.length<=newArr.length){
return false;
}else{
for(int i=0;i<newArr.length-1;i++){
if(!oldArr[i].equals(newArr[i])){
return false;
}
}
}
return true;
}
/**
* Do the main work
* @param projectName
* @param projectType
* @param projectPath
* @return a JSON-String
*/
private static String generateJSONString(String projectName, String projectType, String projectPath){
String jsonString = "";
ArrayList<String> relativeFiles = new ArrayList<String>();
for(int i=0;i<files.size();i++){
if(projectType.equals("normal")){
relativeFiles.add(((ErrorFile) files.get(i)).getPath().substring(projectPath.length()+1));
}else if(projectType.equals("compare")){
relativeFiles.add(((CompareFile) files.get(i)).getPath().substring(projectPath.length()+1));
}else{
exception.throwException(12, null, true, "");
}
}
String[] oldArr = {""};
String oldP = "";
int pathArrLen = 0;
for(int i=0;i<relativeFiles.size();i++){
int notEqual = -1;
String newPath = relativeFiles.get(i);
String[] pathArr;
pathArr = relativeFiles.get(i).split(check.folderSeparator()+"");
//Search for differences between the new and the last file
for(int j=0;j<pathArr.length;j++){
if(oldArr.length>j){
if(!pathArr[j].equals(oldArr[j])){
notEqual = j;
break;
}
}else{
notEqual = j;
break;
}
}
//If a file exists in the tree, do nothing
if(notEqual==-1){
break;
}
//If the path has changed, draw the missing parts
String p = "";
//If a path is change, maybe a "}]" must set
int foldDiff = getFolderDifference(oldArr,pathArr);
for(int j=1;j<=foldDiff;j++){
if(j==foldDiff){
if(isADirChange(oldArr,pathArr)){
jsonString += "}]";
}else{
jsonString += "}]},{";
}
}else{
jsonString += "}]";
}
}
//Write folders
if(pathArr.length-1!=notEqual){
for(int j=notEqual;j<pathArr.length-1;j++){
for(int k=0;k<=j;k++){
p+=check.folderSeparator()+pathArr[k];
}
p = projectPath+p;
if(i!=0&&foldDiff==0&&j==notEqual){
jsonString += "},{";
}
jsonString += "\"data\":\""+pathArr[j].replace("\"", "_")+"\",\"attr\":{\"id\":\"dir"+i+""+j+"\",\"rel\":\""+getIcon(p,projectType)+"\"},\"children\":[{";
}
}else{
jsonString += "},{";
p = oldP;
}
//Write files
newPath = newPath.replace("\\", "/");
newPath = newPath.replace(" ", "_");
jsonString += "\"data\":\""+pathArr[pathArr.length-1].replace("\"", "_")+"\",\"attr\":{\"id\":\"chkbox"+i+"\",\"rel\":\""+getIcon(files.get(i),projectType)+"\"},\"metadata\":{\"link\":\""+newPath+"\"}";
oldArr = pathArr;
oldP = p;
pathArrLen = pathArr.length;
}
for(int j=0;j<pathArrLen-1;j++){
jsonString += "}]";
}
return jsonString;
}
/**
* Main function
* @param args
*/
public static void main(String[] args) {
if(args.length!=2){
System.out.println("Help - web_TreeViewInitializator "+VERSION+" by "+AUTHORS);
System.out.println("----------------------------------------------------");
System.out.println("\nUsage: web_TreeViewInitializator [PROJECTNAME] [GLOBAL_SETTINGS]");
System.out.println("\n[PROJECTNAME]");
System.out.println("\n Project name\n");
System.out.println("\n[GLOBAL_SETTINGS]");
System.out.println("\n Absolute Path for the global_settings.xml\n (include the name of the settings file)\n");
}else{
System.out.println("\nRead needed variables...");
String projectName = args[0];
String globalSettings = args[1];
//Init the XMLParser
Parser settingsParser = new Parser(globalSettings);
String WebIntProjectsPath = settingsParser.getSetting_ProjectPath();
String TreeViewPath = settingsParser.getSetting_TreeviewPath();
//Read the project dir
String project_settings_path = WebIntProjectsPath+check.folderSeparator()+projectName+".project";
String project_settings_xml_path = WebIntProjectsPath+check.folderSeparator()+projectName+".project.xml";
//If the project have minimal one error, the main-folder in the tree-list is a fail folder
Parser parser = new Parser(project_settings_xml_path);
boolean failureProject = parser.getSetting_ProjectFailureProject().equals("true");
String projectPath = parser.getSetting_ProjectBasePath();
String projectType = parser.getSetting_ProjectType();
String projectVersion = parser.getSetting_ProjectVersion();
+ String projectFullName = parser.getSetting_ProjectFullname();
//Do the work
System.out.println("Read folder tree...");
getAllFiles(projectName,globalSettings,projectType,project_settings_path);
System.out.println("Build JSON-File...");
String folderMood = "";
if(projectType.equals("normal")){
if(!failureProject){
folderMood = "folderok";
}else{
folderMood = "folderfail";
}
}else if(projectType.equals("compare")){
if(!failureProject){
folderMood = "folderidentical";
}else{
folderMood = "folderdifference";
}
}else{
exception.throwException(12, null, true, "");
}
- String JSONString = "[{\"data\":\""+projectName+" "+projectVersion+"\",\"attr\":{\"id\":\"maindir\",\"rel\":\""+folderMood+"\"},\"state\":\"open\",\"children\":[{"+generateJSONString(projectName,projectType,projectPath)+"}]}]";
+ String JSONString = "[{\"data\":\""+projectFullName+" "+projectVersion+"\",\"attr\":{\"id\":\"maindir\",\"rel\":\""+folderMood+"\"},\"state\":\"open\",\"children\":[{"+generateJSONString(projectName,projectType,projectPath)+"}]}]";
System.out.println("Save folder tree...");
//Build the path for the JSON-path
writeTxt(TreeViewPath+check.folderSeparator()+projectName+".json",JSONString);
System.out.println("DONE!");
}
}
}
| false | false | null | null |
diff --git a/src/de/ub0r/android/smsdroid/ConversationListActivity.java b/src/de/ub0r/android/smsdroid/ConversationListActivity.java
index 2787052..34ee11f 100644
--- a/src/de/ub0r/android/smsdroid/ConversationListActivity.java
+++ b/src/de/ub0r/android/smsdroid/ConversationListActivity.java
@@ -1,593 +1,593 @@
/*
* Copyright (C) 2010-2012 Felix Bechstein
*
* This file is part of SMSdroid.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; If not, see <http://www.gnu.org/licenses/>.
*/
package de.ub0r.android.smsdroid;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
+import android.support.v4.view.Menu;
+import android.support.v4.view.MenuItem;
import android.text.TextUtils;
import android.text.format.DateFormat;
-import android.view.Menu;
-import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import de.ub0r.android.lib.ChangelogHelper;
import de.ub0r.android.lib.DonationHelper;
import de.ub0r.android.lib.Log;
import de.ub0r.android.lib.Market;
import de.ub0r.android.lib.Utils;
import de.ub0r.android.lib.apis.Contact;
import de.ub0r.android.lib.apis.ContactsWrapper;
/**
* Main {@link FragmentActivity} showing conversations.
*
* @author flx
*/
public final class ConversationListActivity extends FragmentActivity implements
OnItemClickListener, OnItemLongClickListener {
/** Tag for output. */
public static final String TAG = "main";
/** Ad's unit id. */
private static final String AD_UNITID = "a14b9f701ee348f";
/** Ad's keywords. */
public static final HashSet<String> AD_KEYWORDS = new HashSet<String>();
static {
AD_KEYWORDS.add("android");
AD_KEYWORDS.add("mobile");
AD_KEYWORDS.add("handy");
AD_KEYWORDS.add("cellphone");
AD_KEYWORDS.add("google");
AD_KEYWORDS.add("htc");
AD_KEYWORDS.add("samsung");
AD_KEYWORDS.add("motorola");
AD_KEYWORDS.add("market");
AD_KEYWORDS.add("app");
AD_KEYWORDS.add("message");
AD_KEYWORDS.add("txt");
AD_KEYWORDS.add("sms");
AD_KEYWORDS.add("mms");
AD_KEYWORDS.add("game");
AD_KEYWORDS.add("websms");
AD_KEYWORDS.add("amazon");
}
/** ORIG_URI to resolve. */
static final Uri URI = Uri.parse("content://mms-sms/conversations/");
/** Number of items. */
private static final int WHICH_N = 6;
/** Index in dialog: answer. */
private static final int WHICH_ANSWER = 0;
/** Index in dialog: answer. */
private static final int WHICH_CALL = 1;
/** Index in dialog: view/add contact. */
private static final int WHICH_VIEW_CONTACT = 2;
/** Index in dialog: view. */
private static final int WHICH_VIEW = 3;
/** Index in dialog: delete. */
private static final int WHICH_DELETE = 4;
/** Index in dialog: mark as spam. */
private static final int WHICH_MARK_SPAM = 5;
/** Preferences: hide ads. */
private static boolean prefsNoAds = false;
/** Minimum date. */
public static final long MIN_DATE = 10000000000L;
/** Miliseconds per seconds. */
public static final long MILLIS = 1000L;
/** Show contact's photo. */
public static boolean showContactPhoto = false;
/** Show emoticons in {@link MessageListActivity}. */
public static boolean showEmoticons = false;
/** Dialog items shown if an item was long clicked. */
private String[] longItemClickDialog = null;
/** Conversations. */
private ConversationAdapter adapter = null;
/** {@link Calendar} holding today 00:00. */
private static final Calendar CAL_DAYAGO = Calendar.getInstance();
static {
// Get time for now - 24 hours
CAL_DAYAGO.add(Calendar.DAY_OF_MONTH, -1);
}
/**
* {@inheritDoc}
*/
@Override
public void onStart() {
super.onStart();
AsyncHelper.setAdapter(this.adapter);
}
/**
* {@inheritDoc}
*/
@Override
public void onStop() {
super.onStop();
AsyncHelper.setAdapter(null);
}
/**
* Get {@link ListView}.
*
* @return {@link ListView}
*/
private AbsListView getListView() {
return (AbsListView) this.findViewById(android.R.id.list);
}
/**
* Set {@link ListAdapter} to {@link ListView}.
*
* @param la
* ListAdapter
*/
private void setListAdapter(final ListAdapter la) {
AbsListView v = this.getListView();
if (v instanceof GridView) {
((GridView) v).setAdapter(la);
} else if (v instanceof ListView) {
((ListView) v).setAdapter(la);
}
}
/**
* Show all rows of a particular {@link Uri}.
*
* @param context
* {@link Context}
* @param u
* {@link Uri}
*/
static void showRows(final Context context, final Uri u) {
Log.d(TAG, "-----GET HEADERS-----");
Log.d(TAG, "-- " + u.toString() + " --");
Cursor c = context.getContentResolver().query(u, null, null, null, null);
if (c != null) {
int l = c.getColumnCount();
StringBuilder buf = new StringBuilder();
for (int i = 0; i < l; i++) {
buf.append(i + ":");
buf.append(c.getColumnName(i));
buf.append(" | ");
}
Log.d(TAG, buf.toString());
}
}
/**
* Show rows for debugging purposes.
*
* @param context
* {@link Context}
*/
static void showRows(final Context context) {
// this.showRows(ContactsWrapper.getInstance().getUriFilter());
// showRows(context, URI);
// showRows(context, Uri.parse("content://sms/"));
// showRows(context, Uri.parse("content://mms/"));
// showRows(context, Uri.parse("content://mms/part/"));
// showRows(context, ConversationProvider.CONTENT_URI);
// showRows(context, Uri.parse("content://mms-sms/threads"));
// this.showRows(Uri.parse(MessageList.URI));
}
/**
* {@inheritDoc}
*/
@Override
public void onNewIntent(final Intent intent) {
final Intent i = intent;
if (i != null) {
Log.d(TAG, "got intent: " + i.getAction());
Log.d(TAG, "got uri: " + i.getData());
final Bundle b = i.getExtras();
if (b != null) {
Log.d(TAG, "user_query: " + b.get("user_query"));
Log.d(TAG, "got extra: " + b);
}
final String query = i.getStringExtra("user_query");
Log.d(TAG, "user query: " + query);
// TODO: do something with search query
}
}
/**
* {@inheritDoc}
*/
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
final Intent i = this.getIntent();
Log.d(TAG, "got intent: " + i.getAction());
Log.d(TAG, "got uri: " + i.getData());
Log.d(TAG, "got extra: " + i.getExtras());
this.setTheme(PreferencesActivity.getTheme(this));
Utils.setLocale(this);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("use_gridlayout", false)) {
this.setContentView(R.layout.conversationgrid);
} else {
this.setContentView(R.layout.conversationlist);
}
ChangelogHelper.showChangelog(this, true);
final List<ResolveInfo> ri = this.getPackageManager().queryBroadcastReceivers(
new Intent("de.ub0r.android.websms.connector.INFO"), 0);
if (ri.size() == 0) {
final Intent intent = Market.getInstallAppIntent(this, "de.ub0r.android.websms",
Market.ALT_WEBSMS);
ChangelogHelper.showNotes(this, true, "get WebSMS", null, intent);
} else {
ChangelogHelper.showNotes(this, true, null, null, null);
}
showRows(this);
final AbsListView list = this.getListView();
this.adapter = new ConversationAdapter(this);
this.setListAdapter(this.adapter);
list.setOnItemClickListener(this);
list.setOnItemLongClickListener(this);
this.longItemClickDialog = new String[WHICH_N];
this.longItemClickDialog[WHICH_ANSWER] = this.getString(R.string.reply);
this.longItemClickDialog[WHICH_CALL] = this.getString(R.string.call);
this.longItemClickDialog[WHICH_VIEW_CONTACT] = this.getString(R.string.view_contact_);
this.longItemClickDialog[WHICH_VIEW] = this.getString(R.string.view_thread_);
this.longItemClickDialog[WHICH_DELETE] = this.getString(R.string.delete_thread_);
this.longItemClickDialog[WHICH_MARK_SPAM] = this.getString(R.string.filter_spam_);
}
/**
* {@inheritDoc}
*/
@Override
protected void onResume() {
super.onResume();
prefsNoAds = DonationHelper.hideAds(this);
if (!prefsNoAds) {
Ads.loadAd(this, R.id.ad, AD_UNITID, AD_KEYWORDS);
}
CAL_DAYAGO.setTimeInMillis(System.currentTimeMillis());
CAL_DAYAGO.add(Calendar.DAY_OF_MONTH, -1);
final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
showContactPhoto = p.getBoolean(PreferencesActivity.PREFS_CONTACT_PHOTO, true);
showEmoticons = p.getBoolean(PreferencesActivity.PREFS_EMOTICONS, false);
this.adapter.startMsgListQuery();
}
/**
* {@inheritDoc}
*/
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
this.getMenuInflater().inflate(R.menu.conversationlist, menu);
if (prefsNoAds) {
menu.removeItem(R.id.item_donate);
}
return true;
}
/**
* Mark all messages with a given {@link Uri} as read.
*
* @param context
* {@link Context}
* @param uri
* {@link Uri}
* @param read
* read status
*/
static void markRead(final Context context, final Uri uri, final int read) {
Log.d(TAG, "markRead(" + uri + "," + read + ")");
if (uri == null) {
return;
}
String[] sel = Message.SELECTION_UNREAD;
if (read == 0) {
sel = Message.SELECTION_READ;
}
final ContentResolver cr = context.getContentResolver();
final ContentValues cv = new ContentValues();
cv.put(Message.PROJECTION[Message.INDEX_READ], read);
try {
cr.update(uri, cv, Message.SELECTION_READ_UNREAD, sel);
} catch (IllegalArgumentException e) {
Log.e(TAG, "failed update", e);
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
SmsReceiver.updateNewMessageNotification(context, null);
}
/**
* Delete messages with a given {@link Uri}.
*
* @param context
* {@link Context}
* @param uri
* {@link Uri}
* @param title
* title of Dialog
* @param message
* message of the Dialog
* @param activity
* {@link Activity} to finish when deleting.
*/
static void deleteMessages(final Context context, final Uri uri, final int title,
final int message, final Activity activity) {
Log.i(TAG, "deleteMessages(..," + uri + " ,..)");
final Builder builder = new Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setNegativeButton(android.R.string.no, null);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
final int ret = context.getContentResolver().delete(uri, null, null);
Log.d(TAG, "deleted: " + ret);
if (activity != null && !activity.isFinishing()) {
activity.finish();
}
if (ret > 0) {
Conversation.flushCache();
Message.flushCache();
SmsReceiver.updateNewMessageNotification(context, null);
}
}
});
builder.show();
}
/**
* Add or remove an entry to/from blacklist.
*
* @param context
* {@link Context}
* @param addr
* address
*/
private static void addToOrRemoveFromSpamlist(final Context context, final String addr) {
final SpamDB db = new SpamDB(context);
db.open();
if (!db.isInDB(addr)) {
db.insertNr(addr);
Log.d(TAG, "Added " + addr + " to spam list");
} else {
db.removeNr(addr);
Log.d(TAG, "Removed " + addr + " from spam list");
}
db.close();
}
/**
* {@inheritDoc}
*/
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.item_compose:
final Intent i = getComposeIntent(this, null);
try {
this.startActivity(i);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "error launching intent: " + i.getAction() + ", " + i.getData());
Toast.makeText(this,
"error launching messaging app!\n" + "Please contact the developer.",
Toast.LENGTH_LONG).show();
}
return true;
case R.id.item_settings: // start settings activity
if (Utils.isApi(Build.VERSION_CODES.HONEYCOMB)) {
this.startActivity(new Intent(this, Preferences11Activity.class));
} else {
this.startActivity(new Intent(this, PreferencesActivity.class));
}
return true;
case R.id.item_donate:
DonationHelper.startDonationActivity(this, true);
return true;
case R.id.item_delete_all_threads:
deleteMessages(this, Uri.parse("content://sms/"), R.string.delete_threads_,
R.string.delete_threads_question, null);
return true;
case R.id.item_mark_all_read:
markRead(this, Uri.parse("content://sms/"), 1);
markRead(this, Uri.parse("content://mms/"), 1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Get a {@link Intent} for sending a new message.
*
* @param context
* {@link Context}
* @param address
* address
* @return {@link Intent}
*/
static Intent getComposeIntent(final Context context, final String address) {
final Intent i = new Intent(Intent.ACTION_SENDTO);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (address == null) {
i.setData(Uri.parse("sms:"));
} else {
i.setData(Uri.parse("smsto:" + PreferencesActivity.fixNumber(context, address)));
}
return i;
}
/**
* {@inheritDoc}
*/
public void onItemClick(final AdapterView<?> parent, final View view, final int position,
final long id) {
final Conversation c = Conversation.getConversation(this,
(Cursor) parent.getItemAtPosition(position), false);
final Uri target = c.getUri();
final Intent i = new Intent(this, MessageListActivity.class);
i.setData(target);
try {
this.startActivity(i);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "error launching intent: " + i.getAction() + ", " + i.getData());
Toast.makeText(this,
"error launching messaging app!\n" + "Please contact the developer.",
Toast.LENGTH_LONG).show();
}
}
/**
* {@inheritDoc}
*/
public boolean onItemLongClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
final Conversation c = Conversation.getConversation(this,
(Cursor) parent.getItemAtPosition(position), true);
final Uri target = c.getUri();
Builder builder = new Builder(this);
String[] items = this.longItemClickDialog;
final Contact contact = c.getContact();
final String a = contact.getNumber();
Log.d(TAG, "p: " + a);
final String n = contact.getName();
if (TextUtils.isEmpty(n)) {
builder.setTitle(a);
items = items.clone();
items[WHICH_VIEW_CONTACT] = this.getString(R.string.add_contact_);
} else {
builder.setTitle(n);
}
final SpamDB db = new SpamDB(this.getApplicationContext());
db.open();
if (db.isInDB(a)) {
items = items.clone();
items[WHICH_MARK_SPAM] = this.getString(R.string.dont_filter_spam_);
}
db.close();
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
Intent i = null;
switch (which) {
case WHICH_ANSWER:
ConversationListActivity.this.startActivity(getComposeIntent(
ConversationListActivity.this, a));
break;
case WHICH_CALL:
i = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + a));
ConversationListActivity.this.startActivity(i);
break;
case WHICH_VIEW_CONTACT:
if (n == null) {
i = ContactsWrapper.getInstance().getInsertPickIntent(a);
Conversation.flushCache();
} else {
final Uri uri = c.getContact().getUri();
i = new Intent(Intent.ACTION_VIEW, uri);
}
ConversationListActivity.this.startActivity(i);
break;
case WHICH_VIEW:
i = new Intent(ConversationListActivity.this, MessageListActivity.class);
i.setData(target);
ConversationListActivity.this.startActivity(i);
break;
case WHICH_DELETE:
ConversationListActivity.deleteMessages(ConversationListActivity.this, target,
R.string.delete_thread_, R.string.delete_thread_question, null);
break;
case WHICH_MARK_SPAM:
ConversationListActivity.addToOrRemoveFromSpamlist(
ConversationListActivity.this, c.getContact().getNumber());
break;
default:
break;
}
}
});
builder.create().show();
return true;
}
/**
* Convert time into formated date.
*
* @param context
* {@link Context}
* @param time
* time
* @return formated date.
*/
static String getDate(final Context context, final long time) {
long t = time;
if (t < MIN_DATE) {
t *= MILLIS;
}
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
PreferencesActivity.PREFS_FULL_DATE, false)) {
return DateFormat.getTimeFormat(context).format(t) + " "
+ DateFormat.getDateFormat(context).format(t);
} else if (t < CAL_DAYAGO.getTimeInMillis()) {
return DateFormat.getDateFormat(context).format(t);
} else {
return DateFormat.getTimeFormat(context).format(t);
}
}
}
| false | false | null | null |
diff --git a/utils/src/org/jackie/utils/Assert.java b/utils/src/org/jackie/utils/Assert.java
index d6feeea..fc25ca0 100755
--- a/utils/src/org/jackie/utils/Assert.java
+++ b/utils/src/org/jackie/utils/Assert.java
@@ -1,119 +1,119 @@
package org.jackie.utils;
/**
* @author Patrik Beno
*/
@SuppressWarnings({"ThrowableInstanceNeverThrown", "unchecked"})
public class Assert {
static public void doAssert(boolean condition, String msg, Object... args) {
if (!condition) {
throw new AssertionError(msg, args);
}
}
static public AssertionError assertFailed(Throwable thrown) {
return new AssertionError(thrown);
}
static public AssertionError assertFailed(final Throwable thrown, String msg, Object... args) {
return new AssertionError(thrown, msg, args);
}
// todo optimize; make this effectivelly inlinable
static public <T> T typecast(Object o, Class<T> expected) {
if (o == null) {
return null;
}
if (!expected.isAssignableFrom(o.getClass())) {
throw new ClassCastException(String.format(
- "Incompatible types: Expected %s, found: %s",
+ "Incompatible types. Expected: %s, found: %s",
expected.getName(), o.getClass().getName()));
}
return (T) o;
}
static public AssertionError notYetImplemented() {
StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
return new AssertionError("Not Yet Implemented! %s", ste);
}
static public UnsupportedOperationException unsupported() {
StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
return new UnsupportedOperationException(ste.toString());
}
static public AssertionError unexpected(Throwable thrown) {
return new AssertionError(thrown, "Unexpected: %s", thrown.getClass());
}
static public AssertionError notYetHandled(Throwable t) {
return new AssertionError(t, "Not Yet Handled: %s", t.getClass().getName());
}
static public void logNotYetHandled(Throwable thrown) {
Log.warn("Not Yet Handled: at %s", thrown);
}
static public AssertionError invariantFailed(Throwable thrown, String msg, Object ... args) {
return new AssertionError(thrown, msg, args);
}
static public AssertionError invariantFailed(String msg, Object ... args) {
return new AssertionError(String.format(msg, args));
}
static public AssertionError invariantFailed(Enum e) {
return new AssertionError("Unexpected enum value: %s.%s", e.getClass().getName(), e.name());
}
static public void notNull(Object obj) {
if (obj == null) {
throw new AssertionError("Unexpected NULL");
}
}
static public <T> T NOTNULL(T t, String message, Object ... args) {
if (t == null) {
throw new AssertionError("Unexpected NULL: %s", String.format(message, args));
}
return t;
}
static public <T> T NOTNULL(T t) {
if (t == null) {
throw new AssertionError("Unexpected NULL");
}
return t;
}
static public void logNotYetImplemented() {
StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
Log.warn("Not Yet Implemented: at %s", ste);
}
static public void expected(Object expected, Object found, String msg, Object ... args) {
if (expected != null && expected.equals(found) || expected == null && found == null) { return; }
throw assertFailed(null, "Expected [%s], found [%s]. %s", expected, found, String.format(msg, args));
}
static public boolean NOT(boolean expression) {
return !expression;
}
static class AssertionError extends java.lang.AssertionError {
AssertionError(String message, Object ... args) {
this(null, message, args);
}
AssertionError(Throwable thrown) {
this(thrown, thrown.getClass().getSimpleName());
}
AssertionError(Throwable cause, String message, Object ... args) {
super(String.format(message, args));
initCause(cause);
}
}
}
| true | true | static public <T> T typecast(Object o, Class<T> expected) {
if (o == null) {
return null;
}
if (!expected.isAssignableFrom(o.getClass())) {
throw new ClassCastException(String.format(
"Incompatible types: Expected %s, found: %s",
expected.getName(), o.getClass().getName()));
}
return (T) o;
}
| static public <T> T typecast(Object o, Class<T> expected) {
if (o == null) {
return null;
}
if (!expected.isAssignableFrom(o.getClass())) {
throw new ClassCastException(String.format(
"Incompatible types. Expected: %s, found: %s",
expected.getName(), o.getClass().getName()));
}
return (T) o;
}
|
diff --git a/src/java/com/idega/presentation/Shockwave.java b/src/java/com/idega/presentation/Shockwave.java
index a3dbbc089..90367b297 100755
--- a/src/java/com/idega/presentation/Shockwave.java
+++ b/src/java/com/idega/presentation/Shockwave.java
@@ -1,67 +1,69 @@
package com.idega.presentation;
public class Shockwave extends Flash{
public Shockwave(){
super();
setClassId("166B1BCA-3F9C-11CF-8075-444553540000");
setCodeBase("http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,0,0,0");
setPluginSpace("http://www.macromedia.com/shockwave/download/");
}
public Shockwave(String url){
super(url);
}
public Shockwave(String url,String name){
super(url,name);
}
public Shockwave(String url,String name,int width,int height){
super(url,name,width,height);
}
public Shockwave(String url,int width,int height){
super(url,width,height);
}
+//Alex fix
+public void clearParams(){};
}
| true | false | null | null |
diff --git a/src/com/icecondor/nest/GeoRssList.java b/src/com/icecondor/nest/GeoRssList.java
index efe1ef0..ff5906e 100644
--- a/src/com/icecondor/nest/GeoRssList.java
+++ b/src/com/icecondor/nest/GeoRssList.java
@@ -1,179 +1,181 @@
package com.icecondor.nest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
public class GeoRssList extends ListActivity implements OnItemSelectedListener {
static final String appTag = "GeoRssList";
Intent settingsIntent, radarIntent;
EditText url_field;
Spinner service_spinner;
GeoRssSqlite rssdb;
SQLiteDatabase geoRssDb;
Cursor rsses;
View add_url_dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ Log.i(appTag, "onCreate");
setContentView(R.layout.georsslist);
rssdb = new GeoRssSqlite(this, "georss", null, 1);
geoRssDb = rssdb.getReadableDatabase();
//db.execSQL("insert into urls values (null, 'service', 'https://service.com'");
rsses = geoRssDb.query(GeoRssSqlite.SERVICES_TABLE,null, null, null, null, null, null);
ListAdapter adapter = new SimpleCursorAdapter(
this, // Context
android.R.layout.two_line_list_item, // Specify the row template to use (here, two columns bound to the two retrieved cursor rows)
rsses, // Pass in the cursor to bind to.
new String[] {GeoRssSqlite.NAME, GeoRssSqlite.URL}, // Array of cursor columns to bind to.
new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
setListAdapter(adapter);
// Jump Points
settingsIntent = new Intent(this, Settings.class);
radarIntent = new Intent(this, Radar.class);
}
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(appTag, "onCreateOptionsMenu");
boolean result = super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, 1, Menu.NONE, R.string.menu_geo_rss_add).setIcon(android.R.drawable.ic_menu_add);
menu.add(Menu.NONE, 2, Menu.NONE, R.string.menu_settings).setIcon(android.R.drawable.ic_menu_preferences);
menu.add(Menu.NONE, 3, Menu.NONE, R.string.menu_radar).setIcon(android.R.drawable.ic_menu_compass);
return result;
}
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(appTag, "menu:"+item.getItemId());
switch (item.getItemId()) {
case 1:
showDialog(1);
break;
case 2:
startActivity(settingsIntent);
break;
case 3:
startActivity(radarIntent);
break;
}
return false;
}
@Override
protected Dialog onCreateDialog(int id) {
+ Log.i(appTag, "onCreateDialog "+id);
LayoutInflater factory = LayoutInflater.from(this);
add_url_dialog = factory.inflate(R.layout.georssadd, null);
+ url_field = (EditText) add_url_dialog.findViewById(R.id.rss_url_edit);
service_spinner = (Spinner) add_url_dialog.findViewById(R.id.serviceselect);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.location_service_reader_values, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
service_spinner.setAdapter(adapter);
service_spinner.setOnItemSelectedListener(this);
return new AlertDialog.Builder(this)
.setView(add_url_dialog)
.setTitle(R.string.menu_geo_rss_add)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichbutton) {
String service = (String)service_spinner.getSelectedItem();
String url = url_field.getText().toString();
+ String title = url + "/" + service;
if(service.equals("RSS")) {
// nothing left to do
}else if (service.equals("brightkite.com")) {
- service = service + " " + url;
url = "http://brightkite.com/people/"+url+"/objects.rss";
}else if (service.equals("shizzow.com")) {
- service = service + " " + url;
url = "http://shizzow.com/"+url+"/rss";
}else if (service.equals("icecondor.com")) {
- service = service + " " + url;
url = "http://icecondor.com/locations.rss?id="+url;
}
- insert_service(service, url);
+
+ Log.i(appTag, "adding "+title);
+ insert_service(title, url);
// not of the right way to get the list to refresh
finish();
Intent refresh = new Intent(GeoRssList.this, GeoRssList.class);
startActivity(refresh);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichbutton) {
}
})
.create();
}
protected void insert_service(String service, String url) {
// GeoRSS Database
SQLiteDatabase db = rssdb.getWritableDatabase();
ContentValues cv = new ContentValues(2);
cv.put("name", service);
cv.put("url", url);
db.insert(GeoRssSqlite.SERVICES_TABLE, null, cv);
db.close();
}
protected void onPrepareDialog(int id, Dialog dialog) {
- url_field = (EditText) dialog.findViewById(R.id.rss_url_edit);
url_field.setText(""); // initial value
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
Log.i(appTag, "Item clicked position: "+position);
Intent itemIntent = new Intent(this, GeoRssDetail.class);
rsses.moveToPosition(position);
itemIntent.putExtra(GeoRssSqlite.ID, rsses.getInt(rsses.getColumnIndex(GeoRssSqlite.ID)));
startActivity(itemIntent);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String service = (String)service_spinner.getSelectedItem();
TextView title = (TextView) add_url_dialog.findViewById(R.id.rss_field_title);
if(service.equals("RSS")) {
title.setText("");
}else if (service.equals("brightkite.com")) {
title.setText("Username");
}else if (service.equals("shizzow.com")) {
title.setText("Username");
}else if (service.equals("icecondor.com")) {
title.setText("OpenID or Username");
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
| false | false | null | null |
diff --git a/src/test/java/com/versionone/hudson/SvnModificationTest.java b/src/test/java/com/versionone/hudson/SvnModificationTest.java
index 08a3d76..d487ac2 100644
--- a/src/test/java/com/versionone/hudson/SvnModificationTest.java
+++ b/src/test/java/com/versionone/hudson/SvnModificationTest.java
@@ -1,56 +1,59 @@
package com.versionone.hudson;
import hudson.scm.SubversionChangeLogSet;
import junit.framework.Assert;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
+import java.util.TimeZone;
public class SvnModificationTest {
private Mockery mockery = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
@Test
public void getDate() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
+ dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+4"));
final String gmtDate = "2012-01-12T08:43:41.359375Z";//SVN plugin returns date in GMT
- final String localDateWithoutMicrosecond = "2012-01-12T11:43:41.359Z";
+ final String localDateWithoutMicrosecond = "2012-01-12T12:43:41.359Z";
SvnModification modification = CreateSvnModification(gmtDate);
Date date = modification.getDate();
Assert.assertEquals(dateFormat.parse(localDateWithoutMicrosecond), date);
}
@Test
public void getDateWithoutMicrosecond() throws ParseException {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
+ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'", Locale.US);
+ dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+4"));
final String gmtDate = "2012-01-12T08:43:41.359Z";//SVN plugin returns date in GMT
- final String localDate = "2012-01-12T11:43:41.359Z";
+ final String localDate = "2012-01-12T12:43:41.359Z";
SvnModification modification = CreateSvnModification(gmtDate);
Date date = modification.getDate();
Assert.assertEquals(dateFormat.parse(localDate), date);
}
private SvnModification CreateSvnModification(final String strDate) {
final SubversionChangeLogSet.LogEntry changeSet = mockery.mock(SubversionChangeLogSet.LogEntry.class);
SvnModification modification = new SvnModification(changeSet);
mockery.checking(new Expectations() {
{
allowing(changeSet).getDate();
will(returnValue(strDate));
}
});
return modification;
}
}
| false | false | null | null |
diff --git a/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/UserPrefsTool.java b/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/UserPrefsTool.java
index 7b57ad3..6dd8f74 100644
--- a/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/UserPrefsTool.java
+++ b/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/UserPrefsTool.java
@@ -1,2011 +1,2011 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.user.tool;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.api.app.syllabus.SyllabusService;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.mailarchive.api.MailArchiveService;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.user.api.Preferences;
import org.sakaiproject.user.api.PreferencesEdit;
import org.sakaiproject.user.api.PreferencesService;
import org.sakaiproject.util.ResourceLoader;
/**
* UserPrefsTool is the Sakai end-user tool to view and edit one's preferences.
*/
public class UserPrefsTool
{
/** Our log (commons). */
private static final Log LOG = LogFactory.getLog(UserPrefsTool.class);
/** * Resource bundle messages */
ResourceLoader msgs = new ResourceLoader("user-tool-prefs");
/** The string that Charon uses for preferences. */
private static final String CHARON_PREFS = "sakai:portal:sitenav";
/** The string to get whether privacy status should be visible */
private static final String ENABLE_PRIVACY_STATUS = "enable.privacy.status";
/** Should research/collab specific preferences (no syllabus) be displayed */
private static final String PREFS_RESEARCH = "prefs.research.collab";
/**
* Represents a name value pair in a keyed preferences set.
*/
public class KeyNameValue
{
/** Is this value a list?. */
protected boolean m_isList = false;
/** The key. */
protected String m_key = null;
/** The name. */
protected String m_name = null;
/** The original is this value a list?. */
protected boolean m_origIsList = false;
/** The original key. */
protected String m_origKey = null;
/** The original name. */
protected String m_origName = null;
/** The original value. */
protected String m_origValue = null;
/** The value. */
protected String m_value = null;
public KeyNameValue(String key, String name, String value, boolean isList)
{
m_key = key;
m_origKey = key;
m_name = name;
m_origName = name;
m_value = value;
m_origValue = value;
m_isList = isList;
m_origIsList = isList;
}
public String getKey()
{
return m_key;
}
public String getName()
{
return m_name;
}
public String getOrigKey()
{
return m_origKey;
}
public String getOrigName()
{
return m_origName;
}
public String getOrigValue()
{
return m_origValue;
}
public String getValue()
{
return m_value;
}
public boolean isChanged()
{
return ((!m_name.equals(m_origName)) || (!m_value.equals(m_origValue)) || (!m_key.equals(m_origKey)) || (m_isList != m_origIsList));
}
public boolean isList()
{
return m_isList;
}
public boolean origIsList()
{
return m_origIsList;
}
public void setKey(String value)
{
if (!m_key.equals(value))
{
m_key = value;
}
}
public void setList(boolean b)
{
m_isList = b;
}
public void setName(String value)
{
if (!m_name.equals(value))
{
m_name = value;
}
}
public void setValue(String value)
{
if (!m_value.equals(value))
{
m_value = value;
}
}
}
/** The PreferencesEdit being worked on. */
protected PreferencesEdit m_edit = null;
/** Preferences service (injected dependency) */
protected PreferencesService m_preferencesService = null;
/** Session manager (injected dependency) */
protected SessionManager m_sessionManager = null;
/** The PreferencesEdit in KeyNameValue collection form. */
protected Collection m_stuff = null;
// /** The user id (from the end user) to edit. */
// protected String m_userId = null;
/** For display and selection of Items in JSF-- edit.jsp */
private List prefExcludeItems = new ArrayList();
private List prefOrderItems = new ArrayList();
private List prefTimeZones = new ArrayList();
private List prefLocales = new ArrayList();
private String DEFAULT_TAB_COUNT = "4";
private String prefTabCount = null;
private String[] selectedExcludeItems;
private String[] selectedOrderItems;
private String[] tablist;
private int noti_selection, tab_selection, timezone_selection, language_selection, privacy_selection,j;
//The preference list names
private String Notification="prefs_noti_title";
private String CustomTab="prefs_tab_title";
private String Timezone="prefs_timezone_title";
private String Language="prefs_lang_title";
private String Privacy="prefs_privacy_title";
private boolean refreshMode=false;
protected final static String EXCLUDE_SITE_LISTS = "exclude";
protected final static String ORDER_SITE_LISTS = "order";
protected boolean isNewUser = false;
protected boolean tabUpdated = false;
// user's currently selected time zone
private TimeZone m_timeZone = null;
// user's currently selected regional language locale
private Locale m_locale = null;
private LocaleComparator localeComparator = new LocaleComparator();
/** The user id retrieved from UsageSessionService */
private String userId = "";
private String SAKAI_LOCALES = "locales";
/**
* SAK-11460: With DTHML More Sites, there are potentially two
* "Customize Tab" pages, namely "tab.jsp" (for the pre-DHTML more
* sites), and "tab-dhtml-moresites.jsp". Which one is used depends on the
* sakai.properties "portal.use.dhtml.more". Default is to use
* the pre-DTHML page.
*/
private String m_TabOutcome = "tab";
// //////////////////////////////// PROPERTY GETTER AND SETTER ////////////////////////////////////////////
/**
* @return Returns the ResourceLoader value. Note: workaround for <f:selectItem> element, which doesn't like using the <f:loadBundle> map variable
*/
public String getMsgNotiAnn1()
{
return msgs.getString("noti_ann_1");
}
public String getMsgNotiAnn2()
{
return msgs.getString("noti_ann_2");
}
public String getMsgNotiAnn3()
{
return msgs.getString("noti_ann_3");
}
public String getMsgNotiMail1()
{
return msgs.getString("noti_mail_1");
}
public String getMsgNotiMail2()
{
return msgs.getString("noti_mail_2");
}
public String getMsgNotiMail3()
{
return msgs.getString("noti_mail_3");
}
public String getMsgNotiRsrc1()
{
return msgs.getString("noti_rsrc_1");
}
public String getMsgNotiRsrc2()
{
return msgs.getString("noti_rsrc_2");
}
public String getMsgNotiRsrc3()
{
return msgs.getString("noti_rsrc_3");
}
public String getMsgNotiSyll1()
{
return msgs.getString("noti_syll_1");
}
public String getMsgNotiSyll2()
{
return msgs.getString("noti_syll_2");
}
public String getMsgNotiSyll3()
{
return msgs.getString("noti_syll_3");
}
/**
* @return Returns the prefExcludeItems.
*/
public List getPrefExcludeItems()
{
return prefExcludeItems;
}
/**
* @param prefExcludeItems
* The prefExcludeItems to set.
*/
public void setPrefExcludeItems(List prefExcludeItems)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setPrefExcludeItems(List " + prefExcludeItems + ")");
}
this.prefExcludeItems = prefExcludeItems;
}
/**
* @return Returns the prefOrderItems.
*/
public List getPrefOrderItems()
{
return prefOrderItems;
}
/**
* @param prefOrderItems
* The prefOrderItems to set.
*/
public void setPrefOrderItems(List prefOrderItems)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setPrefOrderItems(List " + prefOrderItems + ")");
}
this.prefOrderItems = prefOrderItems;
}
/**
** @return number of worksite tabs to display in standard site navigation bar
**/
public String getTabCount()
{
if ( prefTabCount != null )
return prefTabCount;
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
ResourceProperties props = prefs.getProperties(CHARON_PREFS);
prefTabCount = props.getProperty("tabs");
if ( prefTabCount == null )
prefTabCount = DEFAULT_TAB_COUNT;
return prefTabCount;
}
/**
** @param count
** number of worksite tabs to display in standard site navigation bar
**/
public void setTabCount( String count )
{
if ( count == null || count.trim().equals("") )
prefTabCount = DEFAULT_TAB_COUNT;
else
prefTabCount = count.trim();
if ( Integer.parseInt(prefTabCount) < Integer.parseInt(DEFAULT_TAB_COUNT) )
prefTabCount = count;
}
/**
* @return Returns the prefTimeZones.
*/
public List getPrefTimeZones()
{
if (prefTimeZones.size() == 0)
{
String[] timeZoneArray = TimeZone.getAvailableIDs();
Arrays.sort(timeZoneArray);
for (int i = 0; i < timeZoneArray.length; i++)
prefTimeZones.add(new SelectItem(timeZoneArray[i], timeZoneArray[i]));
}
return prefTimeZones;
}
/**
* @param prefTimeZones
* The prefTimeZones to set.
*/
public void setPrefTimeZones(List prefTimeZones)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setPrefTimeZones(List " + prefTimeZones + ")");
}
this.prefTimeZones = prefTimeZones;
}
/**
* *
*
* @return Locale based on its string representation (language_region)
*/
private Locale getLocaleFromString(String localeString)
{
String[] locValues = localeString.trim().split("_");
if (locValues.length >= 3)
return new Locale(locValues[0], locValues[1], locValues[2]); // language, country, variant
else if (locValues.length == 2)
return new Locale(locValues[0], locValues[1]); // language, country
else if (locValues.length == 1)
return new Locale(locValues[0]); // language
else
return Locale.getDefault();
}
/**
* @return Returns the prefLocales
*/
public List getPrefLocales()
{
// Initialize list of supported locales, if necessary
if (prefLocales.size() == 0)
{
Locale[] localeArray = null;
String localeString = ServerConfigurationService.getString(SAKAI_LOCALES);
if (localeString != null && !localeString.equals(""))
{
String[] sakai_locales = localeString.split(",");
localeArray = new Locale[sakai_locales.length + 1];
for (int i = 0; i < sakai_locales.length; i++)
localeArray[i] = getLocaleFromString(sakai_locales[i]);
localeArray[localeArray.length - 1] = Locale.getDefault();
}
else
// if no locales specified, get default list
{
localeArray = new Locale[] { Locale.getDefault() };
}
// Sort locales and add to prefLocales (removing duplicates)
Arrays.sort(localeArray, localeComparator);
for (int i = 0; i < localeArray.length; i++)
{
if (i == 0 || !localeArray[i].equals(localeArray[i - 1]))
prefLocales.add(new SelectItem(localeArray[i].toString(), localeArray[i].getDisplayName()));
}
}
return prefLocales;
}
/**
* @param prefLocales
* The prefLocales to set.
*/
public void setPrefLocales(List prefLocales)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setPrefLocales(List " + prefLocales + ")");
}
this.prefLocales = prefLocales;
}
/**
* @return Returns the selectedExcludeItems.
*/
public String[] getSelectedExcludeItems()
{
return selectedExcludeItems;
}
/**
* @param selectedExcludeItems
* The selectedExcludeItems to set.
*/
public void setSelectedExcludeItems(String[] selectedExcludeItems)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSelectedExcludeItems(String[] " + Arrays.toString(selectedExcludeItems) + ")");
}
this.selectedExcludeItems = selectedExcludeItems;
}
/**
* @return Returns the selectedOrderItems.
*/
public String[] getSelectedOrderItems()
{
return selectedOrderItems;
}
/**
* @param selectedOrderItems
* The selectedOrderItems to set.
*/
public void setSelectedOrderItems(String[] selectedOrderItems)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSelectedOrderItems(String[] " + Arrays.toString(selectedOrderItems) + ")");
}
this.selectedOrderItems = selectedOrderItems;
}
/**
* @return Returns the user's selected TimeZone ID
*/
public String getSelectedTimeZone()
{
if (m_timeZone != null) return m_timeZone.getID();
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
ResourceProperties props = prefs.getProperties(TimeService.APPLICATION_ID);
String timeZone = props.getProperty(TimeService.TIMEZONE_KEY);
if (hasValue(timeZone))
m_timeZone = TimeZone.getTimeZone(timeZone);
else
m_timeZone = TimeZone.getDefault();
return m_timeZone.getID();
}
/**
* @param selectedTimeZone
* The selectedTimeZone to set.
*/
public void setSelectedTimeZone(String selectedTimeZone)
{
if (selectedTimeZone != null)
m_timeZone = TimeZone.getTimeZone(selectedTimeZone);
else
LOG.warn(this + "setSelctedTimeZone() has null TimeZone");
}
/**
* @return Returns the user's selected Locale ID
*/
private Locale getSelectedLocale()
{
if (m_locale != null) return m_locale;
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
ResourceProperties props = prefs.getProperties(ResourceLoader.APPLICATION_ID);
String prefLocale = props.getProperty(ResourceLoader.LOCALE_KEY);
if (hasValue(prefLocale))
m_locale = getLocaleFromString(prefLocale);
else
m_locale = Locale.getDefault();
return m_locale;
}
/**
* @return Returns the user's selected Locale ID
*/
public String getSelectedLocaleName()
{
return getSelectedLocale().getDisplayName();
}
/**
* @return Returns the user's selected Locale ID
*/
public String getSelectedLocaleString()
{
return getSelectedLocale().toString();
}
/**
* @param selectedLocale
* The selectedLocale to set.
*/
public void setSelectedLocaleString(String selectedLocale)
{
if (selectedLocale != null) m_locale = getLocaleFromString(selectedLocale);
}
/**
* @return Returns the userId.
*/
public String getUserId()
{
return m_sessionManager.getCurrentSessionUserId();
}
/**
* @param userId
* The userId to set.
*/
public void setUserId(String userId)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setUserId(String " + userId + ")");
}
this.userId = userId;
}
/**
* @param mgr
* The preferences service.
*/
public void setPreferencesService(PreferencesService mgr)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setPreferencesService(PreferencesService " + mgr + ")");
}
m_preferencesService = mgr;
}
/**
* @param mgr
* The session manager.
*/
public void setSessionManager(SessionManager mgr)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSessionManager(SessionManager " + mgr + ")");
}
m_sessionManager = mgr;
}
/**
* @return Returns the tabUpdated.
*/
public boolean isTabUpdated()
{
return tabUpdated;
}
/**
* @param tabUpdated
* The tabUpdated to set.
*/
public void setTabUpdated(boolean tabUpdated)
{
this.tabUpdated = tabUpdated;
}
// /////////////////////////////////////// CONSTRUCTOR ////////////////////////////////////////////
/**
* no-arg constructor.
*/
public UserPrefsTool()
{
// Is DTHML more site enabled?
if (ServerConfigurationService.getBoolean ("portal.use.dhtml.more", false))
m_TabOutcome = "tabDHTMLMoreSites";
else
m_TabOutcome = "tab";
//Tab order configuration
String defaultPreference="prefs_tab_title, prefs_noti_title, prefs_timezone_title, prefs_lang_title";
- if (ServerConfigurationService.getString("preference.pages")==null)
+ if (ServerConfigurationService.getString("preference.pages")== null || ServerConfigurationService.getString("preference.pages").length() == 0)
{
- LOG.warn("The preference.pages is not specified in sakai.properties, hence the default option of 'prefs_tab_title, prefs_noti_title, prefs_timezone_title, prefs_lang_title' is considered");
+ LOG.info("The preference.pages is not specified in sakai.properties, hence the default option of 'prefs_tab_title, prefs_noti_title, prefs_timezone_title, prefs_lang_title' is considered");
}
else
{
- LOG.info("Setting preference.pages as "+ ServerConfigurationService.getString("preference.pages"));
+ LOG.debug("Setting preference.pages as "+ ServerConfigurationService.getString("preference.pages"));
}
//To indicate that it is in the refresh mode
refreshMode=true;
String tabOrder=ServerConfigurationService.getString("preference.pages",defaultPreference);
tablist=tabOrder.split(",");
for(int i=0; i<tablist.length; i++)
{
tablist[i]=tablist[i].trim();
if(tablist[i].equals(Notification)) noti_selection=i+1;
else if(tablist[i].equals(CustomTab)) tab_selection=i+1;
else if(tablist[i].equals(Timezone)) timezone_selection=i+1;
else if (tablist[i].equals(Language)) language_selection=i+1;
else if (tablist[i].equals(Privacy)) privacy_selection=i+1;
else LOG.warn(tablist[i] + " is not valid!!! Re-configure preference.pages at sakai.properties");
}
//defaultPage=tablist[0];
// Set the default tab count to the system property, initially.
DEFAULT_TAB_COUNT = ServerConfigurationService.getString ("portal.default.tabs", DEFAULT_TAB_COUNT);
LOG.debug("new UserPrefsTool()");
}
public int getNoti_selection()
{
//Loading the data for notification in the refresh mode
if (noti_selection==1 && refreshMode==true)
{
processActionNotiFrmEdit();
}
return noti_selection;
}
public int getTab_selection()
{
//Loading the data for customize tab in the refresh mode
if (tab_selection==1 && refreshMode==true)
{
processActionEdit();
}
return tab_selection;
}
public int getTimezone_selection()
{
//Loading the data for timezone in the refresh mode
if (timezone_selection==1 && refreshMode==true)
{
processActionTZFrmEdit();
}
return timezone_selection;
}
public int getLanguage_selection()
{
//Loading the data for language in the refresh mode
if (language_selection==1 && refreshMode==true)
{
processActionLocFrmEdit();
}
return language_selection;
}
public int getPrivacy_selection()
{
//Loading the data for notification in the refresh mode
if (privacy_selection==1 && refreshMode==true)
{
processActionPrivFrmEdit();
}
return privacy_selection;
}
public String getTabTitle()
{
return "tabtitle";
}
// Naming in faces-config.xml Refresh jsp- "refresh" , Notification jsp- "noti" , tab cutomization jsp- "tab"
// ///////////////////////////////////// PROCESS ACTION ///////////////////////////////////////////
/**
* Process the add command from the edit view.
*
* @return navigation outcome to tab customization page (edit)
*/
public String processActionAdd()
{
LOG.debug("processActionAdd()");
tabUpdated = false; // reset successful text message if existing with same jsp
String[] values = getSelectedExcludeItems();
if (values.length < 1)
{
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(msgs.getString("add_to_sites_msg")));
return m_TabOutcome;
}
for (int i = 0; i < values.length; i++)
{
String value = values[i];
getPrefOrderItems().add(removeItems(value, getPrefExcludeItems(), ORDER_SITE_LISTS, EXCLUDE_SITE_LISTS));
}
return m_TabOutcome;
}
/**
* Process remove from order list command
*
* @return navigation output to tab customization page (edit)
*/
public String processActionRemove()
{
LOG.debug("processActionRemove()");
tabUpdated = false; // reset successful text message if existing in jsp
String[] values = getSelectedOrderItems();
if (values.length < 1)
{
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(msgs.getString("remove_from_sites_msg")));
return m_TabOutcome;
}
for (int i = 0; i < values.length; i++)
{
String value = values[i];
getPrefExcludeItems().add(removeItems(value, getPrefOrderItems(), EXCLUDE_SITE_LISTS, ORDER_SITE_LISTS));
}
return m_TabOutcome;
}
/**
* Process Add All action
*
* @return navigation output to tab customization page (edit)
*/
public String processActionAddAll()
{
LOG.debug("processActionAddAll()");
getPrefOrderItems().addAll(getPrefExcludeItems());
getPrefExcludeItems().clear();
tabUpdated = false; // reset successful text message if existing in jsp
return m_TabOutcome;
}
/**
* Process Remove All command
*
* @return navigation output to tab customization page (edit)
*/
public String processActionRemoveAll()
{
LOG.debug("processActionRemoveAll()");
getPrefExcludeItems().addAll(getPrefOrderItems());
getPrefOrderItems().clear();
tabUpdated = false; // reset successful text message if existing in jsp
return m_TabOutcome;
}
/**
* Move Up the selected item in Ordered List
*
* @return navigation output to tab customization page (edit)
*/
public String processActionMoveUp()
{
LOG.debug("processActionMoveUp()");
return doSiteMove(true, false); //moveUp = true, absolute = false
}
/**
* Move down the selected item in Ordered List
*
* @return navigation output to tab customization page (edit)
*/
public String processActionMoveDown()
{
LOG.debug("processActionMoveDown()");
return doSiteMove(false, false); //moveUp = false, absolute = false
}
public String processActionMoveTop()
{
LOG.debug("processActionMoveTop()");
return doSiteMove(true, true); //moveUp = true, absolute = true
}
public String processActionMoveBottom()
{
LOG.debug("processActionMoveBottom()");
return doSiteMove(false, true); //moveUp = false, absolute = true
}
private String doSiteMove(boolean moveUp, boolean absolute) {
tabUpdated = false;
Set<String> selected = new HashSet(Arrays.asList(getSelectedOrderItems()));
List<SelectItem> toMove = new ArrayList<SelectItem>();
//Prune bad selections and split lists if moving absolutely
for (Iterator i = prefOrderItems.iterator(); i.hasNext(); ) {
SelectItem item = (SelectItem) i.next();
if (selected.contains(item.getValue())) {
toMove.add(item);
if (absolute)
i.remove();
}
}
if (toMove.size() == 0) {
String message = msgs.getString(moveUp ? "move_up_msg" : "move_down_msg");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(message));
}
else {
if (absolute) {
//Move the selected list, in order to the right spot.
if (moveUp)
prefOrderItems.addAll(0, toMove);
else
prefOrderItems.addAll(toMove);
}
else {
//Iterate in the right direction
int start = 0;
int interval = 1;
int end = prefOrderItems.size() - 1;
if (!moveUp) {
start = prefOrderItems.size() - 1;
interval = -1;
end = 0;
}
for (int i = start; i != end; i += interval) {
SelectItem cur = (SelectItem) prefOrderItems.get(i);
SelectItem next = (SelectItem) prefOrderItems.get(i + interval);
if (toMove.contains(next) && !toMove.contains(cur)) {
prefOrderItems.set(i, next);
prefOrderItems.set(i + interval, cur);
toMove.remove(next);
}
}
}
}
return m_TabOutcome;
}
/**
* Process the edit command.
*
* @return navigation outcome to tab customization page (edit)
*/
public String processActionEdit()
{
LOG.debug("processActionEdit()");
if (!hasValue(getUserId()))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msgs.getString("user_missing")));
return null;
}
tabUpdated = false; // Reset display of text message on JSP
refreshMode=false;
prefExcludeItems = new ArrayList();
prefOrderItems = new ArrayList();
setUserEditingOn();
List prefExclude = new Vector();
List prefOrder = new Vector();
Preferences prefs = m_preferencesService.getPreferences(getUserId());
ResourceProperties props = prefs.getProperties(CHARON_PREFS);
List l = props.getPropertyList("exclude");
if (l != null)
{
prefExclude = l;
}
l = props.getPropertyList("order");
if (l != null)
{
prefOrder = l;
}
List mySites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, null, null,
org.sakaiproject.site.api.SiteService.SortType.TITLE_ASC, null);
// create excluded and order list of Sites and add balance mySites to excluded Site list for display in Form
List ordered = new Vector();
List excluded = new Vector();
for (Iterator i = prefOrder.iterator(); i.hasNext();)
{
String id = (String) i.next();
// find this site in the mySites list
int pos = indexOf(id, mySites);
if (pos != -1)
{
// move it from mySites to order
Site s = (Site) mySites.get(pos);
ordered.add(s);
mySites.remove(pos);
}
}
for (Iterator iter = prefExclude.iterator(); iter.hasNext();)
{
String element = (String) iter.next();
int pos = indexOf(element, mySites);
if (pos != -1)
{
Site s = (Site) mySites.get(pos);
excluded.add(s);
mySites.remove(pos);
}
}
// pick up the rest of the sites if not available with exclude and order list
// and add to the ordered list as when a new site is created it is displayed in header
ordered.addAll(mySites);
// Now convert to SelectItem for display in JSF
for (Iterator iter = excluded.iterator(); iter.hasNext();)
{
Site element = (Site) iter.next();
SelectItem excludeItem = new SelectItem(element.getId(), element.getTitle());
prefExcludeItems.add(excludeItem);
}
for (Iterator iter = ordered.iterator(); iter.hasNext();)
{
Site element = (Site) iter.next();
SelectItem orderItem = new SelectItem(element.getId(), element.getTitle());
prefOrderItems.add(orderItem);
}
// release lock
m_preferencesService.cancel(m_edit);
return m_TabOutcome;
}
/**
* Process the save command from the edit view.
*
* @return navigation outcome to tab customization page (edit)
*/
public String processActionSave()
{
LOG.debug("processActionSave()");
setUserEditingOn();
// Remove existing property
ResourcePropertiesEdit props = m_edit.getPropertiesEdit(CHARON_PREFS);
props.removeProperty("exclude");
props.removeProperty("order");
// Commit to remove from database, for next set of value storing
m_preferencesService.commit(m_edit);
m_stuff = new Vector();
String oparts = "";
String eparts = "";
for (int i = 0; i < prefExcludeItems.size(); i++)
{
SelectItem item = (SelectItem) prefExcludeItems.get(i);
String evalue = (String) item.getValue();
eparts += evalue + ", ";
}
for (int i = 0; i < prefOrderItems.size(); i++)
{
SelectItem item = (SelectItem) prefOrderItems.get(i);
String value = (String) item.getValue();
oparts += value + ", ";
}
// add property name and value for saving
m_stuff.add(new KeyNameValue(CHARON_PREFS, "exclude", eparts, true));
m_stuff.add(new KeyNameValue(CHARON_PREFS, "order", oparts, true));
m_stuff.add(new KeyNameValue(CHARON_PREFS, "tabs", prefTabCount, false));
// save
saveEdit();
// release lock and clear session variables
cancelEdit();
// To stay on the same page - load the page data
processActionEdit();
tabUpdated = true; // set for display of text message on JSP
// schedule a "peer" html element refresh, to update the site nav tabs
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
setRefreshElement("sitenav");
return m_TabOutcome;
}
/**
* Process the cancel command from the edit view.
*
* @return navigation outcome to tab customization page (edit)
*/
public String processActionCancel()
{
LOG.debug("processActionCancel()");
prefTabCount = null; // reset to retrieve original prefs
// remove session variables
cancelEdit();
// To stay on the same page - load the page data
processActionEdit();
return m_TabOutcome;
}
/**
* Process the cancel command from the edit view.
*
* @return navigation outcome to Notification page (list)
*/
public String processActionNotiFrmEdit()
{
LOG.debug("processActionNotiFrmEdit()");
refreshMode=false;
cancelEdit();
// navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool.
return "noti";
}
/**
* Process the cancel command from the edit view.
*
* @return navigation outcome to timezone page (list)
*/
public String processActionTZFrmEdit()
{
LOG.debug("processActionTZFrmEdit()");
refreshMode=false;
cancelEdit();
// navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool.
return "timezone";
}
/**
* Process the cancel command from the edit view.
*
* @return navigation outcome to locale page (list)
*/
public String processActionLocFrmEdit()
{
LOG.debug("processActionLocFrmEdit()");
refreshMode=false;
cancelEdit();
// navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool.
return "locale";
}
/**
* Process the cancel command from the edit view.
*
* @return navigation outcome to locale page (list)
*/
public String processActionPrivFrmEdit()
{
LOG.debug("processActionPrivFrmEdit()");
cancelEdit();
// navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool.
return "privacy";
}
/**
* This is called from edit page for navigation to refresh page
*
* @return navigation outcome to refresh page (refresh)
*/
public String processActionRefreshFrmEdit()
{
LOG.debug("processActionRefreshFrmEdit()");
// is required as user editing is set on while entering to tab customization page
cancelEdit();
loadRefreshData();
return "refresh";
}
// //////////////////////////////////// HELPER METHODS TO ACTIONS ////////////////////////////////////////////
/**
* Cancel the edit and cleanup.
*/
protected void cancelEdit()
{
LOG.debug("cancelEdit()");
// cleanup
m_stuff = null;
m_edit = null;
prefExcludeItems = new ArrayList();
prefOrderItems = new ArrayList();
isNewUser = false;
tabUpdated = false;
notiUpdated = false;
tzUpdated = false;
locUpdated = false;
refreshUpdated = false;
}
/**
* used with processActionAdd() and processActionRemove()
*
* @return SelectItem
*/
private SelectItem removeItems(String value, List items, String addtype, String removetype)
{
if (LOG.isDebugEnabled())
{
LOG.debug("removeItems(String " + value + ", List " + items + ", String " + addtype + ", String " + removetype + ")");
}
SelectItem result = null;
for (int i = 0; i < items.size(); i++)
{
SelectItem item = (SelectItem) items.get(i);
if (value.equals(item.getValue()))
{
result = (SelectItem) items.remove(i);
break;
}
}
return result;
}
/**
* Set editing mode on for user and add user if not existing
*/
protected void setUserEditingOn()
{
LOG.debug("setUserEditingOn()");
try
{
m_edit = m_preferencesService.edit(getUserId());
}
catch (IdUnusedException e)
{
try
{
m_edit = m_preferencesService.add(getUserId());
isNewUser = true;
}
catch (Exception ee)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ee.toString()));
}
}
catch (Exception e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.toString()));
}
}
/**
* Save any changed values from the edit and cleanup.
*/
protected void saveEdit()
{
LOG.debug("saveEdit()");
// user editing is required as commit() disable isActive() flag
setUserEditingOn();
// move the stuff from m_stuff into the edit
if (m_stuff != null)
{
for (Iterator i = m_stuff.iterator(); i.hasNext();)
{
KeyNameValue knv = (KeyNameValue) i.next();
// find the original to remove (unless this one was new)
if (!knv.getOrigKey().equals(""))
{
ResourcePropertiesEdit props = m_edit.getPropertiesEdit(knv.getOrigKey());
props.removeProperty(knv.getOrigName());
}
// add the new if we have a key and name and value
if ((!knv.getKey().equals("")) && (!knv.getName().equals("")) && (!knv.getValue().equals("")))
{
ResourcePropertiesEdit props = m_edit.getPropertiesEdit(knv.getKey());
if (knv.isList())
{
// split by ", "
String[] parts = knv.getValue().split(", ");
for (int p = 0; p < parts.length; p++)
{
props.addPropertyToList(knv.getName(), parts[p]);
}
}
else
{
props.addProperty(knv.getName(), knv.getValue());
}
}
}
}
// save the preferences, release the edit
m_preferencesService.commit(m_edit);
}
/**
* Check String has value, not null
*
* @return boolean
*/
protected boolean hasValue(String eval)
{
if (LOG.isDebugEnabled())
{
LOG.debug("hasValue(String " + eval + ")");
}
if (eval != null && !eval.trim().equals(""))
{
return true;
}
else
{
return false;
}
}
// Copied from CheronPortal.java
/**
* Find the site in the list that has this id - return the position. *
*
* @param value
* The site id to find.
* @param siteList
* The list of Site objects.
* @return The index position in siteList of the site with site id = value, or -1 if not found.
*/
protected int indexOf(String value, List siteList)
{
if (LOG.isDebugEnabled())
{
LOG.debug("indexOf(String " + value + ", List " + siteList + ")");
}
for (int i = 0; i < siteList.size(); i++)
{
Site site = (Site) siteList.get(i);
if (site.equals(value))
{
return i;
}
}
return -1;
}
// ////////////////////////////////// NOTIFICATION ACTIONS ////////////////////////////////
private String selectedAnnItem = "";
private String selectedMailItem = "";
private String selectedRsrcItem = "";
private String selectedSyllItem = "";
protected boolean notiUpdated = false;
protected boolean tzUpdated = false;
protected boolean locUpdated = false;
// ///////////////////////////////// GETTER AND SETTER ///////////////////////////////////
// TODO chec for any preprocessor for handling request for first time. This can simplify getter() methods as below
/**
* @return Returns the selectedAnnItem.
*/
public String getSelectedAnnItem()
{
LOG.debug("getSelectedAnnItem()");
if (!hasValue(selectedAnnItem))
{
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
String a = buildTypePrefsContext(AnnouncementService.APPLICATION_ID, "annc", selectedAnnItem, prefs);
if (hasValue(a))
{
selectedAnnItem = a; // load from saved data
}
else
{
selectedAnnItem = "3"; // default setting
}
}
return selectedAnnItem;
}
/**
* @param selectedAnnItem
* The selectedAnnItem to set.
*/
public void setSelectedAnnItem(String selectedAnnItem)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSelectedAnnItem(String " + selectedAnnItem + ")");
}
this.selectedAnnItem = selectedAnnItem;
}
/**
* @return Returns the selectedMailItem.
*/
public String getSelectedMailItem()
{
LOG.debug("getSelectedMailItem()");
if (!hasValue(this.selectedMailItem))
{
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
String a = buildTypePrefsContext(MailArchiveService.APPLICATION_ID, "mail", selectedMailItem, prefs);
if (hasValue(a))
{
selectedMailItem = a; // load from saved data
}
else
{
selectedMailItem = "3"; // default setting
}
}
return selectedMailItem;
}
/**
* @param selectedMailItem
* The selectedMailItem to set.
*/
public void setSelectedMailItem(String selectedMailItem)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSelectedMailItem(String " + selectedMailItem + ")");
}
this.selectedMailItem = selectedMailItem;
}
/**
* @return Returns the selectedRsrcItem.
*/
public String getSelectedRsrcItem()
{
LOG.debug("getSelectedRsrcItem()");
if (!hasValue(this.selectedRsrcItem))
{
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
String a = buildTypePrefsContext(ContentHostingService.APPLICATION_ID, "rsrc", selectedRsrcItem, prefs);
if (hasValue(a))
{
selectedRsrcItem = a; // load from saved data
}
else
{
selectedRsrcItem = "3"; // default setting
}
}
return selectedRsrcItem;
}
/**
* @param selectedRsrcItem
* The selectedRsrcItem to set.
*/
public void setSelectedRsrcItem(String selectedRsrcItem)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSelectedRsrcItem(String " + selectedRsrcItem + ")");
}
this.selectedRsrcItem = selectedRsrcItem;
}
// syllabus
public String getSelectedSyllItem()
{
LOG.debug("getSelectedSyllItem()");
if (!hasValue(this.selectedSyllItem))
{
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
String a = buildTypePrefsContext(SyllabusService.APPLICATION_ID, "syll", selectedSyllItem, prefs);
if (hasValue(a))
{
selectedSyllItem = a; // load from saved data
}
else
{
selectedSyllItem = "3"; // default setting
}
}
return selectedSyllItem;
}
public void setSelectedSyllItem(String selectedSyllItem)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSelectedRsrcItem(String " + selectedRsrcItem + ")");
}
this.selectedSyllItem = selectedSyllItem;
}
/**
* @return Returns the notiUpdated.
*/
public boolean getNotiUpdated()
{
return notiUpdated;
}
/**
* @param notiUpdated
* The notiUpdated to set.
*/
public void setNotiUpdated(boolean notiUpdated)
{
this.notiUpdated = notiUpdated;
}
/**
* @return Returns the tzUpdated.
*/
public boolean getTzUpdated()
{
return tzUpdated;
}
/**
* @param notiUpdated
* The tzUpdated to set.
*/
public void setTzUpdated(boolean tzUpdated)
{
this.tzUpdated = tzUpdated;
}
/**
* @return Returns the tzUpdated.
*/
public boolean getLocUpdated()
{
return locUpdated;
}
/**
* @param notiUpdated
* The locUpdated to set.
*/
public void setLocUpdated(boolean locUpdated)
{
this.locUpdated = locUpdated;
}
// ///////////////////////////////////////NOTIFICATION ACTION - copied from NotificationprefsAction.java////////
// TODO - clean up method call. These are basically copied from legacy legacy implementations.
/**
* Process the save command from the edit view.
*
* @return navigation outcome to notification page
*/
public String processActionNotiSave()
{
LOG.debug("processActionNotiSave()");
// get an edit
setUserEditingOn();
if (m_edit != null)
{
readTypePrefs(AnnouncementService.APPLICATION_ID, "annc", m_edit, getSelectedAnnItem());
readTypePrefs(MailArchiveService.APPLICATION_ID, "mail", m_edit, getSelectedMailItem());
readTypePrefs(ContentHostingService.APPLICATION_ID, "rsrc", m_edit, getSelectedRsrcItem());
readTypePrefs(SyllabusService.APPLICATION_ID, "syll", m_edit, getSelectedSyllItem());
// update the edit and release it
m_preferencesService.commit(m_edit);
}
notiUpdated = true;
return "noti";
}
/**
* process notification cancel
*
* @return navigation outcome to notification page
*/
public String processActionNotiCancel()
{
LOG.debug("processActionNotiCancel()");
loadNotiData();
return "noti";
}
/**
* Process the save command from the edit view.
*
* @return navigation outcome to timezone page
*/
public String processActionTzSave()
{
setUserEditingOn();
ResourcePropertiesEdit props = m_edit.getPropertiesEdit(TimeService.APPLICATION_ID);
props.addProperty(TimeService.TIMEZONE_KEY, m_timeZone.getID());
m_preferencesService.commit(m_edit);
TimeService.clearLocalTimeZone(getUserId()); // clear user's cached timezone
tzUpdated = true; // set for display of text massage
return "timezone";
}
/**
* process timezone cancel
*
* @return navigation outcome to timezone page
*/
public String processActionTzCancel()
{
LOG.debug("processActionTzCancel()");
// restore original time zone
m_timeZone = null;
getSelectedTimeZone();
return "timezone";
}
/**
* Process the save command from the edit view.
*
* @return navigation outcome to locale page
*/
public String processActionLocSave()
{
setUserEditingOn();
ResourcePropertiesEdit props = m_edit.getPropertiesEdit(ResourceLoader.APPLICATION_ID);
props.addProperty(ResourceLoader.LOCALE_KEY, m_locale.toString());
m_preferencesService.commit(m_edit);
TimeService.clearLocalTimeZone(getUserId()); // clear user's cached timezone
//Save the preference in the session also
ResourceLoader rl = new ResourceLoader();
Locale loc = rl.setContextLocale(null);
locUpdated = true; // set for display of text massage
return "locale";
}
/**
* process locale cancel
*
* @return navigation outcome to locale page
*/
public String processActionLocCancel()
{
LOG.debug("processActionLocCancel()");
// restore original locale
m_locale = null;
getSelectedLocale();
return "locale";
}
/**
* This is called from notification page for navigation to Refresh page
*
* @return navigation outcome to refresh page
*/
public String processActionRefreshFrmNoti()
{
LOG.debug("processActionRefreshFrmNoti()");
loadRefreshData();
return "refresh";
}
// ////////////////////////////////////// HELPER METHODS FOR NOTIFICATIONS /////////////////////////////////////
/**
* Load saved notification data - this is called from cancel button of notification page as navigation stays in the page
*/
protected void loadNotiData()
{
LOG.debug("loadNotiData()");
selectedAnnItem = "";
selectedMailItem = "";
selectedRsrcItem = "";
selectedSyllItem = "";
notiUpdated = false;
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
String a = buildTypePrefsContext(AnnouncementService.APPLICATION_ID, "annc", selectedAnnItem, prefs);
if (hasValue(a))
{
selectedAnnItem = a; // load from saved data
}
else
{
selectedAnnItem = "2"; // default setting
}
String m = buildTypePrefsContext(MailArchiveService.APPLICATION_ID, "mail", selectedMailItem, prefs);
if (hasValue(m))
{
selectedMailItem = m; // load from saved data
}
else
{
selectedMailItem = "3"; // default setting
}
String r = buildTypePrefsContext(ContentHostingService.APPLICATION_ID, "rsrc", selectedRsrcItem, prefs);
if (hasValue(r))
{
selectedRsrcItem = r; // load from saved data
}
else
{
selectedRsrcItem = "3"; // default setting
}
// syllabus
String s = buildTypePrefsContext(SyllabusService.APPLICATION_ID, "syll", selectedSyllItem, prefs);
if (hasValue(s))
{
selectedSyllItem = s; // load from saved data
}
else
{
selectedSyllItem = "3"; // default setting
}
}
/**
* Read the two context references for defaults for this type from the form.
*
* @param type
* The resource type (i.e. a service name).
* @param prefix
* The prefix for context references.
* @param edit
* The preferences being edited.
* @param data
* The rundata with the form fields.
*/
protected void readTypePrefs(String type, String prefix, PreferencesEdit edit, String data)
{
if (LOG.isDebugEnabled())
{
LOG.debug("readTypePrefs(String " + type + ", String " + prefix + ", PreferencesEdit " + edit + ", String " + data
+ ")");
}
// update the default settings from the form
ResourcePropertiesEdit props = edit.getPropertiesEdit(NotificationService.PREFS_TYPE + type);
// read the defaults
props.addProperty(Integer.toString(NotificationService.NOTI_OPTIONAL), data);
} // readTypePrefs
/**
* Add the two context references for defaults for this type.
*
* @param type
* The resource type (i.e. a service name).
* @param prefix
* The prefix for context references.
* @param context
* The context.
* @param prefs
* The full set of preferences.
*/
protected String buildTypePrefsContext(String type, String prefix, String context, Preferences prefs)
{
if (LOG.isDebugEnabled())
{
LOG.debug("buildTypePrefsContext(String " + type + ", String " + prefix + ", String " + context + ", Preferences "
+ prefs + ")");
}
ResourceProperties props = prefs.getProperties(NotificationService.PREFS_TYPE + type);
String value = props.getProperty(new Integer(NotificationService.NOTI_OPTIONAL).toString());
return value;
}
// ////////////////////////////////////// REFRESH //////////////////////////////////////////
private String selectedRefreshItem = "";
protected boolean refreshUpdated = false;
/**
* @return Returns the selectedRefreshItem.
*/
public String getSelectedRefreshItem()
{
return selectedRefreshItem;
}
/**
* @param selectedRefreshItem
* The selectedRefreshItem to set.
*/
public void setSelectedRefreshItem(String selectedRefreshItem)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setSelectedRefreshItem(String " + selectedRefreshItem + ")");
}
this.selectedRefreshItem = selectedRefreshItem;
}
// /**
// * process saving of refresh
// *
// * @return navigation outcome to refresh page
// */
// public String processActionRefreshSave()
// {
// LOG.debug("processActionRefreshSave()");
//
// // get an edit
// setUserEditingOn();
// if (m_edit != null)
// {
// setStringPref(PortalService.SERVICE_NAME, "refresh", m_edit, getSelectedRefreshItem());
// // update the edit and release it
// m_preferencesService.commit(m_edit);
// }
// refreshUpdated = true;
// return "refresh";
// }
/**
* Process cancel and navigate to list page.
*
* @return navigation outcome to refresh page
*/
public String processActionRefreshCancel()
{
LOG.debug("processActionRefreshCancel()");
loadRefreshData();
return "refresh";
}
/**
* Process cancel and navigate to list page.
*
* @return navigation outcome to notification page
*/
public String processActionNotiFrmRefresh()
{
LOG.debug("processActionNotiFrmRefresh()");
loadNotiData();
return "noti";
//return "tab";
}
// ///////////////////////////////////// HELPER METHODS FOR REFRESH /////////////////////////
/**
* Load refresh data from stored information. This is called when navigated into this page for first time.
*/
protected void loadRefreshData()
{
LOG.debug("loadRefreshData()");
selectedRefreshItem = "";
refreshUpdated = false;
if (!hasValue(selectedRefreshItem))
{
Preferences prefs = (PreferencesEdit) m_preferencesService.getPreferences(getUserId());
// String a = getStringPref(PortalService.SERVICE_NAME, "refresh", prefs);
// if (hasValue(a))
// {
// setSelectedRefreshItem(a); // load from saved data
// }
// else
// {
// setSelectedRefreshItem("2"); // default setting
// }
}
}
/**
* Set an integer preference.
*
* @param pres_base
* The name of the group of properties (i.e. a service name)
* @param type
* The particular property
* @param edit
* An edit version of the full set of preferences for the current logged in user.
* @param newval
* The string to be the new preference.
*/
protected void setStringPref(String pref_base, String type, PreferencesEdit edit, String newval)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setStringPref(String " + pref_base + ", String " + type + ", PreferencesEdit " + edit + ", String " + newval
+ ")");
}
ResourcePropertiesEdit props = edit.getPropertiesEdit(pref_base);
props.addProperty(type, newval);
} // setStringPref
/**
* Retrieve a preference
*
* @param pres_base
* The name of the group of properties (i.e. a service name)
* @param type
* The particular property
* @param prefs
* The full set of preferences for the current logged in user.
*/
protected String getStringPref(String pref_base, String type, Preferences prefs)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getStringPref(String " + pref_base + ", String " + type + ", PreferencesEdit " + prefs + ")");
}
ResourceProperties props = prefs.getProperties(pref_base);
String a = props.getProperty(type);
return a;
} // getIntegerPref
/** The html "peer" element to refresh on the next rendering. */
protected String m_refreshElement = null;
/**
* Get, and clear, the refresh element
*
* @return The html "peer" element to refresh on the next rendering, or null if none defined.
*/
public String getRefreshElement()
{
String rv = m_refreshElement;
m_refreshElement = null;
return rv;
}
/**
* Set the "peer" html element to refresh on the next rendering.
*
* @param element
*/
public void setRefreshElement(String element)
{
m_refreshElement = element;
}
/**
* Pull whether privacy status should be enabled from sakai.properties
*
*/
public boolean isPrivacyEnabled()
{
//return ServerConfigurationService.getBoolean(ENABLE_PRIVACY_STATUS, false);
if (getPrivacy_selection()==0){
return false;
}
else {
return true;
}
}
/**
* Should research/collab specific preferences (no syllabus) be displayed?
*
*/
public boolean isResearchCollab()
{
return ServerConfigurationService.getBoolean(PREFS_RESEARCH, false);
}
}
| false | false | null | null |
diff --git a/utils/src/main/java/jaitools/tiledimage/DiskMemImageGraphics.java b/utils/src/main/java/jaitools/tiledimage/DiskMemImageGraphics.java
index 63aad91d..47c40733 100644
--- a/utils/src/main/java/jaitools/tiledimage/DiskMemImageGraphics.java
+++ b/utils/src/main/java/jaitools/tiledimage/DiskMemImageGraphics.java
@@ -1,997 +1,1020 @@
/*
* Copyright 2009-2011 Michael Bedward
*
* This file is part of jai-tools.
*
* jai-tools is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* jai-tools is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with jai-tools. If not, see <http://www.gnu.org/licenses/>.
*
*/
package jaitools.tiledimage;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorModel;
import java.awt.image.ImageObserver;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.RenderableImage;
import java.lang.reflect.Method;
import java.text.AttributedCharacterIterator;
import java.util.Hashtable;
import java.util.Map;
import javax.media.jai.PlanarImage;
/**
* A Graphics class for drawing into a <code>DiskMemImage</code>.
* As with JAI's <code>TiledImageGraphics</code> class, java.awt
* routines do the work and the purpose of this class is to
* serve the image data in a form that those routines can handle.
* <p>
* Most of the methods in this class are identical in function to
* those in Graphics2D; these have not been documented here.
*
* @see DiskMemImage
*
* @author Michael Bedward
* @since 1.0
* @version $Id$
*/
public class DiskMemImageGraphics extends Graphics2D {
private DiskMemImage targetImage;
private ColorModel colorModel;
private Hashtable<String, Object> properties;
private RenderingHints renderingHints;
/**
* Constants for paint mode: PAINT or XOR.
*/
public static enum PaintMode {
/** Simple paint mode. */
PAINT,
/** XOR paint mode. */
XOR;
};
/*
* java.awt.Graphics parameters
*/
private Point origin;
private Shape clip;
private Color color;
private Font font;
private PaintMode paintMode;
private Color XORColor;
/*
* java.awt.Graphics2D parameters
*/
private Color background;
private Composite composite;
private Paint paint;
private Stroke stroke;
private AffineTransform transform;
/**
* Constants and associated data for graphics operations
*/
public static enum OpType {
/** Describes the clearRect method. */
CLEAR_RECT("clearRect", int.class, int.class, int.class, int.class),
/** Describes the copyArea method. */
COPY_AREA("copyArea", int.class, int.class, int.class, int.class, int.class, int.class),
/** Describes the drawArc method. */
DRAW_ARC("drawArc", int.class, int.class, int.class, int.class, int.class, int.class),
/** Describes the drawImage method. */
DRAW_BUFFERED_IMAGE("drawImage", BufferedImage.class, BufferedImageOp.class, int.class, int.class),
/** Describes the drawGlyphVector method. */
DRAW_GLYPH_VECTOR("drawGlyphVector", GlyphVector.class, float.class, float.class),
/** Describes the drawImage method. */
DRAW_IMAGE_DEST_SRC("drawImage", Image.class, int.class, int.class, int.class, int.class,
int.class, int.class, int.class, int.class, ImageObserver.class),
/** Describes the drawImage method. */
DRAW_IMAGE_DEST_SRC_COL("drawImage", Image.class, int.class, int.class, int.class, int.class,
int.class, int.class, int.class, int.class, Color.class, ImageObserver.class),
/** Describes the drawImage method. */
DRAW_IMAGE_TRANSFORM("drawImage", Image.class, AffineTransform.class, ImageObserver.class),
/** Describes the drawImage method. */
DRAW_IMAGE_XY("drawImage", Image.class, int.class, int.class, ImageObserver.class),
/** Describes the drawImage method. */
DRAW_IMAGE_XY_COL("drawImage", Image.class, int.class, int.class, Color.class, ImageObserver.class),
/** Describes the drawImage method. */
DRAW_IMAGE_XYWH("drawImage", Image.class, int.class, int.class, int.class, int.class, ImageObserver.class),
/** Describes the drawImage method. */
DRAW_IMAGE_XYWH_COL("drawImage", Image.class, int.class, int.class, int.class, int.class, Color.class, ImageObserver.class),
/** Describes the drawLine method. */
DRAW_LINE("drawLine", int.class, int.class, int.class, int.class),
/** Describes the drawOval method. */
DRAW_OVAL("drawOval", int.class, int.class, int.class, int.class),
/** Describes the drawPolygon method. */
DRAW_POLYGON("drawPolygon", int[].class, int[].class, int.class),
/** Describes the drawPolyline method. */
DRAW_POLYLINE("drawPolyline", int[].class, int[].class, int.class),
/** Describes the drawRenderableImage method. */
DRAW_RENDERABLE_IMAGE("drawRenderableImage", RenderableImage.class, AffineTransform.class),
/** Describes the drawRenderedImage method. */
DRAW_RENDERED_IMAGE("drawRenderedImage", RenderedImage.class, AffineTransform.class),
/** Describes the drawRoundRect method. */
DRAW_ROUND_RECT("drawRoundRect", int.class, int.class, int.class, int.class, int.class, int.class),
/** Describes the draw method. */
DRAW_SHAPE("draw", Shape.class),
/** Describes the drawString method. */
DRAW_STRING_XY("drawString", String.class, float.class, float.class),
/** Describes the drawString method. */
DRAW_STRING_ITER_XY("drawString", AttributedCharacterIterator.class, float.class, float.class),
/** Describes the fill method. */
FILL("fill", Shape.class),
/** Describes the fillArc method. */
FILL_ARC("fillArc", int.class, int.class, int.class, int.class, int.class, int.class),
/** Describes the fillOval method. */
FILL_OVAL("fillOval", int.class, int.class, int.class, int.class),
/** Describes the fillPolygon method. */
FILL_POLYGON("fillPolygon", int[].class, int[].class, int.class),
/** Describes the fillRect method. */
FILL_RECT("fillRect", int.class, int.class, int.class, int.class),
/** Describes the fillRoundRect method. */
FILL_ROUND_RECT("fillRoundRect", int.class, int.class, int.class, int.class, int.class, int.class);
private String methodName;
private Class<?>[] paramTypes;
private OpType(String methodName, Class<?> ...types) {
this.methodName = methodName;
this.paramTypes = new Class<?>[types.length];
System.arraycopy(types, 0, this.paramTypes, 0, types.length);
}
/**
* Gets the method name.
* @return method name
*/
public String getMethodName() {
return methodName;
}
/**
* Gets the full method name.
* @return full name
*/
public String getFullMethodName() {
StringBuilder sb = new StringBuilder();
sb.append(methodName);
sb.append("(");
if (paramTypes.length > 0) {
sb.append(paramTypes[0].getSimpleName());
for (int i = 1; i < paramTypes.length; i++) {
sb.append(", ");
sb.append(paramTypes[i].getSimpleName());
}
}
sb.append(")");
return sb.toString();
}
/**
* Gets the number of method arguments
* @return number of arguments
*/
public int getNumArgs() {
return paramTypes.length;
}
/**
* Gets the types of the arguments.
* @return argument types
*/
public Class<?>[] getArgTypes() {
return paramTypes;
}
}
/**
* Creates an instance for the given target image
*
* @param targetImage the image to be drawn into
*/
DiskMemImageGraphics(DiskMemImage targetImage) {
this.targetImage = targetImage;
this.renderingHints = new RenderingHints(null);
setColorModel();
setProperties();
setGraphicsParams();
}
@Override
public void draw(Shape s) {
doDraw(OpType.DRAW_SHAPE, correctForStroke(s.getBounds2D()), s);
}
@Override
public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) {
Rectangle2D bounds = new Rectangle(0, 0, img.getWidth(obs), img.getHeight(obs));
Rectangle2D trBounds = xform.createTransformedShape(bounds).getBounds2D();
return doDraw(OpType.DRAW_IMAGE_TRANSFORM, trBounds, img, xform, obs);
}
@Override
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
Rectangle2D bounds = op.getBounds2D(img);
doDraw(OpType.DRAW_BUFFERED_IMAGE, bounds, img, op, x, y);
}
@Override
public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
Rectangle2D bounds = new Rectangle(img.getMinX(), img.getMinY(),
img.getWidth(), img.getHeight());
Rectangle2D trBounds = xform.createTransformedShape(bounds).getBounds2D();
doDraw(OpType.DRAW_RENDERED_IMAGE, trBounds, img, xform);
}
@Override
public void drawRenderableImage(RenderableImage img, AffineTransform xform) {
Rectangle2D bounds = new Rectangle2D.Float(img.getMinX(), img.getMinY(),
img.getWidth(), img.getHeight());
Rectangle2D trBounds = xform.createTransformedShape(bounds).getBounds2D();
doDraw(OpType.DRAW_RENDERABLE_IMAGE, trBounds, img, xform);
}
@Override
public void drawString(String str, int x, int y) {
drawString( str, (float)x, (float)y );
}
@Override
public void drawString(String str, float x, float y) {
Rectangle2D bounds = getFontMetrics().getStringBounds(str, this);
bounds.setRect(x,
y - bounds.getHeight() + 1,
bounds.getWidth(),
bounds.getHeight() );
doDraw(OpType.DRAW_STRING_XY, bounds, str, x, y);
}
@Override
public void drawString(AttributedCharacterIterator iter, int x, int y) {
drawString( iter, (float)x, (float)y );
}
@Override
public void drawString(AttributedCharacterIterator iter, float x, float y) {
Rectangle2D bounds = getFontMetrics().getStringBounds(
iter, iter.getBeginIndex(), iter.getEndIndex(), this);
bounds.setRect(x,
y - bounds.getHeight() + 1,
bounds.getWidth(),
bounds.getHeight() );
doDraw(OpType.DRAW_STRING_ITER_XY, bounds, iter, x, y);
}
@Override
public void drawGlyphVector(GlyphVector g, float x, float y) {
Rectangle2D bounds = g.getVisualBounds();
// expand the rectangle by a single pixel width to allow for
// rasterizing round-off errors
// (see apidocs for Graphics2D.drawGlyphVector)
bounds.setFrame(bounds.getMinX() - 1, bounds.getMinY() - 1,
bounds.getWidth() + 2, bounds.getHeight() + 2);
doDraw(OpType.DRAW_GLYPH_VECTOR, bounds, g, x, y);
}
@Override
public void fill(Shape s) {
doDraw(OpType.FILL, s.getBounds2D(), s);
}
@Override
public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
Graphics2D gr = getProxy();
copyGraphicsParams(gr);
boolean rtnVal = gr.hit(rect, s, onStroke);
gr.dispose();
return rtnVal;
}
@Override
public GraphicsConfiguration getDeviceConfiguration() {
Graphics2D gr = getProxy();
copyGraphicsParams(gr);
GraphicsConfiguration gc = gr.getDeviceConfiguration();
gr.dispose();
return gc;
}
@Override
public void setComposite(Composite comp) {
composite = comp;
}
@Override
public void setPaint(Paint p) {
paint = p;
}
@Override
public void setStroke(Stroke s) {
stroke = s;
}
@Override
public void setRenderingHint(Key hintKey, Object hintValue) {
renderingHints.put(hintKey, hintValue);
}
@Override
public Object getRenderingHint(Key hintKey) {
return renderingHints.get(hintKey);
}
@Override
public void setRenderingHints(Map<?, ?> hints) {
renderingHints = new RenderingHints(null);
renderingHints.putAll(hints);
}
@Override
public void addRenderingHints(Map<?, ?> hints) {
renderingHints.putAll(hints);
}
@Override
public RenderingHints getRenderingHints() {
return renderingHints;
}
@Override
public void translate(int x, int y) {
origin.setLocation(x, y);
transform.translate( (double)x, (double)y );
}
@Override
public void translate(double tx, double ty) {
transform.translate(tx, ty);
}
@Override
public void rotate(double theta) {
transform.rotate(theta);
}
@Override
public void rotate(double theta, double x, double y) {
transform.rotate(theta, x, y);
}
@Override
public void scale(double sx, double sy) {
transform.scale(sx, sy);
}
@Override
public void shear(double shx, double shy) {
transform.shear(shx, shy);
}
@Override
public void transform(AffineTransform Tx) {
transform.concatenate(Tx);
}
@Override
public void setTransform(AffineTransform Tx) {
transform = Tx;
}
@Override
public AffineTransform getTransform() {
return transform;
}
@Override
public Paint getPaint() {
return paint;
}
@Override
public Composite getComposite() {
return composite;
}
@Override
public void setBackground(Color color) {
background = color;
}
@Override
public Color getBackground() {
return background;
}
@Override
public Stroke getStroke() {
return stroke;
}
@Override
public void clip(Shape s) {
if(clip == null) {
clip = s;
} else {
Area clipArea = (clip instanceof Area ? (Area)clip : new Area(clip));
clipArea.intersect(s instanceof Area ? (Area)s : new Area(s));
clip = clipArea;
}
}
@Override
public FontRenderContext getFontRenderContext() {
Graphics2D gr = getProxy();
copyGraphicsParams(gr);
FontRenderContext frc = gr.getFontRenderContext();
gr.dispose();
return frc;
}
/**
* Returns a copy of this object with its current settings
* @return a new instance of this class
*/
@Override
public Graphics create() {
DiskMemImageGraphics gr = new DiskMemImageGraphics(targetImage);
copyGraphicsParams(gr);
return gr;
}
@Override
public Color getColor() {
return color;
}
@Override
public void setColor(Color c) {
color = c;
}
@Override
public void setPaintMode() {
paintMode = PaintMode.PAINT;
}
@Override
public void setXORMode(Color color) {
paintMode = PaintMode.XOR;
XORColor = color;
}
@Override
public Font getFont() {
return font;
}
@Override
public void setFont(Font font) {
if (font != null) {
this.font = font;
}
}
@Override
public FontMetrics getFontMetrics(Font f) {
Graphics2D gr = getProxy();
copyGraphicsParams(gr);
FontMetrics fm = gr.getFontMetrics(f);
gr.dispose();
return fm;
}
@Override
public Rectangle getClipBounds() {
return clip.getBounds();
}
@Override
public void clipRect(int x, int y, int width, int height) {
clip(new Rectangle(x, y, width, height));
}
@Override
public void setClip(int x, int y, int width, int height) {
setClip(new Rectangle(x, y, width, height));
}
@Override
public Shape getClip() {
return clip;
}
@Override
public void setClip(Shape clip) {
this.clip = clip;
}
@Override
public void copyArea(int x, int y, int width, int height, int dx, int dy) {
doDraw(OpType.COPY_AREA,
new Rectangle(x + dx, y + dy, width, height),
x, y, width, height, dx, dy);
}
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
Rectangle2D bounds = new Rectangle();
bounds.setFrameFromDiagonal(x1, y1, x2, y2);
doDraw(OpType.DRAW_LINE, correctForStroke(bounds), x1, y1, x2, y2);
}
@Override
public void fillRect(int x, int y, int width, int height) {
doDraw(OpType.FILL_RECT, new Rectangle(x, y, width, height), x, y, width, height);
}
@Override
public void clearRect(int x, int y, int width, int height) {
doDraw(OpType.CLEAR_RECT, new Rectangle(x, y, width, height), x, y, width, height);
}
@Override
public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) {
Rectangle2D bounds = new Rectangle(
x - arcWidth, y - arcHeight,
width + 2 * arcWidth, height + 2 * arcHeight);
doDraw(OpType.DRAW_ROUND_RECT, correctForStroke(bounds),
x, y, width, height, arcWidth, arcHeight);
}
@Override
public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) {
Rectangle2D bounds = new Rectangle(
x - arcWidth, y - arcHeight,
width + 2 * arcWidth, height + 2 * arcHeight);
doDraw(OpType.FILL_ROUND_RECT, bounds, x, y, width, height, arcWidth, arcHeight);
}
@Override
public void drawOval(int x, int y, int width, int height) {
Rectangle2D bounds = new Rectangle(x, y, width, height);
doDraw(OpType.DRAW_OVAL, correctForStroke(bounds), x, y, width, height);
}
@Override
public void fillOval(int x, int y, int width, int height) {
Rectangle2D bounds = new Rectangle(x, y, width, height);
doDraw(OpType.FILL_OVAL, bounds, x, y, width, height);
}
@Override
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
Rectangle2D bounds = new Rectangle(x, y, width, height);
doDraw(OpType.DRAW_ARC, correctForStroke(bounds), x, y, width, height, startAngle, arcAngle);
}
@Override
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
Rectangle2D bounds = new Rectangle(x, y, width, height);
doDraw(OpType.FILL_ARC, bounds, x, y, width, height, startAngle, arcAngle);
}
@Override
public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) {
doDraw(OpType.DRAW_POLYLINE,
correctForStroke(getPolyBounds(xPoints, yPoints, nPoints)),
xPoints, yPoints, nPoints);
}
@Override
public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) {
doDraw(OpType.DRAW_POLYGON,
correctForStroke(getPolyBounds(xPoints, yPoints, nPoints)),
xPoints, yPoints, nPoints);
}
@Override
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) {
doDraw(OpType.FILL_POLYGON,
getPolyBounds(xPoints, yPoints, nPoints),
xPoints, yPoints, nPoints);
}
@Override
public boolean drawImage(Image img, int x, int y, ImageObserver obs) {
Rectangle2D bounds = new Rectangle(x, y, img.getWidth(obs), img.getHeight(obs));
return doDraw(OpType.DRAW_IMAGE_XY, bounds, img, x, y, obs);
}
@Override
public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver obs) {
Rectangle2D bounds = new Rectangle(x, y, width, height);
return doDraw(OpType.DRAW_IMAGE_XYWH, bounds, img, x, y, width, height, obs);
}
@Override
public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver obs) {
Rectangle2D bounds = new Rectangle(x, y, img.getWidth(obs), img.getHeight(obs));
return doDraw(OpType.DRAW_IMAGE_XY_COL, bounds, img, x, y, bgcolor, obs);
}
@Override
public boolean drawImage(Image img,
int x, int y, int width, int height,
Color bgcolor, ImageObserver obs) {
Rectangle2D bounds = new Rectangle(x, y, width, height);
return doDraw(OpType.DRAW_IMAGE_XYWH_COL, bounds, img, x, y, width, height, bgcolor, obs);
}
@Override
public boolean drawImage(Image img,
int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
ImageObserver obs) {
Rectangle2D bounds = new Rectangle(dx1, dy1, dx2-dx1+1, dy2-dy1+1);
return doDraw(OpType.DRAW_IMAGE_DEST_SRC, bounds, img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, obs);
}
@Override
public boolean drawImage(Image img,
int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
Color bgcolor, ImageObserver obs) {
Rectangle2D bounds = new Rectangle(dx1, dy1, dx2-dx1+1, dy2-dy1+1);
return doDraw(OpType.DRAW_IMAGE_DEST_SRC_COL, bounds, img,
dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2,
bgcolor, obs);
}
@Override
public void dispose() {
/*
* No need to do anything here
*/
}
/**
* Performs the graphics operation by partitioning the work across the image's
* tiles and using Graphics2D routines to draw into each tile.
*
* @param opType the type of operation
* @param bounds bounds of the element to be drawn
* @param args a variable length list of arguments for the operation
*/
private boolean doDraw(OpType opType, Rectangle2D bounds, Object ...args) {
Method method = null;
boolean rtnVal = false;
try {
method = Graphics2D.class.getMethod(opType.getMethodName(), opType.getArgTypes());
} catch (NoSuchMethodException nsmEx) {
// programmer error :-(
throw new RuntimeException("No such method: " + opType.getFullMethodName());
}
int minTileX = Math.max(targetImage.XToTileX((int)bounds.getMinX()),
targetImage.getMinTileX());
int maxTileX = Math.min(targetImage.XToTileX((int)(bounds.getMaxX() + 0.5)),
targetImage.getMaxTileX());
int minTileY = Math.max(targetImage.YToTileY((int)bounds.getMinY()),
targetImage.getMinTileY());
int maxTileY = Math.min(targetImage.YToTileY((int)(bounds.getMaxY() + 0.5)),
targetImage.getMaxTileY());
for (int tileY = minTileY; tileY <= maxTileY; tileY++) {
int minY = targetImage.tileYToY(tileY);
for (int tileX = minTileX; tileX <= maxTileX; tileX++) {
int minX = targetImage.tileXToX(tileX);
WritableRaster tile = targetImage.getWritableTile(tileX, tileY);
// create a live-copy of the tile with the upper-left corner
// translated to 0,0
WritableRaster copy = tile.createWritableTranslatedChild(0, 0);
BufferedImage bufImg = new BufferedImage(
colorModel,
copy,
colorModel.isAlphaPremultiplied(),
properties);
Graphics2D gr = bufImg.createGraphics();
- copyGraphicsParams(gr);
+
+ // Note: we use the version of copyGraphicsParams taking a
+ // Point arg used to adjust the clip area before copying it
+ // into the graphics object
+ copyGraphicsParams(gr, new Point(minX, minY));
try {
Point2D p2d = gr.getTransform().transform(new Point2D.Double(0, 0), null);
Point p = new Point((int)p2d.getX() - minX, (int)p2d.getY() - minY);
p2d = gr.getTransform().inverseTransform(p, null);
gr.translate(p2d.getX(), p2d.getY());
} catch(NoninvertibleTransformException nte) {
// TODO replace this with decent error handling
throw new RuntimeException(nte);
}
try {
Object oRtnVal = method.invoke(gr, args);
if(oRtnVal != null && oRtnVal.getClass() == boolean.class) {
rtnVal = ((Boolean)oRtnVal).booleanValue();
}
} catch(Exception ex) {
// TODO replace this with decent error handling
throw new RuntimeException(ex);
}
gr.dispose();
targetImage.releaseWritableTile(tileX, tileY);
}
}
return rtnVal;
}
/**
* Takes a bounding rectangle calculated by
* one of the drawing methods and expands it, if necessary, to
* account for the current Stroke width.
* <p>
* This correction appears to be missing from JAI's TiledImageGraphics
* class.
*
* @param rect input bounds
* @return expanded bounds as a new Rectangle2D object; or the
* input Rectangle2D if no stroke is set
*/
private Rectangle2D correctForStroke(Rectangle2D rect) {
if (stroke != null) {
Shape shp = stroke.createStrokedShape(rect);
return shp.getBounds2D();
} else {
return rect;
}
}
/**
* Gets the bounding rectangle of the given vertices.
*
* @param xPoints X ordinates
* @param yPoints Y ordinates
* @param nPoints number of vertices
* @return the bounding rectangle
*/
private Rectangle2D getPolyBounds(int[] xPoints, int[] yPoints, int nPoints) {
Rectangle bounds = new Rectangle();
if (nPoints > 0) {
int minX = xPoints[0];
int maxX = minX;
int minY = yPoints[0];
int maxY = minY;
for (int i = 1; i < nPoints; i++) {
if (xPoints[i] < minX) {
minX = xPoints[i];
} else if (xPoints[i] > maxX) {
maxX = xPoints[i];
}
if (yPoints[i] < minY) {
minY = yPoints[i];
} else if (yPoints[i] > maxY) {
maxY = yPoints[i];
}
}
bounds.setBounds(minX, minY, maxX - minX + 1, maxY - minY + 1);
}
return bounds;
}
/**
* Attempts to retrieve or create a <code>ColorModel</code> for the target
* image.
*
* @throws UnsupportedOperationException if a compatible
* <code>ColorModel</code> is not found
*/
private void setColorModel() {
assert(targetImage != null);
colorModel = targetImage.getColorModel();
if (colorModel == null) {
SampleModel sm = targetImage.getSampleModel();
colorModel = PlanarImage.createColorModel(sm);
if (colorModel == null) {
// try simple default
if (ColorModel.getRGBdefault().isCompatibleSampleModel(sm)) {
colorModel = ColorModel.getRGBdefault();
} else {
// admit defeat
throw new UnsupportedOperationException(
"Failed to get or construct a ColorModel for the image");
}
}
}
}
/**
* Retrieves any properties set for the target image.
*/
private void setProperties() {
assert(targetImage != null);
properties = new Hashtable<String, Object>();
String[] propertyNames = targetImage.getPropertyNames();
if (propertyNames != null) {
for (String name : propertyNames) {
properties.put(name, targetImage.getProperty(name));
}
}
// TODO: set rendering hints
}
/**
* Creates a Graphics2D instance based on the first tile of the
* target image and uses its state to set the graphics parameters
* of this instance.
*/
private void setGraphicsParams() {
assert(targetImage != null);
assert(colorModel != null);
assert(properties != null);
Graphics2D gr = getProxy();
origin = new Point(0, 0);
clip = targetImage.getBounds();
color = gr.getColor();
font = gr.getFont();
paintMode = PaintMode.PAINT;
XORColor = null;
background = gr.getBackground();
composite = gr.getComposite();
paint = null;
stroke = gr.getStroke();
transform = gr.getTransform();
gr.dispose();
}
/**
* Copies the current graphics parameters into the given <code>Graphics2D</code>
* object.
*
* @param gr a Graphics2D object
*/
private void copyGraphicsParams(Graphics2D gr) {
+ copyGraphicsParams(gr, null);
+ }
+
+ /**
+ * Copies the current graphics parameters into the given <code>Graphics2D</code>
+ * object. If {@code workingOrigin} is non-null it is used to translate the
+ * clip area before copying it across.
+ *
+ * @param gr a Graphics2D object
+ */
+ private void copyGraphicsParams(Graphics2D gr, Point workingOrigin) {
gr.translate(origin.x, origin.y);
- gr.setClip(clip);
gr.setColor(getColor());
+
+ if (workingOrigin == null) {
+ gr.setClip(clip);
+ } else {
+ AffineTransform tr = AffineTransform.getTranslateInstance(
+ -workingOrigin.x, -workingOrigin.y);
+ Shape trclip = tr.createTransformedShape(clip);
+ gr.setClip(trclip);
+ }
if(paintMode == PaintMode.PAINT) {
gr.setPaintMode();
} else if (XORColor != null) {
gr.setXORMode(XORColor);
}
gr.setFont(font);
// java.awt.Graphics2D state
gr.setBackground(background);
gr.setComposite(composite);
if(paint != null) {
gr.setPaint(paint);
}
if (renderingHints != null) {
gr.setRenderingHints(renderingHints);
}
gr.setStroke(stroke);
gr.setTransform(transform);
}
/**
* Helper method for other methods that need an instantiated
* Graphics2D object that is 'representative' of the target image.
*
* @return a new Graphics2D instance
*/
private Graphics2D getProxy() {
Raster tile = targetImage.getTile(targetImage.getMinTileX(), targetImage.getMinTileY());
WritableRaster tiny = tile.createCompatibleWritableRaster(1, 1);
BufferedImage img = new BufferedImage(
colorModel, tiny, colorModel.isAlphaPremultiplied(), properties);
return img.createGraphics();
}
}
| false | false | null | null |
diff --git a/test/regression/src/org/jacorb/test/orb/connection/GIOPConnectionTest.java b/test/regression/src/org/jacorb/test/orb/connection/GIOPConnectionTest.java
index 5e9f9ee3..afdc37d1 100644
--- a/test/regression/src/org/jacorb/test/orb/connection/GIOPConnectionTest.java
+++ b/test/regression/src/org/jacorb/test/orb/connection/GIOPConnectionTest.java
@@ -1,659 +1,652 @@
package org.jacorb.test.orb.connection;
/**
* GIOPConnectionTest.java
*
*
* Created: Sat Jun 22 14:26:15 2002
*
* @author Nicolas Noffke
- * @version $Id: GIOPConnectionTest.java,v 1.21 2004-05-05 07:56:40 brose Exp $
+ * @version $Id: GIOPConnectionTest.java,v 1.22 2004-12-08 00:07:31 alphonse.bendt Exp $
*/
import org.jacorb.orb.giop.*;
import org.jacorb.orb.iiop.*;
import java.io.*;
import java.util.*;
import org.omg.ETF.BufferHolder;
import org.omg.ETF.Profile;
import org.omg.GIOP.*;
import org.jacorb.orb.*;
import junit.framework.*;
import org.jacorb.config.Configuration;
public class GIOPConnectionTest
extends TestCase
{
- Configuration config;
+ private Configuration config;
+ private ORB orb;
public void setUp()
throws Exception
{
- config = Configuration.getConfiguration(null,null);
+ orb = (ORB) ORB.init(new String[0], null);
+ config = Configuration.getConfiguration(null, orb, false);
}
public static junit.framework.TestSuite suite()
{
- TestSuite suite = new TestSuite ("GIOPConnection Test");
-
- suite.addTest (new GIOPConnectionTest ("testGIOP_1_2_CorrectFragmentedRequest"));
- suite.addTest (new GIOPConnectionTest ("testGIOP_1_0_CorrectRefusing"));
- suite.addTest (new GIOPConnectionTest ("testGIOP_1_1_IllegalMessageType"));
- suite.addTest (new GIOPConnectionTest ("testGIOP_1_1_NoImplement"));
-
- return suite;
+ return new TestSuite (GIOPConnectionTest.class, "GIOPConnection Test");
}
+
private class DummyTransport extends org.omg.ETF._ConnectionLocalBase
{
private boolean closed = false;
private byte[] data = null;
private int index = 0;
private ByteArrayOutputStream b_out = new ByteArrayOutputStream();
private org.omg.ETF.Profile profile = new IIOPProfile
(
new IIOPAddress ("127.0.0.1", 4711),
null
);
public DummyTransport( List messages )
{
// convert the message list into a plain byte array
int size = 0;
for (Iterator i = messages.iterator(); i.hasNext();)
{
size += ((byte[])i.next()).length;
}
data = new byte[size];
int index = 0;
for (Iterator i = messages.iterator(); i.hasNext();)
{
byte[] msg = (byte[])i.next();
System.arraycopy(msg, 0, data, index, msg.length);
index += msg.length;
}
}
public byte[] getWrittenMessage()
{
return b_out.toByteArray();
}
public void connect (org.omg.ETF.Profile profile, long time_out)
{
// nothing
}
public boolean hasBeenClosed()
{
return closed;
}
public boolean is_connected()
{
return !closed;
}
public void write( boolean is_first, boolean is_last,
byte[] message, int start, int size,
long timeout )
{
b_out.write( message, start, size );
}
public void flush()
{
}
public void close()
{
closed = true;
}
public boolean isSSL()
{
return false;
}
public void turnOnFinalTimeout()
{
}
public Profile get_server_profile()
{
return profile;
}
public void read (BufferHolder data, int offset,
int min_length, int max_length, long time_out)
{
if (this.index + min_length > this.data.length)
{
throw new org.omg.CORBA.COMM_FAILURE ("end of stream");
}
- else
- {
- System.arraycopy (this.data, this.index, data.value, offset, min_length);
- this.index += min_length;
- }
+ System.arraycopy(this.data, this.index, data.value, offset, min_length);
+ this.index += min_length;
}
public boolean is_data_available()
{
return true;
}
public boolean supports_callback()
{
return false;
}
public boolean use_handle_time_out()
{
return false;
}
public boolean wait_next_data(long time_out)
{
return false;
}
}
private class DummyRequestListener
implements RequestListener
{
private byte[] request = null;
public DummyRequestListener()
{
}
public byte[] getRequest()
{
return request;
}
public void requestReceived( byte[] request,
GIOPConnection connection )
{
this.request = request;
}
public void locateRequestReceived( byte[] request,
GIOPConnection connection )
{
this.request = request;
}
public void cancelRequestReceived( byte[] request,
GIOPConnection connection )
{
this.request = request;
}
}
private class DummyReplyListener
implements ReplyListener
{
private byte[] reply = null;
public DummyReplyListener()
{
}
public byte[] getReply()
{
return reply;
}
public void replyReceived( byte[] reply,
GIOPConnection connection )
{
this.reply = reply;
}
public void locateReplyReceived( byte[] reply,
GIOPConnection connection )
{
this.reply = reply;
}
public void closeConnectionReceived( byte[] close_conn,
GIOPConnection connection )
{
this.reply = close_conn;
}
}
public GIOPConnectionTest( String name )
{
super( name );
}
public void testGIOP_1_2_CorrectFragmentedRequest()
{
List messages = new Vector();
RequestOutputStream r_out =
new RequestOutputStream( (ClientConnection) null, //ClientConnection
0, //request id
"foo", //operation
true, // response expected
(short)-1, // SYNC_SCOPE (irrelevant)
null, //request start time
null, //request end time
null, //reply start time
new byte[1], //object key
2 // giop minor
);
//manually write the first half of the string "barbaz"
r_out.write_ulong( 6 ); //string length
r_out.write_octet( (byte) 'b' );
r_out.write_octet( (byte) 'a' );
r_out.write_octet( (byte) 'r' );
r_out.insertMsgSize();
byte[] b = r_out.getBufferCopy();
b[6] |= 0x02; //set "more fragments follow"
messages.add( b );
MessageOutputStream m_out =
new MessageOutputStream();
m_out.writeGIOPMsgHeader( MsgType_1_1._Fragment,
2 // giop minor
);
m_out.write_ulong( 0 ); // Fragment Header (request id)
m_out.write_octet( (byte) 'b' );
m_out.write_octet( (byte) 'a' );
m_out.write_octet( (byte) 'z' );
m_out.insertMsgSize();
messages.add( m_out.getBufferCopy() );
DummyTransport transport =
new DummyTransport( messages );
DummyRequestListener request_listener =
new DummyRequestListener();
DummyReplyListener reply_listener =
new DummyReplyListener();
GIOPConnectionManager giopconn_mg =
new GIOPConnectionManager();
try
{
giopconn_mg.configure (config);
}
catch (Exception e)
{
}
ServerGIOPConnection conn =
giopconn_mg.createServerGIOPConnection( null,
transport,
request_listener,
reply_listener );
try
{
//will not return until an IOException is thrown (by the
//DummyTransport)
conn.receiveMessages();
}
catch( IOException e )
{
//o.k., thrown by DummyTransport
}
catch( Exception e )
{
e.printStackTrace();
fail( "Caught exception: " + e );
}
//did the GIOPConnection hand the complete request over to the
//listener?
assertTrue( request_listener.getRequest() != null );
RequestInputStream r_in =
new RequestInputStream( null, request_listener.getRequest() );
//is the body correct?
assertEquals( "barbaz", r_in.read_string() );
}
public void testGIOP_1_0_CorrectRefusing()
{
List messages = new Vector();
RequestOutputStream r_out =
new RequestOutputStream( null, //ClientConnection
0, //request id
"foo", //operation
true, //response expected
(short)-1, //SYNC_SCOPE (irrelevant)
null, //request start time
null, //request end time
null, //reply end time
new byte[1], //object key
0 // giop minor
);
r_out.write_string( "bar" );
r_out.insertMsgSize();
byte[] b = r_out.getBufferCopy();
b[6] |= 0x02; //set "more fragments follow"
messages.add( b );
DummyTransport transport =
new DummyTransport( messages );
DummyRequestListener request_listener =
new DummyRequestListener();
DummyReplyListener reply_listener =
new DummyReplyListener();
GIOPConnectionManager giopconn_mg =
new GIOPConnectionManager();
try
{
giopconn_mg.configure (config);
}
catch (Exception e)
{
}
GIOPConnection conn =
giopconn_mg.createServerGIOPConnection( null,
transport,
request_listener,
reply_listener );
try
{
//will not return until an IOException is thrown (by the
//DummyTransport)
conn.receiveMessages();
}
catch( IOException e )
{
//o.k., thrown by DummyTransport
}
catch( Exception e )
{
e.printStackTrace();
fail( "Caught exception: " + e );
}
//no request or reply must have been handed over
assertTrue( request_listener.getRequest() == null );
assertTrue( reply_listener.getReply() == null );
//instead, an error message have must been sent via the
//transport
assertTrue( transport.getWrittenMessage() != null );
byte[] result = transport.getWrittenMessage();
assertTrue( Messages.getMsgType( result ) == MsgType_1_1._MessageError );
MessageOutputStream m_out =
new MessageOutputStream();
m_out.writeGIOPMsgHeader( MsgType_1_1._Fragment,
0 // giop minor
);
m_out.write_ulong( 0 ); // Fragment Header (request id)
m_out.write_octet( (byte) 'b' );
m_out.write_octet( (byte) 'a' );
m_out.write_octet( (byte) 'z' );
m_out.insertMsgSize();
messages.add( m_out.getBufferCopy() );
try
{
//will not return until an IOException is thrown (by the
//DummyTransport)
conn.receiveMessages();
}
catch( IOException e )
{
//o.k., thrown by DummyTransport
}
catch( Exception e )
{
e.printStackTrace();
fail( "Caught exception: " + e );
}
//no request or reply must have been handed over
assertTrue( request_listener.getRequest() == null );
assertTrue( reply_listener.getReply() == null );
//instead, an error message have must been sent via the
//transport
assertTrue( transport.getWrittenMessage() != null );
//must be a new one
assertTrue( transport.getWrittenMessage() != result );
result = transport.getWrittenMessage();
assertTrue( Messages.getMsgType( result ) == MsgType_1_1._MessageError );
}
public void testGIOP_1_1_IllegalMessageType()
{
List messages = new Vector();
LocateRequestOutputStream r_out =
new LocateRequestOutputStream(
new byte[1], //object key
0, //request id
1 // giop minor
);
r_out.insertMsgSize();
byte[] b = r_out.getBufferCopy();
b[6] |= 0x02; //set "more fragments follow"
messages.add( b );
- MessageOutputStream m_out =
- new MessageOutputStream();
+// MessageOutputStream m_out =
+// new MessageOutputStream();
DummyTransport transport =
new DummyTransport( messages );
DummyRequestListener request_listener =
new DummyRequestListener();
DummyReplyListener reply_listener =
new DummyReplyListener();
GIOPConnectionManager giopconn_mg =
new GIOPConnectionManager();
try
{
giopconn_mg.configure (config);
}
catch (Exception e)
{
}
GIOPConnection conn =
giopconn_mg.createServerGIOPConnection( null,
transport,
request_listener,
reply_listener );
try
{
//will not return until an IOException is thrown (by the
//DummyTransport)
conn.receiveMessages();
}
catch( IOException e )
{
//o.k., thrown by DummyTransport
}
catch( Exception e )
{
e.printStackTrace();
fail( "Caught exception: " + e );
}
//no request or reply must have been handed over
assertTrue( request_listener.getRequest() == null );
assertTrue( reply_listener.getReply() == null );
//instead, an error message have must been sent via the
//transport
assertTrue( transport.getWrittenMessage() != null );
byte[] result = transport.getWrittenMessage();
assertTrue( Messages.getMsgType( result ) == MsgType_1_1._MessageError );
}
public void testGIOP_1_1_NoImplement()
{
List messages = new Vector();
RequestOutputStream r_out =
new RequestOutputStream( null, //ClientConnection
0, //request id
"foo", //operation
true, //response expected
(short)-1, //SYNC_SCOPE (irrelevant)
null, //request start time
null, //request end time
null, //reply end time
new byte[1], //object key
1 // giop minor
);
r_out.write_string( "bar" );
r_out.insertMsgSize();
byte[] b = r_out.getBufferCopy();
b[6] |= 0x02; //set "more fragments follow"
messages.add( b );
DummyTransport transport =
new DummyTransport( messages );
DummyRequestListener request_listener =
new DummyRequestListener();
DummyReplyListener reply_listener =
new DummyReplyListener();
GIOPConnectionManager giopconn_mg =
new GIOPConnectionManager();
try
{
giopconn_mg.configure (config);
}
catch (Exception e)
{
}
GIOPConnection conn =
giopconn_mg.createServerGIOPConnection( null,
transport,
request_listener,
reply_listener );
try
{
//will not return until an IOException is thrown (by the
//DummyTransport)
conn.receiveMessages();
}
catch( IOException e )
{
//o.k., thrown by DummyTransport
}
catch( Exception e )
{
e.printStackTrace();
fail( "Caught exception: " + e );
}
//no request or reply must have been handed over
assertTrue( request_listener.getRequest() == null );
assertTrue( reply_listener.getReply() == null );
//instead, an error message have must been sent via the
//transport
assertTrue( transport.getWrittenMessage() != null );
byte[] result = transport.getWrittenMessage();
ReplyInputStream r_in = new ReplyInputStream( null, result );
Exception ex = r_in.getException();
if ( ex != null && ex.getClass() == org.omg.CORBA.NO_IMPLEMENT.class )
{
// o.k.
}
else
{
fail();
}
MessageOutputStream m_out =
new MessageOutputStream();
m_out.writeGIOPMsgHeader( MsgType_1_1._Fragment,
1 // giop minor
);
m_out.write_ulong( 0 ); // Fragment Header (request id)
m_out.write_octet( (byte) 'b' );
m_out.write_octet( (byte) 'a' );
m_out.write_octet( (byte) 'z' );
m_out.insertMsgSize();
messages.add( m_out.getBufferCopy() );
try
{
//will not return until an IOException is thrown (by the
//DummyTransport)
conn.receiveMessages();
}
catch( IOException e )
{
//o.k., thrown by DummyTransport
}
catch( Exception e )
{
e.printStackTrace();
fail( "Caught exception: " + e );
}
//no request or reply must have been handed over
assertTrue( request_listener.getRequest() == null );
assertTrue( reply_listener.getReply() == null );
//can't check more, message is discarded
}
}// GIOPConnectionTest
| false | false | null | null |
diff --git a/src/main/java/org/dynjs/parser/ast/FunctionCallExpression.java b/src/main/java/org/dynjs/parser/ast/FunctionCallExpression.java
index 876049cd..b62dcd44 100644
--- a/src/main/java/org/dynjs/parser/ast/FunctionCallExpression.java
+++ b/src/main/java/org/dynjs/parser/ast/FunctionCallExpression.java
@@ -1,195 +1,199 @@
/**
* Copyright 2012 Douglas Campos, and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dynjs.parser.ast;
import static me.qmx.jitescript.util.CodegenUtils.*;
import java.util.List;
import me.qmx.jitescript.CodeBlock;
import org.antlr.runtime.tree.Tree;
import org.dynjs.compiler.JSCompiler;
import org.dynjs.parser.CodeVisitor;
import org.dynjs.runtime.EnvironmentRecord;
import org.dynjs.runtime.ExecutionContext;
import org.dynjs.runtime.JSFunction;
import org.dynjs.runtime.Reference;
import org.dynjs.runtime.Types;
import org.objectweb.asm.tree.LabelNode;
public class FunctionCallExpression extends AbstractExpression {
private final Expression memberExpr;
private final List<Expression> argExprs;
public FunctionCallExpression(final Tree tree, final Expression memberExpr, final List<Expression> argExprs) {
super(tree);
this.memberExpr = memberExpr;
this.argExprs = argExprs;
}
public List<Expression> getArgumentExpressions() {
return this.argExprs;
}
public Expression getMemberExpression() {
return this.memberExpr;
}
@Override
public CodeBlock getCodeBlock() {
return new CodeBlock() {
{
LabelNode propertyRef = new LabelNode();
LabelNode noSelf = new LabelNode();
LabelNode doCall = new LabelNode();
LabelNode isCallable = new LabelNode();
// 11.2.3
aload(JSCompiler.Arities.EXECUTION_CONTEXT);
// context
append(memberExpr.getCodeBlock());
// context ref
dup();
// context ref ref
append(jsGetValue());
// context ref function
- dup();
- // context ref function function
- invokestatic(p(Types.class), "isCallable", sig(boolean.class, Object.class));
- // context ref function bool
- iftrue(isCallable);
- // context ref function
- append(jsThrowTypeError(memberExpr + " is not a function"));
- // THROWN!
- // ----------------------------------------
- // Is Callable
-
- label(isCallable);
- // context ref function
swap();
// context function ref
dup();
// context function ref ref
instance_of(p(Reference.class));
// context function ref isref?
iffalse(noSelf);
// ----------------------------------------
// Reference
// context function ref
checkcast(p(Reference.class));
dup();
// context function ref ref
invokevirtual(p(Reference.class), "isPropertyReference", sig(boolean.class));
// context function ref bool(is-prop)
iftrue(propertyRef);
// ----------------------------------------
// Environment Record
// context function ref
append(jsGetBase());
// context function base
checkcast(p(EnvironmentRecord.class));
// context function env-rec
invokeinterface(p(EnvironmentRecord.class), "implicitThisValue", sig(Object.class));
// context function self
go_to(doCall);
// ----------------------------------------
// Property Reference
label(propertyRef);
// context function ref
append(jsGetBase());
// context function self
go_to(doCall);
// ------------------------------------------
// No self
label(noSelf);
// context function ref
pop();
// context function
append(jsPushUndefined());
// context function UNDEFINED
// ------------------------------------------
// call()
label(doCall);
// context function self
aload(JSCompiler.Arities.EXECUTION_CONTEXT );
// context function self context
invokevirtual(p(ExecutionContext.class), "pushCallContext", sig(void.class));
// context function self
+
+ swap();
+ // context self function
int numArgs = argExprs.size();
bipush(numArgs);
anewarray(p(Object.class));
- // context function self array
+ // context self function array
for (int i = 0; i < numArgs; ++i) {
dup();
bipush(i);
append(argExprs.get(i).getCodeBlock());
append(jsGetValue());
aastore();
}
+ // context self function array
+
+ swap();
+ // context self array function
+ dup_x2();
+ // context function self array function
+ invokestatic(p(Types.class), "isCallable", sig(boolean.class, Object.class));
+ // context function self array bool
+ iftrue(isCallable);
+ // context function self array
+ append(jsThrowTypeError(memberExpr + " is not a function"));
+ // THROWN!
+
+ label(isCallable);
// context function self array
aload(JSCompiler.Arities.EXECUTION_CONTEXT );
// context function self array context
invokevirtual(p(ExecutionContext.class), "popCallContext", sig(void.class));
// context function self array
// call ExecutionContext#call(fn, self, args) -> Object
invokevirtual(p(ExecutionContext.class), "call", sig(Object.class, JSFunction.class, Object.class, Object[].class));
// obj
}
};
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(this.memberExpr).append("(");
boolean first = true;
for (Expression each : this.argExprs) {
if (!first) {
buf.append(", ");
}
buf.append(each.toString());
first = false;
}
buf.append(")");
return buf.toString();
}
public String dump(String indent) {
return super.dump(indent) + this.memberExpr.dump( indent + " " );
}
@Override
public void accept(ExecutionContext context, CodeVisitor visitor, boolean strict) {
visitor.visit( context, this, strict );
}
}
| false | false | null | null |
diff --git a/ggj_2013/src/game/CollisionDetector.java b/ggj_2013/src/game/CollisionDetector.java
index 94f2d5a..a9e789c 100644
--- a/ggj_2013/src/game/CollisionDetector.java
+++ b/ggj_2013/src/game/CollisionDetector.java
@@ -1,63 +1,64 @@
package game;
import java.awt.Rectangle;
import java.util.List;
public class CollisionDetector {
/**
* Checks for a collision between two sets of lines
* @param set1
* @param set2
* @return Whether a collision was detected
*/
public static boolean collision(List<CollisionLine> set1, List<CollisionLine> set2) {
for (CollisionLine firstLine : set1) {
for (CollisionLine secondLine : set2) {
if (collision(firstLine, secondLine)) {
return true;
}
}
}
return false;
}
public static boolean collision(Rectangle rect, List<CollisionLine> lines) {
for (CollisionLine line : lines) {
if (rect.intersectsLine(line.x1, line.y1, line.x2, line.y2)) {
+ System.out.println(rect.x + " " + rect.y);
return true;
}
}
return false;
}
public static boolean collision(CollisionLine line1, CollisionLine line2) {
/*
float px = computeDeterminant(
computeDeterminant(line1.x1, line1.y1, line1.x2, line1.y2),
computeDeterminant(line1.x2, 1, line1.x2, 1),
computeDeterminant(line2.x1, line2.y1, line2.x2, line2.y2),
computeDeterminant(line2.x1, 1, line2.x2, 1))/
computeDeterminant(
computeDeterminant(x1)) */
float x1 = line1.x1;
float x2 = line1.x2;
float x3 = line2.x1;
float x4 = line2.x2;
float y1 = line1.y1;
float y2 = line1.y2;
float y3 = line2.y1;
float y4 = line2.y2;
float px = ((x1*y1-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) /
((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4));
float py = ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) /
((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4));
return checkOnLine(px, py, line1) && checkOnLine(px, py, line2);
}
private static boolean checkOnLine(float x, float y, CollisionLine line) {
return (x >= Math.min(line.x1,line.x2) && x <= Math.max(line.x1, line.x2)
&& y >= Math.min(line.y1, line.y2) && y <= Math.max(line.y1, line.y2));
}
}
diff --git a/ggj_2013/src/game/GameControl.java b/ggj_2013/src/game/GameControl.java
index 3ab019d..032e9a2 100644
--- a/ggj_2013/src/game/GameControl.java
+++ b/ggj_2013/src/game/GameControl.java
@@ -1,150 +1,150 @@
package game;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Date;
import java.util.LinkedList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
import sound.BeatListener;
import sound.BeatTrack;
import sound.Jukebox;
public class GameControl implements Runnable, BeatListener{
long milliseconds = new Date().getTime();
private JPanel frame;
private LinkedList<Wave> waves;
private Player player;
private Color lineColor = Color.GREEN;
private Jukebox jukebox;
private float xspeed = 15.55f;
private int intensity = 1;
private long prevTime;
private long currTime;
private JFrame mainframe;
private int bpm = 140;
private int motif = 1;
public GameControl() {
mainframe = new JFrame("HeArT bEaT");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setResizable(false);
mainframe.setSize(800, 480);
frame = new GameFrame(this);
frame.setVisible(true);
jukebox = new Jukebox(this);
mainframe.add(frame);
mainframe.setVisible(true);
}
public float getXSpeed() {
return xspeed;
}
public Color getLineColor() {
return lineColor;
}
public int getBPM() {
return bpm;
}
public void startGame() {
player = new Player();
player.setPosition(frame.getWidth()/4,240);
mainframe.addKeyListener(player);
prevTime = System.currentTimeMillis();
waves = new LinkedList<Wave>();
- intensity = 1;
+ intensity = 8;
endOfTrack();
Thread t = new Thread(this);
t.start();
}
public void paint(Graphics g) {
g.setColor(Color.GREEN);
//Call the render() method of all GameObjects and draw the line of the EKG
player.render((Graphics2D)g);
float posX = 0;
for (Wave w : waves){
w.render((Graphics2D) g);
g.drawLine((int)posX, 240, (int)w.x, 240);
posX = (int) w.x + w.getWidth();
}
g.drawLine((int)posX, 240, frame.getWidth(), 240);
}
@Override
public void run() {
while (true) {
//Calculate time since last step
//Call update() method of all GameObjects
float tpf;
currTime = System.currentTimeMillis();
tpf = (float)(currTime - prevTime)*30f/1000f;
player.update(tpf);
for (Wave w : waves) {
w.update(tpf);
if (CollisionDetector.collision(player.getHitbox(),
w.getCollisionLines())) {
System.out.println("Collision detected: player must die!");
}
}
if (waves.size() > 0 && waves.get(0).x < -waves.get(0).getWidth()) {
waves.removeFirst();
}
jukebox.update(tpf);
prevTime = currTime;
frame.repaint();
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
e.printStackTrace();
System.exit(0);
}
}
}
@Override
public void endOfTrack() {
//Schedule a new track!
motif = (int)Math.ceil(Math.random()*4);
new Timer().schedule(new TimerTask() {
public void run() {
jukebox.playMotif(motif, intensity);
System.out.println("Playing with intensity " + intensity);
}
}, BeatTrack.DELAY);
}
@Override
public void beat() {
//Create a wave
waves.addLast(new Wave(this,8,48,4));
//Schedule a heartbeat
new Timer().schedule(new TimerTask() {
public void run() {
jukebox.playHeartBeat();
System.out.println("Beat");
}
}, BeatTrack.DELAY);
}
}
diff --git a/ggj_2013/src/game/Player.java b/ggj_2013/src/game/Player.java
index 873b9af..3dfbe74 100644
--- a/ggj_2013/src/game/Player.java
+++ b/ggj_2013/src/game/Player.java
@@ -1,97 +1,98 @@
package game;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
public class Player implements GameObject, KeyListener{
BufferedImage sprite;
public float x;
public float y;
public float yspeed = 0;
private Rectangle hitbox;
private boolean inAir = false;
private int maxJumpTime = 12;
private int jumpTime = maxJumpTime;
private float gravity = 6;
private float jumpSpeed = 20;
private boolean holdingButton = false;
private int jumpButton = java.awt.event.KeyEvent.VK_SPACE;
SpriteSheet spriteSheet;
public Player(){
spriteSheet = new SpriteSheet();
sprite = spriteSheet.getSprite(0, 0);
x = 0;
y = 240;
hitbox = new Rectangle((int)x,(int)y-sprite.getHeight(),
sprite.getWidth(),sprite.getHeight());
}
public void setPosition(float x, float y) {
this.x = x;
this.y = y;
}
public Rectangle getHitbox() {
return hitbox;
}
@Override
public void update(float tpf) {
if (inAir) {
if (holdingButton) {
jumpTime -= tpf;
yspeed = -jumpSpeed;
if (jumpTime <= 0) {
holdingButton = false;
}
}
else {
yspeed += gravity*tpf;
}
y += yspeed*tpf;
if (y > 240) {
y = 240;
inAir = false;
yspeed = 0;
}
}
//update collision box
- hitbox.y = (int)y+sprite.getHeight();
+ hitbox.y = (int)y-sprite.getHeight();
+ hitbox.x = (int)x;
}
@Override
public void render(Graphics2D g) {
g.drawImage(sprite, (int)x, (int)y-sprite.getHeight(), null);
}
@Override
public void keyPressed(KeyEvent event) {
if (!inAir && event.getKeyCode() == jumpButton) {
yspeed = -jumpSpeed;
inAir = true;
holdingButton = true;
jumpTime = maxJumpTime;
}
}
@Override
public void keyReleased(KeyEvent event) {
if (event.getKeyCode() == jumpButton) {
holdingButton = false;
}
}
@Override
public void keyTyped(KeyEvent arg0) {
//Not needed
}
}
| false | false | null | null |
diff --git a/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java b/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java
index 7e727fd..f8f4bbd 100644
--- a/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java
+++ b/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java
@@ -1,467 +1,467 @@
/**
* Copyright (c) 2011-2013 Armin Töpfer
*
* This file is part of InDelFixer.
*
* InDelFixer is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* InDelFixer is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* InDelFixer. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.ethz.bsse.indelfixer.minimal;
import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingFastaSingle;
import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingIlluminaPaired;
import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingIlluminaSingle;
import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingSFFSingle;
import ch.ethz.bsse.indelfixer.sffParser.SFFParsing;
import ch.ethz.bsse.indelfixer.stored.Genome;
import ch.ethz.bsse.indelfixer.stored.Globals;
import ch.ethz.bsse.indelfixer.utils.FastaParser;
import ch.ethz.bsse.indelfixer.utils.StatusUpdate;
import ch.ethz.bsse.indelfixer.utils.Utils;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Logger;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
/**
* Entry point.
*
* @author Armin Töpfer (armin.toepfer [at] gmail.com)
*/
public class Start {
@Option(name = "-i")
private String input;
@Option(name = "-ir")
private String inputReverse;
@Option(name = "-g")
private String genome;
@Option(name = "-o", usage = "Path to the output directory (default: current directory)", metaVar = "PATH")
private String output;
@Option(name = "-v")
private int overlap = 2;
@Option(name = "-k")
private int kmerLength = 10;
@Option(name = "-adjust")
private boolean adjust;
@Option(name = "-t")
private int threshold = 30;
@Option(name = "-step")
private int step = 10;
@Option(name = "-r")
private String regions;
@Option(name = "-flat")
private boolean flat;
@Option(name = "-l")
private int minlength = 0;
@Option(name = "-la")
private int minlengthAligned = 0;
@Option(name = "-sub")
private double sub = 1;
@Option(name = "-del")
private double del = 1;
@Option(name = "-ins")
private double ins = 1;
@Option(name = "-gop")
private float gop = 30;
@Option(name = "-gex")
private float gex = 3;
// @Option(name = "-pacbio")
// private boolean pacbio;
// @Option(name = "-illumina")
// private boolean illumina;
// @Option(name = "-454")
// private boolean roche;
@Option(name = "-cut")
private int cut;
@Option(name = "-header")
private String header;
@Option(name = "--filter")
private boolean filter;
@Option(name = "--freq")
private boolean freq;
@Option(name = "-refine")
private int refine;
@Option(name = "--version")
private boolean version;
@Option(name = "-rmDel")
private boolean rmDel;
@Option(name = "-consensus")
private boolean consensus;
@Option(name = "-N")
private int N = 3;
@Option(name = "-sensitive")
private boolean sensitive;
@Option(name = "-maxDel")
private int maxDel = -1;
@Option(name = "-noHashing")
private boolean noHashing;
@Option(name = "-fix")
private boolean fix;
/**
* Remove logging of jaligner.
*/
{
Logger rootLogger = Logger.getLogger("");
Handler[] handlers = rootLogger.getHandlers();
if (handlers.length > 0) {
rootLogger.removeHandler(handlers[0]);
}
}
/**
* Forwards command-line parameters.
*
* @param args command-line parameters
* @throws IOException If parameters are wrong
*/
public static void main(String[] args) throws IOException {
new Start().doMain(args);
System.exit(0);
}
/**
* Main.
*
* @param args command-line parameters
*/
public void doMain(String[] args) {
try {
CmdLineParser parser = new CmdLineParser(this);
parser.setUsageWidth(80);
try {
parser.parseArgument(args);
if (this.version) {
System.out.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion());
return;
}
this.checkOutput();
if (this.input == null && this.genome == null) {
throw new CmdLineException("");
}
if (this.fix) {
if (this.refine == 0) {
refine = 1;
}
}
this.setGlobals();
Genome[] genomes = parseGenome(this.genome);
if (this.regions != null) {
Globals.RS = this.splitRegion();
genomes = parseGenome(this.cutGenomes(genomes));
}
compute(genomes);
if (this.fix) {
Globals.ADJUST = true;
}
if (this.refine > 0) {
this.genome = this.output + "consensus.fasta";
genomes = parseGenome(this.genome);
for (int i = 0; i < this.refine; i++) {
StatusUpdate.readCount = 0;
StatusUpdate.unmappedCount = 0;
StatusUpdate.tooSmallCount = 0;
StatusUpdate.alignCount1 = 0;
StatusUpdate.alignCount2 = 0;
StatusUpdate.alignCount3 = 0;
compute(genomes);
}
}
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion());
System.err.println("Get latest version from http://bit.ly/indelfixer");
System.err.println("");
System.err.println("USAGE: java -jar InDelFixer.jar options...\n");
System.err.println(" ------------------------");
System.err.println(" === GENERAL options ===");
System.err.println(" -o PATH\t\t: Path to the output directory (default: current directory)");
System.err.println(" -i PATH\t\t: Path to the NGS input file (FASTA, FASTQ or SFF format) [REQUIRED]");
System.err.println(" -ir PATH\t\t: Path to the second paired end file (FASTQ) [ONLY REQUIRED if first file is also fastq]");
System.err.println(" -g PATH\t\t: Path to the reference genomes file (FASTA format) [REQUIRED]");
System.err.println(" -r interval\t\t: Region on the reference genome (i.e. 342-944)");
System.err.println(" -k INT\t\t: Kmer size (default 10)");
System.err.println(" -v INT\t\t: Kmer offset (default 2)");
System.err.println(" -cut INT\t\t: Cut given number of bases (primer) from beginning of the read (default 0)");
System.err.println(" -refine INT\t\t: Computes a consensus sequence from alignment and re-aligns against that.");
System.err.println("\t\t\t Refinement is repeated as many times as specified.");
System.err.println(" -rmDel\t\t: Removes conserved gaps from consensus sequence during refinement");
System.err.println(" -sensitive\t\t: More sensitive but slower alignment");
System.err.println(" -fix\t\t\t: Fill frame-shift causing deletions with consensus sequence.");
System.err.println(" -noHashing\t\t: No fast kmer-matching to find approximate mapping region. Please use with PacBio data!");
System.err.println("");
System.err.println(" === FILTER ===");
System.err.println(" -l INT\t\t: Minimal read-length prior alignment (default 0)");
System.err.println(" -la INT\t\t: Minimal read-length after alignment (default 0)");
- System.err.println(" -ins DOUBLE\t\t: The maximum precentage of insertions allowed [range 0.0 - 1.0] (default 1.0)");
- System.err.println(" -del DOUBLE\t\t: The maximum precentage of deletions allowed [range 0.0 - 1.0] (default 1.0)");
- System.err.println(" -sub DOUBLE\t\t: The maximum precentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)");
+ System.err.println(" -ins DOUBLE\t\t: The maximum percentage of insertions allowed [range 0.0 - 1.0] (default 1.0)");
+ System.err.println(" -del DOUBLE\t\t: The maximum percentage of deletions allowed [range 0.0 - 1.0] (default 1.0)");
+ System.err.println(" -sub DOUBLE\t\t: The maximum percentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)");
System.err.println(" -maxDel INT\t\t: The maximum number of consecutive deletions allowed (default no filtering)");
System.err.println("");
System.err.println(" === GAP costs ===");
System.err.println(" -gop\t\t\t: Gap opening costs for Smith-Waterman (default 30)");
System.err.println(" -gex\t\t\t: Gap extension costs for Smith-Waterman (default 3)");
// System.err.println("");
// System.err.println(" === GAP costs predefined ===");
// System.err.println(" -454\t\t\t: 10 open / 1 extend");
// System.err.println(" -illumina\t\t: 30 open / 3 extend");
// System.err.println(" -pacbio\t\t: 10 open / 10 extend");
System.err.println("");
System.err.println(" ------------------------");
System.err.println(" === EXAMPLES ===");
System.err.println(" 454/Roche\t\t: java -jar InDelFixer.jar -i libCase102.fastq -g referenceGenomes.fasta");
System.err.println(" PacBio\t\t: java -jar InDelFixer.jar -i libCase102.ccs.fastq -g referenceGenomes.fasta");
System.err.println(" Illumina\t\t: java -jar InDelFixer.jar -i libCase102_R1.fastq -ir libCase102_R2.fastq -g referenceGenomes.fasta");
System.err.println(" ------------------------");
}
} catch (OutOfMemoryError e) {
Utils.error();
System.err.println("Please increase the heap space.");
}
}
/**
* Creates output directory if not existing.
*/
private void checkOutput() {
if (this.output == null) {
this.output = System.getProperty("user.dir") + File.separator;
} else {
Globals.output = this.output;
}
if (!new File(this.output).exists()) {
new File(this.output).mkdirs();
}
}
/**
* Splits input region in format x-y
*
* @return
*/
private int[] splitRegion() {
String[] split = regions.split("-");
return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1])};
}
/**
* Cuts genomes into defined region.
*
* @param genomes of type Genome
*/
private String cutGenomes(Genome[] genomes) {
int[] rs = Globals.RS;
StringBuilder sb = new StringBuilder();
for (Genome g : genomes) {
try {
sb.append(">").append(g.getHeader()).append("\n");
sb.append(g.getSequence().substring(rs[0] - 1, rs[1] - 1)).append("\n");
} catch (Exception e) {
System.err.println(e);
Utils.error();
}
}
String output = Globals.output + "ref_" + (rs[0]) + "-" + (rs[1] - 1) + ".fasta";
Utils.saveFile(output, sb.toString());
return output;
}
/**
* Parses genomes from multiple fasta file.
*
* @param genomePath multiple fasta file path
* @return Genome sequences wrapped into Genome class
*/
private Genome[] parseGenome(String genomePath) {
Map<String, String> haps = FastaParser.parseHaplotypeFile(genomePath);
List<Genome> genomeList = new LinkedList<>();
for (Map.Entry<String, String> hap : haps.entrySet()) {
if (header == null || hap.getValue().startsWith(this.header)) {
genomeList.add(new Genome(hap));
}
}
Genome[] gs = genomeList.toArray(new Genome[genomeList.size()]);
Globals.GENOMES = gs;
Globals.GENOME_COUNT = gs.length;
Globals.GENOME_SEQUENCES = haps.keySet().toArray(new String[gs.length]);
Globals.GENOME_LENGTH = Globals.GENOME_SEQUENCES[0].length();
return gs;
}
/**
* Set global variables from command-line parameters
*/
private void setGlobals() {
// if (this.pacbio) {
// Globals.GOP = 10;
// Globals.GEX = 10;
// } else if (this.illumina) {
// Globals.GOP = 30;
// Globals.GEX = 3;
// } else if (this.roche) {
// Globals.GOP = 10;
// Globals.GEX = 1;
// } else {
Globals.GOP = this.gop;
Globals.GEX = this.gex;
// }
Globals.MIN_LENGTH_ALIGNED = minlengthAligned;
Globals.MIN_LENGTH = minlength;
Globals.ADJUST = this.adjust;
Globals.STEPS = this.step;
Globals.THRESHOLD = this.threshold;
Globals.KMER_OVERLAP = this.overlap;
Globals.KMER_LENGTH = this.kmerLength;
Globals.MAX_DEL = this.del;
Globals.MAX_INS = this.ins;
Globals.MAX_SUB = this.sub;
Globals.FLAT = this.flat;
Globals.CUT = this.cut;
Globals.FILTER = this.filter;
Globals.REFINE = this.refine > 0;
Globals.RM_DEL = this.rmDel;
Globals.maxN = this.N;
Globals.CONSENSUS = this.consensus;
Globals.SENSITIVE = this.sensitive;
Globals.MAX_CONSECUTIVE_DEL = this.maxDel;
Globals.NO_HASHING = this.noHashing;
}
/**
* Flats multiple fasta file and splits it files with 100 sequences.
*/
private void flatAndSave() {
Map<String, String> far = FastaParser.parseHaplotypeFile(input);
StringBuilder sb = new StringBuilder();
int x = 0;
int i = 0;
for (Map.Entry<String, String> entry : far.entrySet()) {
sb.append(entry.getValue()).append("\n").append(entry.getKey()).append("\n");
if (i++ % 1000 == 0) {
Utils.saveFile(output + "flat-" + x++ + ".fasta", sb.toString());
sb.setLength(0);
}
}
if (sb.length() > 0) {
Utils.saveFile(output + "flat-" + x + ".fasta", sb.toString());
}
}
public static byte[] splitReadIntoByteArray(String read) {
byte[] Rs = new byte[read.length()];
char[] readSplit = read.toCharArray();
int length = readSplit.length;
for (int i = 0; i < length; i++) {
switch ((short) readSplit[i]) {
case 65:
Rs[i] = 0;
break;
case 67:
Rs[i] = 1;
break;
case 71:
Rs[i] = 2;
break;
case 84:
Rs[i] = 3;
break;
case 45:
Rs[i] = 4;
break;
default:
break;
}
}
return Rs;
}
public static String shortenSmall(double value) {
String s;
if (value < 1e-16) {
s = "0 ";
} else if (value == 1.0) {
s = "1 ";
} else {
String t = "" + value;
String r;
if (t.length() > 7) {
r = t.substring(0, 7);
if (t.contains("E")) {
r = r.substring(0, 4);
r += "E" + t.split("E")[1];
}
s = r;
} else {
s = String.valueOf(value);
}
}
return s;
}
private boolean compute(Genome[] genomes) throws CmdLineException, IllegalStateException {
if (this.freq) {
double[][] allels = new double[genomes[0].getSequence().length()][5];
for (Genome g : genomes) {
byte[] a = splitReadIntoByteArray(g.getSequence());
for (int j = 0; j < g.getSequence().length(); j++) {
allels[j][a[j]] += 1d / genomes.length;
}
}
StringBuilder sb = new StringBuilder();
sb.append("\tA\tC\tG\tT\t-\n");
for (int j = 0; j < allels.length; j++) {
sb.append(j);
double sum = 0d;
for (int v = 0; v < 5; v++) {
sum += allels[j][v] > 1e-5 ? allels[j][v] : 0;;
}
for (int v = 0; v < 5; v++) {
sb.append("\t").append(shortenSmall(allels[j][v] / sum));
}
sb.append("\n");
}
Utils.saveFile("Genome_allels.txt", sb.toString());
return true;
}
for (Genome g : genomes) {
g.split();
}
if (!new File(this.input).exists()) {
throw new CmdLineException("Input file does not exist");
}
File readsSam = new File(this.output + "reads.sam");
if (readsSam.exists()) {
readsSam.delete();
}
if (this.inputReverse != null) {
if (!new File(this.inputReverse).exists()) {
throw new CmdLineException("Input reverse file does not exist");
}
new ProcessingIlluminaPaired(this.input, this.inputReverse);
} else if (Utils.isFastaGlobalMatePairFormat(this.input)) {
new ProcessingIlluminaSingle(this.input);
} else if (Utils.isFastaFormat(this.input)) {
new ProcessingFastaSingle(this.input);
} else {
new ProcessingSFFSingle(SFFParsing.parse(this.input));
}
return false;
}
}
| true | true | public void doMain(String[] args) {
try {
CmdLineParser parser = new CmdLineParser(this);
parser.setUsageWidth(80);
try {
parser.parseArgument(args);
if (this.version) {
System.out.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion());
return;
}
this.checkOutput();
if (this.input == null && this.genome == null) {
throw new CmdLineException("");
}
if (this.fix) {
if (this.refine == 0) {
refine = 1;
}
}
this.setGlobals();
Genome[] genomes = parseGenome(this.genome);
if (this.regions != null) {
Globals.RS = this.splitRegion();
genomes = parseGenome(this.cutGenomes(genomes));
}
compute(genomes);
if (this.fix) {
Globals.ADJUST = true;
}
if (this.refine > 0) {
this.genome = this.output + "consensus.fasta";
genomes = parseGenome(this.genome);
for (int i = 0; i < this.refine; i++) {
StatusUpdate.readCount = 0;
StatusUpdate.unmappedCount = 0;
StatusUpdate.tooSmallCount = 0;
StatusUpdate.alignCount1 = 0;
StatusUpdate.alignCount2 = 0;
StatusUpdate.alignCount3 = 0;
compute(genomes);
}
}
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion());
System.err.println("Get latest version from http://bit.ly/indelfixer");
System.err.println("");
System.err.println("USAGE: java -jar InDelFixer.jar options...\n");
System.err.println(" ------------------------");
System.err.println(" === GENERAL options ===");
System.err.println(" -o PATH\t\t: Path to the output directory (default: current directory)");
System.err.println(" -i PATH\t\t: Path to the NGS input file (FASTA, FASTQ or SFF format) [REQUIRED]");
System.err.println(" -ir PATH\t\t: Path to the second paired end file (FASTQ) [ONLY REQUIRED if first file is also fastq]");
System.err.println(" -g PATH\t\t: Path to the reference genomes file (FASTA format) [REQUIRED]");
System.err.println(" -r interval\t\t: Region on the reference genome (i.e. 342-944)");
System.err.println(" -k INT\t\t: Kmer size (default 10)");
System.err.println(" -v INT\t\t: Kmer offset (default 2)");
System.err.println(" -cut INT\t\t: Cut given number of bases (primer) from beginning of the read (default 0)");
System.err.println(" -refine INT\t\t: Computes a consensus sequence from alignment and re-aligns against that.");
System.err.println("\t\t\t Refinement is repeated as many times as specified.");
System.err.println(" -rmDel\t\t: Removes conserved gaps from consensus sequence during refinement");
System.err.println(" -sensitive\t\t: More sensitive but slower alignment");
System.err.println(" -fix\t\t\t: Fill frame-shift causing deletions with consensus sequence.");
System.err.println(" -noHashing\t\t: No fast kmer-matching to find approximate mapping region. Please use with PacBio data!");
System.err.println("");
System.err.println(" === FILTER ===");
System.err.println(" -l INT\t\t: Minimal read-length prior alignment (default 0)");
System.err.println(" -la INT\t\t: Minimal read-length after alignment (default 0)");
System.err.println(" -ins DOUBLE\t\t: The maximum precentage of insertions allowed [range 0.0 - 1.0] (default 1.0)");
System.err.println(" -del DOUBLE\t\t: The maximum precentage of deletions allowed [range 0.0 - 1.0] (default 1.0)");
System.err.println(" -sub DOUBLE\t\t: The maximum precentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)");
System.err.println(" -maxDel INT\t\t: The maximum number of consecutive deletions allowed (default no filtering)");
System.err.println("");
System.err.println(" === GAP costs ===");
System.err.println(" -gop\t\t\t: Gap opening costs for Smith-Waterman (default 30)");
System.err.println(" -gex\t\t\t: Gap extension costs for Smith-Waterman (default 3)");
// System.err.println("");
// System.err.println(" === GAP costs predefined ===");
// System.err.println(" -454\t\t\t: 10 open / 1 extend");
// System.err.println(" -illumina\t\t: 30 open / 3 extend");
// System.err.println(" -pacbio\t\t: 10 open / 10 extend");
System.err.println("");
System.err.println(" ------------------------");
System.err.println(" === EXAMPLES ===");
System.err.println(" 454/Roche\t\t: java -jar InDelFixer.jar -i libCase102.fastq -g referenceGenomes.fasta");
System.err.println(" PacBio\t\t: java -jar InDelFixer.jar -i libCase102.ccs.fastq -g referenceGenomes.fasta");
System.err.println(" Illumina\t\t: java -jar InDelFixer.jar -i libCase102_R1.fastq -ir libCase102_R2.fastq -g referenceGenomes.fasta");
System.err.println(" ------------------------");
}
} catch (OutOfMemoryError e) {
Utils.error();
System.err.println("Please increase the heap space.");
}
}
| public void doMain(String[] args) {
try {
CmdLineParser parser = new CmdLineParser(this);
parser.setUsageWidth(80);
try {
parser.parseArgument(args);
if (this.version) {
System.out.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion());
return;
}
this.checkOutput();
if (this.input == null && this.genome == null) {
throw new CmdLineException("");
}
if (this.fix) {
if (this.refine == 0) {
refine = 1;
}
}
this.setGlobals();
Genome[] genomes = parseGenome(this.genome);
if (this.regions != null) {
Globals.RS = this.splitRegion();
genomes = parseGenome(this.cutGenomes(genomes));
}
compute(genomes);
if (this.fix) {
Globals.ADJUST = true;
}
if (this.refine > 0) {
this.genome = this.output + "consensus.fasta";
genomes = parseGenome(this.genome);
for (int i = 0; i < this.refine; i++) {
StatusUpdate.readCount = 0;
StatusUpdate.unmappedCount = 0;
StatusUpdate.tooSmallCount = 0;
StatusUpdate.alignCount1 = 0;
StatusUpdate.alignCount2 = 0;
StatusUpdate.alignCount3 = 0;
compute(genomes);
}
}
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion());
System.err.println("Get latest version from http://bit.ly/indelfixer");
System.err.println("");
System.err.println("USAGE: java -jar InDelFixer.jar options...\n");
System.err.println(" ------------------------");
System.err.println(" === GENERAL options ===");
System.err.println(" -o PATH\t\t: Path to the output directory (default: current directory)");
System.err.println(" -i PATH\t\t: Path to the NGS input file (FASTA, FASTQ or SFF format) [REQUIRED]");
System.err.println(" -ir PATH\t\t: Path to the second paired end file (FASTQ) [ONLY REQUIRED if first file is also fastq]");
System.err.println(" -g PATH\t\t: Path to the reference genomes file (FASTA format) [REQUIRED]");
System.err.println(" -r interval\t\t: Region on the reference genome (i.e. 342-944)");
System.err.println(" -k INT\t\t: Kmer size (default 10)");
System.err.println(" -v INT\t\t: Kmer offset (default 2)");
System.err.println(" -cut INT\t\t: Cut given number of bases (primer) from beginning of the read (default 0)");
System.err.println(" -refine INT\t\t: Computes a consensus sequence from alignment and re-aligns against that.");
System.err.println("\t\t\t Refinement is repeated as many times as specified.");
System.err.println(" -rmDel\t\t: Removes conserved gaps from consensus sequence during refinement");
System.err.println(" -sensitive\t\t: More sensitive but slower alignment");
System.err.println(" -fix\t\t\t: Fill frame-shift causing deletions with consensus sequence.");
System.err.println(" -noHashing\t\t: No fast kmer-matching to find approximate mapping region. Please use with PacBio data!");
System.err.println("");
System.err.println(" === FILTER ===");
System.err.println(" -l INT\t\t: Minimal read-length prior alignment (default 0)");
System.err.println(" -la INT\t\t: Minimal read-length after alignment (default 0)");
System.err.println(" -ins DOUBLE\t\t: The maximum percentage of insertions allowed [range 0.0 - 1.0] (default 1.0)");
System.err.println(" -del DOUBLE\t\t: The maximum percentage of deletions allowed [range 0.0 - 1.0] (default 1.0)");
System.err.println(" -sub DOUBLE\t\t: The maximum percentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)");
System.err.println(" -maxDel INT\t\t: The maximum number of consecutive deletions allowed (default no filtering)");
System.err.println("");
System.err.println(" === GAP costs ===");
System.err.println(" -gop\t\t\t: Gap opening costs for Smith-Waterman (default 30)");
System.err.println(" -gex\t\t\t: Gap extension costs for Smith-Waterman (default 3)");
// System.err.println("");
// System.err.println(" === GAP costs predefined ===");
// System.err.println(" -454\t\t\t: 10 open / 1 extend");
// System.err.println(" -illumina\t\t: 30 open / 3 extend");
// System.err.println(" -pacbio\t\t: 10 open / 10 extend");
System.err.println("");
System.err.println(" ------------------------");
System.err.println(" === EXAMPLES ===");
System.err.println(" 454/Roche\t\t: java -jar InDelFixer.jar -i libCase102.fastq -g referenceGenomes.fasta");
System.err.println(" PacBio\t\t: java -jar InDelFixer.jar -i libCase102.ccs.fastq -g referenceGenomes.fasta");
System.err.println(" Illumina\t\t: java -jar InDelFixer.jar -i libCase102_R1.fastq -ir libCase102_R2.fastq -g referenceGenomes.fasta");
System.err.println(" ------------------------");
}
} catch (OutOfMemoryError e) {
Utils.error();
System.err.println("Please increase the heap space.");
}
}
|
diff --git a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java
index 0ac087781..eab63cb58 100644
--- a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java
+++ b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java
@@ -1,270 +1,270 @@
/**
* Copyright (c) 2011 Metropolitan Transportation Authority
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.onebusaway.nyc.webapp.actions;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.onebusaway.nyc.webapp.actions.OneBusAwayNYCActionSupport;
/**
* Adapted from Google Analytics' ga.jsp code, which was: Copyright 2009 Google Inc. All Rights Reserved.
**/
@Results( {@Result(type = "stream", name = "pixel", params = {"contentType", "image/gif"})} )
public class GaAction extends OneBusAwayNYCActionSupport {
private static final long serialVersionUID = 1L;
// Download stream to write 1x1 px. GIF back to user.
private InputStream inputStream;
// Tracker version.
private static final String version = "4.4sj";
private static final String COOKIE_NAME = "__utmmobile";
// The path the cookie will be available to, edit this to use a different
// cookie path.
private static final String COOKIE_PATH = "/";
// Two years in seconds.
private static final int COOKIE_USER_PERSISTENCE = 63072000;
// 1x1 transparent GIF
private static final byte[] GIF_DATA = new byte[] {
(byte)0x47, (byte)0x49, (byte)0x46, (byte)0x38, (byte)0x39, (byte)0x61,
(byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x80, (byte)0xff,
(byte)0x00, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x00, (byte)0x00,
(byte)0x00, (byte)0x2c, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
(byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x02,
(byte)0x02, (byte)0x44, (byte)0x01, (byte)0x00, (byte)0x3b
};
// this is the download streamed to the user
public InputStream getInputStream() {
return inputStream;
}
// A string is empty in our terms, if it is null, empty or a dash.
private static boolean isEmpty(String in) {
return in == null || "-".equals(in) || "".equals(in);
}
// The last octect of the IP address is removed to anonymize the user.
private static String getIP(String remoteAddress) {
if (isEmpty(remoteAddress)) {
return "";
}
// Capture the first three octects of the IP address and replace the forth
// with 0, e.g. 124.455.3.123 becomes 124.455.3.0
String regex = "^([^.]+\\.[^.]+\\.[^.]+\\.).*";
Pattern getFirstBitOfIPAddress = Pattern.compile(regex);
Matcher m = getFirstBitOfIPAddress.matcher(remoteAddress);
if (m.matches()) {
return m.group(1) + "0";
} else {
return "";
}
}
// Generate a visitor id for this hit.
// If there is a visitor id in the cookie, use that, otherwise
// use the guid if we have one, otherwise use a random number.
private static String getVisitorId(
String guid, String account, String userAgent, Cookie cookie)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
// If there is a value in the cookie, don't change it.
if (cookie != null && cookie.getValue() != null) {
return cookie.getValue();
}
String message;
if (!isEmpty(guid)) {
// Create the visitor id using the guid.
message = guid + account;
} else {
// otherwise this is a new user, create a new random id.
message = userAgent + getRandomNumber() + UUID.randomUUID().toString();
}
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(message.getBytes("UTF-8"), 0, message.length());
byte[] sum = m.digest();
BigInteger messageAsNumber = new BigInteger(1, sum);
String md5String = messageAsNumber.toString(16);
// Pad to make sure id is 32 characters long.
while (md5String.length() < 32) {
md5String = "0" + md5String;
}
return "0x" + md5String.substring(0, 16);
}
// Get a random number string.
private static String getRandomNumber() {
return Integer.toString((int) (Math.random() * 0x7fffffff));
}
// Make a tracking request to Google Analytics from this server.
// Copies the headers from the original request to the new one.
// If request containg utmdebug parameter, exceptions encountered
// communicating with Google Analytics are thown.
private void sendRequestToGoogleAnalytics(
String utmUrl, HttpServletRequest request) throws Exception {
try {
URL url = new URL(utmUrl);
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
connection.addRequestProperty("User-Agent",
request.getHeader("User-Agent"));
connection.addRequestProperty("Accepts-Language",
request.getHeader("Accepts-Language"));
connection.getContent();
} catch (Exception e) {
if (request.getParameter("utmdebug") != null) {
throw new Exception(e);
}
}
}
// Track a page view, updates all the cookies and campaign tracker,
// makes a server side request to Google Analytics and writes the transparent
// gif byte data to the response.
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String domainName = request.getServerName();
if (isEmpty(domainName)) {
domainName = "";
}
// Get the referrer from the utmr parameter, this is the referrer to the
// page that contains the tracking pixel, not the referrer for tracking
// pixel.
String documentReferer = request.getParameter("utmr");
if (isEmpty(documentReferer)) {
documentReferer = "-";
} else {
documentReferer = URLDecoder.decode(documentReferer, "UTF-8");
}
String documentPath = request.getParameter("utmp");
if (isEmpty(documentPath)) {
documentPath = "";
} else {
documentPath = URLDecoder.decode(documentPath, "UTF-8");
}
String account = request.getParameter("utmac");
String userAgent = request.getHeader("User-Agent");
if (isEmpty(userAgent)) {
userAgent = "";
}
// Try and get visitor cookie from the request.
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
if (cookies != null) {
for(int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(COOKIE_NAME)) {
cookie = cookies[i];
}
}
}
String visitorId = getVisitorId(
request.getHeader("X-DCMGUID"), account, userAgent, cookie);
// Always try and add the cookie to the response.
Cookie newCookie = new Cookie(COOKIE_NAME, visitorId);
newCookie.setMaxAge(COOKIE_USER_PERSISTENCE);
newCookie.setPath(COOKIE_PATH);
response.addCookie(newCookie);
// Construct the gif hit url.
String utmUrl = "utmwv=" + version +
"&utmn=" + getRandomNumber() +
"&utmhn=" + domainName +
"&utmr=" + documentReferer +
"&utmp=" + documentPath +
"&utmac=" + account +
"&utmcc=__utma%3D999.999.999.999.999.1%3B" +
"&utmvid=" + visitorId +
"&utmip=" + getIP(request.getRemoteAddr());
// event tracking
String type = request.getParameter("utmt");
String event = request.getParameter("utme");
if (!isEmpty(type) && !isEmpty(event)) {
utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8");
utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8");
}
URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null);
- sendRequestToGoogleAnalytics(utfGifLocationUri.toASCIIString(), request);
+ sendRequestToGoogleAnalytics(utfGifLocationUri.toString(), request);
// If the debug parameter is on, add a header to the response that contains
// the url that was used to contact Google Analytics.
if (request.getParameter("utmdebug") != null) {
- response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toASCIIString());
+ response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toString());
}
// write 1x1 pixel tracking gif to output stream
final PipedInputStream pipedInputStream = new PipedInputStream();
final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream);
response.addHeader(
"Cache-Control",
"private, no-cache, no-cache=Set-Cookie, proxy-revalidate");
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT");
pipedOutputStream.write(GIF_DATA);
pipedOutputStream.flush();
pipedOutputStream.close();
// the input stream will get populated by the piped output stream
inputStream = pipedInputStream;
return "pixel";
}
}
| false | true | public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String domainName = request.getServerName();
if (isEmpty(domainName)) {
domainName = "";
}
// Get the referrer from the utmr parameter, this is the referrer to the
// page that contains the tracking pixel, not the referrer for tracking
// pixel.
String documentReferer = request.getParameter("utmr");
if (isEmpty(documentReferer)) {
documentReferer = "-";
} else {
documentReferer = URLDecoder.decode(documentReferer, "UTF-8");
}
String documentPath = request.getParameter("utmp");
if (isEmpty(documentPath)) {
documentPath = "";
} else {
documentPath = URLDecoder.decode(documentPath, "UTF-8");
}
String account = request.getParameter("utmac");
String userAgent = request.getHeader("User-Agent");
if (isEmpty(userAgent)) {
userAgent = "";
}
// Try and get visitor cookie from the request.
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
if (cookies != null) {
for(int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(COOKIE_NAME)) {
cookie = cookies[i];
}
}
}
String visitorId = getVisitorId(
request.getHeader("X-DCMGUID"), account, userAgent, cookie);
// Always try and add the cookie to the response.
Cookie newCookie = new Cookie(COOKIE_NAME, visitorId);
newCookie.setMaxAge(COOKIE_USER_PERSISTENCE);
newCookie.setPath(COOKIE_PATH);
response.addCookie(newCookie);
// Construct the gif hit url.
String utmUrl = "utmwv=" + version +
"&utmn=" + getRandomNumber() +
"&utmhn=" + domainName +
"&utmr=" + documentReferer +
"&utmp=" + documentPath +
"&utmac=" + account +
"&utmcc=__utma%3D999.999.999.999.999.1%3B" +
"&utmvid=" + visitorId +
"&utmip=" + getIP(request.getRemoteAddr());
// event tracking
String type = request.getParameter("utmt");
String event = request.getParameter("utme");
if (!isEmpty(type) && !isEmpty(event)) {
utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8");
utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8");
}
URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null);
sendRequestToGoogleAnalytics(utfGifLocationUri.toASCIIString(), request);
// If the debug parameter is on, add a header to the response that contains
// the url that was used to contact Google Analytics.
if (request.getParameter("utmdebug") != null) {
response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toASCIIString());
}
// write 1x1 pixel tracking gif to output stream
final PipedInputStream pipedInputStream = new PipedInputStream();
final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream);
response.addHeader(
"Cache-Control",
"private, no-cache, no-cache=Set-Cookie, proxy-revalidate");
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT");
pipedOutputStream.write(GIF_DATA);
pipedOutputStream.flush();
pipedOutputStream.close();
// the input stream will get populated by the piped output stream
inputStream = pipedInputStream;
return "pixel";
}
| public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String domainName = request.getServerName();
if (isEmpty(domainName)) {
domainName = "";
}
// Get the referrer from the utmr parameter, this is the referrer to the
// page that contains the tracking pixel, not the referrer for tracking
// pixel.
String documentReferer = request.getParameter("utmr");
if (isEmpty(documentReferer)) {
documentReferer = "-";
} else {
documentReferer = URLDecoder.decode(documentReferer, "UTF-8");
}
String documentPath = request.getParameter("utmp");
if (isEmpty(documentPath)) {
documentPath = "";
} else {
documentPath = URLDecoder.decode(documentPath, "UTF-8");
}
String account = request.getParameter("utmac");
String userAgent = request.getHeader("User-Agent");
if (isEmpty(userAgent)) {
userAgent = "";
}
// Try and get visitor cookie from the request.
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
if (cookies != null) {
for(int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(COOKIE_NAME)) {
cookie = cookies[i];
}
}
}
String visitorId = getVisitorId(
request.getHeader("X-DCMGUID"), account, userAgent, cookie);
// Always try and add the cookie to the response.
Cookie newCookie = new Cookie(COOKIE_NAME, visitorId);
newCookie.setMaxAge(COOKIE_USER_PERSISTENCE);
newCookie.setPath(COOKIE_PATH);
response.addCookie(newCookie);
// Construct the gif hit url.
String utmUrl = "utmwv=" + version +
"&utmn=" + getRandomNumber() +
"&utmhn=" + domainName +
"&utmr=" + documentReferer +
"&utmp=" + documentPath +
"&utmac=" + account +
"&utmcc=__utma%3D999.999.999.999.999.1%3B" +
"&utmvid=" + visitorId +
"&utmip=" + getIP(request.getRemoteAddr());
// event tracking
String type = request.getParameter("utmt");
String event = request.getParameter("utme");
if (!isEmpty(type) && !isEmpty(event)) {
utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8");
utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8");
}
URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null);
sendRequestToGoogleAnalytics(utfGifLocationUri.toString(), request);
// If the debug parameter is on, add a header to the response that contains
// the url that was used to contact Google Analytics.
if (request.getParameter("utmdebug") != null) {
response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toString());
}
// write 1x1 pixel tracking gif to output stream
final PipedInputStream pipedInputStream = new PipedInputStream();
final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream);
response.addHeader(
"Cache-Control",
"private, no-cache, no-cache=Set-Cookie, proxy-revalidate");
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT");
pipedOutputStream.write(GIF_DATA);
pipedOutputStream.flush();
pipedOutputStream.close();
// the input stream will get populated by the piped output stream
inputStream = pipedInputStream;
return "pixel";
}
|
diff --git a/cdi_example/src/main/java/eu/droidit/example/controller/SampleController.java b/cdi_example/src/main/java/eu/droidit/example/controller/SampleController.java
index 682c2f1..6f7116b 100644
--- a/cdi_example/src/main/java/eu/droidit/example/controller/SampleController.java
+++ b/cdi_example/src/main/java/eu/droidit/example/controller/SampleController.java
@@ -1,62 +1,70 @@
package eu.droidit.example.controller;
+import com.sun.jersey.api.view.Viewable;
import eu.droidit.example.repository.SampleRepository;
+import eu.droidit.example.repository.SampleRepositoryImpl;
import eu.droidit.example.utils.Forwarder;
+import javax.ejb.Stateless;
import javax.enterprise.inject.Any;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
+import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
import static eu.droidit.example.utils.Forwarder.forward;
/**
* Created with IntelliJ IDEA.
* User: geroen
* Date: 6/11/12
* Time: 19:59
* To change this template use File | Settings | File Templates.
*/
+@Stateless
@Path("/")
public class SampleController {
@Inject
- @Any
private SampleRepository repository;
@GET
- @Path("/")
- public void get(@Context HttpServletRequest request, @Context HttpServletResponse response) {
- forward(request, response).to("index.jsp");
+ public Viewable get(@Context HttpServletRequest request, @Context HttpServletResponse response) throws URISyntaxException {
+ return new Viewable("/index", this);
}
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
public Response post(String message) {
repository.add(message);
return Response.ok().entity("Your message has been posted!").build();
}
- public Response put(String message) {
+ @PUT
+ @Path("{message}")
+ public Response put(@PathParam("message") String message) {
repository.add(message);
return Response.ok().entity("Your message has been put!").build();
}
- public Response delete(int id) {
+ @DELETE
+ @Path("{id}")
+ public Response delete(@PathParam("id") int id) {
if (repository.deleteById(id)) return Response.ok().entity("Your message has been deleted!").build();
return Response.notModified().entity("Your message could not be found!").build();
}
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public Response getMap() {
return Response.ok().entity(repository.getMap()).build();
}
}
| false | false | null | null |
diff --git a/src/com/ichi2/anki/DeckPicker.java b/src/com/ichi2/anki/DeckPicker.java
index bda63cc3..b8c95b73 100644
--- a/src/com/ichi2/anki/DeckPicker.java
+++ b/src/com/ichi2/anki/DeckPicker.java
@@ -1,2823 +1,2821 @@
/****************************************************************************************
* Copyright (c) 2009 Andrew Dubya <[email protected]> *
* Copyright (c) 2009 Nicolas Raoul <[email protected]> *
* Copyright (c) 2009 Edu Zamora <[email protected]> *
* Copyright (c) 2009 Daniel Sv��rd <[email protected]> *
* Copyright (c) 2010 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.database.SQLException;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.ichi2.anim.ActivityTransitionAnimation;
import com.ichi2.anki.receiver.SdCardReceiver;
import com.ichi2.async.Connection;
import com.ichi2.async.Connection.OldAnkiDeckFilter;
import com.ichi2.async.Connection.Payload;
import com.ichi2.async.DeckTask;
import com.ichi2.async.DeckTask.TaskData;
import com.ichi2.charts.ChartBuilder;
import com.ichi2.libanki.Collection;
import com.ichi2.libanki.Decks;
import com.ichi2.libanki.Utils;
import com.ichi2.themes.StyledDialog;
import com.ichi2.themes.StyledOpenCollectionDialog;
import com.ichi2.themes.StyledProgressDialog;
import com.ichi2.themes.Themes;
import com.ichi2.widget.WidgetStatus;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
public class DeckPicker extends FragmentActivity {
public static final int CRAM_DECK_FRAGMENT = -1;
/**
* Dialogs
*/
private static final int DIALOG_NO_SDCARD = 0;
private static final int DIALOG_USER_NOT_LOGGED_IN_SYNC = 1;
private static final int DIALOG_USER_NOT_LOGGED_IN_ADD_SHARED_DECK = 2;
private static final int DIALOG_NO_CONNECTION = 3;
private static final int DIALOG_DELETE_DECK = 4;
private static final int DIALOG_SELECT_STATISTICS_TYPE = 5;
private static final int DIALOG_CONTEXT_MENU = 9;
private static final int DIALOG_REPAIR_COLLECTION = 10;
private static final int DIALOG_NO_SPACE_LEFT = 11;
private static final int DIALOG_SYNC_CONFLICT_RESOLUTION = 12;
private static final int DIALOG_CONNECTION_ERROR = 13;
private static final int DIALOG_SYNC_LOG = 15;
private static final int DIALOG_SELECT_HELP = 16;
private static final int DIALOG_BACKUP_NO_SPACE_LEFT = 17;
private static final int DIALOG_OK = 18;
private static final int DIALOG_DB_ERROR = 19;
private static final int DIALOG_ERROR_HANDLING = 20;
private static final int DIALOG_LOAD_FAILED = 21;
private static final int DIALOG_RESTORE_BACKUP = 22;
private static final int DIALOG_SD_CARD_NOT_MOUNTED = 23;
private static final int DIALOG_NEW_COLLECTION = 24;
private static final int DIALOG_FULL_SYNC_FROM_SERVER = 25;
private static final int DIALOG_SYNC_SANITY_ERROR = 26;
private static final int DIALOG_SYNC_UPGRADE_REQUIRED = 27;
private static final int DIALOG_IMPORT = 28;
private static final int DIALOG_IMPORT_LOG = 29;
private static final int DIALOG_IMPORT_HINT = 30;
private static final int DIALOG_IMPORT_SELECT = 31;
private String mDialogMessage;
private int[] mRepairValues;
private boolean mLoadFailed;
private String mImportPath;
private String[] mImportValues;
/**
* Menus
*/
private static final int MENU_ABOUT = 0;
private static final int MENU_CREATE_DECK = 1;
private static final int MENU_ADD_SHARED_DECK = 2;
private static final int MENU_PREFERENCES = 3;
private static final int MENU_MY_ACCOUNT = 4;
private static final int MENU_FEEDBACK = 5;
private static final int MENU_HELP = 6;
private static final int CHECK_DATABASE = 7;
private static final int MENU_SYNC = 8;
private static final int MENU_ADD_NOTE = 9;
public static final int MENU_CREATE_DYNAMIC_DECK = 10;
private static final int MENU_STATISTICS = 12;
private static final int MENU_CARDBROWSER = 13;
private static final int MENU_IMPORT = 14;
/**
* Context Menus
*/
private static final int CONTEXT_MENU_COLLAPSE_DECK = 0;
private static final int CONTEXT_MENU_RENAME_DECK = 1;
private static final int CONTEXT_MENU_DELETE_DECK = 2;
private static final int CONTEXT_MENU_DECK_SUMMARY = 3;
private static final int CONTEXT_MENU_CUSTOM_DICTIONARY = 4;
private static final int CONTEXT_MENU_RESET_LANGUAGE = 5;
public static final String EXTRA_START = "start";
public static final String EXTRA_DECK_ID = "deckId";
public static final int EXTRA_START_NOTHING = 0;
public static final int EXTRA_START_REVIEWER = 1;
public static final int EXTRA_START_DECKPICKER = 2;
public static final int EXTRA_DB_ERROR = 3;
public static final int RESULT_MEDIA_EJECTED = 202;
public static final int RESULT_DB_ERROR = 203;
public static final int RESULT_RESTART = 204;
/**
* Available options performed by other activities
*/
private static final int PREFERENCES_UPDATE = 0;
private static final int DOWNLOAD_SHARED_DECK = 3;
public static final int REPORT_FEEDBACK = 4;
private static final int LOG_IN_FOR_DOWNLOAD = 5;
private static final int LOG_IN_FOR_SYNC = 6;
private static final int STUDYOPTIONS = 7;
private static final int SHOW_INFO_WELCOME = 8;
private static final int SHOW_INFO_NEW_VERSION = 9;
private static final int REPORT_ERROR = 10;
public static final int SHOW_STUDYOPTIONS = 11;
private static final int ADD_NOTE = 12;
private static final int LOG_IN = 13;
private static final int BROWSE_CARDS = 14;
private static final int ADD_SHARED_DECKS = 15;
private static final int LOG_IN_FOR_SHARED_DECK = 16;
private static final int ADD_CRAM_DECK = 17;
private static final int SHOW_INFO_UPGRADE_DECKS = 18;
private static final int REQUEST_REVIEW = 19;
private StyledProgressDialog mProgressDialog;
private StyledOpenCollectionDialog mOpenCollectionDialog;
private StyledOpenCollectionDialog mNotMountedDialog;
private ImageButton mAddButton;
private ImageButton mCardsButton;
private ImageButton mStatsButton;
private ImageButton mSyncButton;
private File[] mBackups;
private SimpleAdapter mDeckListAdapter;
private ArrayList<HashMap<String, String>> mDeckList;
private ListView mDeckListView;
private boolean mDontSaveOnStop = false;
private BroadcastReceiver mUnmountReceiver = null;
private String mPrefDeckPath = null;
private long mLastTimeOpened;
private long mCurrentDid;
private int mSyncMediaUsn = 0;
private EditText mDialogEditText;
int mStatisticType;
public boolean mFragmented;
private boolean mInvalidateMenu;
boolean mCompletionBarRestrictToActive = false; // set this to true in order to calculate completion bar only for
// active cards
private int[] mDictValues;
private int mContextMenuPosition;
/** Swipe Detection */
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
private boolean mSwipeEnabled;
// ----------------------------------------------------------------------------
// LISTENERS
// ----------------------------------------------------------------------------
private AdapterView.OnItemClickListener mDeckSelHandler = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int p, long id) {
handleDeckSelection(p);
}
};
private DialogInterface.OnClickListener mContextMenuListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
Resources res = getResources();
@SuppressWarnings("unchecked")
HashMap<String, String> data = (HashMap<String, String>) mDeckListAdapter.getItem(mContextMenuPosition);
switch (item) {
case CONTEXT_MENU_COLLAPSE_DECK:
try {
JSONObject deck = AnkiDroidApp.getCol().getDecks().get(mCurrentDid);
if (AnkiDroidApp.getCol().getDecks().children(mCurrentDid).size() > 0) {
deck.put("collapsed", !deck.getBoolean("collapsed"));
AnkiDroidApp.getCol().getDecks().save(deck);
loadCounts();
}
} catch (JSONException e1) {
// do nothing
}
return;
case CONTEXT_MENU_DELETE_DECK:
showDialog(DIALOG_DELETE_DECK);
return;
case CONTEXT_MENU_RESET_LANGUAGE:
// resetDeckLanguages(data.get("filepath"));
return;
case CONTEXT_MENU_CUSTOM_DICTIONARY:
// String[] dicts = res.getStringArray(R.array.dictionary_labels);
// String[] vals = res.getStringArray(R.array.dictionary_values);
// int currentSet = MetaDB.getLookupDictionary(DeckPicker.this, data.get("filepath"));
//
// mCurrentDeckPath = data.get("filepath");
// String[] labels = new String[dicts.length + 1];
// mDictValues = new int[dicts.length + 1];
// int currentChoice = 0;
// labels[0] = res.getString(R.string.deckpicker_select_dictionary_default);
// mDictValues[0] = -1;
// for (int i = 1; i < labels.length; i++) {
// labels[i] = dicts[i-1];
// mDictValues[i] = Integer.parseInt(vals[i-1]);
// if (currentSet == mDictValues[i]) {
// currentChoice = i;
// }
// }
// StyledDialog.Builder builder = new StyledDialog.Builder(DeckPicker.this);
// builder.setTitle(res.getString(R.string.deckpicker_select_dictionary_title));
// builder.setSingleChoiceItems(labels, currentChoice, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int item) {
// MetaDB.storeLookupDictionary(DeckPicker.this, mCurrentDeckPath, mDictValues[item]);
// }
// });
// StyledDialog alert = builder.create();
// alert.show();
return;
case CONTEXT_MENU_RENAME_DECK:
StyledDialog.Builder builder2 = new StyledDialog.Builder(DeckPicker.this);
builder2.setTitle(res.getString(R.string.contextmenu_deckpicker_rename_deck));
mDialogEditText = (EditText) new EditText(DeckPicker.this);
mDialogEditText.setSingleLine();
mDialogEditText.setText(AnkiDroidApp.getCol().getDecks().name(mCurrentDid));
// mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter });
builder2.setView(mDialogEditText, false, false);
builder2.setPositiveButton(res.getString(R.string.rename), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newName = mDialogEditText.getText().toString().replaceAll("['\"]", "");
Collection col = AnkiDroidApp.getCol();
if (col != null) {
if (col.getDecks().rename(col.getDecks().get(mCurrentDid), newName)) {
for (HashMap<String, String> d : mDeckList) {
if (d.get("did").equals(Long.toString(mCurrentDid))) {
d.put("name", newName);
}
}
mDeckListAdapter.notifyDataSetChanged();
loadCounts();
} else {
try {
Themes.showThemedToast(
DeckPicker.this,
getResources().getString(R.string.rename_error,
col.getDecks().get(mCurrentDid).get("name")), false);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
}
});
builder2.setNegativeButton(res.getString(R.string.cancel), null);
builder2.create().show();
return;
case CONTEXT_MENU_DECK_SUMMARY:
// mStatisticType = 0;
// DeckTask.launchDeckTask(DeckTask.TASK_TYPE_LOAD_STATISTICS, mLoadStatisticsHandler, new
// DeckTask.TaskData(DeckPicker.this, new String[]{data.get("filepath")}, mStatisticType, 0));
return;
}
}
};
private Connection.TaskListener mSyncListener = new Connection.TaskListener() {
String currentMessage;
long countUp;
long countDown;
@Override
public void onDisconnected() {
showDialog(DIALOG_NO_CONNECTION);
}
@Override
public void onPreExecute() {
mDontSaveOnStop = true;
countUp = 0;
countDown = 0;
if (mProgressDialog == null || !mProgressDialog.isShowing()) {
mProgressDialog = StyledProgressDialog
.show(DeckPicker.this, getResources().getString(R.string.sync_title),
getResources().getString(R.string.sync_prepare_syncing) + "\n"
+ getResources().getString(R.string.sync_up_down_size, countUp, countDown),
true, false);
}
}
@Override
public void onProgressUpdate(Object... values) {
Resources res = getResources();
if (values[0] instanceof Boolean) {
// This is the part Download missing media of syncing
int total = ((Integer) values[1]).intValue();
int done = ((Integer) values[2]).intValue();
values[0] = ((String) values[3]);
values[1] = res.getString(R.string.sync_downloading_media, done, total);
} else if (values[0] instanceof Integer) {
int id = (Integer) values[0];
if (id != 0) {
currentMessage = res.getString(id);
}
if (values.length >= 3) {
countUp = (Long) values[1];
countDown = (Long) values[2];
}
}
if (mProgressDialog != null && mProgressDialog.isShowing()) {
// mProgressDialog.setTitle((String) values[0]);
mProgressDialog.setMessage(currentMessage + "\n"
+ res.getString(R.string.sync_up_down_size, countUp / 1024, countDown / 1024));
}
}
@Override
public void onPostExecute(Payload data) {
Log.i(AnkiDroidApp.TAG, "onPostExecute");
Resources res = DeckPicker.this.getResources();
mDontSaveOnStop = false;
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (!data.success) {
Object[] result = (Object[]) data.result;
if (result[0] instanceof String) {
String resultType = (String) result[0];
if (resultType.equals("badAuth")) {
// delete old auth information
SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
Editor editor = preferences.edit();
editor.putString("username", "");
editor.putString("hkey", "");
editor.commit();
// then show
showDialog(DIALOG_USER_NOT_LOGGED_IN_SYNC);
} else if (resultType.equals("noChanges")) {
mDialogMessage = res.getString(R.string.sync_no_changes_message);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("clockOff")) {
long diff = (Long) result[1];
if (diff >= 86400) {
// The difference if more than a day
mDialogMessage = res.getString(R.string.sync_log_clocks_unsynchronized, diff,
res.getString(R.string.sync_log_clocks_unsynchronized_date));
} else if (Math.abs((diff % 3600.0) - 1800.0) >= 1500.0) {
// The difference would be within limit if we adjusted the time by few hours
// It doesn't work for all timezones, but it covers most and it's a guess anyway
mDialogMessage = res.getString(R.string.sync_log_clocks_unsynchronized, diff,
res.getString(R.string.sync_log_clocks_unsynchronized_tz));
} else {
mDialogMessage = res.getString(R.string.sync_log_clocks_unsynchronized, diff, "");
}
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("fullSync")) {
if (data.data != null && data.data.length >= 1 && data.data[0] instanceof Integer) {
mSyncMediaUsn = (Integer) data.data[0];
}
showDialog(DIALOG_SYNC_CONFLICT_RESOLUTION);
} else if (resultType.equals("dbError")) {
mDialogMessage = res.getString(R.string.sync_corrupt_database, R.string.repair_deck);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("overwriteError")) {
mDialogMessage = res.getString(R.string.sync_overwrite_error);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("remoteDbError")) {
mDialogMessage = res.getString(R.string.sync_remote_db_error);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("sdAccessError")) {
mDialogMessage = res.getString(R.string.sync_write_access_error);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("finishError")) {
mDialogMessage = res.getString(R.string.sync_log_finish_error);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("IOException")) {
handleDbError();
} else if (resultType.equals("genericError")) {
mDialogMessage = res.getString(R.string.sync_generic_error);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("OutOfMemoryError")) {
mDialogMessage = res.getString(R.string.error_insufficient_memory);
showDialog(DIALOG_SYNC_LOG);
} else if (resultType.equals("upgradeRequired")) {
showDialog(DIALOG_SYNC_UPGRADE_REQUIRED);
} else if (resultType.equals("sanityCheckError")) {
mDialogMessage = res.getString(R.string.sync_log_error_fix, result[1] != null ? (" (" + (String) result[1] + ")") : "");
showDialog(DIALOG_SYNC_SANITY_ERROR);
} else {
if (result.length > 1 && result[1] instanceof Integer) {
int type = (Integer) result[1];
switch (type) {
case 503:
mDialogMessage = res.getString(R.string.sync_too_busy);
break;
default:
mDialogMessage = res.getString(R.string.sync_log_error_specific,
Integer.toString(type), (String) result[2]);
break;
}
} else if (result[0] instanceof String) {
mDialogMessage = res.getString(R.string.sync_log_error_specific,
-1, (String) result[0]);
} else {
mDialogMessage = res.getString(R.string.sync_generic_error);
}
showDialog(DIALOG_SYNC_LOG);
}
}
} else {
updateDecksList((TreeSet<Object[]>) data.result, (Integer) data.data[2], (Integer) data.data[3]);
if (data.data[4] != null) {
mDialogMessage = (String) data.data[4];
} else if (data.data.length > 0 && data.data[0] instanceof String && ((String) data.data[0]).length() > 0) {
String dataString = (String) data.data[0];
if (dataString.equals("upload")) {
mDialogMessage = res.getString(R.string.sync_log_uploading_message);
} else if (dataString.equals("download")) {
mDialogMessage = res.getString(R.string.sync_log_downloading_message);
// set downloaded collection as current one
} else {
mDialogMessage = res.getString(R.string.sync_database_success);
}
} else {
mDialogMessage = res.getString(R.string.sync_database_success);
}
showDialog(DIALOG_SYNC_LOG);
// close opening dialog in case it's open
if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
mOpenCollectionDialog.dismiss();
}
// update StudyOptions too if open
if (mFragmented) {
StudyOptionsFragment frag = getFragment();
if (frag != null) {
frag.resetAndUpdateValuesFromDeck();
}
}
}
}
};
DeckTask.TaskListener mOpenCollectionHandler = new DeckTask.TaskListener() {
@Override
public void onPostExecute(DeckTask.TaskData result) {
Collection col = result.getCollection();
Object[] res = result.getObjArray();
if (col == null || res == null) {
AnkiDatabaseManager.closeDatabase(AnkiDroidApp.getCollectionPath());
showDialog(DIALOG_LOAD_FAILED);
return;
}
updateDecksList((TreeSet<Object[]>) res[0], (Integer) res[1], (Integer) res[2]);
// select last loaded deck if any
if (mFragmented) {
long did = col.getDecks().selected();
for (int i = 0; i < mDeckList.size(); i++) {
if (Long.parseLong(mDeckList.get(i).get("did")) == did) {
final int lastPosition = i;
mDeckListView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mDeckListView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
mDeckListView.performItemClick(null, lastPosition, 0);
}
});
break;
}
}
}
if (AnkiDroidApp.colIsOpen() && mImportPath != null) {
showDialog(DIALOG_IMPORT);
}
if (mOpenCollectionDialog.isShowing()) {
try {
mOpenCollectionDialog.dismiss();
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "onPostExecute - Dialog dismiss Exception = " + e.getMessage());
}
}
}
@Override
public void onPreExecute() {
if (mOpenCollectionDialog == null || !mOpenCollectionDialog.isShowing()) {
mOpenCollectionDialog = StyledOpenCollectionDialog.show(DeckPicker.this, getResources().getString(R.string.open_collection), new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
// TODO: close dbs?
DeckTask.cancelTask();
finishWithAnimation();
}
});
}
if (mNotMountedDialog != null && mNotMountedDialog.isShowing()) {
try {
mNotMountedDialog.dismiss();
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "onPostExecute - Dialog dismiss Exception = " + e.getMessage());
}
}
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
String message = values[0].getString();
if (message != null) {
mOpenCollectionDialog.setMessage(message);
}
}
};
DeckTask.TaskListener mLoadCountsHandler = new DeckTask.TaskListener() {
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (result == null) {
return;
}
Object[] res = result.getObjArray();
updateDecksList((TreeSet<Object[]>) res[0], (Integer) res[1], (Integer) res[2]);
if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
mOpenCollectionDialog.dismiss();
}
}
@Override
public void onPreExecute() {
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
}
};
DeckTask.TaskListener mCloseCollectionHandler = new DeckTask.TaskListener() {
@Override
public void onPostExecute(DeckTask.TaskData result) {
}
@Override
public void onPreExecute() {
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
}
};
DeckTask.TaskListener mLoadStatisticsHandler = new DeckTask.TaskListener() {
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (mProgressDialog.isShowing()) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "onPostExecute - Dialog dismiss Exception = " + e.getMessage());
}
}
if (result.getBoolean()) {
// if (mStatisticType == Statistics.TYPE_DECK_SUMMARY) {
// Statistics.showDeckSummary(DeckPicker.this);
// } else {
Intent intent = new Intent(DeckPicker.this, com.ichi2.charts.ChartBuilder.class);
startActivity(intent);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.DOWN);
}
// }
} else {
// TODO: db error handling
}
}
@Override
public void onPreExecute() {
mProgressDialog = StyledProgressDialog.show(DeckPicker.this, "",
getResources().getString(R.string.calculating_statistics), true);
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
}
};
DeckTask.TaskListener mRepairDeckHandler = new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
mProgressDialog = StyledProgressDialog.show(DeckPicker.this, "",
getResources().getString(R.string.backup_repair_deck_progress), true);
}
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (result.getBoolean()) {
loadCollection();
} else {
Themes.showThemedToast(DeckPicker.this, getResources().getString(R.string.deck_repair_error), true);
showDialog(DIALOG_ERROR_HANDLING);
}
}
@Override
public void onProgressUpdate(TaskData... values) {
}
};
DeckTask.TaskListener mRestoreDeckHandler = new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
mProgressDialog = StyledProgressDialog.show(DeckPicker.this, "", getResources().getString(R.string.backup_restore_deck), true);
}
@Override
public void onPostExecute(DeckTask.TaskData result) {
switch (result.getInt()) {
case BackupManager.RETURN_DECK_RESTORED:
loadCollection();
break;
case BackupManager.RETURN_ERROR:
Themes.showThemedToast(DeckPicker.this, getResources().getString(R.string.backup_restore_error), true);
showDialog(DIALOG_ERROR_HANDLING);
break;
case BackupManager.RETURN_NOT_ENOUGH_SPACE:
showDialog(DIALOG_NO_SPACE_LEFT);
break;
}
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
@Override
public void onProgressUpdate(TaskData... values) {
}
};
// ----------------------------------------------------------------------------
// ANDROID METHODS
// ----------------------------------------------------------------------------
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) throws SQLException {
Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate");
Intent intent = getIntent();
if (!isTaskRoot()) {
Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate: Detected multiple instance of this activity, closing it and return to root activity");
Intent reloadIntent = new Intent(DeckPicker.this, DeckPicker.class);
reloadIntent.setAction(Intent.ACTION_MAIN);
if (intent != null && intent.getExtras() != null) {
reloadIntent.putExtras(intent.getExtras());
}
if (intent != null && intent.getData() != null) {
reloadIntent.setData(intent.getData());
}
reloadIntent.addCategory(Intent.CATEGORY_LAUNCHER);
reloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
startActivityIfNeeded(reloadIntent, 0);
}
if (intent.getData() != null) {
mImportPath = getIntent().getData().getEncodedPath();
}
// need to start this here in order to avoid showing deckpicker before splashscreen
if (AnkiDroidApp.colIsOpen()) {
setTitle(getResources().getString(R.string.app_name));
} else {
setTitle("");
mOpenCollectionHandler.onPreExecute();
}
Themes.applyTheme(this);
super.onCreate(savedInstanceState);
// mStartedByBigWidget = intent.getIntExtra(EXTRA_START, EXTRA_START_NOTHING);
SharedPreferences preferences = restorePreferences();
// activate broadcast messages if first start of a day
if (mLastTimeOpened < UIUtils.getDayStart()) {
preferences.edit().putBoolean("showBroadcastMessageToday", true).commit();
}
preferences.edit().putLong("lastTimeOpened", System.currentTimeMillis()).commit();
// if (intent != null && intent.hasExtra(EXTRA_DECK_ID)) {
// openStudyOptions(intent.getLongExtra(EXTRA_DECK_ID, 1));
// }
BroadcastMessages.checkForNewMessages(this);
View mainView = getLayoutInflater().inflate(R.layout.deck_picker, null);
setContentView(mainView);
// check, if tablet layout
View studyoptionsFrame = findViewById(R.id.studyoptions_fragment);
mFragmented = studyoptionsFrame != null && studyoptionsFrame.getVisibility() == View.VISIBLE;
Themes.setContentStyle(mFragmented ? mainView : mainView.findViewById(R.id.deckpicker_view), Themes.CALLER_DECKPICKER);
registerExternalStorageListener();
if (!mFragmented) {
mAddButton = (ImageButton) findViewById(R.id.deckpicker_add);
mAddButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
addNote();
}
});
mCardsButton = (ImageButton) findViewById(R.id.deckpicker_card_browser);
mCardsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openCardBrowser();
}
});
mStatsButton = (ImageButton) findViewById(R.id.statistics_all_button);
mStatsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_SELECT_STATISTICS_TYPE);
}
});
mSyncButton = (ImageButton) findViewById(R.id.sync_all_button);
mSyncButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sync();
}
});
}
mInvalidateMenu = false;
mDeckList = new ArrayList<HashMap<String, String>>();
mDeckListView = (ListView) findViewById(R.id.files);
mDeckListAdapter = new SimpleAdapter(this, mDeckList, R.layout.deck_item, new String[] { "name", "new", "lrn",
"rev", // "complMat", "complAll",
"sep", "dyn" }, new int[] { R.id.DeckPickerName, R.id.deckpicker_new, R.id.deckpicker_lrn,
R.id.deckpicker_rev, // R.id.deckpicker_bar_mat, R.id.deckpicker_bar_all,
R.id.deckpicker_deck, R.id.DeckPickerName });
mDeckListAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object data, String text) {
if (view.getId() == R.id.deckpicker_deck) {
if (text.equals("top")) {
view.setBackgroundResource(R.drawable.white_deckpicker_top);
return true;
} else if (text.equals("bot")) {
view.setBackgroundResource(R.drawable.white_deckpicker_bottom);
return true;
} else if (text.equals("ful")) {
view.setBackgroundResource(R.drawable.white_deckpicker_full);
return true;
} else if (text.equals("cen")) {
view.setBackgroundResource(R.drawable.white_deckpicker_center);
return true;
}
} else if (view.getId() == R.id.DeckPickerName) {
if (text.equals("d0")) {
((TextView) view).setTextColor(getResources().getColor(R.color.non_dyn_deck));
return true;
} else if (text.equals("d1")) {
((TextView) view).setTextColor(getResources().getColor(R.color.dyn_deck));
return true;
}
}
// } else if (view.getId() == R.id.deckpicker_bar_mat || view.getId() == R.id.deckpicker_bar_all) {
// if (text.length() > 0 && !text.equals("-1.0")) {
// View parent = (View)view.getParent().getParent();
// if (text.equals("-2")) {
// parent.setVisibility(View.GONE);
// } else {
// Utils.updateProgressBars(view, (int) UIUtils.getDensityAdjustedValue(DeckPicker.this, 3.4f),
// (int) (Double.parseDouble(text) * ((View)view.getParent().getParent().getParent()).getHeight()));
// if (parent.getVisibility() == View.INVISIBLE) {
// parent.setVisibility(View.VISIBLE);
// parent.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
// }
// }
// }
// return true;
// } else if (view.getVisibility() == View.INVISIBLE) {
// if (!text.equals("-1")) {
// view.setVisibility(View.VISIBLE);
// view.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
// return false;
// }
// } else if (text.equals("-1")){
// view.setVisibility(View.INVISIBLE);
// return false;
return false;
}
});
mDeckListView.setOnItemClickListener(mDeckSelHandler);
mDeckListView.setAdapter(mDeckListAdapter);
if (mFragmented) {
mDeckListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
registerForContextMenu(mDeckListView);
showStartupScreensAndDialogs(preferences, 0);
if (mSwipeEnabled) {
gestureDetector = new GestureDetector(new MyGestureDetector());
mDeckListView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
});
}
}
@Override
protected void onResume() {
super.onResume();
if (AnkiDroidApp.getCol() != null) {
if (Utils.now() > AnkiDroidApp.getCol().getSched().getDayCutoff() && AnkiDroidApp.isSdCardMounted()) {
loadCounts();
}
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putLong("mCurrentDid", mCurrentDid);
// savedInstanceState.putSerializable("mDeckList", mDeckList);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentDid = savedInstanceState.getLong("mCurrentDid");
// mDeckList = (ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable("mDeckList");
}
private void loadCollection() {
if (!AnkiDroidApp.isSdCardMounted()) {
showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
return;
}
String path = AnkiDroidApp.getCollectionPath();
Collection col = AnkiDroidApp.getCol();
if (col == null || !col.getPath().equals(path) || mDeckListView == null || mDeckListView.getChildCount() == 0) {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_OPEN_COLLECTION, mOpenCollectionHandler, new DeckTask.TaskData(path));
} else {
loadCounts();
}
}
public void loadCounts() {
if (AnkiDroidApp.colIsOpen()) {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_LOAD_DECK_COUNTS, mLoadCountsHandler, new TaskData(AnkiDroidApp.getCol()));
}
}
private void addNote() {
Intent intent = new Intent(DeckPicker.this, CardEditor.class);
intent.putExtra(CardEditor.EXTRA_CALLER, CardEditor.CALLER_DECKPICKER);
startActivityForResult(intent, ADD_NOTE);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.LEFT);
}
}
private void openCardBrowser() {
Intent cardBrowser = new Intent(DeckPicker.this, CardBrowser.class);
cardBrowser.putExtra("fromDeckpicker", true);
startActivityForResult(cardBrowser, BROWSE_CARDS);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.LEFT);
}
}
private boolean hasErrorFiles() {
for (String file : this.fileList()) {
if (file.endsWith(".stacktrace")) {
return true;
}
}
return false;
}
private boolean upgradeNeeded() {
if (!AnkiDroidApp.isSdCardMounted()) {
showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
return false;
}
File dir = new File(AnkiDroidApp.getCurrentAnkiDroidDirectory());
if (!dir.isDirectory()) {
dir.mkdirs();
}
if ((new File(AnkiDroidApp.getCollectionPath())).exists()) {
// collection file exists
return false;
}
// else check for old files to upgrade
if (dir.listFiles(new OldAnkiDeckFilter()).length > 0) {
return true;
}
return false;
}
private SharedPreferences restorePreferences() {
SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
mPrefDeckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory();
mLastTimeOpened = preferences.getLong("lastTimeOpened", 0);
mSwipeEnabled = AnkiDroidApp.initiateGestures(this, preferences);
// mInvertedColors = preferences.getBoolean("invertedColors", false);
// mSwap = preferences.getBoolean("swapqa", false);
// mLocale = preferences.getString("language", "");
// setLanguage(mLocale);
return preferences;
}
private void showStartupScreensAndDialogs(SharedPreferences preferences, int skip) {
if (skip < 1 && preferences.getLong("lastTimeOpened", 0) == 0) {
Intent infoIntent = new Intent(this, Info.class);
infoIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_WELCOME);
startActivityForResult(infoIntent, SHOW_INFO_WELCOME);
if (skip != 0 && AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
}
} else if (skip < 2 && !preferences.getString("lastVersion", "").equals(AnkiDroidApp.getPkgVersion())) {
preferences.edit().putBoolean("showBroadcastMessageToday", true).commit();
Intent infoIntent = new Intent(this, Info.class);
infoIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_NEW_VERSION);
startActivityForResult(infoIntent, SHOW_INFO_NEW_VERSION);
if (skip != 0 && AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
}
} else if (skip < 3 && upgradeNeeded()) {
Intent upgradeIntent = new Intent(this, Info.class);
upgradeIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_UPGRADE_DECKS);
startActivityForResult(upgradeIntent, SHOW_INFO_UPGRADE_DECKS);
if (skip != 0 && AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
}
} else if (skip < 4 && hasErrorFiles()) {
Intent i = new Intent(this, Feedback.class);
startActivityForResult(i, REPORT_ERROR);
if (skip != 0 && AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
}
} else if (!AnkiDroidApp.isSdCardMounted()) {
showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
} else if (!BackupManager.enoughDiscSpace(mPrefDeckPath)) {// && !preferences.getBoolean("dontShowLowMemory",
// false)) {
showDialog(DIALOG_NO_SPACE_LEFT);
} else if (preferences.getBoolean("noSpaceLeft", false)) {
showDialog(DIALOG_BACKUP_NO_SPACE_LEFT);
preferences.edit().putBoolean("noSpaceLeft", false).commit();
} else if (mImportPath != null && AnkiDroidApp.colIsOpen()) {
showDialog(DIALOG_IMPORT);
} else {
loadCollection();
}
}
protected void sendKey(int keycode) {
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keycode));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keycode));
}
@Override
protected void onPause() {
Log.i(AnkiDroidApp.TAG, "DeckPicker - onPause");
super.onPause();
}
@Override
protected void onStop() {
Log.i(AnkiDroidApp.TAG, "DeckPicker - onStop");
super.onStop();
if (!mDontSaveOnStop) {
if (isFinishing()) {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_CLOSE_DECK, mCloseCollectionHandler, new TaskData(AnkiDroidApp.getCol()));
} else {
StudyOptionsFragment frag = getFragment();
if (!(frag != null && !frag.dbSaveNecessary())) {
UIUtils.saveCollectionInBackground();
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
}
Log.i(AnkiDroidApp.TAG, "DeckPicker - onDestroy()");
}
@Override
protected Dialog onCreateDialog(int id) {
StyledDialog dialog;
Resources res = getResources();
StyledDialog.Builder builder = new StyledDialog.Builder(this);
switch (id) {
case DIALOG_OK:
builder.setPositiveButton(R.string.ok, null);
dialog = builder.create();
break;
case DIALOG_NO_SDCARD:
builder.setMessage("The SD card could not be read. Please, turn off USB storage.");
builder.setPositiveButton(R.string.ok, null);
dialog = builder.create();
break;
case DIALOG_SELECT_HELP:
builder.setTitle(res.getString(R.string.help_title));
builder.setItems(
new String[] { res.getString(R.string.help_tutorial), res.getString(R.string.help_online),
res.getString(R.string.help_faq) }, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
if (arg1 == 0) {
createTutorialDeck();
} else {
if (Utils.isIntentAvailable(DeckPicker.this, "android.intent.action.VIEW")) {
Intent intent = new Intent("android.intent.action.VIEW", Uri
.parse(getResources().getString(
arg1 == 0 ? R.string.link_help : R.string.link_faq)));
startActivity(intent);
} else {
startActivity(new Intent(DeckPicker.this, Info.class));
}
}
}
});
dialog = builder.create();
break;
case DIALOG_CONNECTION_ERROR:
builder.setTitle(res.getString(R.string.connection_error_title));
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setMessage(res.getString(R.string.connection_error_message));
builder.setPositiveButton(res.getString(R.string.retry), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sync();
}
});
builder.setNegativeButton(res.getString(R.string.cancel), null);
dialog = builder.create();
break;
case DIALOG_SYNC_CONFLICT_RESOLUTION:
builder.setTitle(res.getString(R.string.sync_conflict_title));
builder.setIcon(android.R.drawable.ic_input_get);
builder.setMessage(res.getString(R.string.sync_conflict_message));
builder.setPositiveButton(res.getString(R.string.sync_conflict_local), mSyncConflictResolutionListener);
builder.setNeutralButton(res.getString(R.string.sync_conflict_remote), mSyncConflictResolutionListener);
builder.setNegativeButton(res.getString(R.string.sync_conflict_cancel), mSyncConflictResolutionListener);
builder.setCancelable(true);
dialog = builder.create();
break;
case DIALOG_LOAD_FAILED:
builder.setMessage(res.getString(R.string.open_collection_failed_message,
BackupManager.BROKEN_DECKS_SUFFIX, res.getString(R.string.repair_deck)));
builder.setTitle(R.string.open_collection_failed_title);
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setPositiveButton(res.getString(R.string.error_handling_options),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
builder.setNegativeButton(res.getString(R.string.close), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishWithAnimation();
}
});
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finishWithAnimation();
}
});
dialog = builder.create();
break;
case DIALOG_DB_ERROR:
builder.setMessage(R.string.answering_error_message);
builder.setTitle(R.string.answering_error_title);
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setPositiveButton(res.getString(R.string.error_handling_options),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
builder.setNeutralButton(res.getString(R.string.answering_error_report),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(DeckPicker.this, Feedback.class);
i.putExtra("request", RESULT_DB_ERROR);
dialog.dismiss();
startActivityForResult(i, REPORT_ERROR);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this,
ActivityTransitionAnimation.RIGHT);
}
}
});
builder.setNegativeButton(res.getString(R.string.close),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!AnkiDroidApp.colIsOpen()) {
finishWithAnimation();
}
}
});
builder.setCancelable(true);
dialog = builder.create();
break;
case DIALOG_ERROR_HANDLING:
builder.setTitle(res.getString(R.string.error_handling_title));
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setSingleChoiceItems(new String[] { "1" }, 0, null);
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (mLoadFailed) {
// dialog has been called because collection could not be opened
showDialog(DIALOG_LOAD_FAILED);
} else {
// dialog has been called because a db error happened
showDialog(DIALOG_DB_ERROR);
}
}
});
builder.setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mLoadFailed) {
// dialog has been called because collection could not be opened
showDialog(DIALOG_LOAD_FAILED);
} else {
// dialog has been called because a db error happened
showDialog(DIALOG_DB_ERROR);
}
}
});
dialog = builder.create();
break;
case DIALOG_USER_NOT_LOGGED_IN_ADD_SHARED_DECK:
builder.setTitle(res.getString(R.string.connection_error_title));
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setMessage(res.getString(R.string.no_user_password_error_message));
builder.setNegativeButton(res.getString(R.string.cancel), null);
builder.setPositiveButton(res.getString(R.string.log_in), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent myAccount = new Intent(DeckPicker.this, MyAccount.class);
myAccount.putExtra("notLoggedIn", true);
startActivityForResult(myAccount, LOG_IN_FOR_SHARED_DECK);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.FADE);
}
}
});
dialog = builder.create();
break;
case DIALOG_USER_NOT_LOGGED_IN_SYNC:
builder.setTitle(res.getString(R.string.connection_error_title));
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setMessage(res.getString(R.string.no_user_password_error_message));
builder.setNegativeButton(res.getString(R.string.cancel), null);
builder.setPositiveButton(res.getString(R.string.log_in), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent myAccount = new Intent(DeckPicker.this, MyAccount.class);
myAccount.putExtra("notLoggedIn", true);
startActivityForResult(myAccount, LOG_IN_FOR_SYNC);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.FADE);
}
}
});
dialog = builder.create();
break;
// case DIALOG_USER_NOT_LOGGED_IN_DOWNLOAD:
// if (id == DIALOG_USER_NOT_LOGGED_IN_SYNC) {
// } else {
// builder.setPositiveButton(res.getString(R.string.log_in),
// new DialogInterface.OnClickListener() {
//
// @Override
// public void onClick(DialogInterface dialog, int which) {
// Intent myAccount = new Intent(DeckPicker.this,
// MyAccount.class);
// myAccount.putExtra("notLoggedIn", true);
// startActivityForResult(myAccount, LOG_IN_FOR_DOWNLOAD);
// if (UIUtils.getApiLevel() > 4) {
// ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.LEFT);
// }
// }
// });
// }
// builder.setNegativeButton(res.getString(R.string.cancel), null);
// dialog = builder.create();
// break;
case DIALOG_NO_CONNECTION:
builder.setTitle(res.getString(R.string.connection_error_title));
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setMessage(res.getString(R.string.connection_needed));
builder.setPositiveButton(res.getString(R.string.ok), null);
dialog = builder.create();
break;
case DIALOG_DELETE_DECK:
if (!AnkiDroidApp.colIsOpen() || mDeckList == null) {
return null;
}
+ // Message is set in onPrepareDialog
builder.setTitle(res.getString(R.string.delete_deck_title));
builder.setIcon(R.drawable.ic_dialog_alert);
- boolean isDyn = AnkiDroidApp.getCol().getDecks().isDyn(mCurrentDid);
- if (isDyn) {
- builder.setMessage(String.format(res.getString(R.string.delete_cram_deck_message), "\'"
- + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
- } else {
- builder.setMessage(String.format(res.getString(R.string.delete_deck_message), "\'"
- + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
- }
builder.setPositiveButton(res.getString(R.string.yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (AnkiDroidApp.getCol().getDecks().selected() == mCurrentDid) {
Fragment frag = (Fragment) getSupportFragmentManager().findFragmentById(
R.id.studyoptions_fragment);
if (frag != null && frag instanceof StudyOptionsFragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(frag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_DELETE_DECK, new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
mProgressDialog = StyledProgressDialog.show(DeckPicker.this, "", getResources()
.getString(R.string.delete_deck), true);
}
@Override
public void onPostExecute(TaskData result) {
if (result == null) {
return;
}
Object[] res = result.getObjArray();
updateDecksList((TreeSet<Object[]>) res[0], (Integer) res[1], (Integer) res[2]);
if (mProgressDialog.isShowing()) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "onPostExecute - Dialog dismiss Exception = "
+ e.getMessage());
}
}
}
@Override
public void onProgressUpdate(TaskData... values) {
}
}, new TaskData(AnkiDroidApp.getCol(), mCurrentDid));
}
});
builder.setNegativeButton(res.getString(R.string.cancel), null);
dialog = builder.create();
break;
case DIALOG_SELECT_STATISTICS_TYPE:
dialog = ChartBuilder.getStatisticsDialog(this, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean muh = mFragmented ? AnkiDroidApp.getSharedPrefs(
AnkiDroidApp.getInstance().getBaseContext()).getBoolean("statsRange", true) : true;
DeckTask.launchDeckTask(
DeckTask.TASK_TYPE_LOAD_STATISTICS,
mLoadStatisticsHandler,
new DeckTask.TaskData(AnkiDroidApp.getCol(), which, mFragmented ? AnkiDroidApp.getSharedPrefs(
AnkiDroidApp.getInstance().getBaseContext()).getBoolean("statsRange", true)
: true));
}
}, mFragmented);
break;
case DIALOG_CONTEXT_MENU:
String[] entries = new String[3];
// entries[CONTEXT_MENU_DECK_SUMMARY] =
// "XXXsum";//res.getStringArray(R.array.statistics_type_labels)[0];
// entries[CONTEXT_MENU_CUSTOM_DICTIONARY] =
// res.getString(R.string.contextmenu_deckpicker_set_custom_dictionary);
// entries[CONTEXT_MENU_RESET_LANGUAGE] =
// res.getString(R.string.contextmenu_deckpicker_reset_language_assignments);
entries[CONTEXT_MENU_COLLAPSE_DECK] = res.getString(R.string.contextmenu_deckpicker_collapse_deck);
entries[CONTEXT_MENU_RENAME_DECK] = res.getString(R.string.contextmenu_deckpicker_rename_deck);
entries[CONTEXT_MENU_DELETE_DECK] = res.getString(R.string.contextmenu_deckpicker_delete_deck);
builder.setTitle("Context Menu");
builder.setIcon(R.drawable.ic_menu_manage);
builder.setItems(entries, mContextMenuListener);
dialog = builder.create();
break;
case DIALOG_REPAIR_COLLECTION:
builder.setTitle(res.getString(R.string.backup_repair_deck));
builder.setMessage(res.getString(R.string.repair_deck_dialog, BackupManager.BROKEN_DECKS_SUFFIX));
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setPositiveButton(res.getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REPAIR_DECK, mRepairDeckHandler,
new DeckTask.TaskData(AnkiDroidApp.getCol(), AnkiDroidApp.getCollectionPath()));
}
});
builder.setNegativeButton(res.getString(R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
dialog = builder.create();
break;
case DIALOG_SYNC_SANITY_ERROR:
builder.setPositiveButton(res.getString(R.string.sync_conflict_local), mSyncConflictResolutionListener);
builder.setNeutralButton(res.getString(R.string.sync_conflict_remote), mSyncConflictResolutionListener);
builder.setNegativeButton(res.getString(R.string.sync_conflict_cancel), mSyncConflictResolutionListener);
builder.setTitle(res.getString(R.string.sync_log_title));
dialog = builder.create();
break;
case DIALOG_SYNC_UPGRADE_REQUIRED:
builder.setMessage(res.getString(R.string.upgrade_required, res.getString(R.string.link_anki)));
builder.setPositiveButton(res.getString(R.string.retry), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sync("download", mSyncMediaUsn);
}
});
builder.setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mLoadFailed) {
// dialog has been called because collection could not be opened
showDialog(DIALOG_LOAD_FAILED);
} else {
// dialog has been called because a db error happened
showDialog(DIALOG_DB_ERROR);
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
if (mLoadFailed) {
// dialog has been called because collection could not be opened
showDialog(DIALOG_LOAD_FAILED);
} else {
// dialog has been called because a db error happened
showDialog(DIALOG_DB_ERROR);
}
}
});
builder.setTitle(res.getString(R.string.sync_log_title));
dialog = builder.create();
break;
case DIALOG_SYNC_LOG:
builder.setTitle(res.getString(R.string.sync_log_title));
builder.setPositiveButton(res.getString(R.string.ok), null);
dialog = builder.create();
break;
case DIALOG_BACKUP_NO_SPACE_LEFT:
builder.setTitle(res.getString(R.string.attention));
builder.setMessage(res.getString(R.string.backup_deck_no_space_left));
builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
loadCollection();
}
});
// builder.setNegativeButton(res.getString(R.string.dont_show_again), new
// DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface arg0, int arg1) {
// PrefSettings.getSharedPrefs(getBaseContext()).edit().putBoolean("dontShowLowMemory", true).commit();
// }
// });
builder.setCancelable(true);
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
loadCollection();
}
});
dialog = builder.create();
break;
case DIALOG_SD_CARD_NOT_MOUNTED:
if (mNotMountedDialog == null || !mNotMountedDialog.isShowing()) {
mNotMountedDialog = StyledOpenCollectionDialog.show(DeckPicker.this, getResources().getString(R.string.sd_card_not_mounted), new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
finishWithAnimation();
}
}, new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(DeckPicker.this, Preferences.class), PREFERENCES_UPDATE);
}
});
}
dialog = null;
break;
case DIALOG_IMPORT:
builder.setTitle(res.getString(R.string.import_title));
builder.setMessage(res.getString(R.string.import_message, mImportPath));
builder.setPositiveButton(res.getString(R.string.import_message_add), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, new DeckTask.TaskListener() {
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (result.getBoolean()) {
Resources res = getResources();
int count = result.getInt();
if (count < 0) {
if (count == -2) {
mDialogMessage = res.getString(R.string.import_log_no_apkg);
} else {
mDialogMessage = res.getString(R.string.import_log_error);
}
showDialog(DIALOG_IMPORT_LOG);
} else {
mDialogMessage = res.getString(R.string.import_log_success, count);
showDialog(DIALOG_IMPORT_LOG);
Object[] info = result.getObjArray();
updateDecksList((TreeSet<Object[]>) info[0], (Integer) info[1], (Integer) info[2]);
}
} else {
handleDbError();
}
}
@Override
public void onPreExecute() {
if (mProgressDialog == null || !mProgressDialog.isShowing()) {
mProgressDialog = StyledProgressDialog
.show(DeckPicker.this, getResources().getString(R.string.import_title),
getResources().getString(R.string.import_importing), true, false);
}
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
}
}, new TaskData(AnkiDroidApp.getCol(), mImportPath));
mImportPath = null;
}
});
builder.setNeutralButton(res.getString(R.string.import_message_replace), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Resources res = getResources();
StyledDialog.Builder builder = new StyledDialog.Builder(DeckPicker.this);
builder.setTitle(res.getString(R.string.import_title));
builder.setMessage(res.getString(R.string.import_message_replace_confirm, mImportPath));
builder.setPositiveButton(res.getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT_REPLACE, new DeckTask.TaskListener() {
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (result.getBoolean()) {
Resources res = getResources();
int code = result.getInt();
if (code == -2) {
mDialogMessage = res.getString(R.string.import_log_no_apkg);
}
Object[] info = result.getObjArray();
updateDecksList((TreeSet<Object[]>) info[0], (Integer) info[1], (Integer) info[2]);
} else {
mDialogMessage = getResources().getString(R.string.import_log_no_apkg);
showDialog(DIALOG_IMPORT_LOG);
}
}
@Override
public void onPreExecute() {
if (mProgressDialog == null || !mProgressDialog.isShowing()) {
mProgressDialog = StyledProgressDialog
.show(DeckPicker.this, getResources().getString(R.string.import_title),
getResources().getString(R.string.import_importing), true, false);
}
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
}
}, new TaskData(AnkiDroidApp.getCol(), mImportPath));
mImportPath = null;
}
});
builder.setNegativeButton(res.getString(R.string.no), null);
builder.show();
}
});
builder.setNegativeButton(res.getString(R.string.cancel), null);
builder.setCancelable(true);
dialog = builder.create();
break;
case DIALOG_IMPORT_SELECT:
builder.setTitle(res.getString(R.string.import_title));
dialog = builder.create();
break;
case DIALOG_IMPORT_HINT:
builder.setTitle(res.getString(R.string.import_title));
builder.setMessage(res.getString(R.string.import_hint, AnkiDroidApp.getCurrentAnkiDroidDirectory()));
builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDialog(DIALOG_IMPORT_SELECT);
}
});
builder.setNegativeButton(res.getString(R.string.cancel), null);
dialog = builder.create();
break;
case DIALOG_IMPORT_LOG:
builder.setIcon(R.drawable.ic_dialog_alert);
builder.setTitle(res.getString(R.string.import_title));
builder.setPositiveButton(res.getString(R.string.ok), null);
dialog = builder.create();
break;
case DIALOG_NO_SPACE_LEFT:
builder.setTitle(res.getString(R.string.attention));
builder.setMessage(res.getString(R.string.sd_space_warning, BackupManager.MIN_FREE_SPACE));
builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishWithAnimation();
}
});
// builder.setNegativeButton(res.getString(R.string.dont_show_again), new
// DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface arg0, int arg1) {
// PrefSettings.getSharedPrefs(getBaseContext()).edit().putBoolean("dontShowLowMemory", true).commit();
// }
// });
builder.setCancelable(true);
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
finishWithAnimation();
}
});
dialog = builder.create();
break;
case DIALOG_RESTORE_BACKUP:
File[] files = BackupManager.getBackups(new File(AnkiDroidApp.getCollectionPath()));
mBackups = new File[files.length];
for (int i = 0; i < files.length; i++) {
mBackups[i] = files[files.length - 1 - i];
}
if (mBackups.length == 0) {
builder.setTitle(getResources().getString(R.string.backup_restore));
builder.setMessage(res.getString(R.string.backup_restore_no_backups));
builder.setPositiveButton(res.getString(R.string.ok), new
Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
builder.setCancelable(true).setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
} else {
String[] dates = new String[mBackups.length];
for (int i = 0; i < mBackups.length; i++) {
dates[i] = mBackups[i].getName().replaceAll(".*-(\\d{4}-\\d{2}-\\d{2})-(\\d{2})-(\\d{2}).anki2", "$1 ($2:$3 h)");
}
builder.setTitle(res.getString(R.string.backup_restore_select_title));
builder.setIcon(android.R.drawable.ic_input_get);
builder.setSingleChoiceItems(dates, dates.length, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_RESTORE_DECK, mRestoreDeckHandler, new DeckTask.TaskData(new Object[]{AnkiDroidApp.getCol(), AnkiDroidApp.getCollectionPath(), mBackups[which].getPath()}));
}
});
builder.setCancelable(true).setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
}
dialog = builder.create();
break;
case DIALOG_NEW_COLLECTION:
builder.setTitle(res.getString(R.string.backup_new_collection));
builder.setMessage(res.getString(R.string.backup_del_collection_question));
builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AnkiDroidApp.closeCollection(false);
String path = AnkiDroidApp.getCollectionPath();
AnkiDatabaseManager.closeDatabase(path);
if (BackupManager.moveDatabaseToBrokenFolder(path, false)) {
loadCollection();
} else {
showDialog(DIALOG_ERROR_HANDLING);
}
}
});
builder.setNegativeButton(res.getString(R.string.no), new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
builder.setCancelable(true);
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
dialog = builder.create();
break;
case DIALOG_FULL_SYNC_FROM_SERVER:
builder.setTitle(res.getString(R.string.backup_full_sync_from_server));
builder.setMessage(res.getString(R.string.backup_full_sync_from_server_question));
builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sync("download", mSyncMediaUsn);
}
});
builder.setNegativeButton(res.getString(R.string.no), new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
builder.setCancelable(true);
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
showDialog(DIALOG_ERROR_HANDLING);
}
});
dialog = builder.create();
break;
default:
dialog = null;
}
if (dialog != null) {
dialog.setOwnerActivity(this);
}
return dialog;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
Resources res = getResources();
StyledDialog ad = (StyledDialog) dialog;
switch (id) {
case DIALOG_DELETE_DECK:
- if (AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
+ if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
return;
}
- mCurrentDid = Long.parseLong(mDeckList.get(mContextMenuPosition).get("did"));
- ad.setMessage(String.format(res.getString(R.string.delete_deck_message),
- "\'" + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
+ boolean isDyn = AnkiDroidApp.getCol().getDecks().isDyn(mCurrentDid);
+ if (isDyn) {
+ ad.setMessage(String.format(res.getString(R.string.delete_cram_deck_message), "\'"
+ + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
+ } else {
+ ad.setMessage(String.format(res.getString(R.string.delete_deck_message), "\'"
+ + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
+ }
break;
case DIALOG_CONTEXT_MENU:
if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
return;
}
mCurrentDid = Long.parseLong(mDeckList.get(mContextMenuPosition).get("did"));
try {
ad.changeListItem(CONTEXT_MENU_COLLAPSE_DECK, getResources().getString(AnkiDroidApp.getCol().getDecks().get(mCurrentDid).getBoolean("collapsed") ? R.string.contextmenu_deckpicker_inflate_deck : R.string.contextmenu_deckpicker_collapse_deck));
} catch (NotFoundException e) {
// do nothing
} catch (JSONException e) {
// do nothing
}
ad.setTitle(AnkiDroidApp.getCol().getDecks().name(mCurrentDid));
break;
case DIALOG_IMPORT_LOG:
case DIALOG_SYNC_LOG:
case DIALOG_SYNC_SANITY_ERROR:
ad.setMessage(mDialogMessage);
break;
case DIALOG_DB_ERROR:
mLoadFailed = false;
ad.getButton(Dialog.BUTTON3).setEnabled(hasErrorFiles());
break;
case DIALOG_LOAD_FAILED:
mLoadFailed = true;
if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
mOpenCollectionDialog.setMessage(res.getString(R.string.col_load_failed));
}
break;
case DIALOG_ERROR_HANDLING:
ArrayList<String> options = new ArrayList<String>();
ArrayList<Integer> values = new ArrayList<Integer>();
if (AnkiDroidApp.getCol() == null) {
// retry
options.add(res.getString(R.string.backup_retry_opening));
values.add(0);
} else {
// fix integrity
options.add(res.getString(R.string.check_db));
values.add(1);
}
// repair db with sqlite
options.add(res.getString(R.string.backup_error_menu_repair));
values.add(2);
// // restore from backup
options.add(res.getString(R.string.backup_restore));
values.add(3);
// delete old collection and build new one
options.add(res.getString(R.string.backup_full_sync_from_server));
values.add(4);
// delete old collection and build new one
options.add(res.getString(R.string.backup_del_collection));
values.add(5);
String[] titles = new String[options.size()];
mRepairValues = new int[options.size()];
for (int i = 0; i < options.size(); i++) {
titles[i] = options.get(i);
mRepairValues[i] = values.get(i);
}
ad.setItems(titles, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (mRepairValues[which]) {
case 0:
loadCollection();
return;
case 1:
integrityCheck();
return;
case 2:
showDialog(DIALOG_REPAIR_COLLECTION);
return;
case 3:
showDialog(DIALOG_RESTORE_BACKUP);
return;
case 4:
showDialog(DIALOG_FULL_SYNC_FROM_SERVER);
return;
case 5:
showDialog(DIALOG_NEW_COLLECTION);
return;
}
}
});
break;
case DIALOG_IMPORT_SELECT:
List<File> fileList = Utils.getImportableDecks();
if (fileList.size() == 0) {
Themes.showThemedToast(DeckPicker.this, getResources().getString(R.string.import_no_file_found),
false);
}
ad.setEnabled(fileList.size() != 0);
String[] tts = new String[fileList.size()];
mImportValues = new String[fileList.size()];
for (int i = 0; i < tts.length; i++) {
tts[i] = fileList.get(i).getName().replace(".apkg", "");
mImportValues[i] = fileList.get(i).getAbsolutePath();
}
ad.setItems(tts, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mImportPath = mImportValues[which];
showDialog(DIALOG_IMPORT);
}
});
break;
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
mContextMenuPosition = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
showDialog(DIALOG_CONTEXT_MENU);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Log.i(AnkiDroidApp.TAG, "DeckPicker - onBackPressed()");
finishWithAnimation();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void finishWithAnimation() {
finish();
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.DIALOG_EXIT);
}
}
// ----------------------------------------------------------------------------
// CUSTOM METHODS
// ----------------------------------------------------------------------------
public void setStudyContentView(long deckId, Bundle cramConfig) {
Fragment frag = (Fragment) getSupportFragmentManager().findFragmentById(R.id.studyoptions_fragment);
if (frag == null || !(frag instanceof StudyOptionsFragment) || ((StudyOptionsFragment) frag).getShownIndex() != deckId) {
StudyOptionsFragment details = StudyOptionsFragment.newInstance(deckId, false, cramConfig);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.replace(R.id.studyoptions_fragment, details);
ft.commit();
}
}
public StudyOptionsFragment getFragment() {
Fragment frag = (Fragment) getSupportFragmentManager().findFragmentById(R.id.studyoptions_fragment);
if (frag != null && (frag instanceof StudyOptionsFragment)) {
return (StudyOptionsFragment) frag;
}
return null;
}
/**
* Show/dismiss dialog when sd card is ejected/remounted (collection is saved by SdCardReceiver)
*/
private void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (AnkiDroidApp.getSharedPrefs(getBaseContext()).getBoolean("internalMemory", false)) {
return;
}
if (intent.getAction().equals(SdCardReceiver.MEDIA_EJECT)) {
showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
} else if (intent.getAction().equals(SdCardReceiver.MEDIA_MOUNT)) {
if (mNotMountedDialog != null && mNotMountedDialog.isShowing()) {
mNotMountedDialog.dismiss();
}
loadCollection();
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(SdCardReceiver.MEDIA_EJECT);
iFilter.addAction(SdCardReceiver.MEDIA_MOUNT);
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Creates an intent to load a deck given the full pathname of it. The constructed intent is equivalent (modulo the
* extras) to the open used by the launcher shortcut, which means it will not open a new study options window but
* bring the existing one to the front.
*/
public static Intent getLoadDeckIntent(Context context, long deckId) {
Intent loadDeckIntent = new Intent(context, DeckPicker.class);
loadDeckIntent.setAction(Intent.ACTION_MAIN);
loadDeckIntent.addCategory(Intent.CATEGORY_LAUNCHER);
loadDeckIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
loadDeckIntent.putExtra(EXTRA_DECK_ID, deckId);
return loadDeckIntent;
}
// private void handleRestoreDecks(boolean reloadIfEmpty) {
// if (mBrokenDecks.size() != 0) {
// while (true) {
// mCurrentDeckPath = mBrokenDecks.remove(0);
// if (!mAlreadyDealtWith.contains(mCurrentDeckPath) || mBrokenDecks.size() == 0) {
// break;
// }
// }
// mDeckNotLoadedAlert.setMessage(getResources().getString(R.string.open_deck_failed, "\'" + new
// File(mCurrentDeckPath).getName() + "\'", BackupManager.BROKEN_DECKS_SUFFIX.replace("/", ""),
// getResources().getString(R.string.repair_deck)));
// mDeckNotLoadedAlert.show();
// } else if (reloadIfEmpty) {
// if (mRestoredOrDeleted) {
// mBrokenDecks = new ArrayList<String>();
// // populateDeckList(mPrefDeckPath);
// }
// }
// }
private void sync() {
sync(null, 0);
}
/**
* The mother of all syncing attempts. This might be called from sync() as first attempt to sync a collection OR
* from the mSyncConflictResolutionListener if the first attempt determines that a full-sync is required. In the
* second case, we have passed the mediaUsn that was obtained during the first attempt.
*
* @param syncConflictResolution Either "upload" or "download", depending on the user's choice.
* @param syncMediaUsn The media Usn, as determined during the prior sync() attempt that determined that full
* syncing was required.
*/
private void sync(String syncConflictResolution, int syncMediaUsn) {
SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
String hkey = preferences.getString("hkey", "");
if (hkey.length() == 0) {
showDialog(DIALOG_USER_NOT_LOGGED_IN_SYNC);
} else {
Connection.sync(mSyncListener, new Connection.Payload(new Object[] { hkey,
preferences.getBoolean("syncFetchesMedia", true),
syncConflictResolution, syncMediaUsn }));
}
}
private void addSharedDeck() {
Intent intent = new Intent(DeckPicker.this, Info.class);
intent.putExtra(Info.TYPE_EXTRA, Info.TYPE_SHARED_DECKS);
startActivityForResult(intent, ADD_SHARED_DECKS);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.RIGHT);
}
}
private DialogInterface.OnClickListener mSyncConflictResolutionListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Resources res = getResources();
StyledDialog.Builder builder;
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
builder = new StyledDialog.Builder(DeckPicker.this);
builder.setPositiveButton(res.getString(R.string.yes), new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sync("upload", mSyncMediaUsn);
}
});
builder.setNegativeButton(res.getString(R.string.no), null);
builder.setTitle(res.getString(R.string.sync_log_title));
builder.setMessage(res.getString(R.string.sync_conflict_local_confirm));
builder.show();
break;
case DialogInterface.BUTTON_NEUTRAL:
builder = new StyledDialog.Builder(DeckPicker.this);
builder.setPositiveButton(res.getString(R.string.yes), new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sync("download", mSyncMediaUsn);
}
});
builder.setNegativeButton(res.getString(R.string.no), null);
builder.setTitle(res.getString(R.string.sync_log_title));
builder.setMessage(res.getString(R.string.sync_conflict_remote_confirm));
builder.show();
break;
case DialogInterface.BUTTON_NEGATIVE:
default:
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item;
if (mFragmented) {
UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_SYNC, Menu.NONE, R.string.sync_title,
R.drawable.ic_menu_refresh);
UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_ADD_NOTE, Menu.NONE, R.string.add,
R.drawable.ic_menu_add);
int icon;
SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this);
if (preferences.getBoolean("invertedColors", false)) {
icon = R.drawable.ic_menu_night_checked;
} else {
icon = R.drawable.ic_menu_night;
}
UIUtils.addMenuItemInActionBar(menu, Menu.NONE, StudyOptionsActivity.MENU_NIGHT, Menu.NONE, R.string.night_mode,
icon);
UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_STATISTICS, Menu.NONE, R.string.statistics_menu,
R.drawable.ic_menu_statistics);
UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_CARDBROWSER, Menu.NONE, R.string.menu_cardbrowser,
R.drawable.ic_menu_cardbrowser);
}
UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_HELP, Menu.NONE, R.string.help_title,
R.drawable.ic_menu_help);
item = menu.add(Menu.NONE, MENU_PREFERENCES, Menu.NONE, R.string.menu_preferences);
item.setIcon(R.drawable.ic_menu_preferences);
item = menu.add(Menu.NONE, MENU_MY_ACCOUNT, Menu.NONE, R.string.menu_my_account);
item.setIcon(R.drawable.ic_menu_home);
item = menu.add(Menu.NONE, MENU_ADD_SHARED_DECK, Menu.NONE, R.string.menu_get_shared_decks);
item.setIcon(R.drawable.ic_menu_download);
item = menu.add(Menu.NONE, MENU_CREATE_DECK, Menu.NONE, R.string.new_deck);
item.setIcon(R.drawable.ic_menu_add);
item = menu.add(Menu.NONE, MENU_CREATE_DYNAMIC_DECK, Menu.NONE, R.string.new_dynamic_deck);
item.setIcon(R.drawable.ic_menu_add);
item = menu.add(Menu.NONE, MENU_IMPORT, Menu.NONE, R.string.menu_import);
item.setIcon(R.drawable.ic_menu_download);
UIUtils.addMenuItem(menu, Menu.NONE, CHECK_DATABASE, Menu.NONE, R.string.check_db, R.drawable.ic_menu_search);
item = menu.add(Menu.NONE, StudyOptionsActivity.MENU_ROTATE, Menu.NONE, R.string.menu_rotate);
item.setIcon(R.drawable.ic_menu_always_landscape_portrait);
item = menu.add(Menu.NONE, MENU_FEEDBACK, Menu.NONE, R.string.studyoptions_feedback);
item.setIcon(R.drawable.ic_menu_send);
item = menu.add(Menu.NONE, MENU_ABOUT, Menu.NONE, R.string.menu_about);
item.setIcon(R.drawable.ic_menu_info_details);
return true;
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (mInvalidateMenu) {
if (menu != null) {
menu.clear();
onCreateOptionsMenu(menu);
}
mInvalidateMenu = false;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean sdCardAvailable = AnkiDroidApp.isSdCardMounted();
if (mFragmented) {
menu.findItem(MENU_SYNC).setEnabled(sdCardAvailable);
menu.findItem(MENU_ADD_NOTE).setEnabled(sdCardAvailable);
menu.findItem(MENU_STATISTICS).setEnabled(sdCardAvailable);
menu.findItem(MENU_CARDBROWSER).setEnabled(sdCardAvailable);
}
menu.findItem(MENU_CREATE_DECK).setEnabled(sdCardAvailable);
menu.findItem(MENU_CREATE_DYNAMIC_DECK).setEnabled(sdCardAvailable);
menu.findItem(CHECK_DATABASE).setEnabled(sdCardAvailable);
return true;
}
/** Handles item selections */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Resources res = getResources();
switch (item.getItemId()) {
case MENU_HELP:
showDialog(DIALOG_SELECT_HELP);
return true;
case MENU_SYNC:
sync();
return true;
case MENU_ADD_NOTE:
addNote();
return true;
case MENU_STATISTICS:
showDialog(DIALOG_SELECT_STATISTICS_TYPE);
return true;
case MENU_CARDBROWSER:
openCardBrowser();
return true;
case MENU_CREATE_DECK:
StyledDialog.Builder builder2 = new StyledDialog.Builder(DeckPicker.this);
builder2.setTitle(res.getString(R.string.new_deck));
mDialogEditText = (EditText) new EditText(DeckPicker.this);
// mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter });
builder2.setView(mDialogEditText, false, false);
builder2.setPositiveButton(res.getString(R.string.create), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String deckName = mDialogEditText.getText().toString()
.replaceAll("[\'\"\\n\\r\\[\\]\\(\\)]", "");
Log.i(AnkiDroidApp.TAG, "Creating deck: " + deckName);
AnkiDroidApp.getCol().getDecks().id(deckName, true);
loadCounts();
}
});
builder2.setNegativeButton(res.getString(R.string.cancel), null);
builder2.create().show();
return true;
case MENU_CREATE_DYNAMIC_DECK:
StyledDialog.Builder builder3 = new StyledDialog.Builder(DeckPicker.this);
builder3.setTitle(res.getString(R.string.new_deck));
mDialogEditText = (EditText) new EditText(DeckPicker.this);
ArrayList<String> names = AnkiDroidApp.getCol().getDecks().allNames();
int n = 1;
String cramDeckName = "Cram 1";
while (names.contains(cramDeckName)) {
n++;
cramDeckName = "Cram " + n;
}
mDialogEditText.setText(cramDeckName);
// mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter });
builder3.setView(mDialogEditText, false, false);
builder3.setPositiveButton(res.getString(R.string.create), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
long id = AnkiDroidApp.getCol().getDecks().newDyn(mDialogEditText.getText().toString());
openStudyOptions(id, new Bundle());
}
});
builder3.setNegativeButton(res.getString(R.string.cancel), null);
builder3.create().show();
return true;
case MENU_ABOUT:
startActivity(new Intent(DeckPicker.this, Info.class));
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.RIGHT);
}
return true;
case MENU_ADD_SHARED_DECK:
if (AnkiDroidApp.getCol() != null) {
SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
String hkey = preferences.getString("hkey", "");
if (hkey.length() == 0) {
showDialog(DIALOG_USER_NOT_LOGGED_IN_ADD_SHARED_DECK);
} else {
addSharedDeck();
}
}
return true;
case MENU_IMPORT:
showDialog(DIALOG_IMPORT_HINT);
return true;
case MENU_MY_ACCOUNT:
startActivity(new Intent(DeckPicker.this, MyAccount.class));
return true;
case MENU_PREFERENCES:
startActivityForResult(new Intent(DeckPicker.this, Preferences.class), PREFERENCES_UPDATE);
return true;
case MENU_FEEDBACK:
Intent i = new Intent(DeckPicker.this, Feedback.class);
i.putExtra("request", REPORT_FEEDBACK);
startActivityForResult(i, REPORT_FEEDBACK);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
}
return true;
case CHECK_DATABASE:
integrityCheck();
return true;
case StudyOptionsActivity.MENU_ROTATE:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
return true;
case StudyOptionsActivity.MENU_NIGHT:
SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this);
if (preferences.getBoolean("invertedColors", false)) {
preferences.edit().putBoolean("invertedColors", false).commit();
item.setIcon(R.drawable.ic_menu_night);
} else {
preferences.edit().putBoolean("invertedColors", true).commit();
item.setIcon(R.drawable.ic_menu_night_checked);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
mDontSaveOnStop = false;
if (resultCode == RESULT_MEDIA_EJECTED) {
showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
return;
} else if (resultCode == RESULT_DB_ERROR) {
handleDbError();
return;
}
if (requestCode == SHOW_STUDYOPTIONS && resultCode == RESULT_OK) {
loadCounts();
} else if (requestCode == ADD_NOTE && resultCode != RESULT_CANCELED) {
loadCounts();
} else if (requestCode == BROWSE_CARDS &&
(resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED)) {
loadCounts();
} else if (requestCode == ADD_CRAM_DECK) {
// TODO: check, if ok has been clicked
loadCounts();
} else if (requestCode == REPORT_ERROR) {
showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 4);
} else if (requestCode == SHOW_INFO_UPGRADE_DECKS) {
if (resultCode == RESULT_CANCELED) {
finishWithAnimation();
} else {
showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 3);
}
} else if (requestCode == SHOW_INFO_WELCOME || requestCode == SHOW_INFO_NEW_VERSION) {
if (resultCode == RESULT_OK) {
showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()),
requestCode == SHOW_INFO_WELCOME ? 1 : 2);
} else {
finishWithAnimation();
}
} else if (requestCode == PREFERENCES_UPDATE) {
String oldPath = mPrefDeckPath;
SharedPreferences pref = restorePreferences();
String newLanguage = pref.getString("language", "");
if (!AnkiDroidApp.getLanguage().equals(newLanguage)) {
AnkiDroidApp.setLanguage(newLanguage);
mInvalidateMenu = true;
}
if (mNotMountedDialog != null && mNotMountedDialog.isShowing() && pref.getBoolean("internalMemory", false)) {
showStartupScreensAndDialogs(pref, 0);
} else if (!mPrefDeckPath.equals(oldPath)) {
loadCollection();
}
// if (resultCode == StudyOptions.RESULT_RESTART) {
// setResult(StudyOptions.RESULT_RESTART);
// finishWithAnimation();
// } else {
// SharedPreferences preferences = PrefSettings.getSharedPrefs(getBaseContext());
// BackupManager.initBackup();
// if (!mPrefDeckPath.equals(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory())) ||
// mPrefDeckOrder != Integer.parseInt(preferences.getString("deckOrder", "0"))) {
// // populateDeckList(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory()));
// }
// }
} else if (requestCode == REPORT_FEEDBACK && resultCode == RESULT_OK) {
} else if (requestCode == LOG_IN_FOR_SYNC && resultCode == RESULT_OK) {
sync();
} else if (requestCode == LOG_IN_FOR_SHARED_DECK && resultCode == RESULT_OK) {
addSharedDeck();
} else if (requestCode == ADD_SHARED_DECKS) {
if (intent != null) {
mImportPath = intent.getStringExtra("importPath");
}
if (AnkiDroidApp.colIsOpen() && mImportPath != null) {
showDialog(DIALOG_IMPORT);
}
} else if (requestCode == REQUEST_REVIEW) {
Log.i(AnkiDroidApp.TAG, "Result code = " + resultCode);
switch (resultCode) {
case Reviewer.RESULT_SESSION_COMPLETED:
default:
// do not reload counts, if activity is created anew because it has been before destroyed by android
loadCounts();
break;
case Reviewer.RESULT_NO_MORE_CARDS:
mDontSaveOnStop = true;
Intent i = new Intent();
i.setClass(this, StudyOptionsActivity.class);
i.putExtra("onlyFnsMsg", true);
startActivityForResult(i, SHOW_STUDYOPTIONS);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
}
break;
}
}
// workaround for hidden dialog on return
BroadcastMessages.showDialog();
}
private void integrityCheck() {
if (!AnkiDroidApp.colIsOpen()) {
loadCollection();
return;
}
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_CHECK_DATABASE, new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
mProgressDialog = StyledProgressDialog.show(DeckPicker.this, "",
getResources().getString(R.string.check_db_message), true);
}
@Override
public void onPostExecute(TaskData result) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (result.getBoolean()) {
StyledDialog dialog = (StyledDialog) onCreateDialog(DIALOG_OK);
dialog.setTitle(getResources().getString(R.string.check_db_title));
dialog.setMessage(String.format(Utils.ENGLISH_LOCALE,
getResources().getString(R.string.check_db_result_message),
Math.round(result.getLong() / 1024)));
dialog.show();
} else {
handleDbError();
}
}
@Override
public void onProgressUpdate(TaskData... values) {
}
}, new DeckTask.TaskData(AnkiDroidApp.getCol()));
}
// private void resetDeckLanguages(String deckPath) {
// if (MetaDB.resetDeckLanguages(this, deckPath)) {
// Themes.showThemedToast(this, getResources().getString(R.string.contextmenu_deckpicker_reset_reset_message),
// true);
// }
// }
//
//
// public void openSharedDeckPicker() {
// // deckLoaded = false;
// startActivityForResult(new Intent(this, SharedDeckPicker.class), DOWNLOAD_SHARED_DECK);
// if (UIUtils.getApiLevel() > 4) {
// ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
// }
// }
public void handleDbError() {
AnkiDatabaseManager.closeDatabase(AnkiDroidApp.getCollectionPath());
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_RESTORE_IF_MISSING, new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
mProgressDialog = StyledProgressDialog.show(DeckPicker.this, "",
getResources().getString(R.string.backup_restore_if_missing), true);
}
@Override
public void onPostExecute(TaskData result) {
if (mProgressDialog.isShowing()) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "onPostExecute - Dialog dismiss Exception = " + e.getMessage());
}
}
showDialog(DIALOG_DB_ERROR);
}
@Override
public void onProgressUpdate(TaskData... values) {
}
}, new DeckTask.TaskData(AnkiDroidApp.getCollectionPath()));
}
private void openStudyOptions(long deckId) {
openStudyOptions(deckId, null);
}
private void openStudyOptions(long deckId, Bundle cramInitialConfig) {
if (mFragmented) {
setStudyContentView(deckId, cramInitialConfig);
} else {
mDontSaveOnStop = true;
Intent intent = new Intent();
intent.putExtra("index", deckId);
intent.putExtra("cramInitialConfig", cramInitialConfig);
intent.setClass(this, StudyOptionsActivity.class);
// if (deckId != 0) {
// intent.putExtra(EXTRA_DECK_ID, deckId);
// }
startActivityForResult(intent, SHOW_STUDYOPTIONS);
// if (deckId != 0) {
// if (UIUtils.getApiLevel() > 4) {
// ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.NONE);
// }
// } else {
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
}
// }
}
}
private void handleDeckSelection(int id) {
if (!AnkiDroidApp.colIsOpen()) {
loadCollection();
}
String deckFilename = null;
@SuppressWarnings("unchecked")
HashMap<String, String> data = (HashMap<String, String>) mDeckListAdapter.getItem(id);
Log.i(AnkiDroidApp.TAG, "Selected " + deckFilename);
long deckId = Long.parseLong(data.get("did"));
AnkiDroidApp.getCol().getDecks().select(deckId);
openStudyOptions(deckId);
}
private void createTutorialDeck() {
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_LOAD_TUTORIAL, new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
mProgressDialog = StyledProgressDialog.show(DeckPicker.this, "",
getResources().getString(R.string.tutorial_load), true);
}
@Override
public void onPostExecute(TaskData result) {
if (result.getBoolean()) {
loadCounts();
openStudyOptions(AnkiDroidApp.getCol().getDecks().selected());
} else {
Themes.showThemedToast(DeckPicker.this, getResources().getString(R.string.tutorial_loading_error),
false);
}
if (mProgressDialog.isShowing()) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "onPostExecute - Dialog dismiss Exception = " + e.getMessage());
}
}
}
@Override
public void onProgressUpdate(TaskData... values) {
}
}, new DeckTask.TaskData(AnkiDroidApp.getCol()));
}
private void updateDecksList(TreeSet<Object[]> decks, int eta, int count) {
if (decks == null) {
Log.e(AnkiDroidApp.TAG, "updateDecksList: empty decks list");
return;
}
mDeckList.clear();
int due = 0;
for (Object[] d : decks) {
HashMap<String, String> m = new HashMap<String, String>();
String[] name = ((String[]) d[0]);
m.put("name", readableDeckName(name));
m.put("did", ((Long) d[1]).toString());
m.put("new", ((Integer) d[2]).toString());
m.put("lrn", ((Integer) d[3]).toString());
m.put("rev", ((Integer) d[4]).toString());
m.put("dyn", ((Boolean) d[5]) ? "d1" : "d0");
// m.put("complMat", ((Float)d[5]).toString());
// m.put("complAll", ((Float)d[6]).toString());
if (name.length == 1) {
due += Integer.parseInt(m.get("new")) + Integer.parseInt(m.get("lrn")) + Integer.parseInt(m.get("rev"));
// top position
m.put("sep", "top");
// correct previous deck
if (mDeckList.size() > 0) {
HashMap<String, String> map = mDeckList.get(mDeckList.size() - 1);
if (map.get("sep").equals("top")) {
map.put("sep", "ful");
} else {
map.put("sep", "bot");
}
}
} else {
// center position
m.put("sep", "cen");
}
if (mDeckList.size() > 0 && mDeckList.size() == decks.size() - 1) {
// bottom position
if (name.length == 1) {
m.put("sep", "ful");
} else {
m.put("sep", "bot");
}
}
mDeckList.add(m);
}
mDeckListAdapter.notifyDataSetChanged();
// set title
Resources res = getResources();
if (count != -1) {
String time = "-";
if (eta != -1) {
time = res.getQuantityString(R.plurals.deckpicker_title_minutes, eta, eta);
}
AnkiDroidApp.getCompat().setSubtitle(this, res.getQuantityString(R.plurals.deckpicker_title, due, due, count, time));
}
setTitle(res.getString(R.string.app_name));
// update widget
WidgetStatus.update(this, decks);
}
// private void restartApp() {
// // restarts application in order to apply new themes or localisations
// Intent i = getBaseContext().getPackageManager()
// .getLaunchIntentForPackage(getBaseContext().getPackageName());
// mCompat.invalidateOptionsMenu(this);
// MetaDB.closeDB();
// StudyOptions.this.finishWithAnimation();
// startActivity(i);
// }
// ----------------------------------------------------------------------------
// INNER CLASSES
// ----------------------------------------------------------------------------
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (mSwipeEnabled && !mFragmented) {
try {
if (e1.getX() - e2.getX() > AnkiDroidApp.sSwipeMinDistance && Math.abs(velocityX) > AnkiDroidApp.sSwipeThresholdVelocity
&& Math.abs(e1.getY() - e2.getY()) < AnkiDroidApp.sSwipeMaxOffPath) {
mDontSaveOnStop = true;
float pos = e1.getY();
for (int j = 0; j < mDeckListView.getChildCount(); j++) {
View v = mDeckListView.getChildAt(j);
Rect rect = new Rect();
v.getHitRect(rect);
if (rect.top < pos && rect.bottom > pos) {
HashMap<String, String> data = (HashMap<String, String>) mDeckListAdapter.getItem(mDeckListView.getPositionForView(v));
Collection col = AnkiDroidApp.getCol();
if (col != null) {
col.getDecks().select(Long.parseLong(data.get("did")));
col.reset();
Intent reviewer = new Intent(DeckPicker.this, Reviewer.class);
startActivityForResult(reviewer, REQUEST_REVIEW);
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.LEFT);
}
return true;
}
}
}
}
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "onFling Exception = " + e.getMessage());
}
}
return false;
}
}
// @Override
// protected void onNewIntent(Intent intent) {
// super.onNewIntent(intent);
// String deck = intent.getStringExtra(EXTRA_DECK);
// Log.d(AnkiDroidApp.TAG, "StudyOptions.onNewIntent: " + intent
// + ", deck=" + deck);
// // if (deck != null && !deck.equals(mDeckFilename)) {
// // mDeckFilename = deck;
// // // loadPreviousDeck();
// // }
// }
public static String readableDeckName(String[] name) {
int len = name.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
if (i == len - 1) {
sb.append(name[i]);
} else if (i == len - 2) {
sb.append("\u21aa");
} else {
sb.append(" ");
}
}
return sb.toString();
}
@Override
public void onAttachedToWindow() {
if (!mFragmented) {
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
}
}
| false | false | null | null |
diff --git a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptErrorWarningConfigurationBlock.java b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptErrorWarningConfigurationBlock.java
index ec9efeeb..1397da4d 100644
--- a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptErrorWarningConfigurationBlock.java
+++ b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptErrorWarningConfigurationBlock.java
@@ -1,57 +1,56 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.javascript.internal.ui.preferences;
import org.eclipse.dltk.javascript.core.JavaScriptCorePreferences;
import org.eclipse.dltk.ui.preferences.AbstractConfigurationBlock;
import org.eclipse.dltk.ui.preferences.OverlayPreferenceStore;
-import org.eclipse.dltk.ui.preferences.PreferencesMessages;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
public class JavaScriptErrorWarningConfigurationBlock extends
AbstractConfigurationBlock {
public JavaScriptErrorWarningConfigurationBlock(
OverlayPreferenceStore store, PreferencePage mainPreferencePage) {
super(store, mainPreferencePage);
}
public JavaScriptErrorWarningConfigurationBlock(
OverlayPreferenceStore overlayPreferenceStore) {
super(overlayPreferenceStore);
getPreferenceStore()
.addKeys(
new OverlayPreferenceStore.OverlayKey[] { new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.BOOLEAN,
JavaScriptCorePreferences.USE_STRICT_MODE) });
}
public Control createControl(Composite parent) {
final GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.numColumns = 2;
final Composite markersComposite = new Composite(parent, SWT.NULL);
markersComposite.setLayout(layout);
markersComposite.setFont(parent.getFont());
addCheckBox(markersComposite,
- PreferencesMessages.ErrorWarning_strictMode,
+ JavaScriptPreferenceMessages.ErrorWarning_strictMode,
JavaScriptCorePreferences.USE_STRICT_MODE, 0);
// bindControl(enableCheckbox, STRICT_MODE, null);
return markersComposite;
}
}
diff --git a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptPreferenceMessages.java b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptPreferenceMessages.java
index 19949047..4956b7f2 100644
--- a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptPreferenceMessages.java
+++ b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/preferences/JavaScriptPreferenceMessages.java
@@ -1,33 +1,34 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.javascript.internal.ui.preferences;
import org.eclipse.osgi.util.NLS;
public class JavaScriptPreferenceMessages extends NLS {
private static final String BUNDLE_NAME = "org.eclipse.dltk.javascript.internal.ui.preferences.JavaScriptPreferenceMessages";//$NON-NLS-1$
public static String JavascriptEditorPreferencePage_general;
public static String JavaScriptGlobalPreferencePage_description;
public static String JavascriptSmartTypingConfigurationBlock_smartPaste;
public static String JavascriptSmartTypingConfigurationBlock_typing_smartTab;
public static String JavascriptSmartTypingConfigurationBlock_closeStrings;
public static String JavascriptSmartTypingConfigurationBlock_closeBrackets;
public static String JavascriptSmartTypingConfigurationBlock_typing_tabTitle;
public static String TodoTaskDescription;
public static String ErrorWarningDescription;
+ public static String ErrorWarning_strictMode;
public static String JavascriptFoldingPreferencePage_initiallyFoldFunctions;
static {
NLS.initializeMessages(BUNDLE_NAME, JavaScriptPreferenceMessages.class);
}
}
| false | false | null | null |
diff --git a/src/org/gridsphere/provider/portletui/tags/ActionLinkTag.java b/src/org/gridsphere/provider/portletui/tags/ActionLinkTag.java
index 7158908e4..a424d409c 100644
--- a/src/org/gridsphere/provider/portletui/tags/ActionLinkTag.java
+++ b/src/org/gridsphere/provider/portletui/tags/ActionLinkTag.java
@@ -1,187 +1,187 @@
/**
* @author <a href="mailto:[email protected]">Jason Novotny</a>
* @version $Id$
*/
package org.gridsphere.provider.portletui.tags;
import org.gridsphere.portlet.impl.SportletProperties;
import org.gridsphere.provider.portletui.beans.ActionLinkBean;
import org.gridsphere.provider.portletui.beans.ImageBean;
import org.gridsphere.provider.portletui.beans.MessageStyle;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
/**
* The <code>ActionLinkTag</code> provides a hyperlink element that includes a <code>DefaultPortletAction</code>
* and can contain nested <code>ActionParamTag</code>s
*/
public class ActionLinkTag extends ActionTag {
protected ActionLinkBean actionlink = null;
protected String style = MessageStyle.MSG_INFO;
protected ImageBean imageBean = null;
/**
* Sets the style of the text: Available styles are
* <ul>
* <li>nostyle</li>
* <li>error</li>
* <li>info</li>
* <li>status</li>
* <li>alert</li>
* <li>success</li>
*
* @param style the text style
*/
public void setStyle(String style) {
this.style = style;
}
/**
* Returns the style of the text: Available styles are
* <ul>
* <li>nostyle</li>
* <li>error</li>
* <li>info</li>
* <li>status</li>
* <li>alert</li>
* <li>success</li>
*
* @return the text style
*/
public String getStyle() {
return style;
}
/**
* Sets the image bean
*
* @param imageBean the image bean
*/
public void setImageBean(ImageBean imageBean) {
this.imageBean = imageBean;
}
/**
* Returns the image bean
*
* @return the image bean
*/
public ImageBean getImageBean() {
return imageBean;
}
public int doStartTag() throws JspException {
if (!beanId.equals("")) {
actionlink = (ActionLinkBean) getTagBean();
if (actionlink == null) {
actionlink = new ActionLinkBean(beanId);
actionlink.setStyle(style);
this.setBaseComponentBean(actionlink);
} else {
if (actionlink.getParamBeanList() != null) {
paramBeans = actionlink.getParamBeanList();
}
if (actionlink.getAction() != null) {
action = actionlink.getAction();
}
if (actionlink.getValue() != null) {
value = actionlink.getValue();
}
if (actionlink.getKey() != null) {
key = actionlink.getKey();
}
if (actionlink.getOnClick() != null) {
onClick = actionlink.getOnClick();
}
}
} else {
actionlink = new ActionLinkBean();
this.setBaseComponentBean(actionlink);
actionlink.setStyle(style);
}
actionlink.setUseAjax(useAjax);
if (name != null) actionlink.setName(name);
if (anchor != null) actionlink.setAnchor(anchor);
if (action != null) actionlink.setAction(action);
if (value != null) actionlink.setValue(value);
if (onClick != null) actionlink.setOnClick(onClick);
if (style != null) actionlink.setStyle(style);
if (cssStyle != null) actionlink.setCssStyle(cssStyle);
if (cssClass != null) actionlink.setCssClass(cssClass);
- if (layout != null) actionlink.setLayout(label);
+ if (layout != null) actionlink.setLayout(layout);
+ if (label != null) actionlink.setLabel(label);
if (onMouseOut != null) actionlink.setOnMouseOut(onMouseOut);
if (onMouseOver != null) actionlink.setOnMouseOver(onMouseOver);
Tag parent = getParent();
if (parent instanceof ActionMenuTag) {
ActionMenuTag actionMenuTag = (ActionMenuTag) parent;
if (!actionMenuTag.getLayout().equals("horizontal")) {
actionlink.setCssStyle("display: block");
}
}
if (key != null) {
actionlink.setKey(key);
actionlink.setValue(getLocalizedText(key));
value = actionlink.getValue();
}
return EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspException {
if (!beanId.equals("")) {
paramBeans = actionlink.getParamBeanList();
- label = actionlink.getLabel();
action = actionlink.getAction();
}
if (action != null) {
actionlink.setPortletURI(createActionURI());
} else {
actionlink.setPortletURI(createRenderURI());
}
if ((bodyContent != null) && (value == null)) {
actionlink.setValue(bodyContent.getString());
}
if (pageContext.getRequest().getAttribute(SportletProperties.USE_AJAX) != null) {
String paction = ((!action.equals("")) ? "&" + portletPhase.toString() : "");
String portlet = (String) pageContext.getRequest().getAttribute(SportletProperties.PORTLET_NAME);
String compname = (String) pageContext.getRequest().getAttribute(SportletProperties.COMPONENT_NAME);
actionlink.setUseAjax(true);
actionlink.setOnClick("GridSphereAjaxHandler2.startRequest('" + portlet + "', '" + compname + "', '" + paction + "');");
}
if (useAjax) {
String cid = (String) pageContext.getRequest().getAttribute(SportletProperties.COMPONENT_ID);
String paction = ((!action.equals("")) ? "&" + portletPhase.toString() : "");
actionlink.setOnClick("GridSphereAjaxHandler.startRequest(" + cid + ", '" + paction + "');");
}
if (imageBean != null) {
String val = actionlink.getValue();
if (val == null) val = "";
actionlink.setValue(imageBean.toStartString() + val);
}
if (var == null) {
try {
JspWriter out = pageContext.getOut();
out.print(actionlink.toEndString());
} catch (Exception e) {
throw new JspException(e);
}
} else {
pageContext.setAttribute(var, actionlink.toEndString(), PageContext.PAGE_SCOPE);
}
release();
return EVAL_PAGE;
}
}
| false | false | null | null |
diff --git a/src/persistency/DatabaseConnection.java b/src/persistency/DatabaseConnection.java
index 029be59..7b3d254 100644
--- a/src/persistency/DatabaseConnection.java
+++ b/src/persistency/DatabaseConnection.java
@@ -1,139 +1,140 @@
package persistency;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import exceptions.DeleteNonExistingException;
import exceptions.UpdateNonExistingException;
import utils.Query;
public class DatabaseConnection {
private Connection conn;
private Statement stmt;
public DatabaseConnection(String dbFile) {
try {
Class.forName("org.sqlite.JDBC");
this.conn = DriverManager.getConnection("jdbc:sqlite:" + dbFile);
this.stmt = this.conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public int create(String table, String[] columns, String[] values) {
int id = -1;
try {
this.execUpdate(Query.insertInto(table, columns, values));
// Get the id of the inserted row
ResultSet rs = this.execQuery(Query.select("last_insert_rowid()"));
if (rs.next()) {
id = rs.getInt("last_insert_rowid()");
}
} catch (SQLException e) {
e.printStackTrace();
}
return id;
}
public ResultSet execQuery(Query query) {
return this.execQuery(query.end());
}
private ResultSet execQuery(String query) {
//System.out.println(query);
try {
return this.stmt.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public int execUpdate(String query) {
//System.out.println(query);
try {
this.stmt.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
public int execUpdate(Query query) {
return this.execUpdate(query.end());
}
public ResultSet readWhereEquals(String table, String key, String value){
return this.execQuery(Query.selectAllFrom(table).whereEquals(key, value));
}
public ResultSet readWhereEquals(String table, String key, int value){
return this.execQuery(Query.selectAllFrom(table).whereEquals(key, value));
}
public ResultSet readByID(String table, int id) {
return this.readWhereEquals(table, "id", id);
}
public ResultSet readAll(String table) {
return this.execQuery(Query.selectAllFrom(table));
}
public ResultSet readAllWhere(String table, String key, String value) {
return this.execQuery(Query.selectAllFrom(table).whereEquals(key, value));
}
public boolean update(String table, int id, String column, String value) {
if (!this.exists(table, id)) return false;
this.execUpdate(Query.update(table, column, value).whereEquals("id", id));
return true;
}
public boolean update(String table, int id, String[] columns, String[] values)
throws UpdateNonExistingException {
if (!this.exists(table, id)) throw new UpdateNonExistingException();
this.execUpdate(Query.update(table, columns, values).whereEquals("id", id));
return true;
}
public boolean delete(String table, int id) throws DeleteNonExistingException {
if (!this.exists(table, id)) throw new DeleteNonExistingException();
this.execUpdate(Query.deleteFrom(table).whereEquals("id", id));
return true;
}
public int count(String table) {
ResultSet rs = this.execQuery(Query.count(table));
int count = 0;
try {
while (rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
public boolean exists(String table, int id) {
ResultSet rs = this.execQuery(Query.exists(table, id));
+ boolean exists = false;
try {
while (rs.next()) {
- return rs.getBoolean(1);
+ exists = rs.getBoolean(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
- return false;
+ return exists;
}
}
| false | false | null | null |
diff --git a/core/src/processing/core/PGraphicsJava2D.java b/core/src/processing/core/PGraphicsJava2D.java
index aed126c8d..bb88a2f52 100644
--- a/core/src/processing/core/PGraphicsJava2D.java
+++ b/core/src/processing/core/PGraphicsJava2D.java
@@ -1,1362 +1,1366 @@
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2005-06 Ben Fry and Casey Reas
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
/**
* Subclass for PGraphics that implements the graphics API
* in Java 1.3+ using Java 2D.
*
* <p>Pixel operations too slow? As of release 0085 (the first beta),
* the default renderer uses Java2D. It's more accurate than the renderer
* used in alpha releases of Processing (it handles stroke caps and joins,
* and has better polygon tessellation), but it's super slow for handling
* pixels. At least until we get a chance to get the old 2D renderer
* (now called P2D) working in a similar fashion, you can use
* <TT>size(w, h, P3D)</TT> instead of <TT>size(w, h)</TT> which will
* be faster for general pixel flipping madness. </p>
*
* <p>To get access to the Java 2D "Graphics2D" object for the default
* renderer, use:
* <PRE>Graphics2D g2 = ((PGraphics2)g).g2;</PRE>
* This will let you do Java 2D stuff directly, but is not supported in
* any way shape or form. Which just means "have fun, but don't complain
* if it breaks."</p>
*/
public class PGraphicsJava2D extends PGraphics {
public Graphics2D g2;
GeneralPath gpath;
int transformCount;
AffineTransform transformStack[] =
new AffineTransform[MATRIX_STACK_DEPTH];
double transform[] = new double[6];
Line2D.Float line = new Line2D.Float();
Ellipse2D.Float ellipse = new Ellipse2D.Float();
Rectangle2D.Float rect = new Rectangle2D.Float();
Arc2D.Float arc = new Arc2D.Float();
protected Color tintColorObject;
protected Color fillColorObject;
public boolean fillGradient;
public Paint fillGradientObject;
protected Color strokeColorObject;
public boolean strokeGradient;
public Paint strokeGradientObject;
//////////////////////////////////////////////////////////////
// INTERNAL
/**
* Constructor for the PGraphicsJava object.
* This prototype only exists because of annoying
* java compilers, and should not be used.
*/
//public PGraphicsJava2D() { }
/**
* Constructor for the PGraphics object. Use this to ensure that
* the defaults get set properly. In a subclass, use this(w, h)
* as the first line of a subclass' constructor to properly set
* the internal fields and defaults.
*
* @param iwidth viewport width
* @param iheight viewport height
*/
public PGraphicsJava2D(int iwidth, int iheight, PApplet parent) {
super(iwidth, iheight, parent);
//resize(iwidth, iheight);
}
/**
* Called in repsonse to a resize event, handles setting the
* new width and height internally, as well as re-allocating
* the pixel buffer for the new size.
*
* Note that this will nuke any cameraMode() settings.
*/
public void resize(int iwidth, int iheight) { // ignore
//System.out.println("resize " + iwidth + " " + iheight);
insideDrawWait();
insideResize = true;
width = iwidth;
height = iheight;
width1 = width - 1;
height1 = height - 1;
allocate();
// ok to draw again
insideResize = false;
}
// broken out because of subclassing for opengl
protected void allocate() {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2 = (Graphics2D) image.getGraphics();
// can't un-set this because this may be only a resize (Bug #463)
//defaultsInited = false;
}
//////////////////////////////////////////////////////////////
// FRAME
public void beginDraw() {
insideResizeWait();
insideDraw = true;
// need to call defaults(), but can only be done when it's ok
// to draw (i.e. for opengl, no drawing can be done outside
// beginDraw/endDraw).
if (!defaultsInited) defaults();
resetMatrix(); // reset model matrix
// reset vertices
vertexCount = 0;
}
public void endDraw() {
// hm, mark pixels as changed, because this will instantly do a full
// copy of all the pixels to the surface.. so that's kind of a mess.
//updatePixels();
if (!mainDrawingSurface) {
loadPixels();
}
insideDraw = false;
}
//////////////////////////////////////////////////////////////
// SHAPES
public void beginShape(int kind) {
//super.beginShape(kind);
shape = kind;
vertexCount = 0;
splineVertexCount = 0;
// set gpath to null, because when mixing curves and straight
// lines, vertexCount will be set back to zero, so vertexCount == 1
// is no longer a good indicator of whether the shape is new.
// this way, just check to see if gpath is null, and if it isn't
// then just use it to continue the shape.
gpath = null;
}
public void textureMode(int mode) {
unavailableError("textureMode(mode)");
}
public void texture(PImage image) {
unavailableError("texture(image)");
}
public void vertex(float x, float y) {
splineVertexCount = 0;
//float vertex[];
if (vertexCount == vertices.length) {
float temp[][] = new float[vertexCount<<1][VERTEX_FIELD_COUNT];
System.arraycopy(vertices, 0, temp, 0, vertexCount);
vertices = temp;
//message(CHATTER, "allocating more vertices " + vertices.length);
}
// not everyone needs this, but just easier to store rather
// than adding another moving part to the code...
vertices[vertexCount][MX] = x;
vertices[vertexCount][MY] = y;
vertexCount++;
switch (shape) {
case POINTS:
point(x, y);
break;
case LINES:
if ((vertexCount % 2) == 0) {
line(vertices[vertexCount-2][MX],
vertices[vertexCount-2][MY], x, y);
}
break;
/*
case LINE_STRIP:
case LINE_LOOP:
if (gpath == null) {
gpath = new GeneralPath();
gpath.moveTo(x, y);
} else {
gpath.lineTo(x, y);
}
break;
*/
case TRIANGLES:
if ((vertexCount % 3) == 0) {
triangle(vertices[vertexCount - 3][MX],
vertices[vertexCount - 3][MY],
vertices[vertexCount - 2][MX],
vertices[vertexCount - 2][MY],
x, y);
}
break;
case TRIANGLE_STRIP:
if (vertexCount >= 3) {
triangle(vertices[vertexCount - 2][MX],
vertices[vertexCount - 2][MY],
vertices[vertexCount - 1][MX],
vertices[vertexCount - 1][MY],
vertices[vertexCount - 3][MX],
vertices[vertexCount - 3][MY]);
}
break;
case TRIANGLE_FAN:
if (vertexCount == 3) {
triangle(vertices[0][MX], vertices[0][MY],
vertices[1][MX], vertices[1][MY],
x, y);
} else if (vertexCount > 3) {
gpath = new GeneralPath();
// when vertexCount > 3, draw an un-closed triangle
// for indices 0 (center), previous, current
gpath.moveTo(vertices[0][MX],
vertices[0][MY]);
gpath.lineTo(vertices[vertexCount - 2][MX],
vertices[vertexCount - 2][MY]);
gpath.lineTo(x, y);
draw_shape(gpath);
}
break;
case QUADS:
if ((vertexCount % 4) == 0) {
quad(vertices[vertexCount - 4][MX],
vertices[vertexCount - 4][MY],
vertices[vertexCount - 3][MX],
vertices[vertexCount - 3][MY],
vertices[vertexCount - 2][MX],
vertices[vertexCount - 2][MY],
x, y);
}
break;
case QUAD_STRIP:
// 0---2---4
// | | |
// 1---3---5
if ((vertexCount >= 4) && ((vertexCount % 2) == 0)) {
quad(vertices[vertexCount - 4][MX],
vertices[vertexCount - 4][MY],
vertices[vertexCount - 2][MX],
vertices[vertexCount - 2][MY],
x, y,
vertices[vertexCount - 3][MX],
vertices[vertexCount - 3][MY]);
}
break;
case POLYGON:
if (gpath == null) {
gpath = new GeneralPath();
gpath.moveTo(x, y);
} else if (breakShape) {
gpath.moveTo(x, y);
breakShape = false;
} else {
gpath.lineTo(x, y);
}
break;
}
}
public void vertex(float x, float y, float u, float v) {
unavailableError("vertex(x, y, u, v");
}
public void vertex(float x, float y, float z) {
depthErrorXYZ("vertex");
}
public void vertex(float x, float y, float z, float u, float v) {
depthErrorXYZ("vertex");
}
public void bezierVertex(float x1, float y1,
float x2, float y2,
float x3, float y3) {
if (gpath == null) {
throw new RuntimeException("Must call vertex() at least once " +
"before using bezierVertex()");
}
switch (shape) {
//case LINE_LOOP:
//case LINE_STRIP:
case POLYGON:
gpath.curveTo(x1, y1, x2, y2, x3, y3);
break;
default:
throw new RuntimeException("bezierVertex() can only be used with " +
"LINE_STRIP, LINE_LOOP, or POLYGON");
}
}
float curveX[] = new float[4];
float curveY[] = new float[4];
public void curveVertex(float x, float y) {
//if ((shape != LINE_LOOP) && (shape != LINE_STRIP) && (shape != POLYGON)) {
if (shape != POLYGON) {
throw new RuntimeException("curveVertex() can only be used with " +
"POLYGON shapes");
//"LINE_LOOP, LINE_STRIP, and POLYGON shapes");
}
if (!curve_inited) curve_init();
vertexCount = 0;
if (splineVertices == null) {
splineVertices = new float[DEFAULT_SPLINE_VERTICES][VERTEX_FIELD_COUNT];
}
// if more than 128 points, shift everything back to the beginning
if (splineVertexCount == DEFAULT_SPLINE_VERTICES) {
System.arraycopy(splineVertices[DEFAULT_SPLINE_VERTICES - 3], 0,
splineVertices[0], 0, VERTEX_FIELD_COUNT);
System.arraycopy(splineVertices[DEFAULT_SPLINE_VERTICES - 2], 0,
splineVertices[1], 0, VERTEX_FIELD_COUNT);
System.arraycopy(splineVertices[DEFAULT_SPLINE_VERTICES - 1], 0,
splineVertices[2], 0, VERTEX_FIELD_COUNT);
splineVertexCount = 3;
}
// this new guy will be the fourth point (or higher),
// which means it's time to draw segments of the curve
if (splineVertexCount >= 3) {
curveX[0] = splineVertices[splineVertexCount-3][MX];
curveY[0] = splineVertices[splineVertexCount-3][MY];
curveX[1] = splineVertices[splineVertexCount-2][MX];
curveY[1] = splineVertices[splineVertexCount-2][MY];
curveX[2] = splineVertices[splineVertexCount-1][MX];
curveY[2] = splineVertices[splineVertexCount-1][MY];
curveX[3] = x;
curveY[3] = y;
curveToBezierMatrix.mult(curveX, curveX);
curveToBezierMatrix.mult(curveY, curveY);
// since the paths are continuous,
// only the first point needs the actual moveto
if (gpath == null) {
gpath = new GeneralPath();
gpath.moveTo(curveX[0], curveY[0]);
}
gpath.curveTo(curveX[1], curveY[1],
curveX[2], curveY[2],
curveX[3], curveY[3]);
}
// add the current point to the list
splineVertices[splineVertexCount][MX] = x;
splineVertices[splineVertexCount][MY] = y;
splineVertexCount++;
}
boolean breakShape;
public void breakShape() {
breakShape = true;
}
public void endShape(int mode) {
if (gpath != null) { // make sure something has been drawn
if (shape == POLYGON) {
if (mode == CLOSE) {
gpath.closePath();
}
draw_shape(gpath);
}
}
shape = 0;
}
//////////////////////////////////////////////////////////////
/*
protected void fillGradient(Paint paint) {
fillGradient = true;
fillGradientObject = paint;
}
protected void noFillGradient() {
fillGradient = false;
}
*/
//////////////////////////////////////////////////////////////
protected void fill_shape(Shape s) {
if (fillGradient) {
g2.setPaint(fillGradientObject);
g2.fill(s);
} else if (fill) {
g2.setColor(fillColorObject);
g2.fill(s);
}
}
protected void stroke_shape(Shape s) {
if (strokeGradient) {
g2.setPaint(strokeGradientObject);
g2.draw(s);
} else if (stroke) {
g2.setColor(strokeColorObject);
g2.draw(s);
}
}
protected void draw_shape(Shape s) {
if (fillGradient) {
g2.setPaint(fillGradientObject);
g2.fill(s);
} else if (fill) {
g2.setColor(fillColorObject);
g2.fill(s);
}
if (strokeGradient) {
g2.setPaint(strokeGradientObject);
g2.draw(s);
} else if (stroke) {
g2.setColor(strokeColorObject);
g2.draw(s);
}
}
//////////////////////////////////////////////////////////////
public void point(float x, float y) {
line(x, y, x, y);
}
public void line(float x1, float y1, float x2, float y2) {
//graphics.setColor(strokeColorObject);
//graphics.drawLine(x1, y1, x2, y2);
line.setLine(x1, y1, x2, y2);
stroke_shape(line);
}
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
gpath = new GeneralPath();
gpath.moveTo(x1, y1);
gpath.lineTo(x2, y2);
gpath.lineTo(x3, y3);
gpath.closePath();
draw_shape(gpath);
}
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
GeneralPath gp = new GeneralPath();
gp.moveTo(x1, y1);
gp.lineTo(x2, y2);
gp.lineTo(x3, y3);
gp.lineTo(x4, y4);
gp.closePath();
draw_shape(gp);
}
//////////////////////////////////////////////////////////////
protected void rectImpl(float x1, float y1, float x2, float y2) {
rect.setFrame(x1, y1, x2-x1, y2-y1);
draw_shape(rect);
}
protected void ellipseImpl(float x, float y, float w, float h) {
ellipse.setFrame(x, y, w, h);
draw_shape(ellipse);
}
protected void arcImpl(float x, float y, float w, float h,
float start, float stop) {
// 0 to 90 in java would be 0 to -90 for p5 renderer
// but that won't work, so -90 to 0?
if (stop - start >= TWO_PI) {
start = 0;
stop = 360;
} else {
start = -start * RAD_TO_DEG;
stop = -stop * RAD_TO_DEG;
// ok to do this because already checked for NaN
while (start < 0) {
start += 360;
stop += 360;
}
if (start > stop) {
float temp = start;
start = stop;
stop = temp;
}
}
float span = stop - start;
// stroke as Arc2D.OPEN, fill as Arc2D.PIE
if (fill) {
//System.out.println("filla");
arc.setArc(x, y, w, h, start, span, Arc2D.PIE);
fill_shape(arc);
}
if (stroke) {
//System.out.println("strokey");
arc.setArc(x, y, w, h, start, span, Arc2D.OPEN);
stroke_shape(arc);
}
}
//////////////////////////////////////////////////////////////
/** Ignored (not needed) in Java 2D. */
public void bezierDetail(int detail) {
}
/** Ignored (not needed) in Java 2D. */
public void curveDetail(int detail) {
}
//////////////////////////////////////////////////////////////
/**
* Handle renderer-specific image drawing.
*/
protected void imageImpl(PImage who,
float x1, float y1, float x2, float y2,
int u1, int v1, int u2, int v2) {
if (who.cache == null) {
who.cache = new ImageCache(who);
//who.updatePixels(); // mark the whole thing for update
who.modified = true;
}
ImageCache cash = (ImageCache) who.cache;
// if image previously was tinted, or the color changed
// or the image was tinted, and tint is now disabled
if ((tint && !cash.tinted) ||
(tint && (cash.tintedColor != tintColor)) ||
(!tint && cash.tinted)) {
// for tint change, mark all pixels as needing update
who.updatePixels();
}
if (who.modified) {
cash.update();
who.modified = false;
}
g2.drawImage(((ImageCache) who.cache).image,
(int) x1, (int) y1, (int) x2, (int) y2,
u1, v1, u2, v2, null);
}
class ImageCache {
PImage source;
boolean tinted;
int tintedColor;
int tintedPixels[];
BufferedImage image;
public ImageCache(PImage source) {
this.source = source;
// even if RGB, set the image type to ARGB, because the
// image may have an alpha value for its tint().
int type = BufferedImage.TYPE_INT_ARGB;
image = new BufferedImage(source.width, source.height, type);
}
public void update() { //boolean t, int argb) {
if ((source.format == ARGB) || (source.format == RGB)) {
if (tint) {
// create tintedPixels[] if necessary
if (tintedPixels == null) {
tintedPixels = new int[source.width * source.height];
}
//int argb2 = tintColor;
int a2 = (tintColor >> 24) & 0xff;
int r2 = (tintColor >> 16) & 0xff;
int g2 = (tintColor >> 8) & 0xff;
int b2 = (tintColor) & 0xff;
//System.out.println("a2 is " + a2);
// multiply each of the color components into tintedPixels
// if straight RGB image, don't bother multiplying
// (also avoids problems if high bits not set)
if (source.format == RGB) {
int alpha = a2 << 24;
for (int i = 0; i < tintedPixels.length; i++) {
int argb1 = source.pixels[i];
int r1 = (argb1 >> 16) & 0xff;
int g1 = (argb1 >> 8) & 0xff;
int b1 = (argb1) & 0xff;
tintedPixels[i] = alpha |
(((r2 * r1) & 0xff00) << 8) |
((g2 * g1) & 0xff00) |
(((b2 * b1) & 0xff00) >> 8);
}
} else {
for (int i = 0; i < tintedPixels.length; i++) {
int argb1 = source.pixels[i];
int a1 = (argb1 >> 24) & 0xff;
int r1 = (argb1 >> 16) & 0xff;
int g1 = (argb1 >> 8) & 0xff;
int b1 = (argb1) & 0xff;
tintedPixels[i] =
(((a2 * a1) & 0xff00) << 16) |
(((r2 * r1) & 0xff00) << 8) |
((g2 * g1) & 0xff00) |
(((b2 * b1) & 0xff00) >> 8);
}
}
tinted = true;
tintedColor = tintColor;
// finally, do a setRGB based on tintedPixels
image.setRGB(0, 0, source.width, source.height,
tintedPixels, 0, source.width);
} else { // no tint
// just do a setRGB like before
// (and we'll just hope that the high bits are set)
image.setRGB(0, 0, source.width, source.height,
source.pixels, 0, source.width);
}
} else if (source.format == ALPHA) {
if (tintedPixels == null) {
tintedPixels = new int[source.width * source.height];
}
int lowbits = tintColor & 0x00ffffff;
if (((tintColor >> 24) & 0xff) >= 254) {
// no actual alpha to the tint, set the image's alpha
// as the high 8 bits, and use the color as the low 24 bits
for (int i = 0; i < tintedPixels.length; i++) {
// don't bother with the math if value is zero
tintedPixels[i] = (source.pixels[i] == 0) ?
0 : (source.pixels[i] << 24) | lowbits;
}
} else {
// multiply each image alpha by the tint alpha
int alphabits = (tintColor >> 24) & 0xff;
for (int i = 0; i < tintedPixels.length; i++) {
tintedPixels[i] = (source.pixels[i] == 0) ?
0 : (((alphabits * source.pixels[i]) & 0xFF00) << 16) | lowbits;
}
}
// mark the pixels for next time
tinted = true;
tintedColor = tintColor;
// finally, do a setRGB based on tintedPixels
image.setRGB(0, 0, source.width, source.height,
tintedPixels, 0, source.width);
}
}
}
//////////////////////////////////////////////////////////////
public float textAscent() {
if (textFontNative == null) {
return super.textAscent();
}
return textFontNativeMetrics.getAscent();
}
public float textDescent() {
if (textFontNative == null) {
return super.textDescent();
}
return textFontNativeMetrics.getDescent();
}
/**
* Same as parent, but override for native version of the font.
* <p/>
* Also gets called by textFont, so the metrics
* will get recorded properly.
*/
public void textSize(float size) {
// if a native version available, subset this font
if (textFontNative != null) {
textFontNative = textFontNative.deriveFont(size);
g2.setFont(textFontNative);
textFontNativeMetrics = g2.getFontMetrics(textFontNative);
}
// take care of setting the textSize and textLeading vars
// this has to happen second, because it calls textAscent()
// (which requires the native font metrics to be set)
super.textSize(size);
}
protected float textWidthImpl(char buffer[], int start, int stop) {
if (textFontNative == null) {
//System.out.println("native is null");
return super.textWidthImpl(buffer, start, stop);
}
// maybe should use one of the newer/fancier functions for this?
int length = stop - start;
return textFontNativeMetrics.charsWidth(buffer, start, length);
}
protected void textLinePlacedImpl(char buffer[], int start, int stop,
float x, float y) {
if (textFontNative == null) {
super.textLinePlacedImpl(buffer, start, stop, x, y);
return;
}
/*
// save the current setting for text smoothing. note that this is
// different from the smooth() function, because the font smoothing
// is controlled when the font is created, not now as it's drawn.
// fixed a bug in 0116 that handled this incorrectly.
Object textAntialias =
g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
// override the current text smoothing setting based on the font
// (don't change the global smoothing settings)
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
textFont.smooth ?
RenderingHints.VALUE_ANTIALIAS_ON :
RenderingHints.VALUE_ANTIALIAS_OFF);
*/
Object antialias =
g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
if (antialias == null) {
// if smooth() and noSmooth() not called, this will be null (0120)
antialias = RenderingHints.VALUE_ANTIALIAS_DEFAULT;
}
// override the current smoothing setting based on the font
// also changes global setting for antialiasing, but this is because it's
// not possible to enable/disable them independently in some situations.
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
textFont.smooth ?
RenderingHints.VALUE_ANTIALIAS_ON :
RenderingHints.VALUE_ANTIALIAS_OFF);
g2.setColor(fillColorObject);
// better to use drawString(float, float)?
int length = stop - start;
g2.drawChars(buffer, start, length, (int) (x + 0.5f), (int) (y + 0.5f));
// this didn't seem to help the scaling issue
// and creates garbage because of the new temporary object
//java.awt.font.GlyphVector gv = textFontNative.createGlyphVector(g2.getFontRenderContext(), new String(buffer, start, stop));
//g2.drawGlyphVector(gv, x, y);
// return to previous smoothing state if it was changed
//g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialias);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialias);
textX = x + textWidthImpl(buffer, start, stop);
textY = y;
textZ = 0; // this will get set by the caller if non-zero
}
//////////////////////////////////////////////////////////////
public void translate(float tx, float ty) {
g2.translate(tx, ty);
}
public void rotate(float angle) {
g2.rotate(angle);
}
public void scale(float s) {
g2.scale(s, s);
}
public void scale(float sx, float sy) {
g2.scale(sx, sy);
}
//////////////////////////////////////////////////////////////
public void pushMatrix() {
if (transformCount == transformStack.length) {
throw new RuntimeException("pushMatrix() cannot use push more than " +
transformStack.length + " times");
}
transformStack[transformCount] = g2.getTransform();
transformCount++;
}
public void popMatrix() {
if (transformCount == 0) {
throw new RuntimeException("missing a popMatrix() " +
"to go with that pushMatrix()");
}
transformCount--;
g2.setTransform(transformStack[transformCount]);
}
public void resetMatrix() {
g2.setTransform(new AffineTransform());
}
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
g2.transform(new AffineTransform(n00, n10, n01, n11, n02, n12));
}
public void loadMatrix() {
g2.getTransform().getMatrix(transform);
m00 = (float) transform[0];
m01 = (float) transform[2];
m02 = (float) transform[4];
m10 = (float) transform[1];
m11 = (float) transform[3];
m12 = (float) transform[5];
}
public float screenX(float x, float y) {
loadMatrix();
return super.screenX(x, y);
//g2.getTransform().getMatrix(transform);
//return (float)transform[0]*x + (float)transform[2]*y + (float)transform[4];
}
public float screenY(float x, float y) {
loadMatrix();
return super.screenY(x, y);
//g2.getTransform().getMatrix(transform);
//return (float)transform[1]*x + (float)transform[3]*y + (float)transform[5];
}
//////////////////////////////////////////////////////////////
protected void tintFromCalc() {
super.tintFromCalc();
// TODO actually implement tinted images
tintColorObject = new Color(tintColor, true);
}
protected void fillFromCalc() {
super.fillFromCalc();
fillColorObject = new Color(fillColor, true);
fillGradient = false;
}
protected void strokeFromCalc() {
super.strokeFromCalc();
strokeColorObject = new Color(strokeColor, true);
- strokeGradient = false;
+ strokeGradient = false;
}
//////////////////////////////////////////////////////////////
public void strokeWeight(float weight) {
super.strokeWeight(weight);
set_stroke();
}
public void strokeJoin(int join) {
super.strokeJoin(join);
set_stroke();
}
public void strokeCap(int cap) {
super.strokeCap(cap);
set_stroke();
}
protected void set_stroke() {
int cap = BasicStroke.CAP_BUTT;
if (strokeCap == ROUND) {
cap = BasicStroke.CAP_ROUND;
} else if (strokeCap == PROJECT) {
cap = BasicStroke.CAP_SQUARE;
}
int join = BasicStroke.JOIN_BEVEL;
if (strokeJoin == MITER) {
join = BasicStroke.JOIN_MITER;
} else if (strokeJoin == ROUND) {
join = BasicStroke.JOIN_ROUND;
}
g2.setStroke(new BasicStroke(strokeWeight, cap, join));
}
//////////////////////////////////////////////////////////////
public void background(PImage image) {
if ((image.width != width) || (image.height != height)) {
throw new RuntimeException("background image must be " +
"the same size as your application");
}
if ((image.format != RGB) && (image.format != ARGB)) {
throw new RuntimeException("background images should be RGB or ARGB");
}
// draw the image to screen without any transformations
set(0, 0, image);
}
public void clear() {
// the only way to properly clear the screen is to re-allocate
if (backgroundAlpha) {
// clearRect() doesn't work because it just makes everything black.
// instead, just wipe out the canvas to its transparent original
allocate();
}
// in case people do transformations before background(),
// need to handle this with a push/reset/pop
pushMatrix();
resetMatrix();
g2.setColor(new Color(backgroundColor, backgroundAlpha));
g2.fillRect(0, 0, width, height);
popMatrix();
}
//////////////////////////////////////////////////////////////
// FROM PIMAGE
public void smooth() {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
public void noSmooth() {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
+ g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
//////////////////////////////////////////////////////////////
public void beginRaw(PGraphics recorderRaw) {
throw new RuntimeException("beginRaw() not available with this renderer");
}
public void endRaw() {
}
//////////////////////////////////////////////////////////////
public void loadPixels() {
if ((pixels == null) || (pixels.length != width * height)) {
pixels = new int[width * height];
}
//((BufferedImage) image).getRGB(0, 0, width, height, pixels, 0, width);
WritableRaster raster = ((BufferedImage) image).getRaster();
raster.getDataElements(0, 0, width, height, pixels);
}
/**
* Update the pixels[] buffer to the PGraphics image.
* <P>
* Unlike in PImage, where updatePixels() only requests that the
* update happens, in PGraphicsJava2D, this will happen immediately.
*/
public void updatePixels() {
//updatePixels(0, 0, width, height);
WritableRaster raster = ((BufferedImage) image).getRaster();
raster.setDataElements(0, 0, width, height, pixels);
}
/**
* Update the pixels[] buffer to the PGraphics image.
* <P>
* Unlike in PImage, where updatePixels() only requests that the
* update happens, in PGraphicsJava2D, this will happen immediately.
*/
public void updatePixels(int x, int y, int c, int d) {
if ((x == 0) && (y == 0) && (c == width) && (d == height)) {
updatePixels();
} else {
throw new RuntimeException("updatePixels(x, y, c, d) not implemented");
}
/*
((BufferedImage) image).setRGB(x, y,
(imageMode == CORNER) ? c : (c - x),
(imageMode == CORNER) ? d : (d - y),
pixels, 0, width);
WritableRaster raster = ((BufferedImage) image).getRaster();
raster.setDataElements(x, y,
(imageMode == CORNER) ? c : (c - x),
(imageMode == CORNER) ? d : (d - y),
pixels);
*/
}
//////////////////////////////////////////////////////////////
static int getset[] = new int[1];
public int get(int x, int y) {
if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0;
//return ((BufferedImage) image).getRGB(x, y);
WritableRaster raster = ((BufferedImage) image).getRaster();
raster.getDataElements(x, y, getset);
return getset[0];
}
public PImage get(int x, int y, int w, int h) {
if (imageMode == CORNERS) { // if CORNER, do nothing
// w/h are x2/y2 in this case, bring em down to size
w = (w - x);
h = (h - x);
}
if (x < 0) {
w += x; // clip off the left edge
x = 0;
}
if (y < 0) {
h += y; // clip off some of the height
y = 0;
}
if (x + w > width) w = width - x;
if (y + h > height) h = height - y;
PImage output = new PImage(w, h);
// oops, the last parameter is the scan size of the *target* buffer
//((BufferedImage) image).getRGB(x, y, w, h, output.pixels, 0, w);
WritableRaster raster = ((BufferedImage) image).getRaster();
raster.getDataElements(x, y, w, h, output.pixels);
return output;
}
/**
* Grab a copy of the current pixel buffer.
*/
public PImage get() {
/*
PImage outgoing = new PImage(width, height);
((BufferedImage) image).getRGB(0, 0, width, height,
outgoing.pixels, 0, width);
return outgoing;
*/
return get(0, 0, width, height);
}
public void set(int x, int y, int argb) {
if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return;
//((BufferedImage) image).setRGB(x, y, argb);
getset[0] = argb;
WritableRaster raster = ((BufferedImage) image).getRaster();
raster.setDataElements(x, y, getset);
}
// fully debugged
/*
public void set(int dx, int dy, PImage src) {
int sx = 0;
int sy = 0;
int sw = src.width;
int sh = src.height;
if (dx < 0) { // off left edge
sx -= dx;
sw += dx;
dx = 0;
}
if (dy < 0) { // off top edge
sy -= dy;
sh += dy;
dy = 0;
}
if (dx + sw > width) { // off right edge
sw = width - dx;
}
if (dy + sh > height) { // off bottom edge
sh = height - dy;
}
//System.out.println(dx + " " + dy + " " +
// sx + " " + sy + " " + sw + " " + sh + " " +
// src.pixels + " " + 0 + " " + src.width);
BufferedImage bi = (BufferedImage) image;
bi.setRGB(dx, dy, sw, sh, src.pixels, sy*src.width + sx, src.width);
}
*/
protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh,
PImage src) {
//BufferedImage bi = (BufferedImage) image;
//bi.setRGB(dx, dy, sw, sh, src.pixels, sy*src.width + sx, src.width);
WritableRaster raster = ((BufferedImage) image).getRaster();
if ((sx == 0) && (sy == 0) && (sw == src.width) && (sh == src.height)) {
raster.setDataElements(dx, dy, src.width, src.height, src.pixels);
} else {
int mode = src.imageMode;
src.imageMode = CORNERS;
PImage temp = src.get(sx, sy, sw, sh);
src.imageMode = mode;
raster.setPixels(dx, dy, temp.width, temp.height, temp.pixels);
}
}
//////////////////////////////////////////////////////////////
public void mask(int alpha[]) {
throw new RuntimeException("mask() cannot be used with JAVA2D");
}
public void mask(PImage alpha) {
throw new RuntimeException("mask() cannot be used with JAVA2D");
}
//////////////////////////////////////////////////////////////
public void filter(int kind) {
loadPixels();
super.filter(kind);
updatePixels();
}
public void filter(int kind, float param) {
loadPixels();
super.filter(kind, param);
updatePixels();
}
//////////////////////////////////////////////////////////////
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if ((sw != dw) || (sh != dh)) {
// use slow version if changing size
copy(this, sx, sy, sw, sh, dx, dy, dw, dh);
}
if (imageMode == CORNERS) {
sw -= sx;
sh -= sy;
}
dx = dx - sx; // java2d's "dx" is the delta, not dest
dy = dy - sy;
g2.copyArea(sx, sy, sw, sh, dx, dy);
}
public void copy(PImage src,
int sx1, int sy1, int sx2, int sy2,
int dx1, int dy1, int dx2, int dy2) {
loadPixels();
super.copy(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2);
updatePixels();
}
//////////////////////////////////////////////////////////////
/*
public void blend(PImage src, int sx, int sy, int dx, int dy, int mode) {
loadPixels();
super.blend(src, sx, sy, dx, dy, mode);
updatePixels();
}
public void blend(int sx, int sy, int dx, int dy, int mode) {
loadPixels();
super.blend(sx, sy, dx, dy, mode);
updatePixels();
}
*/
public void blend(int sx1, int sy1, int sx2, int sy2,
int dx1, int dy1, int dx2, int dy2, int mode) {
loadPixels();
super.blend(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode);
updatePixels();
}
public void blend(PImage src, int sx1, int sy1, int sx2, int sy2,
int dx1, int dy1, int dx2, int dy2, int mode) {
loadPixels();
super.blend(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode);
updatePixels();
}
//////////////////////////////////////////////////////////////
public void save(String filename) {
//System.out.println("start load");
loadPixels();
//System.out.println("end load, start save");
super.save(filename);
//System.out.println("done with save");
}
}
| false | false | null | null |
diff --git a/src/com/imaginea/android/sugarcrm/WizardActivity.java b/src/com/imaginea/android/sugarcrm/WizardActivity.java
index fb591bd..d34e432 100644
--- a/src/com/imaginea/android/sugarcrm/WizardActivity.java
+++ b/src/com/imaginea/android/sugarcrm/WizardActivity.java
@@ -1,545 +1,544 @@
package com.imaginea.android.sugarcrm;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.imaginea.android.sugarcrm.provider.DatabaseHelper;
import com.imaginea.android.sugarcrm.util.ModuleField;
import com.imaginea.android.sugarcrm.util.RestUtil;
import com.imaginea.android.sugarcrm.util.SugarCrmException;
import com.imaginea.android.sugarcrm.util.Util;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WizardActivity extends Activity {
private final String LOG_TAG = "WizardActivity";
// In-order list of wizard steps to present to user. These are layout resource ids.
public final static int[] STEPS = new int[] { R.layout.url_config_wizard,
R.layout.login_activity };
protected ViewFlipper flipper = null;
protected Button next, prev;
private SugarCrmApp app;
private boolean isValidUrl = false;
private UrlValidationTask mUrlTask;
private AuthenticationTask mAuthTask;
private LayoutInflater mInflater;
private int wizardState;
private Menu mMenu;
private ProgressDialog progressDialog;
private TextView mHeaderTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
app = ((SugarCrmApp) getApplicationContext());
if (app.getSessionId() != null) {
setResult(RESULT_OK);
finish();
}
final String restUrl = SugarCrmSettings.getSugarRestUrl(WizardActivity.this);
final String usr = SugarCrmSettings.getUsername(WizardActivity.this).toString();
final String pwd = SugarCrmSettings.getPassword(WizardActivity.this).toString();
final boolean isPwdRemembered = SugarCrmSettings.isPasswordSaved(WizardActivity.this);
Log.i(LOG_TAG, "restUrl - " + restUrl + "\n usr - " + usr + "\n pwd - " + pwd
+ "\n rememberedPwd - " + isPwdRemembered);
mInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// if the password is already saved
if (isPwdRemembered && !TextUtils.isEmpty(restUrl)) {
Log.i(LOG_TAG, "Password is remembered!");
wizardState = Util.URL_USER_PWD_AVAILABLE;
mAuthTask = new AuthenticationTask();
mAuthTask.execute(usr, pwd, isPwdRemembered);
} else {
// if the REST url is not available
if (TextUtils.isEmpty(restUrl)) {
Log.i(LOG_TAG, "REST URL is not available!");
wizardState = Util.URL_NOT_AVAILABLE;
setFlipper();
mHeaderTextView.setText(R.string.sugarCrmUrlHeader);
// inflate both url layout and username_password layout
for (int layout : STEPS) {
View step = mInflater.inflate(layout, this.flipper, false);
this.flipper.addView(step);
}
- } else {
-
- mHeaderTextView.setText(R.string.login);
+ } else {
// if the username is not available
if (TextUtils.isEmpty(usr)) {
Log.i(LOG_TAG, "REST URL is available but not the username!");
wizardState = Util.URL_AVAILABLE;
setFlipper();
View loginView = inflateLoginView();
} else {
Log.i(LOG_TAG, "REST URL and username are available!");
wizardState = Util.URL_USER_AVAILABLE;
setFlipper();
View loginView = inflateLoginView();
EditText editTextUser = (EditText) loginView.findViewById(R.id.loginUsername);
editTextUser.setText(usr);
}
+ mHeaderTextView.setText(R.string.login);
}
this.updateButtons(wizardState);
}
}
private View inflateLoginView() {
// inflate only the username_password layout
View loginView = mInflater.inflate(STEPS[1], this.flipper, false);
this.flipper.addView(loginView);
return loginView;
}
private void setFlipper() {
setContentView(R.layout.sugar_wizard);
mHeaderTextView = (TextView) findViewById(R.id.headerText);
this.flipper = (ViewFlipper) this.findViewById(R.id.wizardFlipper);
prev = (Button) this.findViewById(R.id.actionPrev);
next = (Button) this.findViewById(R.id.actionNext);
final int finalState = wizardState;
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if (isFirstDisplayed()) {
if (flipper.getCurrentView().getId() == R.id.urlStep) {
String url = ((EditText) flipper.findViewById(R.id.wizardUrl)).getText().toString();
TextView tv = (TextView) flipper.findViewById(R.id.wizardUrlStatus);
if (TextUtils.isEmpty(url)) {
tv.setText(getString(R.string.validFieldMsg)
+ " REST url \n\n"
+ getBaseContext().getString(R.string.sampleRestUrl));
} else {
mUrlTask = new UrlValidationTask();
mUrlTask.execute(url);
}
} else if (flipper.getCurrentView().getId() == R.id.signInStep) {
handleLogin(v);
} else {
// show next step and update buttons
flipper.showNext();
updateButtons(finalState);
}
}
});
prev.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (isFirstDisplayed()) {
// user walked past beginning of wizard, so return that they cancelled
WizardActivity.this.setResult(Activity.RESULT_CANCELED);
WizardActivity.this.finish();
} else {
// show previous step and update buttons
flipper.showPrevious();
updateButtons(finalState);
}
}
});
}
public void handleLogin(View view) {
String usr = ((EditText) flipper.findViewById(R.id.loginUsername)).getText().toString();
String pwd = ((EditText) flipper.findViewById(R.id.loginPassword)).getText().toString();
boolean rememberPwd = ((CheckBox) flipper.findViewById(R.id.loginRememberPwd)).isChecked();
TextView tv = (TextView) flipper.findViewById(R.id.loginStatusMsg);
String msg = "";
if (TextUtils.isEmpty(usr) || TextUtils.isEmpty(pwd)) {
msg = getString(R.string.validFieldMsg) + "username and password.\n";
tv.setText(msg);
} else {
mAuthTask = new AuthenticationTask();
mAuthTask.execute(usr, pwd, rememberPwd);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.i(LOG_TAG, "onNewIntent");
}
@Override
protected void onPause() {
super.onPause();
Log.i(LOG_TAG, "onPause");
}
@Override
protected void onResume() {
super.onResume();
Log.i(LOG_TAG, "onResume");
}
protected boolean isFirstDisplayed() {
return (flipper.getDisplayedChild() == 0);
}
protected boolean isLastDisplayed() {
return (flipper.getDisplayedChild() == flipper.getChildCount() - 1);
}
protected void updateButtons(int state) {
/*
* Log.i(LOG_TAG, "currentView Id : " + flipper.getCurrentView().getId()); Log.i(LOG_TAG,
* "urlView Id : " + R.id.urlStep); Log.i(LOG_TAG, "signInView Id : " + R.id.signInStep);
*/
if (flipper.getCurrentView().getId() == R.id.urlStep) {
prev.setVisibility(View.INVISIBLE);
next.setText("Next");
next.setVisibility(View.VISIBLE);
} else if (flipper.getCurrentView().getId() == R.id.signInStep) {
if (flipper.getChildCount() == 2) {
prev.setVisibility(View.VISIBLE);
next.setText("Finish");
} else {
next.setText("Sign In");
}
next.setVisibility(View.VISIBLE);
}
if (state == Util.URL_USER_PWD_AVAILABLE) {
next.setVisibility(View.INVISIBLE);
}
}
// Task to validate the REST URL
class UrlValidationTask extends AsyncTask<Object, Void, Object> {
private boolean hasExceptions = false;
private String sceDesc;
@Override
protected Object doInBackground(Object... urls) {
try {
isValidUrl = isValidUrl(urls[0].toString());
} catch (SugarCrmException sce) {
hasExceptions = true;
sceDesc = sce.getDescription();
Log.e(LOG_TAG, sce.getDescription(), sce);
}
return urls[0].toString();
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPostExecute(Object restUrl) {
super.onPostExecute(restUrl);
if (isCancelled())
return;
TextView tv = (TextView) flipper.findViewById(R.id.wizardUrlStatus);
if (hasExceptions) {
tv.setText("Invalid Url : "
+ sceDesc
+ "\n\n Please check the url you have entered! \n\n"
+ getBaseContext().getString(R.string.sampleRestUrl));
} else {
if (isValidUrl) {
tv.setText("VALID URL");
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(WizardActivity.this);
Editor editor = sp.edit();
editor.putString(Util.PREF_REST_URL, restUrl.toString());
editor.commit();
// show next step and update buttons
flipper.showNext();
updateButtons(wizardState);
} else {
tv.setText("Invalid Url : "
+ "\n\n Please check the url you have entered! \n\n"
+ getBaseContext().getString(R.string.sampleRestUrl));
}
}
}
protected boolean isValidUrl(String restUrl) throws SugarCrmException {
HttpClient httpClient = new DefaultHttpClient();
try {
HttpGet reqUrl = new HttpGet(restUrl);
HttpResponse response = httpClient.execute(reqUrl);
int statusCode = response.getStatusLine().getStatusCode();
return statusCode == 200 ? true : false;
} catch (IllegalStateException ise) {
throw new SugarCrmException(ise.getMessage());
} catch (ClientProtocolException cpe) {
throw new SugarCrmException(cpe.getMessage());
} catch (IOException ioe) {
throw new SugarCrmException(ioe.getMessage());
} catch (Exception e) {
throw new SugarCrmException(e.getMessage());
}
}
}
// Task to authenticate
class AuthenticationTask extends AsyncTask<Object, Void, Object> {
private String usr;
private String pwd;
private boolean rememberPwd;
boolean hasExceptions = false;
private String sceDesc;
// TODO: remove this moduleNames from here and use the one from DB
// reference to the module names
private String[] moduleNames = { "Accounts", "Contacts", "Leads", "Opportunities" };
@Override
protected Object doInBackground(Object... args) {
/*
* arg[0] : String - username arg[1] : String - password arg[2] : boolean -
* rememberPassword
*/
usr = args[0].toString();
pwd = args[1].toString();
rememberPwd = Boolean.valueOf(args[2].toString());
String url = SugarCrmSettings.getSugarRestUrl(getBaseContext());
String sessionId = null;
try {
sessionId = RestUtil.loginToSugarCRM(url, usr, pwd);
Log.i(LOG_TAG, "SessionId - " + sessionId);
HashMap<String, HashMap<String, ModuleField>> moduleNameVsFields = new HashMap<String, HashMap<String, ModuleField>>();
for (String moduleName : moduleNames) {
String[] fields = {};
List<ModuleField> moduleFields = RestUtil.getModuleFields(url, sessionId, moduleName, fields);
HashMap<String, ModuleField> nameVsModuleField = new HashMap<String, ModuleField>();
for (int i = 0; i < moduleFields.size(); i++) {
nameVsModuleField.put(moduleFields.get(i).getName(), moduleFields.get(i));
}
moduleNameVsFields.put(moduleName, nameVsModuleField);
}
DatabaseHelper.moduleFields = moduleNameVsFields;
} catch (SugarCrmException sce) {
hasExceptions = true;
sceDesc = sce.getDescription();
}
return sessionId;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (wizardState != Util.URL_USER_PWD_AVAILABLE) {
progressDialog = ProgressDialog.show(WizardActivity.this, "Sugar CRM", "Processing", true, false);
}
}
@Override
protected void onPostExecute(Object sessionId) {
super.onPostExecute(sessionId);
if (isCancelled())
return;
if (hasExceptions) {
if (wizardState != Util.URL_USER_PWD_AVAILABLE) {
TextView tv = (TextView) flipper.findViewById(R.id.loginStatusMsg);
tv.setText(sceDesc);
progressDialog.cancel();
} else {
setFlipper();
View loginView = inflateLoginView();
next.setText("Sign In");
next.setVisibility(View.VISIBLE);
EditText editTextUser = (EditText) loginView.findViewById(R.id.loginUsername);
editTextUser.setText(usr);
TextView tv = (TextView) flipper.findViewById(R.id.loginStatusMsg);
tv.setText(sceDesc);
}
} else {
// save the sessionId in the application context after the succesful login
app.setSessionId(sessionId.toString());
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(WizardActivity.this);
Editor editor = sp.edit();
editor.putString(Util.PREF_USERNAME, usr);
if (rememberPwd) {
editor.putString(Util.PREF_PASSWORD, pwd);
editor.putBoolean(Util.PREF_REMEMBER_PASSWORD, true);
}
editor.commit();
if (wizardState != Util.URL_USER_PWD_AVAILABLE) {
progressDialog.cancel();
}
setResult(RESULT_OK);
finish();
}
}
}
// Not using this anywhere
private void showAlertDialog() {
final String usr = SugarCrmSettings.getUsername(WizardActivity.this).toString();
final View loginView = mInflater.inflate(R.layout.login_activity, this.flipper, false);
EditText editTextUser = (EditText) loginView.findViewById(R.id.loginUsername);
editTextUser.setText(usr);
editTextUser.setEnabled(false);
Button loginBtn = (Button) loginView.findViewById(R.id.loginOk);
loginBtn.setVisibility(View.VISIBLE);
final AlertDialog loginDialog = new AlertDialog.Builder(WizardActivity.this).setTitle(R.string.password).setView(loginView).setPositiveButton(R.string.signIn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
EditText etPwd = ((EditText) loginView.findViewById(R.id.loginPassword));
boolean rememberPwd = ((CheckBox) loginView.findViewById(R.id.loginRememberPwd)).isChecked();
mAuthTask = new AuthenticationTask();
mAuthTask.execute(usr, etPwd.getText().toString(), rememberPwd);
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
WizardActivity.this.finish();
}
}).create();
loginDialog.show();
}
/**
* new method for back presses in android 2.0, instead of the standard mechanism defined in the
* docs to handle legacy applications we use version code to handle back button... implement
* onKeyDown for older versions and use Override on that.
*/
public void onBackPressed() {
setResult(RESULT_CANCELED);
finish();
}
/*
* @Override
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (Log.isLoggable(LOG_TAG, Log.VERBOSE))
Log.v(LOG_TAG, "OnBackButton: onKeyDown " + Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ECLAIR) {
setResult(RESULT_CANCELED);
finish();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Hold on to this
mMenu = menu;
// Inflate the currently selected menu XML resource.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent myIntent = new Intent(WizardActivity.this, SugarCrmSettings.class);
WizardActivity.this.startActivity(myIntent);
return true;
}
return false;
}
}
| false | false | null | null |
diff --git a/src/org/broad/igv/bbfile/ZoomDataBlock.java b/src/org/broad/igv/bbfile/ZoomDataBlock.java
index 7f7dda63a..cb8278aef 100755
--- a/src/org/broad/igv/bbfile/ZoomDataBlock.java
+++ b/src/org/broad/igv/bbfile/ZoomDataBlock.java
@@ -1,216 +1,216 @@
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
package org.broad.igv.bbfile;
import net.sf.samtools.seekablestream.SeekableStream;
import org.apache.log4j.Logger;
import org.broad.igv.util.CompressionUtils;
import org.broad.tribble.util.LittleEndianInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by IntelliJ IDEA.
* User: Owner
* Date: May 5, 2010
* Time: 8:27:56 PM
* To change this template use File | Settings | File Templates.
*/
/*
* Container class for reading and storing a block of zoom level data records.
* */
public class ZoomDataBlock {
private static Logger log = Logger.getLogger(ZoomDataBlock.class);
// Bed data block access variables - for reading in bed records from a file
private long fileOffset; // data block file offset
private long dataBlockSize; // byte size for data block specified in the R+ leaf
private boolean isLowToHigh; // if true, data is low to high byte order; else high to low
// defines the zoom level source chromosomes
private int zoomLevel; // zoom level for the R+ chromosome data location tree
private HashMap<Integer, String> chromosomeMap; // map of chromosome ID's and corresponding names
private RPTreeLeafNodeItem leafHitItem; //R+ leaf item with chromosome region and file data location
// Provides uncompressed byte stream data reader
private byte[] zoomBuffer; // buffer containing leaf block data uncompressed
private int remDataSize; // number of unread decompressed data bytes
// byte stream readers
private LittleEndianInputStream lbdis = null; // low to high byte stream reader
private DataInputStream dis = null; // high to low byte stream reader
// Bed data extraction members
private ArrayList<ZoomDataRecord> zoomDataList; // array of zoom level data
/*
* Constructor for Bed data block reader.
*
* Parameters:
* zoomLevel - zoom level for data block
* fis - file input stream handle
* leafItem - R+ tree leaf item containing block data file location
* chromIDTree - B+ chromosome index tree returns chromosome ID's for names
* isLowToHigh - byte order is low to high if true; else high to low
* uncompressBufSize - byte size for decompression buffer; else 0 for uncompressed
* */
public ZoomDataBlock(int zoomLevel, SeekableStream fis, RPTreeLeafNodeItem leafHitItem,
HashMap<Integer, String> chromosomeMap,
boolean isLowToHigh, int uncompressBufSize,
CompressionUtils compressionUtils) {
this.zoomLevel = zoomLevel;
this.leafHitItem = leafHitItem;
this.chromosomeMap = chromosomeMap;
this.isLowToHigh = isLowToHigh;
fileOffset = this.leafHitItem.getDataOffset();
dataBlockSize = this.leafHitItem.geDataSize();
byte[] buffer = new byte[(int) dataBlockSize];
// read Bed data block into a buffer
try {
fis.seek(fileOffset);
fis.readFully(buffer);
// decompress if necessary - the buffer size is 0 for uncomressed data
// Note: BBFile Table C specifies a decompression buffer size
if (uncompressBufSize > 0) {
zoomBuffer = compressionUtils.decompress(buffer, uncompressBufSize);
}
else {
zoomBuffer = buffer; // use uncompressed read buffer directly
}
} catch (IOException ex) {
- log.error("Error reading Zoom level " + this.zoomLevel + " data for leaf item ", ex);
- String error = String.format("Error reading zoom level %d data for leaf item %d\n", this.zoomLevel);
+ String error = String.format("Error reading zoom level %d data for leaf item\n", this.zoomLevel);
+ log.error(error, ex);
throw new RuntimeException(error, ex);
}
// wrap the bed buffer as an input stream
if (this.isLowToHigh)
lbdis = new LittleEndianInputStream(new ByteArrayInputStream(zoomBuffer));
else
dis = new DataInputStream(new ByteArrayInputStream(zoomBuffer));
// initialize unread data size
remDataSize = zoomBuffer.length;
// use method getZoomData to extract block data
}
/*
* Method returns all zoom level data within the decompressed block buffer
*
* Parameters:
* selectionRegion - chromosome region for selecting zoom level data records
* contained - indicates selected data must be contained in selection region
* if true, else may intersect selection region
*
* Returns:
* zoom data records in the data block
*
* Note: Remaining bytes to data block are used to determine end of reading
* since a zoom record count for the data block is not known.
* */
public ArrayList<ZoomDataRecord> getZoomData(RPChromosomeRegion selectionRegion,
boolean contained) {
int chromID, chromStart, chromEnd, validCount;
float minVal, maxVal, sumData, sumSquares;
int itemHitValue;
int recordNumber = 0;
// allocate the bed feature array list
zoomDataList = new ArrayList<ZoomDataRecord>();
// check if all leaf items are selection hits
RPChromosomeRegion itemRegion = new RPChromosomeRegion(leafHitItem.getChromosomeBounds());
int leafHitValue = itemRegion.compareRegions(selectionRegion);
try {
//for(int index = 0; mRemDataSize >= ZoomDataRecord.RECORD_SIZE; ++index) {
for (int index = 0; remDataSize > 0; ++index) {
recordNumber = index + 1;
if (isLowToHigh) { // buffer stream arranged low to high bytes
chromID = lbdis.readInt();
chromStart = lbdis.readInt();
chromEnd = lbdis.readInt();
validCount = lbdis.readInt();
minVal = lbdis.readFloat();
maxVal = lbdis.readFloat();
sumData = lbdis.readFloat();
sumSquares = lbdis.readFloat();
} else { // buffer stream arranged high to low bytes
chromID = dis.readInt();
chromStart = dis.readInt();
chromEnd = dis.readInt();
validCount = dis.readInt();
minVal = dis.readFloat();
maxVal = dis.readFloat();
sumData = dis.readFloat();
sumSquares = dis.readFloat();
}
if (leafHitValue == 0) { // contained leaf region always a hit
String chromName = chromosomeMap.get(chromID);
ZoomDataRecord zoomRecord = new ZoomDataRecord(zoomLevel, recordNumber, chromName,
chromID, chromStart, chromEnd, validCount, minVal, maxVal, sumData, sumSquares);
zoomDataList.add(zoomRecord);
} else { // test for hit
itemRegion = new RPChromosomeRegion(chromID, chromStart, chromID, chromEnd);
itemHitValue = itemRegion.compareRegions(selectionRegion);
// itemHitValue < 2 for intersection; itemHitValue == 0 for is contained
if (!contained && Math.abs(itemHitValue) < 2 || itemHitValue == 0) {
String chromName = chromosomeMap.get(chromID);
ZoomDataRecord zoomRecord = new ZoomDataRecord(zoomLevel, recordNumber, chromName,
chromID, chromStart, chromEnd, validCount, minVal, maxVal, sumData, sumSquares);
zoomDataList.add(zoomRecord);
}
}
// compute data block remainder fom size item read
remDataSize -= ZoomDataRecord.RECORD_SIZE;
}
} catch (IOException ex) {
log.error("Read error for zoom level " + zoomLevel + " leaf item " );
// accept this as an end of block condition unless no items were read
if (recordNumber == 1)
throw new RuntimeException("Read error for zoom level " + zoomLevel + " leaf item ");
}
return zoomDataList;
}
public void print() {
log.debug("Zoom Level " + zoomLevel + "data for leaf item :");
for (int index = 0; index <= zoomDataList.size(); ++index) {
// zoom data records print themselves
zoomDataList.get(index).print();
}
}
}
| true | false | null | null |
diff --git a/editor/src/main/java/io/dahuapp/editor/app/DahuApp.java b/editor/src/main/java/io/dahuapp/editor/app/DahuApp.java
index bd3c53b..c6b0133 100644
--- a/editor/src/main/java/io/dahuapp/editor/app/DahuApp.java
+++ b/editor/src/main/java/io/dahuapp/editor/app/DahuApp.java
@@ -1,156 +1,156 @@
package io.dahuapp.editor.app;
import io.dahuapp.editor.proxy.DahuAppProxy;
import io.dahuapp.editor.utils.Dialogs;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.event.EventHandler;
import javafx.scene.web.PromptData;
import javafx.scene.web.WebEvent;
import javafx.stage.WindowEvent;
import javafx.util.Callback;
/**
* Main class of the application. Runs the GUI to allow the user to take
* screenshots and edit the presentation he wants to make.
*/
public class DahuApp extends Application {
/**
* Title of the application.
*/
public static final String TITLE = "DahuApp Editor";
/**
* Minimum width of the editor window.
*/
private static final int MIN_WIDTH = 720;
/**
* Minimum height of the editor window.
*/
private static final int MIN_HEIGHT = 520;
/**
* Webview of the application, all the elements will be displayed in this
* webview.
*/
private WebView webview;
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
// init dahuapp
initDahuApp(primaryStage);
-
+
// pin it to stackpane
root.getChildren().add(webview);
// create the sceen
Scene scene = new Scene(root, MIN_WIDTH, MIN_HEIGHT);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
webview.getEngine().executeScript("dahuapp.drivers.onStop();");
Platform.exit();
}
});
primaryStage.setMinWidth(MIN_WIDTH);
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setTitle(TITLE);
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
/* fix for osx */
System.setProperty("javafx.macosx.embedded", "true");
java.awt.Toolkit.getDefaultToolkit();
/* launch app */
launch(args);
}
/**
* Gets the path of a ressource of the application.
* @param name Name of the resource to find.
* @return The path to the resource (as it can be put in a file and opened).
*/
public static String getResource(String name) {
return DahuApp.class.getResource(name).getFile();
}
/**
* Initialises the webview with the html content and binds the drivers to
* the dahuapp javascript object.
*
* @param primaryStage Main stage of the app (for the proxy).
*/
private void initDahuApp(final Stage primaryStage) {
webview = new WebView();
webview.setContextMenuEnabled(false);
// load main app
webview.getEngine().load(getClass().getResource("dahuapp.html").toExternalForm());
// extend the webview js context
webview.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
@Override
public void changed(final ObservableValue<? extends Worker.State> observableValue, final State oldState, final State newState) {
if (newState == State.SUCCEEDED) {
// load drivers
JSObject dahuapp = (JSObject) webview.getEngine().executeScript("window.dahuapp");
dahuapp.setMember("drivers", new DahuAppProxy(primaryStage, webview.getEngine()));
// init engine
webview.getEngine().executeScript("dahuapp.editor.init();");
// load the drivers
webview.getEngine().executeScript("dahuapp.drivers.onLoad();");
}
}
});
// adds a dialog alert handler
webview.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {
@Override
public void handle(WebEvent<String> e) {
Dialogs.showMessage(e.getData());
e.consume();
}
});
// adds a confirm dialog handler
webview.getEngine().setConfirmHandler(new Callback<String, Boolean>() {
@Override
public Boolean call(String p) {
return Dialogs.showConfirm(p);
}
});
// adds a prompt dialog handler
webview.getEngine().setPromptHandler(new Callback<PromptData, String>() {
@Override
public String call(PromptData p) {
return Dialogs.showPrompt(p.getMessage(), p.getDefaultValue());
}
});
}
}
diff --git a/editor/src/main/java/io/dahuapp/editor/proxy/PreviewProxy.java b/editor/src/main/java/io/dahuapp/editor/proxy/PreviewProxy.java
index 005e9f5..8c6aa54 100644
--- a/editor/src/main/java/io/dahuapp/editor/proxy/PreviewProxy.java
+++ b/editor/src/main/java/io/dahuapp/editor/proxy/PreviewProxy.java
@@ -1,55 +1,60 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package io.dahuapp.editor.proxy;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javafx.application.Platform;
/**
*
* @author denis
*/
public class PreviewProxy implements Proxy {
/**
* Allows this proxy to open the default browser.
*/
private Desktop desktop;
/**
* Runs the preview (opens the default web browser).
* @param htmlFile The absolute path to the html file to display.
*/
public void runPreview(String htmlFile) {
try {
- final URI u = new URI("file://" + htmlFile);
+ /*
+ * The 'replaceAll' is a fix for windows.
+ * The URI seems not to support strings with '\' so we replace all
+ * of them by '/' otherwise a malformed URI exception is thrown.
+ */
+ final URI u = new URI("file://" + htmlFile.replaceAll("\\\\", "/"));
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
desktop.browse(u);
} catch (IOException e) {
LoggerProxy.severe("Browser couldn't have been opened.", e);
}
}
});
} catch (URISyntaxException e) {
LoggerProxy.severe("Error in URI Syntax", e);
}
}
@Override
public void onLoad() {
desktop = Desktop.getDesktop();
}
@Override
public void onStop() {
}
}
| false | false | null | null |
diff --git a/openstack-api/src/main/java/org/openstack/client/identity/TokensResource.java b/openstack-api/src/main/java/org/openstack/client/identity/TokensResource.java
index a2f15c8..3fbfd62 100644
--- a/openstack-api/src/main/java/org/openstack/client/identity/TokensResource.java
+++ b/openstack-api/src/main/java/org/openstack/client/identity/TokensResource.java
@@ -1,43 +1,34 @@
package org.openstack.client.identity;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;
import org.openstack.model.identity.Access;
import org.openstack.model.identity.Authentication;
+import com.google.common.base.Charsets;
+
public class TokensResource extends IdentityResourceBase {
public Access authenticate(Authentication authentication) {
// String password = authentication.getPasswordCredentials().getPassword();
// authentication.getPasswordCredentials().setPassword(sha512(password));
// .type(MediaType.APPLICATION_XML) ?
return resource().post(Access.class, authentication);
}
- private String toHex(byte[] digest) {
- String hash = "";
- for (byte aux : digest) {
- int b = aux & 0xff; // Hace un cast del byte a hexadecimal
- if (Integer.toHexString(b).length() == 1)
- hash += "0";
- hash += Integer.toHexString(b);
- }
- return hash;
- }
-
private String sha512(String text) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.reset();
- md.update(text.getBytes());
+ md.update(text.getBytes(Charsets.UTF_8));
byte[] digest = md.digest();
return Hex.encodeHexString(digest);
// return toHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
| false | false | null | null |
diff --git a/modules/kernel/src/com/caucho/env/meter/MeterService.java b/modules/kernel/src/com/caucho/env/meter/MeterService.java
index dddd5fb78..304a006c7 100644
--- a/modules/kernel/src/com/caucho/env/meter/MeterService.java
+++ b/modules/kernel/src/com/caucho/env/meter/MeterService.java
@@ -1,417 +1,398 @@
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.env.meter;
import java.util.concurrent.ConcurrentHashMap;
import com.caucho.env.service.AbstractResinService;
import com.caucho.env.service.ResinSystem;
import com.caucho.util.L10N;
public class MeterService extends AbstractResinService {
private static final L10N L = new L10N(MeterService.class);
private static MeterService _manager = new MeterService();
private final ConcurrentHashMap<String,AbstractMeter> _meterMap
= new ConcurrentHashMap<String,AbstractMeter>();
protected MeterService()
{
}
protected void setManager(MeterService manager)
{
if (manager == null)
manager = new MeterService();
else {
manager._meterMap.putAll(_meterMap);
}
_manager = manager;
}
public static MeterService getCurrent()
{
- return ResinSystem.getCurrentService(MeterService.class);
+ return _manager;
}
public static MeterService create()
{
- ResinSystem system = ResinSystem.getCurrent();
-
- if (system == null) {
- throw new IllegalStateException(L.l("{0} requires an active {1}",
- MeterService.class.getSimpleName(),
- ResinSystem.class.getSimpleName()));
- }
-
- MeterService meterService = system.getService(MeterService.class);
-
- if (meterService == null) {
- meterService = new MeterService();
-
- MeterService oldService = system.addServiceIfAbsent(meterService);
-
- if (oldService != null)
- meterService = oldService;
- }
-
- return meterService;
+ return _manager;
}
public static AbstractMeter getMeter(String name)
{
return create().getMeterImpl(name);
}
private AbstractMeter getMeterImpl(String name)
{
return _meterMap.get(name);
}
public static AverageTimeMeter createAverageTimeMeter(String name)
{
return create().createAverageTimeMeterImpl(name);
}
private AverageTimeMeter createAverageTimeMeterImpl(String name)
{
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new AverageTimeMeter(name));
}
return (AverageTimeMeter) meter;
}
public static SampleCountMeter createSampleCountMeter(String name)
{
return create().createSampleCountMeterImpl(name);
}
private SampleCountMeter createSampleCountMeterImpl(String name)
{
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new SampleCountMeter(name));
}
return (SampleCountMeter) meter;
}
public static CountMeter createCountMeter(String name)
{
return create().createCountMeterImpl(name);
}
private CountMeter createCountMeterImpl(String name)
{
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new CountMeter(name));
}
return (CountMeter) meter;
}
public static AbstractMeter createJmx(String name,
String objectName,
String attribute)
{
return create().createJmxImpl(name, objectName, attribute);
}
private AbstractMeter createJmxImpl(String name,
String objectName,
String attribute)
{
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new JmxAttributeMeter(name, objectName, attribute));
}
return meter;
}
public static AbstractMeter createJmxDelta(String name,
String objectName,
String attribute)
{
return create().createJmxDeltaImpl(name, objectName, attribute);
}
private AbstractMeter createJmxDeltaImpl(String name,
String objectName,
String attribute)
{
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new JmxDeltaMeter(name, objectName, attribute));
}
return meter;
}
public static TimeMeter createTimeMeter(String name)
{
return create().createTimeMeterImpl(name);
}
private TimeMeter createTimeMeterImpl(String name)
{
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new TimeMeter(name));
}
return (TimeMeter) meter;
}
public static TimeRangeMeter createTimeRangeMeter(String baseName)
{
return create().createTimeRangeMeterImpl(baseName);
}
private TimeRangeMeter createTimeRangeMeterImpl(String baseName)
{
String timeName = baseName + " Time";
AbstractMeter meter = _meterMap.get(timeName);
if (meter == null) {
meter = createMeter(new TimeRangeMeter(timeName));
TimeRangeMeter timeRangeMeter = (TimeRangeMeter) meter;
String countName = baseName + " Count";
createMeter(timeRangeMeter.createCount(countName));
String maxName = baseName + " Max";
createMeter(timeRangeMeter.createMax(maxName));
}
return (TimeRangeMeter) meter;
}
public static AverageMeter createAverageMeter(String name, String type)
{
return create().createAverageMeterImpl(name, type);
}
private AverageMeter createAverageMeterImpl(String baseName, String type)
{
String name;
if (! "".equals(type))
name = baseName + " " + type;
else
name = baseName;
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new AverageMeter(name));
AverageMeter averageMeter = (AverageMeter) meter;
String countName = baseName + " Count";
createMeter(averageMeter.createCount(countName));
String sigmaName = name + " 95%";
createMeter(averageMeter.createSigma(sigmaName, 3));
String maxName = name + " Max";
createMeter(averageMeter.createMax(maxName));
}
return (AverageMeter) meter;
}
public static ActiveTimeMeter createActiveTimeMeter(String name)
{
return create().createActiveTimeMeterImpl(name, "Time", null);
}
public static ActiveTimeMeter createActiveTimeMeter(String name,
String type,
String subName)
{
return create().createActiveTimeMeterImpl(name, type, subName);
}
private ActiveTimeMeter
createActiveTimeMeterImpl(String baseName,
String type,
String subName)
{
if (subName == null || subName.equals(""))
subName = "";
else if (! subName.startsWith("|"))
subName = "|" + subName;
String name = baseName + " " + type + subName;
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new ActiveTimeMeter(name));
ActiveTimeMeter activeTimeMeter = (ActiveTimeMeter) meter;
/*
String activeCountName = baseName + " Active" + subName;
createMeter(activeTimeMeter.createActiveCount(activeCountName));
*/
String sigmaName = baseName + " " + type + " 95%" + subName;
createMeter(activeTimeMeter.createSigma(sigmaName, 3));
String maxName = baseName + " " + type + " Max" + subName;
createMeter(activeTimeMeter.createMax(maxName));
String activeMaxName = baseName + " Active" + subName;
createMeter(activeTimeMeter.createActiveCountMax(activeMaxName));
String totalCountName = baseName + " Count" + subName;
createMeter(activeTimeMeter.createTotalCount(totalCountName));
}
return (ActiveTimeMeter) meter;
}
/**
* An ActiveMeter counts the number of an active resource, e.g. the
* number of active connections.
*/
public static ActiveMeter createActiveMeter(String name)
{
return create().createActiveMeterImpl(name, null);
}
public static ActiveMeter createActiveMeter(String name,
String subName)
{
return _manager.createActiveMeterImpl(name, subName);
}
private ActiveMeter
createActiveMeterImpl(String baseName,
String subName)
{
if (subName == null || subName.equals(""))
subName = "";
else if (! subName.startsWith("|"))
subName = "|" + subName;
String name = baseName + " Count" + subName;
AbstractMeter meter = _meterMap.get(name);
if (meter == null) {
meter = createMeter(new ActiveMeter(name));
ActiveMeter activeMeter = (ActiveMeter) meter;
String maxName = baseName + " Active" + subName;
createMeter(activeMeter.createMax(maxName));
/*
String totalName = baseName + " Total" + subName;
createMeter(activeMeter.createTotal(totalName));
*/
}
return (ActiveMeter) meter;
}
public static SemaphoreMeter createSimpleSemaphoreMeter(String name)
{
return create().createSemaphoreMeterImpl(name, false);
}
/**
* Creates a semaphore meter and generate Count, Min, and Max meter.
*/
public static SemaphoreMeter createSemaphoreMeter(String name)
{
return create().createSemaphoreMeterImpl(name, true);
}
private SemaphoreMeter createSemaphoreMeterImpl(String baseName,
boolean isExtended)
{
String name = baseName;
AbstractMeter meter = _meterMap.get(name);
if (meter == null)
meter = createMeter(new SemaphoreMeter(name));
SemaphoreMeter semaphoreMeter = (SemaphoreMeter) meter;
if (! isExtended)
return semaphoreMeter;
String countName = baseName + " Acquire";
createMeter(semaphoreMeter.createCount(countName));
String maxName = name + " Max";
createMeter(semaphoreMeter.createMax(maxName));
String minName = name + " Min";
createMeter(semaphoreMeter.createMin(minName));
return (SemaphoreMeter) meter;
}
protected AbstractMeter createMeter(AbstractMeter newMeter)
{
AbstractMeter meter = _meterMap.putIfAbsent(newMeter.getName(), newMeter);
if (meter != null) {
return meter;
}
else {
registerMeter(newMeter);
return newMeter;
}
}
protected void registerMeter(AbstractMeter meter)
{
}
}
| false | false | null | null |
diff --git a/src/main/java/de/berlin/hu/chemspot/ChemSpot.java b/src/main/java/de/berlin/hu/chemspot/ChemSpot.java
index e853b53..aad1a3c 100644
--- a/src/main/java/de/berlin/hu/chemspot/ChemSpot.java
+++ b/src/main/java/de/berlin/hu/chemspot/ChemSpot.java
@@ -1,633 +1,635 @@
/*
* Copyright (c) 2012. Humboldt-Universität zu Berlin, Dept. of Computer Science and Dept.
* of Wissensmanagement in der Bioinformatik
* -------------------------------
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC
* LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
* CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* http://www.opensource.org/licenses/cpl1.0
*/
package de.berlin.hu.chemspot;
import de.berlin.hu.types.PubmedDocument;
import de.berlin.hu.util.Constants;
import de.berlin.hu.wbi.common.research.Evaluator;
import org.apache.uima.UIMAException;
import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CAS;
import org.apache.uima.examples.SourceDocumentInformation;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.metadata.TypeSystemDescription;
import org.apache.uima.util.XMLInputSource;
import org.u_compare.shared.semantic.NamedEntity;
import org.u_compare.shared.syntactic.Token;
import org.uimafit.factory.AnalysisEngineFactory;
import org.uimafit.factory.JCasFactory;
import org.uimafit.util.JCasUtil;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
public class ChemSpot {
private TypeSystemDescription typeSystem;
private AnalysisEngine sentenceDetector;
private AnalysisEngine sentenceConverter;
private AnalysisEngine crfTagger;
private AnalysisEngine dictionaryTagger;
private AnalysisEngine chemicalFormulaTagger;
private AnalysisEngine abbrevTagger;
private AnalysisEngine annotationMerger;
private AnalysisEngine fineTokenizer;
private AnalysisEngine stopwordFilter;
private AnalysisEngine normalizer;
/**
* Initializes ChemSpot without a dictionary automaton and a normalizer.
* @param pathToCRFModelFile the Path to a CRF model
*/
public ChemSpot(String pathToCRFModelFile, String pathToSentenceModelFile) {
new ChemSpot(pathToCRFModelFile, null, pathToSentenceModelFile, null);
}
/**
* Initializes ChemSpot without a normalizer.
* @param pathToCRFModelFile the Path to a CRF model
*/
public ChemSpot(String pathToCRFModelFile, String pathToDictionaryFile, String pathToSentenceModelFile) {
new ChemSpot(pathToCRFModelFile, pathToDictionaryFile, pathToSentenceModelFile, null);
}
/**
* Initializes ChemSpot with a CRF model, an OpenNLP sentence model and a dictionary automaton.
* @param pathToCRFModelFile the path to a CRF model
* @param pathToDictionaryFile the ath to a dictionary automaton
*/
public ChemSpot(String pathToCRFModelFile, String pathToDictionaryFile, String pathToSentenceModelFile, String pathToIDs) {
try {
typeSystem = UIMAFramework.getXMLParser().parseTypeSystemDescription(new XMLInputSource(this.getClass().getClassLoader().getResource("desc/TypeSystem.xml")));
fineTokenizer = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tokenizer/FineGrainedTokenizerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
sentenceDetector = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/opennlp/SentenceDetector.xml"))), "opennlp.uima.ModelName", pathToSentenceModelFile);
sentenceConverter = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/converter/OpenNLPToUCompareSentenceConverterAE.xml"))), CAS.NAME_DEFAULT_SOFA);
System.out.println("Loading CRF...");
crfTagger = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/banner/tagger/BANNERTaggerAE.xml"))), "BannerModelFile", pathToCRFModelFile);
if (pathToDictionaryFile != null) {
System.out.println("Loading dictionary...");
dictionaryTagger = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/BricsTaggerAE.xml"))), "DrugBankMatcherDictionaryAutomat", pathToDictionaryFile);
} else System.out.println("No dictionary location specified! Tagging without dictionary...");
chemicalFormulaTagger = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/ChemicalFormulaTaggerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
abbrevTagger = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/AbbreviationTaggerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
annotationMerger = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/AnnotationMergerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
if (pathToIDs != null) {
normalizer = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/normalizer/NormalizerAE.xml"))), "PathToIDs", pathToIDs);
} else System.out.println("No location for ids specified! Tagging without subsequent normalization...");
stopwordFilter = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/filter/StopwordFilterAE.xml"))), CAS.NAME_DEFAULT_SOFA);
System.out.println("Finished initializing ChemSpot.");
} catch (UIMAException e) {
System.err.println("Failed initializing ChemSpot.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("Failed initializing ChemSpot.");
e.printStackTrace();
}
}
/**
* Returns all mentions (non-goldstandard entities) from a jcas object.
*
* @param jcas the jcas
* @return
*/
public static List<Mention> getMentions(JCas jcas) {
List<Mention> mentions = new ArrayList<Mention>();
Iterator<NamedEntity> entities = JCasUtil.iterator(jcas, NamedEntity.class);
while (entities.hasNext()) {
NamedEntity entity = entities.next();
//disregards gold-standard mentions
if (!Constants.GOLDSTANDARD.equals(entity.getSource())) {
mentions.add(new Mention(entity));
}
}
return mentions;
}
/**
* Returns all goldstandard entities from a jcas object.
*
* @param jcas the jcas
* @return
*/
public static List<Mention> getGoldstandardAnnotations(JCas jcas) {
List<Mention> result = new ArrayList<Mention>();
Iterator<NamedEntity> entities = JCasUtil.iterator(jcas, NamedEntity.class);
while (entities.hasNext()) {
NamedEntity entity = entities.next();
if (Constants.GOLDSTANDARD.equals(entity.getSource())) {
result.add(new Mention(entity));
}
}
return result;
}
/**
* Reads a text from a file and puts the content into the provided jcas.
*
* @param jcas the jcas
* @param pathToFile the path to the text file
* @throws IOException
*/
public static void readFile(JCas jcas, String pathToFile) throws IOException {
FileInputStream stream = new FileInputStream(new File(pathToFile));
String text = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
text = Charset.defaultCharset().decode(bb).toString();
} finally {
stream.close();
}
jcas.setDocumentText(text);
PubmedDocument pd = new PubmedDocument(jcas);
pd.setBegin(0);
pd.setEnd(text.length());
pd.setPmid("");
pd.addToIndexes(jcas);
}
/**
* Reads a text from a gzipped file and puts the content into the provided jcas.
*
* @param jcas the jcas
* @param pathToFile the path to the text file
* @throws IOException
*/
public static void readGZFile(JCas jcas, String pathToFile) throws IOException {
File file = new File(pathToFile);
String text;
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream(file)) ) );
StringBuilder textBuffer = new StringBuilder();
Integer currindex = -1;
while(reader.ready()){
PubmedDocument pmdoc = new PubmedDocument(jcas);
String s = reader.readLine();
if (s != null) {
//split line into pmid and text
String pmid = s.substring(0, s.indexOf("\t"));
String annot = s.substring(s.indexOf("\t"));
//two = splitFirst(s, "\t");
pmdoc.setPmid(pmid);
//append text
textBuffer.append(annot).append("\n");
pmdoc.setBegin(currindex + 1);
Integer len = annot.length();
currindex = currindex + len + 1;
pmdoc.setEnd(currindex);
pmdoc.addToIndexes();
}
}
text = textBuffer.toString();
//put document in CAS
jcas.setDocumentText(text);
SourceDocumentInformation srcDocInfo = new SourceDocumentInformation(jcas);
srcDocInfo.setUri(file.getAbsoluteFile().toURI().toString());
srcDocInfo.setOffsetInSource(0);
srcDocInfo.setDocumentSize((int) file.length());
srcDocInfo.setBegin(0);
srcDocInfo.setEnd(currindex);
srcDocInfo.addToIndexes();
}
/**
* Finds chemical entities in the document of a {@code JCas} object and returns a list of mentions.
* @param jcas contains the document text
* @return a list of mentions
*/
public List<Mention> tag(JCas jcas) {
try {
fineTokenizer.process(jcas);
synchronized (this) {
sentenceDetector.process(jcas);
}
sentenceConverter.process(jcas);
crfTagger.process(jcas);
if (dictionaryTagger != null) dictionaryTagger.process(jcas);
chemicalFormulaTagger.process(jcas);
abbrevTagger.process(jcas);
annotationMerger.process(jcas);
stopwordFilter.process(jcas);
if (normalizer != null) normalizer.process(jcas);
} catch (AnalysisEngineProcessException e) {
System.err.println("Failed to extract chemicals from text.");
e.printStackTrace();
}
return null;
}
/**
* Finds chemical entities in a {@code text} and returns a list of mentions.
* @param text natural language text from which ChemSpot shall extract chemical entities
* @return a list of mentions
* @throws UIMAException
*/
public List<Mention> tag(String text) throws UIMAException {
JCas jcas = JCasFactory.createJCas(typeSystem);
jcas.setDocumentText(text);
PubmedDocument pd = new PubmedDocument(jcas);
pd.setBegin(0);
pd.setEnd(text.length());
pd.setPmid("");
pd.addToIndexes(jcas);
return tag(jcas);
}
/**
* Converts all annotations from jcas to the IOB format
*
* @param jcas the jcas
* @return
*/
public static String convertToIOB(JCas jcas) {
StringBuilder sb = new StringBuilder();
HashMap<String, ArrayList<NamedEntity>> goldAnnotations = new HashMap<String, ArrayList<NamedEntity>>();
HashMap<String, ArrayList<NamedEntity>> pipelineAnnotations = new HashMap<String, ArrayList<NamedEntity>>();
System.out.println("Converting annotations to IOB format...");
Iterator<PubmedDocument> abstracts = JCasUtil.iterator(jcas, PubmedDocument.class);
while (abstracts.hasNext()) {
PubmedDocument pubmedAbstract = abstracts.next();
sb.append("### ").append(pubmedAbstract.getPmid()).append("\n");
int offset = pubmedAbstract.getBegin();
String pmid = pubmedAbstract.getPmid();
List<Token> tokens = JCasUtil.selectCovered(Token.class, pubmedAbstract);
for (Token token : tokens) {
token.setLabel("O");
}
List<NamedEntity> entities = JCasUtil.selectCovered(NamedEntity.class, pubmedAbstract);
for (NamedEntity entity : entities) {
int firstTokenBegin = 0;
int lastTokenEnd = 0;
String id = entity.getId();
if (id == null) id = "";
if (!Constants.GOLDSTANDARD.equals(entity.getSource())) {
if (pipelineAnnotations.containsKey(pmid)) {
pipelineAnnotations.get(pmid).add(entity);
} else {
ArrayList<NamedEntity> tempArray = new ArrayList<NamedEntity>();
tempArray.add(entity);
pipelineAnnotations.put(pmid, tempArray);
}
List<Token> entityTokens = JCasUtil.selectCovered(Token.class, entity);
boolean first = true;
for (Token token : entityTokens) {
if (first) {
if (id.isEmpty()) token.setLabel("B-CHEMICAL"); else token.setLabel("B-CHEMICAL" + "\t" + id);
first = false;
firstTokenBegin = token.getBegin();
} else {
token.setLabel("I-CHEMICAL" + "\t" + id);
}
lastTokenEnd = token.getEnd();
}
assert entity.getBegin() == firstTokenBegin : (id + ": " + entity.getBegin() + " -> " + firstTokenBegin);
assert entity.getEnd() == lastTokenEnd : (id + ": " + entity.getEnd() + " -> " + lastTokenEnd);
} else {
if (goldAnnotations.containsKey(pmid)) {
goldAnnotations.get(pmid).add(entity);
} else {
ArrayList<NamedEntity> tempArray = new ArrayList<NamedEntity>();
tempArray.add(entity);
goldAnnotations.put(pmid, tempArray);
}
}
}
List<Token> tokensToPrint = JCasUtil.selectCovered(Token.class, pubmedAbstract);
boolean firstToken = true;
for (Token token : tokensToPrint) {
if (firstToken && (token.getBegin() - offset) != 0) {
sb.append(" " + "\t" + 0 + "\t").append(token.getBegin() - offset).append("\t\t|O\n");
}
firstToken = false;
sb.append(token.getCoveredText()).append("\t").append(token.getBegin() - offset).append("\t").append(token.getEnd() - offset).append("\t\t|").append(token.getLabel()).append("\n");
}
}
return sb.toString();
}
private int TP = 0;
private int FP = 0;
private int FN = 0;
private Object evaluationLock = new Object();
private List<Mention> truePositives = new ArrayList<Mention>();
private List<Mention> falsePositives = new ArrayList<Mention>();
private List<Mention> falseNegatives = new ArrayList<Mention>();
/**
* Evaluates the annotation results.
*
* @param jcas
*/
public void evaluate(JCas jcas) {
System.out.println("Starting evaluation...");
List<Mention> mentions = getMentions(jcas);
List<Mention> goldstandardAnnotations = getGoldstandardAnnotations(jcas);
synchronized(evaluationLock) {
if (goldstandardAnnotations.size() == 0) {
FP += mentions.size();
falsePositives.addAll(mentions);
} else if (mentions.size() == 0) {
FN += goldstandardAnnotations.size();
falseNegatives.addAll(goldstandardAnnotations);
} else {
Evaluator<Mention, Mention> evaluator = new Evaluator<Mention, Mention>(mentions, goldstandardAnnotations);
evaluator.evaluate();
TP += evaluator.getTruePositives().size();
FP += evaluator.getFalsePositives().size();
FN += evaluator.getFalseNegatives().size();
truePositives.addAll(evaluator.getTruePositives());
falsePositives.addAll(evaluator.getFalsePositives());
falseNegatives.addAll(evaluator.getFalseNegatives());
System.out.format("True Positives:\t\t%d\nFalse Positives:\t%d\nFalse Negatives:\t%d\n", TP, FP, FN);
double precision = (double) TP / ((double) TP + FP);
double recall = (double) TP / ((double) TP + FN);
double fscore = precision + recall > 0 ? 2 * (precision * recall) / (precision + recall) : 0;
System.out.format("Precision:\t\t%f\nRecall:\t\t\t%f\nF1 Score:\t\t%f\n", precision, recall, fscore);
System.out.println();
}
}
}
private static List<List<Mention>> sortMentionListsBySize(List<Mention> list, boolean bySource) {
List<List<Mention>> result = new ArrayList<List<Mention>>();
Map<String, List<Mention>> annotationMap = new HashMap<String, List<Mention>>();
for (Mention mention : list) {
String key = bySource ? mention.getSource() : mention.getText();
if (!annotationMap.containsKey(key)) {
annotationMap.put(key, new ArrayList<Mention>());
}
annotationMap.get(key).add(mention);
}
for (String key : annotationMap.keySet()) {
result.add(annotationMap.get(key));
}
Comparator<List<Mention>> comparator = new Comparator<List<Mention>>() {
public int compare(List<Mention> o1, List<Mention> o2) {
return o1.size() - o2.size();
}
};
Collections.sort(result, Collections.reverseOrder(comparator));
return result;
}
private static void writeOverlapping(OutputStream s, String name1, List<Mention> list1, String name2, List<Mention> list2) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s));
list1 = new ArrayList<Mention>(list1);
Collections.sort(list1);
list2 = new ArrayList<Mention>(list2);
Collections.sort(list2);
Pattern startPattern = Pattern.compile("(\\S+\\s+){5}\\S*$");
Pattern stopPattern = Pattern.compile("^\\S*(\\s+\\S+){5}");
writer.write(String.format("Overlapping occurrences of <%s> and [%s]:%n", name1, name2));
int maxLength = 100;
int i = 0;
for (Mention m1 : list1) {
while (i < list2.size() && list2.get(i).getEnd() < m1.getStart()) i++;
int j = i;
while (j < list2.size() && list2.get(j).overlaps(m1)) {
Mention m2 = list2.get(j++);
if (!m1.getCas().getDocumentText().equals(m2.getCas().getDocumentText())) continue;
String text = m1.getCas().getDocumentText();
int begin = Math.min(m1.getStart(), m2.getStart());
int end = Math.max(m1.getEnd(), m2.getEnd());
Matcher matcher = startPattern.matcher(text.substring(Math.max(begin-maxLength, 0), begin));
int start = matcher.find() ? Math.max(begin-maxLength, 0) + matcher.start() : Math.max(begin-30, 0);
matcher = stopPattern.matcher(text.substring(end, Math.min(end+maxLength, text.length())));
int stop = matcher.find() ? end + matcher.end() : Math.min(end+30, text.length());
StringBuilder sb = new StringBuilder();
sb.append(text.substring(start, stop));
sb.insert(m1.getStart() - start, '<');
sb.insert(m1.getEnd() - start + 1, '>');
sb.insert(m2.getStart() - start + (m1.getStart() < m2.getStart() ? 1 : 0) + (m1.getStart() == m2.getStart() && m1.getEnd() > m2.getEnd() ? 1 : 0), "[");
sb.insert(m2.getEnd() - start + 2 + (m1.getEnd() < m2.getEnd() || (m1.getEnd() == m2.getEnd() && m1.getStart() > m2.getStart()) ? 1 : 0), "]").toString();
writer.write("..." + sb.toString().replaceAll("\r?\n", "\\\\n") + "...");
writer.newLine();
}
}
writer.flush();
}
private static void writeList(OutputStream s, String name, List<Mention> list) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s));
List<List<Mention>> listBySize = sortMentionListsBySize(list, false);
writer.write(String.format("%n%n%n%s:%n", name));
writer.write(String.format("%8s\t%25s\t%s%n", "#", "CHEMICAL", "SOURCE"));
for (List<Mention> annotationList : listBySize) {
List<List<Mention>> listBySource = sortMentionListsBySize(annotationList, true);
String sources = "";
for (List<Mention> sourceList : listBySource) {
String source = !sourceList.isEmpty() ? sourceList.get(0).getSource() : "";
source = source == null || source.isEmpty() ? Constants.UNKNOWN : source;
if (listBySource.size() == 1) {
source = (sourceList.size() > 1 ? "all " : "") + source;
} else {
source = sourceList.size() + " " + source;
}
sources += String.format("%s%s", !sources.isEmpty() ? ", " : "", source);
}
String annotation = !annotationList.isEmpty() ? annotationList.get(0).getText() : "";
writer.write(String.format("%8d\t%25s\t%s%n", annotationList.size(), annotation, sources));
}
writer.flush();
}
private static void writeContext(OutputStream s, String name, List<Mention> list) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s));
List<List<Mention>> listBySize = sortMentionListsBySize(list, false);
writer.write(String.format("%s:%n", name));
Pattern startPattern = Pattern.compile("(\\S+\\s+){5}\\S*$");
Pattern stopPattern = Pattern.compile("^\\S*(\\s+\\S+){5}");
int maxLength = 100;
try {
for (List<Mention> annotationList : listBySize) {
if (annotationList.isEmpty()) continue;
writer.write(String.format("%n%n%s (%d):%n", annotationList.get(0).getText(), annotationList.size()));
int i = 0;
for (Mention mention : annotationList) {
if (i++ > 30) {
writer.write("...");
writer.newLine();
break;
}
String text = null;
text = mention.getCas().getDocumentText();
int begin = mention.getStart();
int end = mention.getEnd();
Matcher matcher = startPattern.matcher(text.substring(Math.max(begin-maxLength, 0), begin));
int start = matcher.find() ? Math.max(begin-maxLength, 0) + matcher.start() : Math.max(begin-30, 0);
matcher = stopPattern.matcher(text.substring(end, Math.min(end+maxLength, text.length())));
int stop = matcher.find() ? end + matcher.end() : Math.min(end+30, text.length());
String output = String.format("...%s<%s>%s...", text.substring(start , begin), text.substring(begin, end), text.substring(end, stop));
output = output.replaceAll("\r?\n", "\\\\n");
writer.write(output);
writer.newLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
writer.flush();
}
public void writeDetailedEvaluationResults(String outputPath) throws IOException {
synchronized (evaluationLock) {
+ if (outputPath == null) outputPath = "";
+
File evaluationFile = new File(outputPath + "evaluation.txt");
OutputStream writer = new FileOutputStream(evaluationFile);
writeList(writer, "true positives", truePositives);
writeList(writer, "false negatives", falseNegatives);
writeList(writer, "false positives", falsePositives);
writer.close();
System.out.println("Evaluation results written to: " + evaluationFile.getName());
File falsePositivesFile = new File(outputPath + "evaluation-FPs.txt");
writer = new FileOutputStream(falsePositivesFile);
writeContext(writer, "false positives contexts", falsePositives);
writer.close();
System.out.println("False positive contexts written to: " + falsePositivesFile.getName());
File falseNegativesFile = new File(outputPath + "evaluation-FNs.txt");
writer = new FileOutputStream(falseNegativesFile);
writeContext(writer, "false negatives contexts", falseNegatives);
writer.close();
System.out.println("False negative contexts written to: " + falseNegativesFile.getName());
File falsePositivesNegativesFile = new File(outputPath + "evaluation-FP-FNs.txt");
writer = new FileOutputStream(falsePositivesNegativesFile);
writeOverlapping(writer, "false negatives", falseNegatives, "false positives", falsePositives);
writer.close();
System.out.println("Overlapping occurrences of false positives and negatives written to: " + falsePositivesNegativesFile.getName());
}
}
public static String serializeAnnotations(JCas jcas) {
int offset;
StringBuilder sb = new StringBuilder();
Iterator<PubmedDocument> documentIterator = JCasUtil.iterator(jcas, PubmedDocument.class);
while (documentIterator.hasNext()) {
PubmedDocument document = documentIterator.next();
offset = document.getBegin();
String pmid = document.getPmid();
int numberOfEntities = 0;
Iterator<NamedEntity> entityIterator = JCasUtil.iterator(document, NamedEntity.class, true, true);
while (entityIterator.hasNext()) {
NamedEntity entity = entityIterator.next();
if (!Constants.GOLDSTANDARD.equals(entity.getSource())) {
//offset fix for GeneView
//int begin = entity.getBegin() - offset;
int begin = entity.getBegin() - offset - 1;
//int end = entity.getEnd() - offset - 1;
int end = entity.getEnd() - offset - 2;
String id = (new Mention(entity)).getCHID();
String text = entity.getCoveredText();
if (id == null || id.isEmpty()) {
sb.append(pmid + "\t" + begin + "\t" + end + "\t" + text + "\t" + "\\N\n");
} else {
sb.append(pmid + "\t" + begin + "\t" + end + "\t" + text + "\t" + id + "\n");
}
}
numberOfEntities++;
}
if (numberOfEntities == 0) {
sb.append(pmid + "\t-1\t-1\t\\N\t\\N\n");
}
}
return sb.toString();
}
}
| true | false | null | null |
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteMapContext.java b/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteMapContext.java
index ce6588da8..e3f6b9240 100644
--- a/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteMapContext.java
+++ b/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteMapContext.java
@@ -1,207 +1,207 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.core.layerModel.mapcatalog;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import org.orbisgis.core.layerModel.MapContext;
import org.orbisgis.core.renderer.se.common.Description;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
/**
* Remote map context abstraction
* @author Nicolas Fortin
*/
public abstract class RemoteMapContext {
private int id = 0;
private Description description = new Description();
private ConnectionProperties cParams;
private transient String workspaceName; // Not serialised
private Date date;
private static final I18n I18N = I18nFactory.getI18n(RemoteMapContext.class);
/**
* Constructor
* @param cParams Connection parameters
*/
public RemoteMapContext(ConnectionProperties cParams) {
this.cParams = cParams;
}
/**
* Delete this map context on the remote server.
* This call may take a long time to execute.
*/
public void delete() throws IOException {
// Construct request
String url = RemoteCommons.getUrlDeleteContext(cParams, workspaceName, id);
URL requestWorkspacesURL =
new URL(url);
// Establish connection
HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection();
connection.setRequestMethod("DELETE");
connection.setConnectTimeout(cParams.getConnectionTimeOut());
if (!(connection.getResponseCode() == HttpURLConnection.HTTP_OK || connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT)) {
throw new IOException(I18N.tr("HTTP Error {0} message : {1} while removing the map context from {2}",connection.getResponseCode(),connection.getResponseMessage(),url));
}
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof RemoteMapContext)) {
return false;
}
final RemoteMapContext other = (RemoteMapContext) obj;
if (this.id != other.id) {
return false;
}
if (this.description != other.description && (this.description == null || !this.description.equals(other.description))) {
return false;
}
if (this.cParams != other.cParams && (this.cParams == null || !this.cParams.equals(other.cParams))) {
return false;
}
if (this.date != other.date && (this.date == null || !this.date.equals(other.date))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + this.id;
hash = 67 * hash + (this.description != null ? this.description.hashCode() : 0);
hash = 67 * hash + (this.cParams != null ? this.cParams.hashCode() : 0);
hash = 67 * hash + (this.workspaceName != null ? this.workspaceName.hashCode() : 0);
hash = 67 * hash + (this.date != null ? this.date.hashCode() : 0);
return hash;
}
/**
*
* @return The Map id
*/
public int getId() {
return id;
}
/**
* Set the workspace name associated with this id
* @param workspaceName
*/
public void setWorkspaceName(String workspaceName) {
this.workspaceName = workspaceName;
}
/**
*
* @param description
*/
public void setDescription(Description description) {
this.description = description;
}
/**
* Get remote map context Id
* @param id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* @return Date of the document
*/
public Date getDate() {
return date;
}
/**
* Set the date
* @param date Date of the document
*/
public void setDate(Date date) {
this.date = date;
}
/**
* Request Map Description, the description is buffered.
* @return Map description
*/
public Description getDescription() {
return description;
}
/**
* Return the stream of the map content node
* This call may take a long time to execute.
* @return
* @throws IOException
*/
- public InputStream getMapContent() throws IOException {
+ public HttpURLConnection getMapContent() throws IOException {
// Construct request
String url = RemoteCommons.getUrlContext(cParams, workspaceName, id);
URL requestWorkspacesURL =
new URL(url);
// Establish connection
HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(cParams.getConnectionTimeOut());
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(I18N.tr("HTTP Error {0} message : {1} while downloading from {2}", connection.getResponseCode(), connection.getResponseMessage(), url));
}
- return connection.getInputStream();
+ return connection;
}
/**
* Connect to the server and request the map content.
* This call may take a long time to execute.
* @return
* @throws IOException The request fail
*/
public abstract MapContext getMapContext() throws IOException;
/**
*
* @return The file extension used to save this kind of map context
*/
public abstract String getFileExtension();
}
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteOwsMapContext.java b/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteOwsMapContext.java
index 3b1340c26..a4ff5ba80 100644
--- a/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteOwsMapContext.java
+++ b/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/mapcatalog/RemoteOwsMapContext.java
@@ -1,60 +1,60 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.core.layerModel.mapcatalog;
import java.io.IOException;
import org.orbisgis.core.layerModel.MapContext;
import org.orbisgis.core.layerModel.OwsMapContext;
/**
* Ows specific map context implementation of a remote map context.
* @author Nicolas Fortin
*/
public class RemoteOwsMapContext extends RemoteMapContext {
/**
* Constructor
* @param cParams Connection parameters
*/
public RemoteOwsMapContext(ConnectionProperties cParams) {
super(cParams);
}
@Override
public MapContext getMapContext() throws IOException {
OwsMapContext mapContext = new OwsMapContext();
- mapContext.read(getMapContent());
+ mapContext.read(getMapContent().getInputStream());
return mapContext;
}
@Override
public String getFileExtension() {
return "ows";
}
}
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/TransferableRemoteMap.java b/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/TransferableRemoteMap.java
index 05264a2cd..396ebf195 100644
--- a/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/TransferableRemoteMap.java
+++ b/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/TransferableRemoteMap.java
@@ -1,132 +1,137 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.view.map.mapsManager;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
import java.util.Arrays;
import org.apache.log4j.Logger;
import org.orbisgis.core.Services;
+import org.orbisgis.core.layerModel.mapcatalog.RemoteCommons;
import org.orbisgis.core.layerModel.mapcatalog.RemoteMapContext;
import org.orbisgis.view.components.fstree.TransferableFileContent;
import org.orbisgis.view.edition.TransferableEditableElement;
import org.orbisgis.view.map.MapElement;
import org.orbisgis.view.map.TransferableMap;
import org.orbisgis.view.workspace.ViewWorkspace;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
/**
* Download the Map Content only if the user drop this transferable
* @author Nicolas Fortin
*/
public class TransferableRemoteMap extends TransferableMap {
private static final Logger LOGGER = Logger.getLogger(TransferableRemoteMap.class);
private static final I18n I18N = I18nFactory.getI18n(TransferableRemoteMap.class);
- RemoteMapContext remoteMap;
+ private RemoteMapContext remoteMap;
public TransferableRemoteMap(RemoteMapContext remoteMap) {
this.remoteMap = remoteMap;
}
@Override
public boolean isDataFlavorSupported(DataFlavor df) {
return super.isDataFlavorSupported(df) || df.equals(TransferableFileContent.FILE_CONTENT_FLAVOR);
}
@Override
public DataFlavor[] getTransferDataFlavors() {
// Append FILE_CONTENT_FLAVOR
DataFlavor[] flavors = super.getTransferDataFlavors();
DataFlavor[] extendedFlavors = Arrays.copyOf(flavors, flavors.length + 1);
extendedFlavors[extendedFlavors.length-1] = TransferableFileContent.FILE_CONTENT_FLAVOR;
return extendedFlavors;
}
/**
* Transfer is requested, the remote map must be download and
* a file name must be defined
* @param df
* @return
* @throws UnsupportedFlavorException
*/
@Override
public Object getTransferData(DataFlavor df) throws UnsupportedFlavorException {
if(df.equals(TransferableMap.mapFlavor) || df.equals(TransferableEditableElement.editableElementFlavor) ) {
//Find appropriate file name
ViewWorkspace viewWorkspace = Services.getService(ViewWorkspace.class);
//Load the map context
File mapContextFolder = new File(viewWorkspace.getMapContextPath());
if (!mapContextFolder.exists()) {
mapContextFolder.mkdir();
}
File mapContextFile = new File(mapContextFolder, remoteMap.getDescription().getDefaultTitle() + "." + remoteMap.getFileExtension());
try {
MapElement mapElement = new MapElement(remoteMap.getMapContext(), mapContextFile);
mapElement.setModified(true);
return new MapElement[] {mapElement};
} catch( IOException ex) {
LOGGER.error(I18N.tr("Error while downloading the map content"),ex);
return ex;
}
} else if(df.equals(TransferableFileContent.FILE_CONTENT_FLAVOR)) {
// Make a Reader
try {
- return new ReaderWithName(remoteMap);
+ //Establish connection with the remote map
+ HttpURLConnection connection = remoteMap.getMapContent();
+ return new ReaderWithName(connection.getInputStream(),RemoteCommons.getConnectionCharset(connection),remoteMap);
} catch(IOException ex) {
LOGGER.error(ex.getLocalizedMessage(),ex);
return null;
}
} else {
return null;
}
}
/**
* Reader input stream that provide a content file name
*/
private static class ReaderWithName extends InputStreamReader implements TransferableFileContent {
- RemoteMapContext remoteMapContext;
+ private RemoteMapContext remoteMapContext;
- public ReaderWithName(RemoteMapContext remoteMapContext) throws UnsupportedEncodingException, IOException {
- super(remoteMapContext.getMapContent(),remoteMapContext.getContentEncoding());
+ public ReaderWithName(InputStream inputStream, String encoding, RemoteMapContext remoteMapContext) throws UnsupportedEncodingException, IOException {
+ super(inputStream, encoding);
this.remoteMapContext = remoteMapContext;
}
@Override
public String getFileNameHint() {
return remoteMapContext.getDescription().getDefaultTitle() + "." + remoteMapContext.getFileExtension();
}
}
}
| false | false | null | null |
diff --git a/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/ir/EngineIRReaderTest.java b/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/ir/EngineIRReaderTest.java
index 17fad1c0f..e0977e269 100644
--- a/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/ir/EngineIRReaderTest.java
+++ b/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/ir/EngineIRReaderTest.java
@@ -1,125 +1,130 @@
package org.eclipse.birt.report.engine.ir;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import org.eclipse.birt.report.engine.EngineCase;
import org.eclipse.birt.report.engine.parser.ReportDesignWriter;
import org.eclipse.birt.report.engine.parser.ReportParser;
/**
* Used to test the different version reader.
* Current EngineIRWriter and EngineIRReader test can see class EngineIRIOTest.
* If we change the EngineIRWriter and EngineIRReader, we should do as following:
* 1. use current EngineIRReader to read streams from the stored old version files.
* 2. compare the current wrote and readed stream with result in step1.
*
* Do not forget to use current EngineIRWriter to write the design to a stream,
* and store it to a file like ir_io_test.V1. This will be used for later versions.
*
*/
public class EngineIRReaderTest extends EngineCase
{
static final String DESIGN_STREAM = "ir_io_test.rptdesign";
+ static final String VALUE_V1_STREAM = "org/eclipse/birt/report/engine/ir/ir_io_test_V1.xml";
+ static final String VALUE_V2_STREAM = "org/eclipse/birt/report/engine/ir/ir_io_test_V2.xml";
+ static final String VALUE_V3_STREAM = "org/eclipse/birt/report/engine/ir/ir_io_test_V3.xml";
static final String GOLDEN_V1_STREAM = "ir_io_test_V1.golden";
static final String GOLDEN_V2_STREAM = "ir_io_test_V2.golden";
-
- String value = "";
-
- public EngineIRReaderTest( )
- {
- try
- {
- value = getCurrentStream( );
- }
- catch ( Exception e )
- {
- e.printStackTrace( );
- }
- }
+ static final String GOLDEN_V3_STREAM = "ir_io_test_V3.golden";
public void testV1( ) throws Exception
{
+ String value = getValue( VALUE_V1_STREAM );
String golden = getGolden( GOLDEN_V1_STREAM );
assertEquals( golden, value );
}
public void testV2( ) throws Exception
{
+ String value = getValue( VALUE_V2_STREAM );
String golden = getGolden( GOLDEN_V2_STREAM );
assertEquals( golden, value );
}
+ public void testV3( ) throws Exception
+ {
+ String value = getValue( VALUE_V3_STREAM );
+ String golden = getGolden( GOLDEN_V3_STREAM );
+ assertEquals( golden, value );
+ }
+
+ private String getValue( String value )
+ {
+ assert ( value != null );
+ return new String( loadResource( value ) );
+ }
+
public String getCurrentStream( ) throws Exception
{
// load the report design
ReportParser parser = new ReportParser( );
Report report = parser.parse( ".", this.getClass( )
.getResourceAsStream( DESIGN_STREAM ) );
assertTrue( report != null );
// write it into the stream
ByteArrayOutputStream out = new ByteArrayOutputStream( );
new EngineIRWriter( ).write( out, report );
out.close( );
// load it from the stream
InputStream in = new ByteArrayInputStream( out.toByteArray( ) );
EngineIRReader reader = new EngineIRReader( false );
Report report2 = reader.read( in );
ByteArrayOutputStream out2 = new ByteArrayOutputStream( );
ReportDesignWriter writer = new ReportDesignWriter( );
writer.write( out2, report2 );
String value = new String( out2.toByteArray( ) );
return value;
}
private String getGolden( String fileName ) throws Exception
{
InputStream in = this.getClass( ).getResourceAsStream( fileName );
assertTrue( in != null );
EngineIRReader reader = new EngineIRReader( false );
Report report = reader.read( in );
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
ReportDesignWriter writer = new ReportDesignWriter( );
writer.write( outputStream, report );
return new String( outputStream.toByteArray( ) );
}
/**
* Used to create the current stream wrote by current version EngineWriter.
* The file will be stored in eclipse folder. Please copy it here and commit it to CVS.
*
* now the version is 2
*
* @throws Exception
*/
public void writeGolden( ) throws Exception
{
//load the report design
ReportParser parser = new ReportParser( );
Report report = parser.parse( ".", this.getClass( )
.getResourceAsStream( DESIGN_STREAM ) );
assertTrue( report != null );
// write it into the stream
ByteArrayOutputStream out = new ByteArrayOutputStream( );
new EngineIRWriter( ).write( out, report );
out.close( );
File file = new File( GOLDEN_V2_STREAM );
if ( !file.exists( ) )
{
file.createNewFile( );
RandomAccessFile rf = new RandomAccessFile( file, "rw" );
rf.write( out.toByteArray( ) );
}
}
}
| false | false | null | null |
diff --git a/src/com/ph/tymyreader/TymyParser.java b/src/com/ph/tymyreader/TymyParser.java
index 453c527..eef4b47 100644
--- a/src/com/ph/tymyreader/TymyParser.java
+++ b/src/com/ph/tymyreader/TymyParser.java
@@ -1,190 +1,196 @@
package com.ph.tymyreader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Html;
import com.ph.tymyreader.model.DsItem;
/**
* @author petr Haering
*
*/
public class TymyParser {
//private final String TAG = TymyReader.TAG;
private String s = null;
private Integer position = 0;
public TymyParser(final String inputString) {
this.s = inputString;
}
public TymyParser() {
this(null);
}
/**
* public Integer findStartTag (final String tagName)
* <br>
* return index of last char before the stop tag ($lt;/tag>)
*
* @param tagName Name of tag
* @return index of last character before stop tag ($lt;/tag>) or -1 if not found
*/
public Integer startTag (final String tagName, final String attr) {
boolean hit = false;
Integer absPos = 0;
Integer relStart = 0;
Integer relEnd = 0;
String tag = "<" + tagName;
while ((relStart = (s.substring(absPos)).indexOf(tag)) != -1) {
while ((relEnd = (s.substring(absPos + relStart)).indexOf('>')) != -1) {
break;
}
String t = s.substring(absPos + relStart, absPos + relStart + relEnd + 1);
if (hit = t.matches(".*" + attr + ".*")) {
absPos += relStart;
break;
}
absPos += relStart + relEnd;
}
return (hit ? absPos : -1);
}
/**
* public Integer findStartTag (final String tagName)
* <br>
* return index of last char before the stop tag (</tag>)
*
* @param tagName Name of tag
* @return index of last character before stop tag ($lt;/tag>) or -1 if not found
*/
public Integer stopTag (final String tagName, final String cls) {
Integer position = -1;
String tag = "</" + tagName;
if ((position = startTag(tagName, cls)) != -1) {
position += s.substring(position).indexOf(tag) + tag.length();
}
return position;
}
/**
* extract text and the start and stop tag: <tag>..</tag>
*
* @param tagName Name of tag
* @return a string representation of whole tag
*/
public String getWholeTag (final String tagName, final String attr) {
String out = "";
int start, end;
s = s.substring(position);
start = startTag(tagName, attr);
end = stopTag(tagName, attr);
if (start != -1) {
if (end != -1) {
out = s.substring(start, end + 1);
position = end + 1;
}
else {
out = s.substring(start);
position = s.length();
}
}
return out;
}
/**
* extract text between the start and stop tag: <tag>..</tag>
*
* @param tagName Name of tag
* @param attr attribute of tag
* @return a string representation of content of tag
*/
public String getBodyOfTag (final String tagName, final String attr) {
String out = "";
out = getWholeTag(tagName, attr);
int x = out.indexOf('>') + 1;
int y = out.lastIndexOf('<');
return out.substring(x, y);
}
public String getRawText () {
s = s.substring(position);
return s;
}
@SuppressWarnings("unused")
private int getPosition () {
return position;
}
public DsItem getDsItem () {
final String ITEMTAG = "td";
final String ITEMTAGATTR = "class=\"dsitem\"";
final String CAPTAG = "div";
final String CAPTAGATTR = "class=\"dscaption\"";
DsItem dsItem = new DsItem();
String post;
if ((post = getWholeTag(ITEMTAG, ITEMTAGATTR)) != "") {
TymyParser postParser = new TymyParser(post);
dsItem.setDsCaption(Html.fromHtml(postParser.getWholeTag(CAPTAG, CAPTAGATTR)).toString().trim());
dsItem.setDsItemText(Html.fromHtml(postParser.getRawText()).toString().trim());
return dsItem;
} else {
return null;
}
}
// TODO dodelat automaticke vytazeni jmen diskusi
/**
* detDisArray parse page and try to find pairs discussion ID and NAME. Returns
* String Array with String of "ID:NAME"
*
* @param mainPage tymy main page
* @return String Array of pairs "ID:NAME"
*/
public ArrayList<String> getDsArray(String mainPage) {
ArrayList<String> ds = new ArrayList<String>();
- Pattern MY_PATTERN = Pattern.compile("<a .*?page=discussion&id=(.*?)&level=101\">(.*?)</a>");
+ Pattern MY_PATTERN;
+ if (mainPage.indexOf("menu_item") == -1) {
+ MY_PATTERN = Pattern.compile("<a .*?page=discussion&id=(.*?)&level=101\">(.*?)</a> <span");
+ } else {
+ //Complete menu version
+ MY_PATTERN = Pattern.compile("<a href=\"/index.php\\?page=discussion&id=(.*?)&level=101\"><img alt=\"(.*?)\".*?</span>");
+ }
Matcher m = MY_PATTERN.matcher(mainPage);
while (m.find()) {
ds.add(m.group(1) + ":" + m.group(2));
}
return ds;
}
/**
* Parse ajaxPage contains information about new items in discussions. Returns
* HashMap<String, Integer> where key id dsId and value is number of new items
* e.g. [dsId, newItems]
* @param ajaxPage String
* @return Returns HashMap<String, Integer> where K=dsId and V=newItems.
*/
public HashMap<String, Integer> getNewItems (String ajaxPage) {
HashMap<String, Integer> ds_news = new HashMap<String, Integer>();
Pattern MY_PATTERN = Pattern.compile("ds_new_(.*?)\".*?:(.*?)</b>");
Matcher m = MY_PATTERN.matcher(ajaxPage);
while (m.find()) {
ds_news.put(m.group(1), Integer.parseInt(m.group(2).trim()));
}
return ds_news;
}
// TODO for parsing dsItems could be used regular expresion
//Pattern MY_PATTERN = Pattern.compile("<td valign=\"top\" class=\"dsitem\"><div class=\"dscaption\"><b>(.*?)</b> - (.*?) </div>(.*?)</td>");
}
| true | false | null | null |
diff --git a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractSshWagon.java b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractSshWagon.java
index 53527720..168354b1 100644
--- a/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractSshWagon.java
+++ b/wagon-providers/wagon-ssh/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractSshWagon.java
@@ -1,538 +1,542 @@
package org.apache.maven.wagon.providers.ssh;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Proxy;
import com.jcraft.jsch.ProxyHTTP;
import com.jcraft.jsch.ProxySOCKS5;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import org.apache.maven.wagon.AbstractWagon;
import org.apache.maven.wagon.CommandExecutionException;
import org.apache.maven.wagon.CommandExecutor;
import org.apache.maven.wagon.PermissionModeUtils;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.WagonConstants;
import org.apache.maven.wagon.authentication.AuthenticationException;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.apache.maven.wagon.authorization.AuthorizationException;
import org.apache.maven.wagon.events.TransferEvent;
import org.apache.maven.wagon.providers.ssh.interactive.InteractiveUserInfo;
import org.apache.maven.wagon.providers.ssh.interactive.NullInteractiveUserInfo;
import org.apache.maven.wagon.providers.ssh.interactive.UserInfoUIKeyboardInteractiveProxy;
import org.apache.maven.wagon.providers.ssh.knownhost.KnownHostsProvider;
import org.apache.maven.wagon.repository.RepositoryPermissions;
import org.apache.maven.wagon.resource.Resource;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Properties;
/**
* Common SSH operations.
*
* @author <a href="mailto:[email protected]">Brett Porter</a>
* @version $Id$
* @todo cache pass[words|phases]
*/
public abstract class AbstractSshWagon
extends AbstractWagon
implements CommandExecutor
{
public static final int DEFAULT_SSH_PORT = 22;
public static final int SOCKS5_PROXY_PORT = 1080;
protected Session session;
public static final String EXEC_CHANNEL = "exec";
private static final int LINE_BUFFER_SIZE = 256;
private static final byte LF = '\n';
private KnownHostsProvider knownHostsProvider;
private InteractiveUserInfo interactiveUserInfo;
private UIKeyboardInteractive uIKeyboardInteractive;
public void openConnection()
throws AuthenticationException
{
if ( authenticationInfo == null )
{
authenticationInfo = new AuthenticationInfo();
}
if ( authenticationInfo.getUserName() == null )
{
authenticationInfo.setUserName( System.getProperty( "user.name" ) );
}
JSch sch = new JSch();
int port = getRepository().getPort();
if ( port == WagonConstants.UNKNOWN_PORT )
{
port = DEFAULT_SSH_PORT;
}
String host = getRepository().getHost();
try
{
session = sch.getSession( authenticationInfo.getUserName(), host, port );
}
catch ( JSchException e )
{
fireSessionError( e );
throw new AuthenticationException( "Cannot connect. Reason: " + e.getMessage(), e );
}
// If user don't define a password, he want to use a private key
if ( authenticationInfo.getPassword() == null )
{
File privateKey;
if ( authenticationInfo.getPrivateKey() != null )
{
privateKey = new File( authenticationInfo.getPrivateKey() );
}
else
{
privateKey = findPrivateKey();
}
if ( privateKey.exists() )
{
if ( authenticationInfo.getPassphrase() == null )
{
authenticationInfo.setPassphrase( "" );
}
fireSessionDebug( "Using private key: " + privateKey );
try
{
sch.addIdentity( privateKey.getAbsolutePath(), authenticationInfo.getPassphrase() );
}
catch ( JSchException e )
{
fireSessionError( e );
throw new AuthenticationException( "Cannot connect. Reason: " + e.getMessage(), e );
}
}
}
if ( proxyInfo != null && proxyInfo.getHost() != null )
{
Proxy proxy;
int proxyPort = proxyInfo.getPort();
// HACK: if port == 1080 we will use SOCKS5 Proxy, otherwise will use HTTP Proxy
if ( proxyPort == SOCKS5_PROXY_PORT )
{
proxy = new ProxySOCKS5( proxyInfo.getHost() );
( (ProxySOCKS5) proxy ).setUserPasswd( proxyInfo.getUserName(), proxyInfo.getPassword() );
}
else
{
proxy = new ProxyHTTP( proxyInfo.getHost(), proxyPort );
( (ProxyHTTP) proxy ).setUserPasswd( proxyInfo.getUserName(), proxyInfo.getPassword() );
}
try
{
proxy.connect( session, host, port );
}
catch ( Exception e )
{
fireSessionError( e );
throw new AuthenticationException( "Cannot connect. Reason: " + e.getMessage(), e );
}
}
Properties config = new Properties();
config.setProperty( "BatchMode", interactive ? "no" : "yes" );
if ( !interactive )
{
interactiveUserInfo = new NullInteractiveUserInfo();
uIKeyboardInteractive = null;
}
// username and password will be given via UserInfo interface.
UserInfo ui = new WagonUserInfo( authenticationInfo, interactiveUserInfo );
if ( uIKeyboardInteractive != null )
{
ui = new UserInfoUIKeyboardInteractiveProxy( ui, uIKeyboardInteractive );
}
if ( knownHostsProvider != null )
{
try
{
knownHostsProvider.addConfiguration( config );
knownHostsProvider.addKnownHosts( sch, ui );
}
catch ( JSchException e )
{
fireSessionError( e );
// continue without known_hosts
}
}
session.setConfig( config );
session.setUserInfo( ui );
try
{
session.connect();
if ( knownHostsProvider != null )
{
knownHostsProvider.storeKnownHosts( sch );
}
}
catch ( JSchException e )
{
fireSessionError( e );
throw new AuthenticationException( "Cannot connect. Reason: " + e.getMessage(), e );
}
}
private File findPrivateKey()
{
String privateKeyDirectory = System.getProperty( "wagon.privateKeyDirectory" );
if ( privateKeyDirectory == null )
{
privateKeyDirectory = System.getProperty( "user.home" );
}
File privateKey = new File( privateKeyDirectory, ".ssh/id_dsa" );
if ( !privateKey.exists() )
{
privateKey = new File( privateKeyDirectory, ".ssh/id_rsa" );
}
return privateKey;
}
public void executeCommand( String command )
throws CommandExecutionException
{
ChannelExec channel = null;
InputStream in = null;
InputStream err = null;
OutputStream out = null;
try
{
fireTransferDebug( "Executing command: " + command );
channel = (ChannelExec) session.openChannel( EXEC_CHANNEL );
channel.setCommand( command + "\n" );
out = channel.getOutputStream();
in = channel.getInputStream();
err = channel.getErrStream();
channel.connect();
sendEom( out );
String line = readLine( err );
if ( line != null )
{
- throw new CommandExecutionException( line );
+ // ignore this error
+ if ( !line.startsWith( "Could not chdir to home directory" ) )
+ {
+ throw new CommandExecutionException( line );
+ }
}
}
catch ( JSchException e )
{
throw new CommandExecutionException( "Cannot execute remote command: " + command, e );
}
catch ( IOException e )
{
throw new CommandExecutionException( "Cannot execute remote command: " + command, e );
}
finally
{
IOUtil.close( out );
IOUtil.close( in );
IOUtil.close( err );
if ( channel != null )
{
channel.disconnect();
}
}
}
protected String readLine( InputStream in )
throws IOException
{
byte[] buf = new byte[LINE_BUFFER_SIZE];
String result = null;
for ( int i = 0; result == null; i++ )
{
if ( in.read( buf, i, 1 ) != 1 )
{
return null;
}
if ( buf[i] == LF )
{
result = new String( buf, 0, i );
}
}
return result;
}
protected static void sendEom( OutputStream out )
throws IOException
{
out.write( 0 );
out.flush();
}
public void closeConnection()
{
if ( session != null )
{
session.disconnect();
session = null;
}
}
protected void handleGetException( Resource resource, Exception e, File destination )
throws TransferFailedException, ResourceDoesNotExistException
{
fireTransferError( resource, e, TransferEvent.REQUEST_GET );
if ( destination.exists() )
{
boolean deleted = destination.delete();
if ( !deleted )
{
destination.deleteOnExit();
}
}
String msg = "Error occured while downloading '" + resource + "' from the remote repository:" + getRepository();
throw new TransferFailedException( msg, e );
}
private static class WagonUserInfo
implements UserInfo
{
private final InteractiveUserInfo userInfo;
private String password;
private String passphrase;
WagonUserInfo( AuthenticationInfo authInfo, InteractiveUserInfo userInfo )
{
this.userInfo = userInfo;
this.password = authInfo.getPassword();
this.passphrase = authInfo.getPassphrase();
}
public String getPassphrase()
{
return passphrase;
}
public String getPassword()
{
return password;
}
public boolean promptPassphrase( String arg0 )
{
if ( passphrase == null && userInfo != null )
{
passphrase = userInfo.promptPassphrase( arg0 );
}
return passphrase != null;
}
public boolean promptPassword( String arg0 )
{
if ( password == null && userInfo != null )
{
password = userInfo.promptPassword( arg0 );
}
return password != null;
}
public boolean promptYesNo( String arg0 )
{
if ( userInfo != null )
{
return userInfo.promptYesNo( arg0 );
}
else
{
return false;
}
}
public void showMessage( String message )
{
if ( userInfo != null )
{
userInfo.showMessage( message );
}
}
}
public final KnownHostsProvider getKnownHostsProvider()
{
return knownHostsProvider;
}
public final void setKnownHostsProvider( KnownHostsProvider knownHostsProvider )
{
if ( knownHostsProvider == null )
{
throw new IllegalArgumentException( "knownHostsProvider can't be null" );
}
this.knownHostsProvider = knownHostsProvider;
}
public InteractiveUserInfo getInteractiveUserInfo()
{
return interactiveUserInfo;
}
public void setInteractiveUserInfo( InteractiveUserInfo interactiveUserInfo )
{
if ( interactiveUserInfo == null )
{
throw new IllegalArgumentException( "interactiveUserInfo can't be null" );
}
this.interactiveUserInfo = interactiveUserInfo;
}
public void putDirectory( File sourceDirectory, String destinationDirectory )
throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
{
String basedir = getRepository().getBasedir();
destinationDirectory = StringUtils.replace( destinationDirectory, "\\", "/" );
String path = getPath( basedir, destinationDirectory );
try
{
if ( getRepository().getPermissions() != null )
{
String dirPerms = getRepository().getPermissions().getDirectoryMode();
if ( dirPerms != null )
{
String umaskCmd = "umask " + PermissionModeUtils.getUserMaskFor( dirPerms );
executeCommand( umaskCmd );
}
}
String mkdirCmd = "mkdir -p " + path;
executeCommand( mkdirCmd );
}
catch ( CommandExecutionException e )
{
throw new TransferFailedException( "Error performing commands for file transfer", e );
}
File zipFile;
try
{
zipFile = File.createTempFile( "wagon", ".zip" );
zipFile.deleteOnExit();
List files = FileUtils.getFileNames( sourceDirectory, "**/**", "", false );
createZip( files, zipFile, sourceDirectory );
}
catch ( IOException e )
{
throw new TransferFailedException( "Unable to create ZIP archive of directory", e );
}
put( zipFile, getPath( destinationDirectory, zipFile.getName() ) );
try
{
executeCommand( "cd " + path + "; unzip -o " + zipFile.getName() + "; rm -f " + zipFile.getName() );
zipFile.delete();
RepositoryPermissions permissions = getRepository().getPermissions();
if ( permissions != null && permissions.getGroup() != null )
{
executeCommand( "chgrp -Rf " + permissions.getGroup() + " " + path );
}
if ( permissions != null && permissions.getFileMode() != null )
{
executeCommand( "chmod -Rf " + permissions.getFileMode() + " " + path );
}
}
catch ( CommandExecutionException e )
{
throw new TransferFailedException( "Error performing commands for file transfer", e );
}
}
public boolean supportsDirectoryCopy()
{
return true;
}
}
| true | false | null | null |
diff --git a/src/directtalkserver/MainClass.java b/src/directtalkserver/MainClass.java
index fb3915c..5c0efad 100644
--- a/src/directtalkserver/MainClass.java
+++ b/src/directtalkserver/MainClass.java
@@ -1,58 +1,57 @@
package directtalkserver;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MainClass
{
public static void main(String[] args)
{
ServerSocket ssocket = null;
Socket connection = null;
OutputStream client = null;
int ch = 0;
if (args.length != 1)
{
System.out.println("Wrong number of args (takes 1).");
return;
}
try
{
ssocket = new ServerSocket(Integer.parseInt(args[0]));
}
catch (IOException | NumberFormatException e)
{
e.printStackTrace();
return;
}
try
{
System.out.println("Listening on port 4444 (single connection).");
connection = ssocket.accept();
client = connection.getOutputStream();
System.out.println("Got Connection: "
+ connection.getInetAddress().getHostName());
while (true)
{
ch = (int) (Math.random() * 255);
System.out.println("Sending random byte " + ch);
client.write(ch);
- client.flush();
Thread.sleep(1000);
}
}
catch (IOException e)
{
- e.printStackTrace();
+ System.out.println("Error: " + e.getMessage());
}
catch (InterruptedException e)
{
- e.printStackTrace();
+ System.out.println("Error: " + e.getMessage());
}
}
}
| false | true | public static void main(String[] args)
{
ServerSocket ssocket = null;
Socket connection = null;
OutputStream client = null;
int ch = 0;
if (args.length != 1)
{
System.out.println("Wrong number of args (takes 1).");
return;
}
try
{
ssocket = new ServerSocket(Integer.parseInt(args[0]));
}
catch (IOException | NumberFormatException e)
{
e.printStackTrace();
return;
}
try
{
System.out.println("Listening on port 4444 (single connection).");
connection = ssocket.accept();
client = connection.getOutputStream();
System.out.println("Got Connection: "
+ connection.getInetAddress().getHostName());
while (true)
{
ch = (int) (Math.random() * 255);
System.out.println("Sending random byte " + ch);
client.write(ch);
client.flush();
Thread.sleep(1000);
}
}
catch (IOException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
| public static void main(String[] args)
{
ServerSocket ssocket = null;
Socket connection = null;
OutputStream client = null;
int ch = 0;
if (args.length != 1)
{
System.out.println("Wrong number of args (takes 1).");
return;
}
try
{
ssocket = new ServerSocket(Integer.parseInt(args[0]));
}
catch (IOException | NumberFormatException e)
{
e.printStackTrace();
return;
}
try
{
System.out.println("Listening on port 4444 (single connection).");
connection = ssocket.accept();
client = connection.getOutputStream();
System.out.println("Got Connection: "
+ connection.getInetAddress().getHostName());
while (true)
{
ch = (int) (Math.random() * 255);
System.out.println("Sending random byte " + ch);
client.write(ch);
Thread.sleep(1000);
}
}
catch (IOException e)
{
System.out.println("Error: " + e.getMessage());
}
catch (InterruptedException e)
{
System.out.println("Error: " + e.getMessage());
}
}
|
diff --git a/src/com/android/inputmethod/latin/ContactsDictionary.java b/src/com/android/inputmethod/latin/ContactsDictionary.java
index e8faf45a..6f7f4b6a 100644
--- a/src/com/android/inputmethod/latin/ContactsDictionary.java
+++ b/src/com/android/inputmethod/latin/ContactsDictionary.java
@@ -1,128 +1,130 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.inputmethod.latin;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.provider.ContactsContract.Contacts;
-import android.util.Log;
public class ContactsDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
Contacts._ID,
Contacts.DISPLAY_NAME,
};
private static final int INDEX_NAME = 1;
private ContentObserver mObserver;
private boolean mRequiresReload;
+ private long mLastLoadedContacts;
+
public ContactsDictionary(Context context) {
super(context);
// Perform a managed query. The Activity will handle closing and requerying the cursor
// when needed.
ContentResolver cres = context.getContentResolver();
cres.registerContentObserver(Contacts.CONTENT_URI, true, mObserver = new ContentObserver(null) {
@Override
public void onChange(boolean self) {
mRequiresReload = true;
}
});
loadDictionary();
}
public synchronized void close() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
}
private synchronized void loadDictionary() {
- Cursor cursor = getContext().getContentResolver()
- .query(Contacts.CONTENT_URI, PROJECTION, null, null, null);
- if (cursor != null) {
- addWords(cursor);
+ long now = android.os.SystemClock.uptimeMillis();
+ if (mLastLoadedContacts == 0
+ || now - mLastLoadedContacts > 30 * 60 * 1000 /* 30 minutes */) {
+ Cursor cursor = getContext().getContentResolver()
+ .query(Contacts.CONTENT_URI, PROJECTION, null, null, null);
+ if (cursor != null) {
+ addWords(cursor);
+ }
+ mRequiresReload = false;
+ mLastLoadedContacts = now;
}
- mRequiresReload = false;
}
@Override
public synchronized void getWords(final WordComposer codes, final WordCallback callback) {
if (mRequiresReload) loadDictionary();
super.getWords(codes, callback);
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
if (mRequiresReload) loadDictionary();
return super.isValidWord(word);
}
private void addWords(Cursor cursor) {
clearDictionary();
final int maxWordLength = getMaxWordLength();
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(INDEX_NAME);
if (name != null) {
int len = name.length();
// TODO: Better tokenization for non-Latin writing systems
for (int i = 0; i < len; i++) {
if (Character.isLetter(name.charAt(i))) {
int j;
for (j = i + 1; j < len; j++) {
char c = name.charAt(j);
if (!(c == '-' || c == '\'' ||
Character.isLetter(c))) {
break;
}
}
String word = name.substring(i, j);
i = j - 1;
// Safeguard against adding really long words. Stack
// may overflow due to recursion
if (word.length() < maxWordLength) {
super.addWord(word, 128);
}
}
}
}
cursor.moveToNext();
}
}
cursor.close();
}
}
| false | false | null | null |
diff --git a/Player.java b/Player.java
index acce839..2bc80f9 100644
--- a/Player.java
+++ b/Player.java
@@ -1,197 +1,214 @@
import java.awt.*;
public class Player {
static final int SIZE = 20; // the pentagon's side size
- int pase = 10;
+ int pase = 20;
// initial positions
int x = Volfied.BOARD_WIDTH/2;
int y = Volfied.BOARD_HEIGHT;
boolean first_time = true;
boolean dead = false;
boolean isAttacking = false;
static int lives = 3;
BrokenLine trail = new BrokenLine(false); // an open broken line of points
public Polygon getPolygon() {
Polygon p = new Polygon();
int n = 5; // pentagon has 5 points.
double angle = 2 * Math.PI / n;
int r = SIZE;
for(int i=0; i < n; i++) {
double v = i * angle;
int x, y;
x = (int) Math.round(r * Math.cos(v));
y = (int) Math.round(r * Math.sin(v));
p.addPoint(x, y);
}
return p;
}
public void draw(Graphics g) {
if (!isDead()) {
g.setColor(Color.blue);
trail.draw(g, Volfied.GRID_X, Volfied.GRID_Y);
g.setColor(Color.CYAN);
g.fillPolygon(getPaintable());
}
else {
g.drawString("Dead!", x + Volfied.GRID_X, y + Volfied.GRID_Y);
manageDeath();
lives--;
}
}
public String toString() {
Polygon poli = getPolygon();
String ret = "Player position=" + x + ", " + y + "\n";
for (int i = 0; i < poli.npoints; i++)
ret += "P[" + i + "]=[" + poli.xpoints[i] + ", " + poli.ypoints[i] + "] ";
ret += "\n";
return ret;
}
public void setSpeed(int new_speed) {
this.pase = new_speed;
}
public Polygon getPaintable() {
Polygon ret = getPolygon();
ret.translate(x + Volfied.GRID_X, y + Volfied.GRID_Y);
return ret;
}
public Polygon getTranslatedPolygon() {
Polygon cp_poly = getPolygon();
cp_poly.translate(x, y);
return cp_poly;
}
public boolean isMovingOnPerimeter(Point curr_player_pos, Point next_player_pos) {
return Volfied.terain.isPointOnPerimeter(curr_player_pos)
&& Volfied.terain.isPointOnPerimeter(next_player_pos);
}
public int getLives() {
return lives;
}
public static void waiting (int n){
long t0, t1;
t0 = System.currentTimeMillis();
do{
t1 = System.currentTimeMillis();
}
while ((t1 - t0) < (n * 1000));
}
public void manageDeath() {
this.x = trail.points.get(0).x;
this.y = trail.points.get(0).y;
isAttacking = false;
first_time = true;
trail.points.clear();
}
public void attack(Point curr_player_pos, Point next_player_pos) {
if (first_time) {
trail.addPointExtdeningSegment(curr_player_pos);
first_time = false;
}
this.trail.addPointExtdeningSegment(next_player_pos);
System.out.println("TRAIL:" + trail);
if (Volfied.terain.isPointOnPerimeter(next_player_pos)) {
// finalize attack
isAttacking = false;
first_time = true; // reset first_time
BrokenLine polys[] = Volfied.terain.poli.cutTerrain(trail);
int monsterPosition = Volfied.ship.getPosition(polys);
trail = new BrokenLine(false);
Volfied.terain.poli = polys[monsterPosition];
}
}
public boolean hasMoreLives() {
if (lives > 0)
return true;
return false;
}
public boolean isTrailOnPoly(Polygon enemy) {
int n = enemy.npoints;
for (int i = 0; i < n; i++)
if (trail.isPointOnPerimeter(new Point(enemy.xpoints[i], enemy.ypoints[i])))
return true;
return false;
}
public boolean isDead() {
Polygon cp_ship = Volfied.ship.getTranslatedPolygon();
Polygon cp_player = getTranslatedPolygon();
if (isAttacking && (cp_player.intersects(cp_ship.getBounds())))
return true;
for (int i = 0; i < Volfied.n_critter; i++) {
Volfied.critters.get(i);
if (isAttacking && cp_player.intersects(Volfied.critters.get(i).getPolygon().getBounds()))
return true;
if (isAttacking && isTrailOnPoly(Volfied.critters.get(i).getTranslatedPolygon()))
return true;
}
if (isAttacking && (isTrailOnPoly(cp_ship)))
return true;
for (int i = 0; i < Volfied.ship.bombs.size(); i++)
if (isAttacking && Volfied.ship.bombs.get(i).getTranslated().intersects(cp_player.getBounds2D()))
return true;
return false;
}
public boolean isPacket(Point next_player_pos) {
for (int i = 0; i < Volfied.packets.size(); i++) {
Polygon next_player = getPolygon();
next_player.translate(next_player_pos.x, next_player_pos.y);
if (next_player.intersects(Volfied.packets.get(i).getTranslatedPolygon().getBounds2D()))
return true;
}
return false;
}
public void key_decide(int keyCode) {
Point curr_player_pos = new Point(this.x, this.y);
- Point next_player_pos = curr_player_pos.getNewPosition(keyCode, pase);
- if (Volfied.terain.isOuter(next_player_pos)) {
+
+ Point next_player_pos = null;
+
+ int p = pase;
+ while (p > 0)
+ {
+ next_player_pos = curr_player_pos.getNewPosition(keyCode, p);
+
+ if (!Volfied.terain.isOuter(next_player_pos))
+ break;
+ // when nearing an edge we might not have enough space to do a full pase
+ // in that case retry with a smaller pase.
+ p--;
+ }
+
+ if (p == 0) {
+ // if moving a single pixel from the current position in the direction
+ // indicated by keyCode will get us out of the terrain, then we
+ // surely cannot move in that direction.
System.out.println("next point is outer: " + next_player_pos);
return;
}
if (isMovingOnPerimeter(curr_player_pos, next_player_pos)) {
this.x = next_player_pos.x;
this.y = next_player_pos.y;
System.out.println("TERIT:" + Volfied.terain.poli);
}
else if (!isPacket(next_player_pos)) {
isAttacking = true;
attack(curr_player_pos, next_player_pos);
this.x = next_player_pos.x;
this.y = next_player_pos.y;
}
}
}
| false | false | null | null |
diff --git a/yahoo-weather-java-api/src/main/java/com/github/fedy2/weather/binding/adapter/RFC822DateAdapter.java b/yahoo-weather-java-api/src/main/java/com/github/fedy2/weather/binding/adapter/RFC822DateAdapter.java
index 84a43d3..57ad225 100644
--- a/yahoo-weather-java-api/src/main/java/com/github/fedy2/weather/binding/adapter/RFC822DateAdapter.java
+++ b/yahoo-weather-java-api/src/main/java/com/github/fedy2/weather/binding/adapter/RFC822DateAdapter.java
@@ -1,60 +1,60 @@
/**
*
*/
package com.github.fedy2.weather.binding.adapter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author "Federico De Faveri [email protected]"
*
*/
public class RFC822DateAdapter extends XmlAdapter<String, Date> {
public static final SimpleDateFormat rfc822DateFormats[] = new SimpleDateFormat[] {
- new SimpleDateFormat("EEE, d MMM yy HH:mm:ss z"),
- new SimpleDateFormat("EEE, d MMM yy HH:mm z"),
- new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"),
- new SimpleDateFormat("EEE, d MMM yyyy HH:mm z"),
- new SimpleDateFormat("d MMM yy HH:mm z"),
- new SimpleDateFormat("d MMM yy HH:mm:ss z"),
- new SimpleDateFormat("d MMM yyyy HH:mm z"),
- new SimpleDateFormat("d MMM yyyy HH:mm:ss z"),
+ new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss z"),
+ new SimpleDateFormat("EEE, dd MMM yy HH:mm z"),
+ new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"),
+ new SimpleDateFormat("EEE, dd MMM yyyy HH:mm z"),
+ new SimpleDateFormat("dd MMM yy HH:mm z"),
+ new SimpleDateFormat("dd MMM yy HH:mm:ss z"),
+ new SimpleDateFormat("dd MMM yyyy HH:mm z"),
+ new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"),
//exception to RFC 822 format used by Yahoo "Thu, 22 Dec 2011 1:50 pm CET"
- new SimpleDateFormat("EEE, d MMM yyyy HH:mm a z")};
+ new SimpleDateFormat("EEE, dd MMM yyyy HH:mm a z")};
protected Logger logger = LoggerFactory.getLogger(RFC822DateAdapter.class);
protected SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yy HH:mm:ss z");
/**
* {@inheritDoc}
*/
@Override
public String marshal(Date v) throws Exception {
return dateFormat.format(v);
}
/**
* {@inheritDoc}
*/
@Override
public Date unmarshal(String v) throws Exception {
for (SimpleDateFormat format:rfc822DateFormats) {
try {
return format.parse(v);
} catch(Exception e)
{}//skipping exception
}
logger.warn("Unknow date format \"{}\"",v);
return null;
}
}
| false | false | null | null |
diff --git a/bundles/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java b/bundles/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java
index d1e50f84fc..3d37aacfa8 100644
--- a/bundles/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java
+++ b/bundles/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java
@@ -1,749 +1,752 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.engine.export.switcher;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.bonitasoft.engine.bpm.flownode.GatewayType;
import org.bonitasoft.engine.bpm.flownode.TaskPriority;
import org.bonitasoft.engine.bpm.flownode.TimerType;
import org.bonitasoft.engine.bpm.process.impl.ActivityDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.AutomaticTaskDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.BoundaryEventDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.CallActivityBuilder;
import org.bonitasoft.engine.bpm.process.impl.CatchMessageEventTriggerDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.EndEventDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.FlowElementBuilder;
import org.bonitasoft.engine.bpm.process.impl.GatewayDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.IntermediateCatchEventDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.IntermediateThrowEventDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.MultiInstanceLoopCharacteristicsBuilder;
import org.bonitasoft.engine.bpm.process.impl.ProcessDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.ReceiveTaskDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.SendTaskDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.StartEventDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.SubProcessDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.ThrowMessageEventTriggerBuilder;
import org.bonitasoft.engine.bpm.process.impl.UserFilterDefinitionBuilder;
import org.bonitasoft.engine.bpm.process.impl.UserTaskDefinitionBuilder;
import org.bonitasoft.engine.operation.LeftOperandBuilder;
import org.bonitasoft.engine.operation.OperationBuilder;
import org.bonitasoft.engine.operation.OperatorType;
import org.bonitasoft.studio.common.ExpressionConstants;
import org.bonitasoft.studio.common.TimerUtil;
import org.bonitasoft.studio.common.emf.tools.ModelHelper;
import org.bonitasoft.studio.common.log.BonitaStudioLog;
import org.bonitasoft.studio.engine.export.EngineExpressionUtil;
import org.bonitasoft.studio.model.connectorconfiguration.ConnectorParameter;
import org.bonitasoft.studio.model.expression.AbstractExpression;
import org.bonitasoft.studio.model.expression.Expression;
import org.bonitasoft.studio.model.expression.ListExpression;
import org.bonitasoft.studio.model.expression.Operation;
import org.bonitasoft.studio.model.process.AbstractCatchMessageEvent;
import org.bonitasoft.studio.model.process.AbstractTimerEvent;
import org.bonitasoft.studio.model.process.Activity;
import org.bonitasoft.studio.model.process.ActorFilter;
import org.bonitasoft.studio.model.process.BoundaryEvent;
import org.bonitasoft.studio.model.process.BoundaryMessageEvent;
import org.bonitasoft.studio.model.process.BoundarySignalEvent;
import org.bonitasoft.studio.model.process.BoundaryTimerEvent;
import org.bonitasoft.studio.model.process.CallActivity;
import org.bonitasoft.studio.model.process.Connection;
+import org.bonitasoft.studio.model.process.Correlation;
+import org.bonitasoft.studio.model.process.CorrelationTypeActive;
import org.bonitasoft.studio.model.process.Data;
import org.bonitasoft.studio.model.process.Element;
import org.bonitasoft.studio.model.process.EndErrorEvent;
import org.bonitasoft.studio.model.process.EndEvent;
import org.bonitasoft.studio.model.process.EndMessageEvent;
import org.bonitasoft.studio.model.process.EndSignalEvent;
import org.bonitasoft.studio.model.process.EndTerminatedEvent;
import org.bonitasoft.studio.model.process.FlowElement;
import org.bonitasoft.studio.model.process.InputMapping;
import org.bonitasoft.studio.model.process.IntermediateCatchMessageEvent;
import org.bonitasoft.studio.model.process.IntermediateCatchSignalEvent;
import org.bonitasoft.studio.model.process.IntermediateCatchTimerEvent;
import org.bonitasoft.studio.model.process.IntermediateErrorCatchEvent;
import org.bonitasoft.studio.model.process.IntermediateThrowMessageEvent;
import org.bonitasoft.studio.model.process.IntermediateThrowSignalEvent;
import org.bonitasoft.studio.model.process.Lane;
import org.bonitasoft.studio.model.process.Message;
import org.bonitasoft.studio.model.process.MultiInstantiation;
import org.bonitasoft.studio.model.process.NonInterruptingBoundaryTimerEvent;
import org.bonitasoft.studio.model.process.OperationContainer;
import org.bonitasoft.studio.model.process.OutputMapping;
import org.bonitasoft.studio.model.process.Pool;
import org.bonitasoft.studio.model.process.ProcessPackage;
import org.bonitasoft.studio.model.process.ReceiveTask;
import org.bonitasoft.studio.model.process.SearchIndex;
import org.bonitasoft.studio.model.process.SendTask;
import org.bonitasoft.studio.model.process.SourceElement;
import org.bonitasoft.studio.model.process.StartErrorEvent;
import org.bonitasoft.studio.model.process.StartEvent;
import org.bonitasoft.studio.model.process.StartMessageEvent;
import org.bonitasoft.studio.model.process.StartSignalEvent;
import org.bonitasoft.studio.model.process.StartTimerEvent;
import org.bonitasoft.studio.model.process.SubProcessEvent;
import org.bonitasoft.studio.model.process.Task;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
/**
* @author Romain Bioteau
*
*/
public class FlowElementSwitch extends AbstractSwitch {
private FlowElementBuilder builder;
public FlowElementSwitch(FlowElementBuilder processBuilder,Set<EObject> eObjectNotExported){
super(eObjectNotExported) ;
this.builder = processBuilder;
}
@Override
public Element caseSubProcessEvent(SubProcessEvent subProcessEvent) {
final SubProcessDefinitionBuilder subProcessBuilder = builder.addSubProcess(subProcessEvent.getName(), true).getSubProcessBuilder();
final FlowElementSwitch subProcessSwitch = new FlowElementSwitch(subProcessBuilder, eObjectNotExported);
List<FlowElement> flowElements = ModelHelper.getAllItemsOfType(subProcessEvent, ProcessPackage.Literals.FLOW_ELEMENT);
for (FlowElement flowElement : flowElements) {
if(!eObjectNotExported.contains(flowElement)){
subProcessSwitch.doSwitch(flowElement);
}
}
List<SourceElement> sourceElements = ModelHelper.getAllItemsOfType(subProcessEvent, ProcessPackage.Literals.SOURCE_ELEMENT);
SequenceFlowSwitch sequenceFlowSwitch = new SequenceFlowSwitch(subProcessBuilder) ;
for (SourceElement sourceElement : sourceElements) {
for (Connection connection : sourceElement.getOutgoing()) {
sequenceFlowSwitch.doSwitch(connection);
}
}
return subProcessEvent;
}
@Override
public Activity caseActivity(final Activity activity) {
AutomaticTaskDefinitionBuilder taskBuilder = builder.addAutomaticTask(activity.getName());
handleCommonActivity(activity, taskBuilder);
return activity;
}
@Override
public Element caseSendTask(SendTask senTask) {
org.bonitasoft.engine.expression.Expression targetProcess = null;
Message message = null;
if(!senTask.getEvents().isEmpty()){
message = senTask.getEvents().get(0);
targetProcess = EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetProcessExpression());
}
final SendTaskDefinitionBuilder taskBuilder = ((ProcessDefinitionBuilder)builder).addSendTask(senTask.getName(), message.getName(), targetProcess);
if(message != null){
taskBuilder.setTargetFlowNode(EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetElementExpression()));
if(message.getMessageContent() != null){
for(ListExpression row : message.getMessageContent().getExpressions()){
List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ;
org.bonitasoft.studio.model.expression.Expression idExp = col.get(0);
org.bonitasoft.studio.model.expression.Expression messageContentExp = col.get(1) ;
if(col.size()==2){
if (idExp.getContent()!=null
&& !idExp.getContent().isEmpty()
&& messageContentExp.getContent()!=null
&& !messageContentExp.getContent().isEmpty()){
taskBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ;
}
}
}
}
if(message.getCorrelation() != null){
for(ListExpression row : message.getCorrelation().getCorrelationAssociation().getExpressions()){
List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ;
if(col.size() == 2){
org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0);
org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1);
if(correlationKeyExp.getContent() != null
&& !correlationKeyExp.getContent().isEmpty()
&& valueExpression.getContent() != null
&& !valueExpression.getContent().isEmpty()){
taskBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ;
}
}
}
}
}
handleCommonActivity(senTask, taskBuilder);
return senTask;
}
@Override
public Element caseReceiveTask(ReceiveTask receiveTask) {
String messageName = receiveTask.getEvent();
final ReceiveTaskDefinitionBuilder taskBuilder = builder.addReceiveTask(receiveTask.getName(), messageName);
if(messageName != null){
for(Operation operation : receiveTask.getMessageContent()){
taskBuilder.addOperation(EngineExpressionUtil.createOperationForMessageContent(operation)) ;
}
if(receiveTask.getCorrelation() != null){
for(ListExpression row : receiveTask.getCorrelation().getExpressions()){
List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ;
if(col.size() == 2){
org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0);
org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1);
if(correlationKeyExp.getContent() != null
&& !correlationKeyExp.getContent().isEmpty()
&& valueExpression.getContent() != null
&& !valueExpression.getContent().isEmpty()){
taskBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ;
}
}
}
}
}
handleCommonActivity(receiveTask, taskBuilder);
return receiveTask;
}
@Override
public FlowElement caseStartMessageEvent(StartMessageEvent object) {
StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(object.getName()) ;
String message = object.getEvent() ;
if(message != null){
CatchMessageEventTriggerDefinitionBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message) ;
addMessageContent(object, triggerBuilder);
addMessageCorrelation(object, triggerBuilder);
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
@Override
public FlowElement caseIntermediateCatchMessageEvent(IntermediateCatchMessageEvent object) {
IntermediateCatchEventDefinitionBuilder eventBuilder = builder.addIntermediateCatchEvent(object.getName()) ;
String message = object.getEvent() ;
if(message != null){
CatchMessageEventTriggerDefinitionBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message) ;
addMessageContent(object, triggerBuilder);
addMessageCorrelation(object, triggerBuilder);
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
private void addMessageContent(AbstractCatchMessageEvent messageEvent, CatchMessageEventTriggerDefinitionBuilder triggerBuilder) {
for(Operation operation : messageEvent.getMessageContent()){
triggerBuilder.addOperation(EngineExpressionUtil.createOperationForMessageContent(operation)) ;
}
}
private void addMessageCorrelation(AbstractCatchMessageEvent messageEvent, CatchMessageEventTriggerDefinitionBuilder triggerBuilder){
if(messageEvent.getCorrelation() != null){
for(ListExpression row : messageEvent.getCorrelation().getExpressions()){
List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ;
if(col.size() == 2){
org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0);
org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1);
if(correlationKeyExp.getContent() != null
&& !correlationKeyExp.getContent().isEmpty()
&& valueExpression.getContent() != null
&& !valueExpression.getContent().isEmpty()){
triggerBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ;
}
}
}
}
}
@Override
public FlowElement caseIntermediateThrowMessageEvent(IntermediateThrowMessageEvent object) {
IntermediateThrowEventDefinitionBuilder eventBuilder = builder.addIntermediateThrowEvent(object.getName()) ;
for(Message message : object.getEvents()){
ThrowMessageEventTriggerBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message.getName(),EngineExpressionUtil.createExpression(message.getTargetProcessExpression()),EngineExpressionUtil.createExpression(message.getTargetElementExpression())) ;
if(message.getMessageContent() != null){
addThrowMessageContent(message, triggerBuilder);
}
- if(message.getCorrelation() != null){
+ final Correlation correlation = message.getCorrelation();
+ if(correlation != null && correlation.getCorrelationType()!=CorrelationTypeActive.INACTIVE){
addThrowMessageCorrelation(message, triggerBuilder);
}
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
protected void addThrowMessageCorrelation(Message message,
ThrowMessageEventTriggerBuilder triggerBuilder) {
for(ListExpression row : message.getCorrelation().getCorrelationAssociation().getExpressions()){
List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ;
if(col.size() == 2){
org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0);
org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1);
if(correlationKeyExp.getContent() != null
&& !correlationKeyExp.getContent().isEmpty()
&& valueExpression.getContent() != null
&& !valueExpression.getContent().isEmpty()){
triggerBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ;
}
}
}
}
protected void addThrowMessageContent(Message message,
ThrowMessageEventTriggerBuilder triggerBuilder) {
for(ListExpression row : message.getMessageContent().getExpressions()){
List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ;
org.bonitasoft.studio.model.expression.Expression idExp = col.get(0);
org.bonitasoft.studio.model.expression.Expression messageContentExp = col.get(1) ;
if(col.size()==2){
if (idExp.getContent()!=null
&& !idExp.getContent().isEmpty()
&& messageContentExp.getContent()!=null
&& !messageContentExp.getContent().isEmpty()){
triggerBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ;
}
}
}
}
@Override
public FlowElement caseEndMessageEvent(EndMessageEvent object) {
EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(object.getName()) ;
for(Message message : object.getEvents()){
ThrowMessageEventTriggerBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message.getName(),EngineExpressionUtil.createExpression(message.getTargetProcessExpression()),EngineExpressionUtil.createExpression(message.getTargetElementExpression())) ;
if(message.getMessageContent() != null){
for(ListExpression row : message.getMessageContent().getExpressions()){
List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ;
if(col.size()==2){
org.bonitasoft.studio.model.expression.Expression idExp=col.get(0);
org.bonitasoft.studio.model.expression.Expression messageContentExp =col.get(1);
if (idExp.getContent()!=null
&& !idExp.getContent().isEmpty()
&& messageContentExp.getContent()!=null
&& !messageContentExp.getContent().isEmpty()){
triggerBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ;
}
}
}
}
-
- if(message.getCorrelation() != null){
+ final Correlation correlation = message.getCorrelation();
+ if(correlation != null && correlation.getCorrelationType()!=CorrelationTypeActive.INACTIVE){
addThrowMessageCorrelation(message, triggerBuilder);
}
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
@Override
public Element caseStartSignalEvent(StartSignalEvent object) {
StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(object.getName()) ;
String signal = object.getSignalCode() ;
if(signal != null){
eventBuilder.addSignalEventTrigger(signal) ;
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
@Override
public EndSignalEvent caseEndSignalEvent(EndSignalEvent object) {
EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(object.getName()) ;
String signalCode = object.getSignalCode() ;
if(signalCode != null){
eventBuilder.addSignalEventTrigger(signalCode) ;
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
@Override
public IntermediateCatchSignalEvent caseIntermediateCatchSignalEvent(IntermediateCatchSignalEvent object) {
IntermediateCatchEventDefinitionBuilder eventBuilder = builder.addIntermediateCatchEvent(object.getName()) ;
String signal = object.getSignalCode() ;
if(signal != null){
eventBuilder.addSignalEventTrigger(signal) ;
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
@Override
public IntermediateThrowSignalEvent caseIntermediateThrowSignalEvent(IntermediateThrowSignalEvent object) {
IntermediateThrowEventDefinitionBuilder eventBuilder = builder.addIntermediateThrowEvent(object.getName()) ;
String signal = object.getSignalCode() ;
if(signal != null){
eventBuilder.addSignalEventTrigger(signal) ;
}
addDescription(eventBuilder, object.getDocumentation()) ;
return object;
}
@Override
public CallActivity caseCallActivity(CallActivity object) {
Expression version = object.getCalledActivityVersion() ;
if(version == null || version.getContent() == null || version.getContent().trim().isEmpty()){
version = null ; //latest version will be used by the engine
}
final CallActivityBuilder activityBuilder = builder.addCallActivity(object.getName(),
EngineExpressionUtil.createExpression(object.getCalledActivityName()),
EngineExpressionUtil.createExpression(version)) ;
for(InputMapping mapping : object.getInputMappings()){
final OperationBuilder opBuilder = new OperationBuilder();
opBuilder.createNewInstance();
opBuilder.setRightOperand(EngineExpressionUtil.createVariableExpression(mapping.getProcessSource()));
final LeftOperandBuilder builder = new LeftOperandBuilder() ;
builder.createNewInstance() ;
builder.setName(mapping.getSubprocessTarget()) ;
opBuilder.setLeftOperand(builder.done());
opBuilder.setType(OperatorType.ASSIGNMENT);
activityBuilder.addDataInputOperation(opBuilder.done());
}
for(OutputMapping mapping : object.getOutputMappings()){
final OperationBuilder opBuilder = new OperationBuilder();
opBuilder.createNewInstance();
final Data d = EcoreUtil.copy(mapping.getProcessTarget());
d.setName(mapping.getSubprocessSource());
opBuilder.setRightOperand(EngineExpressionUtil.createVariableExpression(d));
final LeftOperandBuilder builder = new LeftOperandBuilder() ;
builder.createNewInstance() ;
builder.setName(mapping.getProcessTarget().getName()) ;
opBuilder.setLeftOperand(builder.done());
opBuilder.setType(OperatorType.ASSIGNMENT);
activityBuilder.addDataOutputOperation(opBuilder.done());
}
handleCommonActivity(object, activityBuilder) ;
return object ;
}
@Override
public Task caseTask(final Task task) {
String actor = null;
ActorFilter filter = null ;
if(!task.getFilters().isEmpty()){
filter = task.getFilters().get(0) ;
}
if(task.isOverrideActorsOfTheLane()){
if (task.getActor() != null) {
actor = task.getActor().getName();
}
}else{
final Lane lane = ModelHelper.getParentLane(task) ;
if(lane != null && lane.getActor() != null){
actor = lane.getActor().getName();
}
if(task.getFilters().isEmpty() && !lane.getFilters().isEmpty()){
filter = lane.getFilters().get(0) ;
}
}
final UserTaskDefinitionBuilder taskBuilder = builder.addUserTask(task.getName(), actor);
handleCommonActivity(task, taskBuilder) ;
taskBuilder.addPriority(TaskPriority.values()[task.getPriority()].name()) ;
addExpectedDuration(taskBuilder,task) ;
if(filter != null){
final UserFilterDefinitionBuilder filterBuilder = taskBuilder.addUserFilter(filter.getName(), filter.getDefinitionId(),filter.getDefinitionVersion()) ;
for(ConnectorParameter parameter : filter.getConfiguration().getParameters()){
filterBuilder.addInput(parameter.getKey(), EngineExpressionUtil.createExpression(parameter.getExpression())) ;
}
}
return task;
}
@Override
public StartEvent caseStartEvent(final StartEvent startEvent) {
StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(startEvent.getName());
addDescription(eventBuilder, startEvent.getDocumentation()) ;
return startEvent;
}
@Override
public FlowElement caseStartTimerEvent(final StartTimerEvent startTimer) {
StartEventDefinitionBuilder startTimerBuilder = builder.addStartEvent(startTimer.getName());
final org.bonitasoft.engine.expression.Expression startConditionExpression = EngineExpressionUtil.createExpression(startTimer.getCondition());
if(ModelHelper.isInEvenementialSubProcessPool(startTimer)){
TimerType timerType = getTimerType(startTimer);
if(timerType != null){
startTimerBuilder.addTimerEventTriggerDefinition(timerType, startConditionExpression);
}
}else{
TimerType type = TimerType.CYCLE;
if(startConditionExpression.getReturnType().equals(String.class.getName())){
type = TimerType.CYCLE;
}else if(startConditionExpression.getReturnType().equals(Date.class.getName())){
type = TimerType.DATE;
}else if(startConditionExpression.getReturnType().equals(Long.class.getName())){
type = TimerType.DURATION;
}else{
throw new RuntimeException("Unsupported return type "+startConditionExpression.getReturnType()+" for Start timer condition "+startTimer.getName());
}
startTimerBuilder.addTimerEventTriggerDefinition(type, startConditionExpression);
}
addDescription(startTimerBuilder, startTimer.getDocumentation()) ;
return startTimer;
}
@Override
public FlowElement caseIntermediateCatchTimerEvent(IntermediateCatchTimerEvent timer) {
IntermediateCatchEventDefinitionBuilder timerBuilder = builder.addIntermediateCatchEvent(timer.getName());
TimerType timerType = getTimerType(timer);
if(timerType != null){
timerBuilder.addTimerEventTriggerDefinition(timerType, EngineExpressionUtil.createExpression(timer.getCondition()));
}
addDescription(timerBuilder, timer.getDocumentation()) ;
return timer;
}
private TimerType getTimerType(AbstractTimerEvent timer) {
if(TimerUtil.isDuration(timer)){
return TimerType.DURATION;
}else{
final String timerConditionReturnType = timer.getCondition().getReturnType();
try {
if(Number.class.isAssignableFrom(Class.forName(timerConditionReturnType))){
return TimerType.DURATION;
}else if(Date.class.getName().equals(timerConditionReturnType)){
return TimerType.DATE;
}
} catch (ClassNotFoundException e) {
BonitaStudioLog.error(e);
}
}
BonitaStudioLog.error("Timer type can't be defined for timer "+timer.getName()+". You might use a wrong return type. ", "org.bonitasoft.studio.engine");
return null;
}
@Override
public FlowElement caseEndEvent(final EndEvent endEvent) {
final EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(endEvent.getName());
addDescription(eventBuilder, endEvent.getDocumentation()) ;
return endEvent;
}
@Override
public Element caseStartErrorEvent(StartErrorEvent startErrorEvent) {
StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(startErrorEvent.getName());
eventBuilder.addErrorEventTrigger(startErrorEvent.getErrorCode());
addDescription(eventBuilder, startErrorEvent.getDocumentation()) ;
return startErrorEvent;
}
@Override
public Element caseEndErrorEvent(EndErrorEvent endErrorEvent) {
EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(endErrorEvent.getName());
eventBuilder.addErrorEventTrigger(endErrorEvent.getErrorCode());
addDescription(eventBuilder, endErrorEvent.getDocumentation()) ;
return endErrorEvent;
}
@Override
public FlowElement caseEndTerminatedEvent(final EndTerminatedEvent endTerminatedEvent) {
EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(endTerminatedEvent.getName());
eventBuilder.addTerminateEventTrigger();
addDescription(eventBuilder, endTerminatedEvent.getDocumentation()) ;
return endTerminatedEvent;
}
@Override
public FlowElement caseANDGateway(final org.bonitasoft.studio.model.process.ANDGateway gateway) {
builder.addGateway(gateway.getName(), GatewayType.PARALLEL);
// addDescription(gatewayBuilder, gateway.getDocumentation()) ;
return gateway;
}
@Override
public FlowElement caseInclusiveGateway(final org.bonitasoft.studio.model.process.InclusiveGateway gateway) {
builder.addGateway(gateway.getName(), GatewayType.INCLUSIVE);
return gateway;
}
@Override
public FlowElement caseXORGateway(final org.bonitasoft.studio.model.process.XORGateway gateway) {
final GatewayDefinitionBuilder gatewayBuilder = builder.addGateway(gateway.getName(), GatewayType.EXCLUSIVE);
// addDescription(gatewayBuilder, gateway.getDocumentation()) ;
return gateway;
}
protected void handleCommonActivity(final Activity activity, ActivityDefinitionBuilder taskBuilder) {
addData(taskBuilder, activity);
addOperation(taskBuilder, activity) ;
addLoop(taskBuilder,activity) ;
addConnector(taskBuilder,activity) ;
addKPIBinding(taskBuilder, activity);
addDisplayTitle(taskBuilder, activity) ;
addDescription(taskBuilder, activity.getDocumentation()) ;
addDisplayDescription(taskBuilder,activity) ;
addDisplayDescriptionAfterCompletion(taskBuilder,activity) ;
addMultiInstantiation(taskBuilder,activity);
addBoundaryEvents(taskBuilder, activity);
addDescription(taskBuilder, activity.getDocumentation());
}
private void addBoundaryEvents(ActivityDefinitionBuilder taskBuilder, Activity activity) {
for(BoundaryEvent boundaryEvent :activity.getBoundaryIntermediateEvents()){
BoundaryEventDefinitionBuilder boundaryEventBuilder = taskBuilder.addBoundaryEvent(boundaryEvent.getName(),!(boundaryEvent instanceof NonInterruptingBoundaryTimerEvent));
if(boundaryEvent instanceof IntermediateErrorCatchEvent){
String errorCode = ((IntermediateErrorCatchEvent) boundaryEvent).getErrorCode();
if(errorCode != null && errorCode.trim().isEmpty()){
errorCode = null;
}
boundaryEventBuilder.addErrorEventTrigger(errorCode);
} else if(boundaryEvent instanceof BoundaryMessageEvent){
CatchMessageEventTriggerDefinitionBuilder catchMessageEventTriggerDefinitionBuilder = boundaryEventBuilder.addMessageEventTrigger(((BoundaryMessageEvent) boundaryEvent).getEvent());
addMessageContent((BoundaryMessageEvent)boundaryEvent, catchMessageEventTriggerDefinitionBuilder);
} else if(boundaryEvent instanceof BoundaryTimerEvent){
TimerType timerType = getTimerType((BoundaryTimerEvent) boundaryEvent);
if(timerType != null){
boundaryEventBuilder.addTimerEventTriggerDefinition(timerType, EngineExpressionUtil.createExpression(((AbstractTimerEvent) boundaryEvent).getCondition()));
}
} else if(boundaryEvent instanceof BoundarySignalEvent){
boundaryEventBuilder.addSignalEventTrigger(((BoundarySignalEvent) boundaryEvent).getSignalCode());
}
}
}
protected void addMultiInstantiation( ActivityDefinitionBuilder taskBuilder , final Activity activity) {
if(activity.isIsMultiInstance()){
final MultiInstantiation multiInstantiation = activity.getMultiInstantiation();
final Expression completionCondition = multiInstantiation.getCompletionCondition();
if(multiInstantiation.isUseCardinality()){
final Expression cardinality = multiInstantiation.getCardinality();
if(cardinality != null && cardinality.getContent() != null && !cardinality.getContent().isEmpty()){
MultiInstanceLoopCharacteristicsBuilder multiInstanceBuilder = taskBuilder.addMultiInstance(multiInstantiation.isSequential(), EngineExpressionUtil.createExpression(cardinality));
if(completionCondition != null
&& completionCondition.getContent() != null
&& !completionCondition.getContent().isEmpty()){
multiInstanceBuilder.addCompletionCondition(EngineExpressionUtil.createExpression(completionCondition));
}
}
} else {
final Data collectionDataToMultiInstantiate = multiInstantiation.getCollectionDataToMultiInstantiate();
if(collectionDataToMultiInstantiate != null){
MultiInstanceLoopCharacteristicsBuilder multiInstanceBuilder = taskBuilder.addMultiInstance(multiInstantiation.isSequential(), collectionDataToMultiInstantiate.getName());
if(completionCondition != null
&& completionCondition.getContent() != null
&& !completionCondition.getContent().isEmpty()){
multiInstanceBuilder.addCompletionCondition(EngineExpressionUtil.createExpression(completionCondition));
}
final Data inputData = multiInstantiation.getInputData();
if(inputData != null){
multiInstanceBuilder.addDataInputItemRef(inputData.getName());
}
final Data outputData = multiInstantiation.getOutputData();
if(outputData != null) {
multiInstanceBuilder.addDataOutputItemRef(outputData.getName());
}
Data listDataContainingOutputResults = multiInstantiation.getListDataContainingOutputResults();
if(listDataContainingOutputResults != null){
multiInstanceBuilder.addLoopDataOutputRef(listDataContainingOutputResults.getName());
}
}
}
}
}
protected void addExpectedDuration(UserTaskDefinitionBuilder taskBuilder, Task task) {
final String duration = task.getDuration() ;
if(duration != null && !duration.isEmpty()){
try{
taskBuilder.addExpectedDuration(Long.parseLong(duration)) ;
}catch (NumberFormatException e) {
BonitaStudioLog.error(e) ;
}
}
}
protected void addDisplayDescription(ActivityDefinitionBuilder builder, FlowElement flowElement) {
org.bonitasoft.engine.expression.Expression exp = EngineExpressionUtil.createExpression(flowElement.getDynamicDescription()) ;
if(exp != null){
builder.addDisplayDescription(exp) ;
}
}
protected void addDisplayDescriptionAfterCompletion(ActivityDefinitionBuilder builder, FlowElement flowElement){
org.bonitasoft.engine.expression.Expression exp = EngineExpressionUtil.createExpression(flowElement.getStepSummary()) ;
if(exp != null){
builder.addDisplayDescriptionAfterCompletion(exp) ;
}
}
protected void addDisplayTitle(ActivityDefinitionBuilder builder, FlowElement flowElement) {
org.bonitasoft.engine.expression.Expression exp = EngineExpressionUtil.createExpression(flowElement.getDynamicLabel()) ;
if(exp != null){
builder.addDisplayName(exp) ;
}
}
protected void addOperation(ActivityDefinitionBuilder builder,OperationContainer activity) {
for(Operation operation : activity.getOperations()){
String inputType = null ;
if(!operation.getOperator().getInputTypes().isEmpty()){
inputType = operation.getOperator().getInputTypes().get(0) ;
}
if(operation.getLeftOperand() != null
&& operation.getLeftOperand().getContent() != null
&& operation.getRightOperand() != null
&& operation.getRightOperand().getContent() != null){
if (ExpressionConstants.SEARCH_INDEX_TYPE.equals(operation.getLeftOperand().getType())){
// get the pool to get the list of searchIndex list
Pool pool = null;
if(activity.eContainer() instanceof Pool){
pool = (Pool) activity.eContainer();
}else if(activity.eContainer().eContainer() instanceof Pool){
pool = (Pool) activity.eContainer().eContainer();
}
// get the searchIndex list
List<SearchIndex> searchIndexList = new ArrayList<SearchIndex>();
if(pool!=null){
searchIndexList = pool.getSearchIndexes();
}
int idx=1;
for(SearchIndex searchIdx : searchIndexList){
// get the related searchIndex to set the operation
if(searchIdx.getName().getContent().equals(operation.getLeftOperand().getName())){
builder.addOperation(EngineExpressionUtil.createLeftOperandIndex(idx), OperatorType.STRING_INDEX, null, null, EngineExpressionUtil.createExpression(operation.getRightOperand()));
break;
}
idx++;
}
} else {
builder.addOperation(EngineExpressionUtil.createLeftOperand(operation.getLeftOperand()), OperatorType.valueOf(operation.getOperator().getType()), operation.getOperator().getExpression(),inputType, EngineExpressionUtil.createExpression(operation.getRightOperand())) ;
}
}
}
}
protected void addLoop(ActivityDefinitionBuilder builder,Activity activity) {
if(activity.getIsLoop()){
if(activity.getLoopCondition() != null){
builder.addLoop(activity.getTestBefore(), EngineExpressionUtil.createExpression(activity.getLoopCondition()), EngineExpressionUtil.createExpression(activity.getLoopMaximum())) ;
}
}
}
}
| false | false | null | null |
diff --git a/src/bspkrs/worldstatecheckpoints/fml/WorldStateCheckpointsMod.java b/src/bspkrs/worldstatecheckpoints/fml/WorldStateCheckpointsMod.java
index b33cae7..58a5bb6 100644
--- a/src/bspkrs/worldstatecheckpoints/fml/WorldStateCheckpointsMod.java
+++ b/src/bspkrs/worldstatecheckpoints/fml/WorldStateCheckpointsMod.java
@@ -1,163 +1,171 @@
package bspkrs.worldstatecheckpoints.fml;
import java.util.EnumSet;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.NetLoginHandler;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet1Login;
import net.minecraft.server.MinecraftServer;
import bspkrs.fml.util.bspkrsCoreProxy;
import bspkrs.util.Const;
import bspkrs.util.ModVersionChecker;
+import bspkrs.worldstatecheckpoints.CommandWSC;
import bspkrs.worldstatecheckpoints.WSCSettings;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.Metadata;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
+import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.network.IConnectionHandler;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
@Mod(name = "WorldStateCheckpoints", modid = "WorldStateCheckpoints", version = "Forge " + WSCSettings.VERSION_NUMBER, dependencies = "required-after:mod_bspkrsCore", useMetadata = true)
@NetworkMod(connectionHandler = WorldStateCheckpointsMod.class)
public class WorldStateCheckpointsMod implements IConnectionHandler
{
public static ModVersionChecker versionChecker;
private String versionURL = Const.VERSION_URL + "/Minecraft/" + Const.MCVERSION + "/worldStateCheckpointsForge.version";
private String mcfTopic = "http://www.minecraftforum.net/topic/1009577-";
@Metadata(value = "WorldStateCheckpoints")
public static ModMetadata metadata;
@Instance(value = "WorldStateCheckpoints")
public static WorldStateCheckpointsMod instance;
private static WSCTicker ticker;
public WorldStateCheckpointsMod()
{
new bspkrsCoreProxy();
}
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
metadata = event.getModMetadata();
WSCSettings.loadConfig(event.getSuggestedConfigurationFile());
if (bspkrsCoreProxy.instance.allowUpdateCheck)
{
versionChecker = new ModVersionChecker(metadata.name, metadata.version, versionURL, mcfTopic);
versionChecker.checkVersionWithLoggingBySubStringAsFloat(metadata.version.length() - 1, metadata.version.length());
}
}
@EventHandler
public void init(FMLInitializationEvent event)
{
KeyBinding[] keys = { WSCSettings.bindKey };
boolean[] repeats = { false };
KeyBindingRegistry.registerKeyBinding(new WSCKeyHandler(keys, repeats));
ticker = new WSCTicker(EnumSet.noneOf(TickType.class));
TickRegistry.registerTickHandler(ticker, Side.CLIENT);
}
+ @EventHandler
+ public void serverStarting(FMLServerStartingEvent event)
+ {
+ event.registerServerCommand(new CommandWSC());
+ }
+
/**
* 2) Called when a player logs into the server SERVER SIDE
*
* @param player
* @param netHandler
* @param manager
*/
@Override
public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager)
{
}
/**
* If you don't want the connection to continue, return a non-empty string here If you do, you can do other stuff here- note no FML
* negotiation has occured yet though the client is verified as having FML installed
*
* SERVER SIDE
*
* @param netHandler
* @param manager
*/
@Override
public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager)
{
return null;
}
/**
* 1) Fired when a remote connection is opened CLIENT SIDE
*
* @param netClientHandler
* @param server
* @param port
*/
@Override
public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager)
{
}
/**
*
* 1) Fired when a local connection is opened
*
* CLIENT SIDE
*
* @param netClientHandler
* @param servers
*/
@Override
public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager)
{
}
/**
* 4) Fired when a connection closes
*
* ALL SIDES
*
* @param manager
*/
@Override
public void connectionClosed(INetworkManager manager)
{
ticker.removeTicks(EnumSet.of(TickType.CLIENT));
WSCSettings.cpm = null;
}
/**
* 3) Fired when the client established the connection to the server
*
* CLIENT SIDE
*
* @param clientHandler
* @param manager
* @param login
*/
@Override
public void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login)
{
if (WSCSettings.mc.isSingleplayer())
{
WSCSettings.justLoadedWorld = true;
ticker.addTicks(EnumSet.of(TickType.CLIENT));
}
}
}
| false | false | null | null |
diff --git a/modules/suggest/src/java/org/apache/lucene/search/suggest/Lookup.java b/modules/suggest/src/java/org/apache/lucene/search/suggest/Lookup.java
index e200225b2..5783eea53 100644
--- a/modules/suggest/src/java/org/apache/lucene/search/suggest/Lookup.java
+++ b/modules/suggest/src/java/org/apache/lucene/search/suggest/Lookup.java
@@ -1,153 +1,162 @@
package org.apache.lucene.search.suggest;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Comparator;
import java.util.List;
import org.apache.lucene.search.spell.Dictionary;
import org.apache.lucene.search.spell.TermFreqIterator;
import org.apache.lucene.util.BytesRefIterator;
import org.apache.lucene.util.PriorityQueue;
/**
* Simple Lookup interface for {@link CharSequence} suggestions.
* @lucene.experimental
*/
public abstract class Lookup {
/**
* Result of a lookup.
*/
public static final class LookupResult implements Comparable<LookupResult> {
public final CharSequence key;
public final long value;
public LookupResult(CharSequence key, long value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return key + "/" + value;
}
/** Compare alphabetically. */
public int compareTo(LookupResult o) {
return CHARSEQUENCE_COMPARATOR.compare(key, o.key);
}
}
+ /**
+ * A simple char-by-char comparator for {@link CharSequence}
+ */
public static final Comparator<CharSequence> CHARSEQUENCE_COMPARATOR = new CharSequenceComparator();
private static class CharSequenceComparator implements Comparator<CharSequence> {
@Override
public int compare(CharSequence o1, CharSequence o2) {
final int l1 = o1.length();
final int l2 = o2.length();
final int aStop = Math.min(l1, l2);
for (int i = 0; i < aStop; i++) {
int diff = o1.charAt(i) - o2.charAt(i);
if (diff != 0) {
return diff;
}
}
// One is a prefix of the other, or, they are equal:
return l1 - l2;
}
}
+ /**
+ * A {@link PriorityQueue} collecting a fixed size of high priority {@link LookupResult}
+ */
public static final class LookupPriorityQueue extends PriorityQueue<LookupResult> {
-
+ // TODO: should we move this out of the interface into a utility class?
public LookupPriorityQueue(int size) {
super(size);
}
@Override
protected boolean lessThan(LookupResult a, LookupResult b) {
return a.value < b.value;
}
+ /**
+ * Returns the top N results in descending order.
+ * @return the top N results in descending order.
+ */
public LookupResult[] getResults() {
int size = size();
LookupResult[] res = new LookupResult[size];
for (int i = size - 1; i >= 0; i--) {
res[i] = pop();
}
return res;
}
}
/** Build lookup from a dictionary. Some implementations may require sorted
* or unsorted keys from the dictionary's iterator - use
* {@link SortedTermFreqIteratorWrapper} or
* {@link UnsortedTermFreqIteratorWrapper} in such case.
*/
public void build(Dictionary dict) throws IOException {
BytesRefIterator it = dict.getWordsIterator();
TermFreqIterator tfit;
if (it instanceof TermFreqIterator) {
tfit = (TermFreqIterator)it;
} else {
tfit = new TermFreqIterator.TermFreqIteratorWrapper(it);
}
build(tfit);
}
/**
* Builds up a new internal {@link Lookup} representation based on the given {@link TermFreqIterator}.
* The implementation might re-sort the data internally.
*/
public abstract void build(TermFreqIterator tfit) throws IOException;
/**
* Look up a key and return possible completion for this key.
* @param key lookup key. Depending on the implementation this may be
* a prefix, misspelling, or even infix.
* @param onlyMorePopular return only more popular results
* @param num maximum number of results to return
* @return a list of possible completions, with their relative weight (e.g. popularity)
*/
public abstract List<LookupResult> lookup(CharSequence key, boolean onlyMorePopular, int num);
/**
* Persist the constructed lookup data to a directory. Optional operation.
* @param output {@link OutputStream} to write the data to.
* @return true if successful, false if unsuccessful or not supported.
* @throws IOException when fatal IO error occurs.
*/
public abstract boolean store(OutputStream output) throws IOException;
/**
* Discard current lookup data and load it from a previously saved copy.
* Optional operation.
* @param input the {@link InputStream} to load the lookup data.
* @return true if completed successfully, false if unsuccessful or not supported.
* @throws IOException when fatal IO error occurs.
*/
public abstract boolean load(InputStream input) throws IOException;
}
diff --git a/modules/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java b/modules/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java
index 86a10cde7..dc656e4ae 100644
--- a/modules/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java
+++ b/modules/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java
@@ -1,201 +1,200 @@
package org.apache.lucene.search.suggest.tst;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.search.suggest.Lookup;
import org.apache.lucene.search.suggest.SortedTermFreqIteratorWrapper;
import org.apache.lucene.search.spell.TermFreqIterator;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.UnicodeUtil;
public class TSTLookup extends Lookup {
TernaryTreeNode root = new TernaryTreeNode();
TSTAutocomplete autocomplete = new TSTAutocomplete();
@Override
public void build(TermFreqIterator tfit) throws IOException {
root = new TernaryTreeNode();
// buffer first
if (tfit.getComparator() != BytesRef.getUTF8SortedAsUTF16Comparator()) {
// make sure it's sorted and the comparator uses UTF16 sort order
tfit = new SortedTermFreqIteratorWrapper(tfit, BytesRef.getUTF8SortedAsUTF16Comparator());
}
ArrayList<String> tokens = new ArrayList<String>();
ArrayList<Number> vals = new ArrayList<Number>();
BytesRef spare;
CharsRef charsSpare = new CharsRef();
while ((spare = tfit.next()) != null) {
charsSpare.grow(spare.length);
UnicodeUtil.UTF8toUTF16(spare.bytes, spare.offset, spare.length, charsSpare);
tokens.add(charsSpare.toString());
vals.add(Long.valueOf(tfit.weight()));
}
autocomplete.balancedTree(tokens.toArray(), vals.toArray(), 0, tokens.size() - 1, root);
}
public boolean add(CharSequence key, Object value) {
autocomplete.insert(root, key, value, 0);
// XXX we don't know if a new node was created
return true;
}
public Object get(CharSequence key) {
List<TernaryTreeNode> list = autocomplete.prefixCompletion(root, key, 0);
if (list == null || list.isEmpty()) {
return null;
}
for (TernaryTreeNode n : list) {
if (charSeqEquals(n.token, key)) {
return n.val;
}
}
return null;
}
private static boolean charSeqEquals(CharSequence left, CharSequence right) {
int len = left.length();
if (len != right.length()) {
return false;
}
for (int i = 0; i < len; i++) {
if (left.charAt(i) != right.charAt(i)) {
return false;
}
}
return true;
}
@Override
public List<LookupResult> lookup(CharSequence key, boolean onlyMorePopular, int num) {
List<TernaryTreeNode> list = autocomplete.prefixCompletion(root, key, 0);
List<LookupResult> res = new ArrayList<LookupResult>();
if (list == null || list.size() == 0) {
return res;
}
int maxCnt = Math.min(num, list.size());
if (onlyMorePopular) {
LookupPriorityQueue queue = new LookupPriorityQueue(num);
+
for (TernaryTreeNode ttn : list) {
queue.insertWithOverflow(new LookupResult(ttn.token, ((Number)ttn.val).longValue()));
}
for (LookupResult lr : queue.getResults()) {
res.add(lr);
}
} else {
for (int i = 0; i < maxCnt; i++) {
TernaryTreeNode ttn = list.get(i);
res.add(new LookupResult(ttn.token, ((Number)ttn.val).longValue()));
}
}
return res;
}
private static final byte LO_KID = 0x01;
private static final byte EQ_KID = 0x02;
private static final byte HI_KID = 0x04;
private static final byte HAS_TOKEN = 0x08;
private static final byte HAS_VALUE = 0x10;
// pre-order traversal
private void readRecursively(DataInputStream in, TernaryTreeNode node) throws IOException {
node.splitchar = in.readChar();
byte mask = in.readByte();
if ((mask & HAS_TOKEN) != 0) {
node.token = in.readUTF();
}
if ((mask & HAS_VALUE) != 0) {
node.val = Long.valueOf(in.readLong());
}
if ((mask & LO_KID) != 0) {
node.loKid = new TernaryTreeNode();
readRecursively(in, node.loKid);
}
if ((mask & EQ_KID) != 0) {
node.eqKid = new TernaryTreeNode();
readRecursively(in, node.eqKid);
}
if ((mask & HI_KID) != 0) {
node.hiKid = new TernaryTreeNode();
readRecursively(in, node.hiKid);
}
}
// pre-order traversal
private void writeRecursively(DataOutputStream out, TernaryTreeNode node) throws IOException {
// write out the current node
out.writeChar(node.splitchar);
// prepare a mask of kids
byte mask = 0;
if (node.eqKid != null) mask |= EQ_KID;
if (node.loKid != null) mask |= LO_KID;
if (node.hiKid != null) mask |= HI_KID;
if (node.token != null) mask |= HAS_TOKEN;
if (node.val != null) mask |= HAS_VALUE;
out.writeByte(mask);
if (node.token != null) out.writeUTF(node.token);
if (node.val != null) out.writeLong(((Number)node.val).longValue());
// recurse and write kids
if (node.loKid != null) {
writeRecursively(out, node.loKid);
}
if (node.eqKid != null) {
writeRecursively(out, node.eqKid);
}
if (node.hiKid != null) {
writeRecursively(out, node.hiKid);
}
}
@Override
public synchronized boolean store(OutputStream output) throws IOException {
DataOutputStream out = new DataOutputStream(output);
try {
writeRecursively(out, root);
out.flush();
} finally {
IOUtils.close(output);
}
return true;
}
@Override
public synchronized boolean load(InputStream input) throws IOException {
DataInputStream in = new DataInputStream(input);
root = new TernaryTreeNode();
try {
readRecursively(in, root);
} finally {
IOUtils.close(in);
}
return true;
}
+
}
| false | false | null | null |
diff --git a/src/jvm/clojure/lang/BytecodeCompiler.java b/src/jvm/clojure/lang/BytecodeCompiler.java
index 33add518..4931df51 100644
--- a/src/jvm/clojure/lang/BytecodeCompiler.java
+++ b/src/jvm/clojure/lang/BytecodeCompiler.java
@@ -1,1658 +1,1662 @@
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
* which can be found in the file CPL.TXT at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Aug 21, 2007 */
package clojure.lang;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.Method;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
import org.objectweb.asm.util.CheckClassAdapter;
import java.io.*;
import java.math.BigInteger;
public class BytecodeCompiler implements Opcodes{
static final Symbol DEF = Symbol.create("def");
static final Symbol LOOP = Symbol.create("loop");
static final Symbol RECUR = Symbol.create("recur");
static final Symbol IF = Symbol.create("if");
static final Symbol LET = Symbol.create("let");
static final Symbol DO = Symbol.create("do");
static final Symbol FN = Symbol.create("fn");
static final Symbol QUOTE = Symbol.create("quote");
static final Symbol THE_VAR = Symbol.create("the-var");
static final Symbol DOT = Symbol.create(".");
static final Symbol ASSIGN = Symbol.create("=");
static final Symbol TRY_FINALLY = Symbol.create("try-finally");
static final Symbol THROW = Symbol.create("throw");
static final Symbol THISFN = Symbol.create("thisfn");
static final Symbol IFN = Symbol.create("clojure.lang", "IFn");
static final Symbol CLASS = Symbol.create("class");
static final Symbol IMPORT = Symbol.create("import");
static final Symbol USE = Symbol.create("use");
static final Symbol _AMP_ = Symbol.create("&");
private static final int MAX_POSITIONAL_ARITY = 20;
private static final Type OBJECT_TYPE;
private static final Type KEYWORD_TYPE = Type.getType(Keyword.class);
private static final Type VAR_TYPE = Type.getType(Var.class);
private static final Type SYMBOL_TYPE = Type.getType(Symbol.class);
private static final Type NUM_TYPE = Type.getType(Num.class);
private static final Type IFN_TYPE = Type.getType(IFn.class);
final static Type CLASS_TYPE = Type.getType(Class.class);
final static Type REFLECTOR_TYPE = Type.getType(Reflector.class);
final static Type THROWABLE_TYPE = Type.getType(Throwable.class);
private static final Type[][] ARG_TYPES;
private static final Type[] EXCEPTION_TYPES = {Type.getType(Exception.class)};
static
{
OBJECT_TYPE = Type.getType(Object.class);
ARG_TYPES = new Type[MAX_POSITIONAL_ARITY][];
for(int i = 0; i < MAX_POSITIONAL_ARITY; ++i)
{
Type[] a = new Type[i];
for(int j = 0; j < i; j++)
a[j] = OBJECT_TYPE;
ARG_TYPES[i] = a;
}
}
//symbol->localbinding
static public Var LOCAL_ENV = Var.create(null);
//vector<localbinding>
static public Var LOOP_LOCALS = Var.create();
//Label
static public Var LOOP_LABEL = Var.create();
//keyword->keywordexpr
static public Var KEYWORDS = Var.create();
//var->var
static public Var VARS = Var.create();
//FnFrame
static public Var METHOD = Var.create(null);
//String
static public Var SOURCE = Var.create(null);
//Integer
static public Var NEXT_LOCAL_NUM = Var.create(0);
//Integer
static public Var RET_LOCAL_NUM = Var.create();
//DynamicClassLoader
static public Var LOADER = Var.create();
enum C{
STATEMENT, //value ignored
EXPRESSION, //value required
RETURN, //tail position relative to enclosing recur frame
EVAL
}
interface Expr{
Object eval() throws Exception;
void emit(C context, FnExpr fn, GeneratorAdapter gen);
}
static class DefExpr implements Expr{
final Var var;
final Expr init;
final boolean initProvided;
final static Method bindRootMethod = Method.getMethod("void bindRoot(Object)");
public DefExpr(Var var, Expr init, boolean initProvided){
this.var = var;
this.init = init;
this.initProvided = initProvided;
}
public Object eval() throws Exception{
if(initProvided)
var.bindRoot(init.eval());
return var;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
fn.emitVar(gen, var);
if(initProvided)
{
gen.dup();
init.emit(C.EXPRESSION, fn, gen);
gen.invokeVirtual(VAR_TYPE, bindRootMethod);
}
if(context == C.STATEMENT)
gen.pop();
}
public static Expr parse(C context, ISeq form) throws Exception{
//(def x) or (def x initexpr)
if(RT.count(form) > 3)
throw new Exception("Too many arguments to def");
else if(RT.count(form) < 2)
throw new Exception("Too few arguments to def");
else if(!(RT.second(form) instanceof Symbol))
throw new Exception("Second argument to def must be a Symbol");
Var v = lookupVar((Symbol) RT.second(form), true);
if(!v.sym.ns.equals(currentNS()))
throw new Exception("Can't create defs outside of current ns");
return new DefExpr(v, analyze(C.EXPRESSION, RT.third(form), v.sym.name), RT.count(form) == 3);
}
}
static class AssignExpr implements Expr{
final AssignableExpr target;
final Expr val;
public AssignExpr(AssignableExpr target, Expr val){
this.target = target;
this.val = val;
}
public Object eval() throws Exception{
return target.evalAssign(val);
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
target.emitAssign(context, fn, gen, val);
}
public static Expr parse(C context, ISeq form) throws Exception{
if(RT.length(form) != 3)
throw new IllegalArgumentException("Malformed assignment, expecting (= target val)");
Expr target = analyze(C.EXPRESSION, RT.second(form));
if(!(target instanceof AssignableExpr))
throw new IllegalArgumentException("Invalid assignment target");
return new AssignExpr((AssignableExpr) target, analyze(C.EXPRESSION, RT.third(form)));
}
}
static class VarExpr implements Expr, AssignableExpr{
final Var var;
final Symbol tag;
final static Method getMethod = Method.getMethod("Object get()");
final static Method setMethod = Method.getMethod("Object set(Object)");
public VarExpr(Var var, Symbol tag){
this.var = var;
this.tag = tag;
}
public Object eval() throws Exception{
return var.get();
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
{
fn.emitVar(gen, var);
gen.invokeVirtual(VAR_TYPE, getMethod);
}
}
public Object evalAssign(Expr val) throws Exception{
return var.set(val.eval());
}
public void emitAssign(C context, FnExpr fn, GeneratorAdapter gen,
Expr val){
fn.emitVar(gen, var);
val.emit(C.EXPRESSION, fn, gen);
gen.invokeVirtual(VAR_TYPE, setMethod);
if(context == C.STATEMENT)
gen.pop();
}
}
static class TheVarExpr implements Expr{
final Var var;
public TheVarExpr(Var var){
this.var = var;
}
public Object eval() throws Exception{
return var;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
fn.emitVar(gen, var);
}
public static Expr parse(C context, ISeq form) throws Exception{
Symbol sym = (Symbol) RT.second(form);
Var v = lookupVar(sym, false);
if(v != null)
return new TheVarExpr(v);
throw new Exception("Unable to resolve var: " + sym + " in this context");
}
}
static class KeywordExpr implements Expr{
final Keyword k;
public KeywordExpr(Keyword k){
this.k = k;
}
public Object eval() throws Exception{
return k;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
fn.emitKeyword(gen, k);
}
}
static abstract class LiteralExpr implements Expr{
abstract Object val();
public Object eval(){
return val();
}
}
static interface AssignableExpr{
Object evalAssign(Expr val) throws Exception;
void emitAssign(C context, FnExpr fn, GeneratorAdapter gen, Expr val);
}
static abstract class HostExpr implements Expr{
public static Expr parse(C context, ISeq form) throws Exception{
//(. x fieldname-sym) or (. x (methodname-sym args...))
if(RT.length(form) != 3)
throw new IllegalArgumentException("Malformed member expression, expecting (. target member)");
//determine static or instance
//static target must be symbol, either fully.qualified.Classname or Classname that has been imported
String className = null;
if(RT.second(form) instanceof Symbol)
{
Symbol sym = (Symbol) RT.second(form);
if(sym.ns == null) //if ns-qualified can't be classname
{
if(sym.name.indexOf('.') > 0)
className = sym.name;
else
{
IPersistentMap imports = (IPersistentMap) RT.IMPORTS.get();
className = (String) imports.valAt(sym);
}
}
}
//at this point className will be non-null if static
Expr instance = null;
if(className == null)
instance = analyze(C.EXPRESSION, RT.second(form));
if(RT.third(form) instanceof Symbol) //field
{
Symbol sym = (Symbol) RT.third(form);
if(className != null)
return new StaticFieldExpr(className, sym.name);
else
return new InstanceFieldExpr(instance, sym.name);
}
else if(RT.third(form) instanceof ISeq && RT.first(RT.third(form)) instanceof Symbol)
{
Symbol sym = (Symbol) RT.first(RT.third(form));
PersistentVector args = PersistentVector.EMPTY;
for(ISeq s = RT.rest(RT.third(form)); s != null; s = s.rest())
args = args.cons(analyze(C.EXPRESSION, s.first()));
if(className != null)
return new StaticMethodExpr(className, sym.name, args);
else
return new InstanceMethodExpr(instance, sym.name, args);
}
else
throw new IllegalArgumentException("Malformed member expression");
}
}
static abstract class FieldExpr extends HostExpr{
}
static class InstanceFieldExpr extends FieldExpr implements AssignableExpr{
final Expr target;
final String fieldName;
final static Method getInstanceFieldMethod = Method.getMethod("Object getInstanceField(Object,String)");
final static Method setInstanceFieldMethod = Method.getMethod("Object setInstanceField(Object,String,Object)");
public InstanceFieldExpr(Expr target, String fieldName){
this.target = target;
this.fieldName = fieldName;
}
public Object eval() throws Exception{
return Reflector.getInstanceField(target.eval(), fieldName);
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
{
target.emit(C.EXPRESSION, fn, gen);
gen.push(fieldName);
gen.invokeStatic(REFLECTOR_TYPE, getInstanceFieldMethod);
}
}
public Object evalAssign(Expr val) throws Exception{
return Reflector.setInstanceField(target.eval(), fieldName, val.eval());
}
public void emitAssign(C context, FnExpr fn, GeneratorAdapter gen,
Expr val){
target.emit(C.EXPRESSION, fn, gen);
gen.push(fieldName);
val.emit(C.EXPRESSION, fn, gen);
gen.invokeStatic(REFLECTOR_TYPE, setInstanceFieldMethod);
if(context == C.STATEMENT)
gen.pop();
}
}
static class StaticFieldExpr extends FieldExpr implements AssignableExpr{
final String className;
final String fieldName;
final static Method getStaticFieldMethod = Method.getMethod("Object getStaticField(String,String)");
final static Method setStaticFieldMethod = Method.getMethod("Object setStaticField(String,String,Object)");
public StaticFieldExpr(String className, String fieldName){
this.className = className;
this.fieldName = fieldName;
}
public Object eval() throws Exception{
return Reflector.getStaticField(className, fieldName);
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
gen.push(className);
gen.push(fieldName);
gen.invokeStatic(REFLECTOR_TYPE, getStaticFieldMethod);
}
public Object evalAssign(Expr val) throws Exception{
return Reflector.setStaticField(className, fieldName, val.eval());
}
public void emitAssign(C context, FnExpr fn, GeneratorAdapter gen,
Expr val){
gen.push(className);
gen.push(fieldName);
val.emit(C.EXPRESSION, fn, gen);
gen.invokeStatic(REFLECTOR_TYPE, setStaticFieldMethod);
if(context == C.STATEMENT)
gen.pop();
}
}
static abstract class MethodExpr extends HostExpr{
static void emitArgsAsArray(IPersistentArray args, FnExpr fn, GeneratorAdapter gen){
gen.push(args.count());
gen.newArray(OBJECT_TYPE);
for(int i = 0; i < args.count(); i++)
{
gen.dup();
gen.push(i);
((Expr) args.nth(i)).emit(C.EXPRESSION, fn, gen);
gen.arrayStore(OBJECT_TYPE);
}
}
}
static class InstanceMethodExpr extends MethodExpr{
final Expr target;
final String methodName;
final IPersistentArray args;
final static Method invokeInstanceMethodMethod =
Method.getMethod("Object invokeInstanceMethod(Object,String,Object[])");
public InstanceMethodExpr(Expr target, String methodName, IPersistentArray args){
this.args = args;
this.methodName = methodName;
this.target = target;
}
public Object eval() throws Exception{
Object targetval = target.eval();
Object[] argvals = new Object[args.count()];
for(int i = 0; i < args.count(); i++)
argvals[i] = ((Expr) args.nth(i)).eval();
return Reflector.invokeInstanceMethod(targetval, methodName, argvals);
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
target.emit(C.EXPRESSION, fn, gen);
gen.push(methodName);
emitArgsAsArray(args, fn, gen);
gen.invokeStatic(REFLECTOR_TYPE, invokeInstanceMethodMethod);
if(context == C.STATEMENT)
gen.pop();
}
}
static class StaticMethodExpr extends MethodExpr{
final String className;
final String methodName;
final IPersistentArray args;
final static Method invokeStaticMethodMethod =
Method.getMethod("Object invokeStaticMethod(String,String,Object[])");
public StaticMethodExpr(String className, String methodName, IPersistentArray args){
this.className = className;
this.methodName = methodName;
this.args = args;
}
public Object eval() throws Exception{
Object[] argvals = new Object[args.count()];
for(int i = 0; i < args.count(); i++)
argvals[i] = ((Expr) args.nth(i)).eval();
return Reflector.invokeStaticMethod(className, methodName, argvals);
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
gen.push(className);
gen.push(methodName);
emitArgsAsArray(args, fn, gen);
gen.invokeStatic(REFLECTOR_TYPE, invokeStaticMethodMethod);
if(context == C.STATEMENT)
gen.pop();
}
}
static class QuoteExpr extends LiteralExpr{
//stuff quoted vals in classloader at compile time, pull out at runtime
//this won't work for static compilation...
final Object v;
final int id;
final static Type DYNAMIC_CLASSLOADER_TYPE = Type.getType(DynamicClassLoader.class);
final static Method getClassMethod = Method.getMethod("Class getClass()");
final static Method getClassLoaderMethod = Method.getMethod("ClassLoader getClassLoader()");
final static Method getQuotedValMethod = Method.getMethod("Object getQuotedVal(int)");
public QuoteExpr(int id, Object v){
this.id = id;
this.v = v;
}
Object val(){
return v;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
{
gen.loadThis();
gen.invokeVirtual(OBJECT_TYPE, getClassMethod);
gen.invokeVirtual(CLASS_TYPE, getClassLoaderMethod);
gen.checkCast(DYNAMIC_CLASSLOADER_TYPE);
gen.push(id);
gen.invokeVirtual(DYNAMIC_CLASSLOADER_TYPE, getQuotedValMethod);
}
}
public static Expr parse(C context, ISeq form){
Object v = RT.second(form);
int id = RT.nextID();
DynamicClassLoader loader = (DynamicClassLoader) LOADER.get();
loader.registerQuotedVal(id, v);
return new QuoteExpr(id, v);
}
}
static class NilExpr extends LiteralExpr{
Object val(){
return null;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
gen.visitInsn(Opcodes.ACONST_NULL);
}
}
static NilExpr NIL_EXPR = new NilExpr();
static class NumExpr extends LiteralExpr{
final Num num;
final static Method numFromIntMethod = Method.getMethod("clojure.lang.Num from(int)");
final static Method numFromDoubleMethod = Method.getMethod("clojure.lang.Num from(double)");
final static Method numFromBigIntMethod = Method.getMethod("clojure.lang.Num from(java.math.BigInteger)");
final static Method numDivideMethod =
Method.getMethod("clojure.lang.Num divide(java.math.BigInteger,java.math.BigInteger)");
final static Type BIGINT_TYPE = Type.getType(BigInteger.class);
final static Method bigintFromStringCtor = Method.getMethod("void <init>(String)");
public NumExpr(Num num){
this.num = num;
}
Object val(){
return num;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
{
Class nclass = num.getClass();
if(nclass == FixNum.class)
{
gen.push(num.intValue());
gen.invokeStatic(NUM_TYPE, numFromIntMethod);
}
else if(nclass == DoubleNum.class)
{
gen.push(num.doubleValue());
gen.invokeStatic(NUM_TYPE, numFromDoubleMethod);
}
else if(nclass == BigNum.class)
{
emitBigInteger(gen, num);
gen.invokeStatic(NUM_TYPE, numFromBigIntMethod);
}
else if(nclass == RatioNum.class)
{
RatioNum r = (RatioNum) num;
emitBigInteger(gen, r.numerator);
emitBigInteger(gen, r.denominator);
gen.invokeStatic(NUM_TYPE, numDivideMethod);
}
else
throw new UnsupportedOperationException("Unknown Num type");
}
}
static void emitBigInteger(GeneratorAdapter gen, Num num){
gen.newInstance(BIGINT_TYPE);
gen.dup();
gen.push(num.toString());
gen.invokeConstructor(BIGINT_TYPE, bigintFromStringCtor);
}
}
static class StringExpr extends LiteralExpr{
final String str;
public StringExpr(String str){
this.str = str;
}
Object val(){
return str;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
gen.push(str);
}
}
static class CharExpr extends LiteralExpr{
final Character ch;
final static Type CHARACTER_TYPE = Type.getObjectType("java/lang/Character");
final static Method charValueOfMethod = Method.getMethod("Character valueOf(char)");
public CharExpr(Character ch){
this.ch = ch;
}
Object val(){
return ch;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
{
gen.push(ch.charValue());
gen.invokeStatic(CHARACTER_TYPE, charValueOfMethod);
}
}
}
static class TryFinallyExpr implements Expr{
final Expr tryExpr;
final Expr finallyExpr;
public TryFinallyExpr(Expr tryExpr, Expr finallyExpr){
this.tryExpr = tryExpr;
this.finallyExpr = finallyExpr;
}
public Object eval() throws Exception{
throw new UnsupportedOperationException("Can't eval try");
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
Label startTry = gen.newLabel();
Label endTry = gen.newLabel();
Label end = gen.newLabel();
Label finallyLabel = gen.newLabel();
gen.visitTryCatchBlock(startTry, endTry, finallyLabel, null);
gen.mark(startTry);
tryExpr.emit(context, fn, gen);
gen.mark(endTry);
finallyExpr.emit(C.STATEMENT, fn, gen);
gen.goTo(end);
gen.mark(finallyLabel);
//exception should be on stack
finallyExpr.emit(C.STATEMENT, fn, gen);
gen.throwException();
gen.mark(end);
}
public static Expr parse(C context, ISeq form) throws Exception{
//(try-finally try-expr finally-expr)
if(form.count() != 3)
throw new IllegalArgumentException(
"Wrong number of arguments, expecting: (try-finally try-expr finally-expr) ");
if(context == C.EVAL)
return analyze(context, RT.list(RT.list(FN, PersistentVector.EMPTY, form)));
return new TryFinallyExpr(analyze(context, RT.second(form)),
analyze(C.STATEMENT, RT.third(form)));
}
}
static class ThrowExpr implements Expr{
final Expr excExpr;
public ThrowExpr(Expr excExpr){
this.excExpr = excExpr;
}
public Object eval() throws Exception{
throw (Exception) excExpr.eval();
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
excExpr.emit(C.EXPRESSION, fn, gen);
gen.checkCast(THROWABLE_TYPE);
gen.throwException();
}
public static Expr parse(C context, ISeq form) throws Exception{
return new ThrowExpr(analyze(C.EXPRESSION, RT.second(form)));
}
}
static class IfExpr implements Expr{
final Expr testExpr;
final Expr thenExpr;
final Expr elseExpr;
public IfExpr(Expr testExpr, Expr thenExpr, Expr elseExpr){
this.testExpr = testExpr;
this.thenExpr = thenExpr;
this.elseExpr = elseExpr;
}
public Object eval() throws Exception{
if(testExpr.eval() != null)
return thenExpr.eval();
return elseExpr.eval();
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
Label elseLabel = gen.newLabel();
Label endLabel = gen.newLabel();
testExpr.emit(C.EXPRESSION, fn, gen);
gen.ifNull(elseLabel);
thenExpr.emit(context, fn, gen);
gen.goTo(endLabel);
gen.mark(elseLabel);
elseExpr.emit(context, fn, gen);
gen.mark(endLabel);
}
public static Expr parse(C context, ISeq form) throws Exception{
//(if test then) or (if test then else)
if(form.count() > 4)
throw new Exception("Too many arguments to if");
else if(form.count() < 3)
throw new Exception("Too few arguments to if");
return new IfExpr(analyze(C.EXPRESSION, RT.second(form)),
analyze(context, RT.third(form)),
analyze(context, RT.fourth(form)));
}
}
static public IPersistentMap CHAR_MAP =
PersistentHashMap.create('-', "_",
'.', "_DOT_",
':', "_COLON_",
'+', "_PLUS_",
'>', "_GT_",
'<', "_LT_",
'=', "_EQ_",
'~', "_TILDE_",
'!', "_BANG_",
'@', "_CIRCA_",
'#', "_SHARP_",
'$', "_DOLLARSIGN_",
'%', "_PERCENT_",
'^', "_CARET_",
'&', "_AMPERSAND_",
'*', "_STAR_",
'{', "_LBRACE_",
'}', "_RBRACE_",
'[', "_LBRACK_",
']', "_RBRACK_",
'/', "_SLASH_",
'\\', "_BSLASH_",
'?', "_QMARK_");
static String munge(String name){
StringBuilder sb = new StringBuilder();
for(char c : name.toCharArray())
{
String sub = (String) CHAR_MAP.valAt(c);
if(sub != null)
sb.append(sub);
else
sb.append(c);
}
return sb.toString();
}
static class InvokeExpr implements Expr{
final Expr fexpr;
final IPersistentArray args;
public InvokeExpr(Expr fexpr, IPersistentArray args){
this.fexpr = fexpr;
this.args = args;
}
public Object eval() throws Exception{
IFn fn = (IFn) fexpr.eval();
PersistentVector argvs = PersistentVector.EMPTY;
for(int i = 0; i < args.count(); i++)
argvs = argvs.cons(((Expr) args.nth(i)).eval());
return fn.applyTo(RT.seq(argvs));
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
fexpr.emit(C.EXPRESSION, fn, gen);
gen.checkCast(IFN_TYPE);
for(int i = 0; i < args.count(); i++)
{
Expr e = (Expr) args.nth(i);
e.emit(C.EXPRESSION, fn, gen);
}
gen.invokeInterface(IFN_TYPE, new Method("invoke", OBJECT_TYPE, ARG_TYPES[args.count()]));
if(context == C.STATEMENT)
gen.pop();
}
public static Expr parse(C context, ISeq form) throws Exception{
Expr fexpr = analyze(C.EXPRESSION, form.first());
PersistentVector args = PersistentVector.EMPTY;
for(ISeq s = RT.seq(form.rest()); s != null; s = s.rest())
{
args = args.cons(analyze(C.EXPRESSION, s.first()));
}
if(args.count() > MAX_POSITIONAL_ARITY)
throw new IllegalArgumentException(String.format("No more than %d args supported", MAX_POSITIONAL_ARITY));
return new InvokeExpr(fexpr, args);
}
}
static class FnExpr implements Expr{
IPersistentCollection methods;
//if there is a variadic overload (there can only be one) it is stored here
FnMethod variadicMethod = null;
String name;
String internalName;
Type fntype;
//localbinding->itself
IPersistentMap closes = PersistentHashMap.EMPTY;
//Keyword->KeywordExpr
IPersistentMap keywords = PersistentHashMap.EMPTY;
IPersistentMap vars = PersistentHashMap.EMPTY;
Class compiledClass;
final static Method kwintern = Method.getMethod("clojure.lang.Keyword intern(String, String)");
final static Method symcreate = Method.getMethod("clojure.lang.Symbol create(String, String)");
final static Method varintern = Method.getMethod("clojure.lang.Var intern(clojure.lang.Symbol)");
final static Method afnctor = Method.getMethod("void <init>()");
final static Method restfnctor = Method.getMethod("void <init>(int)");
final static Type aFnType = Type.getType(AFn.class);
final static Type restFnType = Type.getType(RestFn.class);
static Expr parse(C context, ISeq form, String name) throws Exception{
FnExpr fn = new FnExpr();
FnMethod enclosingMethod = (FnMethod) METHOD.get();
String basename = enclosingMethod != null ?
(enclosingMethod.fn.name + "$")
: (munge(currentNS()) + ".");
fn.name = basename + (name != null ?
munge(name)
: ("fn__" + RT.nextID()));
fn.internalName = fn.name.replace('.', '/');
fn.fntype = Type.getObjectType(fn.internalName);
try
{
Var.pushThreadBindings(
RT.map(
KEYWORDS, PersistentHashMap.EMPTY,
VARS, PersistentHashMap.EMPTY));
//(fn [args] body...) or (fn ([args] body...) ([args2] body2...) ...)
//turn former into latter
if(RT.second(form) instanceof IPersistentArray)
form = RT.list(FN, RT.rest(form));
FnMethod[] methodArray = new FnMethod[MAX_POSITIONAL_ARITY + 1];
FnMethod variadicMethod = null;
for(ISeq s = RT.rest(form); s != null; s = RT.rest(s))
{
FnMethod f = FnMethod.parse(fn, (ISeq) RT.first(s));
if(f.isVariadic())
{
if(variadicMethod == null)
variadicMethod = f;
else
throw new Exception("Can't have more than 1 variadic overload");
}
else if(methodArray[f.reqParms.count()] == null)
methodArray[f.reqParms.count()] = f;
else
throw new Exception("Can't have 2 overloads with same arity");
}
if(variadicMethod != null)
{
for(int i = variadicMethod.reqParms.count() + 1; i <= MAX_POSITIONAL_ARITY; i++)
if(methodArray[i] != null)
throw new Exception("Can't have fixed arity function with more params than variadic function");
}
IPersistentCollection methods = null;
for(int i = 0; i < methodArray.length; i++)
if(methodArray[i] != null)
methods = RT.cons(methodArray[i], methods);
if(variadicMethod != null)
methods = RT.cons(variadicMethod, methods);
fn.methods = methods;
fn.variadicMethod = variadicMethod;
fn.keywords = (IPersistentMap) KEYWORDS.get();
fn.vars = (IPersistentMap) VARS.get();
}
finally
{
Var.popThreadBindings();
}
fn.compile();
return fn;
}
boolean isVariadic(){
return variadicMethod != null;
}
private void compile(){
//create bytecode for a class
//with name current_ns.defname[$letname]+
//anonymous fns get names fn__id
//derived from AFn/RestFn
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
// ClassWriter cw = new ClassWriter(0);
//ClassVisitor cv = cw;
ClassVisitor cv = new TraceClassVisitor(new CheckClassAdapter(cw), new PrintWriter(System.out));
// ClassVisitor cv = new TraceClassVisitor(cw, new PrintWriter(System.out));
cv.visit(V1_5, ACC_PUBLIC, internalName, null, isVariadic() ? "clojure/lang/RestFn" : "clojure/lang/AFn", null);
String source = (String) SOURCE.get();
if(source != null)
cv.visitSource(source, null);
//static fields for keywords
for(ISeq s = RT.keys(keywords); s != null; s = s.rest())
{
Keyword k = (Keyword) s.first();
cv.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, munge(k.sym.toString()),
KEYWORD_TYPE.getDescriptor(), null, null);
}
//static fields for vars
for(ISeq s = RT.keys(vars); s != null; s = s.rest())
{
Var v = (Var) s.first();
cv.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, munge(v.sym.toString()),
VAR_TYPE.getDescriptor(), null, null);
}
//static init for keywords and vars
GeneratorAdapter clinitgen = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC,
Method.getMethod("void <clinit> ()"),
null,
null,
cv);
clinitgen.visitCode();
for(ISeq s = RT.keys(keywords); s != null; s = s.rest())
{
Keyword k = (Keyword) s.first();
clinitgen.push(k.sym.ns);
clinitgen.push(k.sym.name);
clinitgen.invokeStatic(KEYWORD_TYPE, kwintern);
clinitgen.putStatic(fntype, munge(k.sym.toString()), KEYWORD_TYPE);
}
for(ISeq s = RT.keys(vars); s != null; s = s.rest())
{
Var v = (Var) s.first();
clinitgen.push(v.sym.ns);
clinitgen.push(v.sym.name);
clinitgen.invokeStatic(SYMBOL_TYPE, symcreate);
clinitgen.invokeStatic(VAR_TYPE, varintern);
clinitgen.putStatic(fntype, munge(v.sym.toString()), VAR_TYPE);
}
clinitgen.returnValue();
clinitgen.endMethod();
// clinitgen.visitMaxs(1, 1);
//instance fields for closed-overs
for(ISeq s = RT.keys(closes); s != null; s = s.rest())
{
LocalBinding lb = (LocalBinding) s.first();
cv.visitField(ACC_PUBLIC + ACC_FINAL, lb.name, OBJECT_TYPE.getDescriptor(), null, null);
}
//ctor that takes closed-overs and inits base + fields
Method m = new Method("<init>", Type.VOID_TYPE, ARG_TYPES[closes.count()]);
GeneratorAdapter ctorgen = new GeneratorAdapter(ACC_PUBLIC,
m,
null,
null,
cv);
ctorgen.visitCode();
ctorgen.loadThis();
if(isVariadic()) //RestFn ctor takes reqArity arg
{
ctorgen.push(variadicMethod.reqParms.count());
ctorgen.invokeConstructor(restFnType, restfnctor);
}
else
ctorgen.invokeConstructor(aFnType, afnctor);
int a = 1;
for(ISeq s = RT.keys(closes); s != null; s = s.rest(), ++a)
{
LocalBinding lb = (LocalBinding) s.first();
+ ctorgen.loadThis();
ctorgen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ILOAD), a);
ctorgen.putField(fntype, lb.name, OBJECT_TYPE);
}
ctorgen.returnValue();
// ctorgen.visitMaxs(1, 1);
ctorgen.endMethod();
//override of invoke/doInvoke for each method
for(ISeq s = RT.seq(methods); s != null; s = s.rest())
{
FnMethod method = (FnMethod) s.first();
method.emit(this, cv);
}
//end of class
cv.visitEnd();
//define class and store
DynamicClassLoader loader = (DynamicClassLoader) LOADER.get();
compiledClass = loader.defineClass(name, cw.toByteArray());
}
public Object eval() throws Exception{
return compiledClass.newInstance();
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
//emitting a Fn means constructing an instance, feeding closed-overs from enclosing scope, if any
//fn arg is enclosing fn, not this
if(context != C.STATEMENT)
{
gen.newInstance(fntype);
gen.dup();
for(ISeq s = RT.keys(closes); s != null; s = s.rest())
{
LocalBinding lb = (LocalBinding) s.first();
fn.emitLocal(gen, lb);
}
gen.invokeConstructor(fntype, new Method("<init>", Type.VOID_TYPE, ARG_TYPES[closes.count()]));
}
}
private void emitLocal(GeneratorAdapter gen, LocalBinding lb){
if(closes.contains(lb))
+ {
+ gen.loadThis();
gen.getField(fntype, lb.name, OBJECT_TYPE);
+ }
else
gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ILOAD), lb.idx);
}
public void emitVar(GeneratorAdapter gen, Var var){
gen.getStatic(fntype, munge(var.sym.toString()), VAR_TYPE);
}
public void emitKeyword(GeneratorAdapter gen, Keyword k){
gen.getStatic(fntype, munge(k.sym.toString()), KEYWORD_TYPE);
}
}
enum PSTATE{
REQ, REST, DONE
}
static class FnMethod{
//when closures are defined inside other closures,
//the closed over locals need to be propagated to the enclosing fn
final FnMethod parent;
//localbinding->localbinding
IPersistentMap locals = null;
//localbinding->localbinding
PersistentVector reqParms = PersistentVector.EMPTY;
LocalBinding restParm = null;
Expr body = null;
FnExpr fn;
public FnMethod(FnExpr fn, FnMethod parent){
this.parent = parent;
this.fn = fn;
}
boolean isVariadic(){
return restParm != null;
}
int numParams(){
return reqParms.count() + (isVariadic() ? 1 : 0);
}
private static FnMethod parse(FnExpr fn, ISeq form) throws Exception{
//([args] body...)
IPersistentArray parms = (IPersistentArray) RT.first(form);
ISeq body = RT.rest(form);
try
{
FnMethod method = new FnMethod(fn, (FnMethod) METHOD.get());
//register as the current method and set up a new env frame
Var.pushThreadBindings(
RT.map(
METHOD, method,
LOCAL_ENV, LOCAL_ENV.get(),
LOOP_LOCALS, null,
NEXT_LOCAL_NUM, 0));
//register 'this' as local 0
registerLocal(THISFN, null);
PSTATE state = PSTATE.REQ;
PersistentVector loopLocals = PersistentVector.EMPTY;
for(int i = 0; i < parms.count(); i++)
{
if(!(parms.nth(i) instanceof Symbol))
throw new IllegalArgumentException("fn params must be Symbols");
Symbol p = (Symbol) parms.nth(i);
if(p.equals(_AMP_))
{
if(state == PSTATE.REQ)
state = PSTATE.REST;
else
throw new Exception("Invalid parameter list");
}
else
{
LocalBinding lb = registerLocal(p, tagOf(p));
loopLocals = loopLocals.cons(lb);
switch(state)
{
case REQ:
method.reqParms = method.reqParms.cons(lb);
break;
case REST:
method.restParm = lb;
state = PSTATE.DONE;
break;
default:
throw new Exception("Unexpected parameter");
}
}
}
if(method.reqParms.count() > MAX_POSITIONAL_ARITY)
throw new Exception("Can't specify more than " + MAX_POSITIONAL_ARITY + " params");
LOOP_LOCALS.set(loopLocals);
method.body = BodyExpr.parse(C.RETURN, body);
return method;
}
finally
{
Var.popThreadBindings();
}
}
public void emit(FnExpr fn, ClassVisitor cv){
Method m = new Method(isVariadic() ? "doInvoke" : "invoke",
OBJECT_TYPE, ARG_TYPES[numParams()]);
GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC,
m,
null,
EXCEPTION_TYPES,
cv);
gen.visitCode();
Label loopLabel = gen.mark();
try
{
Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel));
body.emit(C.RETURN, fn, gen);
}
finally
{
Var.popThreadBindings();
}
gen.returnValue();
//gen.visitMaxs(1, 1);
gen.endMethod();
}
}
static class LocalBinding{
final Symbol sym;
final Symbol tag;
final int idx;
final String name;
public LocalBinding(int num, Symbol sym, Symbol tag){
this.idx = num;
this.sym = sym;
this.tag = tag;
name = munge(sym.name);
}
}
static class LocalBindingExpr implements Expr{
final LocalBinding b;
final Symbol tag;
public LocalBindingExpr(LocalBinding b, Symbol tag){
this.b = b;
this.tag = tag;
}
public Object eval() throws Exception{
throw new UnsupportedOperationException("Can't eval locals");
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(context != C.STATEMENT)
fn.emitLocal(gen, b);
}
}
static class BodyExpr implements Expr{
PersistentVector exprs;
public BodyExpr(PersistentVector exprs){
this.exprs = exprs;
}
static Expr parse(C context, ISeq forms) throws Exception{
PersistentVector exprs = PersistentVector.EMPTY;
for(; forms != null; forms = forms.rest())
{
Expr e = (context == C.STATEMENT || forms.rest() != null) ?
analyze(C.STATEMENT, forms.first())
:
analyze(context, forms.first());
exprs = exprs.cons(e);
}
return new BodyExpr(exprs);
}
public Object eval() throws Exception{
Object ret = null;
for(Object o : exprs)
{
Expr e = (Expr) o;
ret = e.eval();
}
return ret;
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
if(exprs.count() > 0)
{
for(int i = 0; i < exprs.count() - 1; i++)
{
Expr e = (Expr) exprs.nth(i);
e.emit(C.STATEMENT, fn, gen);
}
Expr last = (Expr) exprs.nth(exprs.count() - 1);
last.emit(context, fn, gen);
}
else if(context != C.STATEMENT)
{
NIL_EXPR.emit(context, fn, gen);
}
}
}
static class BindingInit{
LocalBinding binding;
Expr init;
public BindingInit(LocalBinding binding, Expr init){
this.binding = binding;
this.init = init;
}
}
static class LetExpr implements Expr{
final PersistentVector bindingInits;
final Expr body;
final boolean isLoop;
public LetExpr(PersistentVector bindingInits, Expr body, boolean isLoop){
this.bindingInits = bindingInits;
this.body = body;
this.isLoop = isLoop;
}
static Expr parse(C context, ISeq form, boolean isLoop) throws Exception{
//(let [var val var2 val2 ...] body...)
if(!(RT.second(form) instanceof IPersistentArray))
throw new IllegalArgumentException("Bad binding form, expected vector");
IPersistentArray bindings = (IPersistentArray) RT.second(form);
if((bindings.count() % 2) != 0)
throw new IllegalArgumentException("Bad binding form, expected matched symbol expression pairs");
ISeq body = RT.rest(RT.rest(form));
if(context == C.EVAL)
return analyze(context, RT.list(RT.list(FN, PersistentVector.EMPTY, form)));
IPersistentMap dynamicBindings = RT.map(LOCAL_ENV, LOCAL_ENV.get(),
NEXT_LOCAL_NUM, NEXT_LOCAL_NUM.get());
if(isLoop)
dynamicBindings = dynamicBindings.assoc(LOOP_LOCALS, null);
try
{
Var.pushThreadBindings(dynamicBindings);
PersistentVector bindingInits = PersistentVector.EMPTY;
PersistentVector loopLocals = PersistentVector.EMPTY;
for(int i = 0; i < bindings.count(); i += 2)
{
if(!(bindings.nth(i) instanceof Symbol))
throw new IllegalArgumentException("Bad binding form, expected symbol, got: " + bindings.nth(i));
Symbol sym = (Symbol) bindings.nth(i);
Expr init = analyze(C.EXPRESSION, bindings.nth(i + 1), sym.name);
//sequential enhancement of env (like Lisp let*)
LocalBinding lb = registerLocal(sym, tagOf(sym));
BindingInit bi = new BindingInit(lb, init);
bindingInits = bindingInits.cons(bi);
if(isLoop)
loopLocals = loopLocals.cons(lb);
}
if(isLoop)
LOOP_LOCALS.set(loopLocals);
return new LetExpr(bindingInits, BodyExpr.parse(isLoop ? C.RETURN : context, body), isLoop);
}
finally
{
Var.popThreadBindings();
}
}
public Object eval() throws Exception{
throw new UnsupportedOperationException("Can't eval let/loop");
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
for(int i = 0; i < bindingInits.count(); i++)
{
BindingInit bi = (BindingInit) bindingInits.nth(i);
bi.init.emit(C.EXPRESSION, fn, gen);
gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), bi.binding.idx);
}
if(isLoop)
{
Label loopLabel = gen.mark();
try
{
Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel));
body.emit(context, fn, gen);
}
finally
{
Var.popThreadBindings();
}
}
else
body.emit(context, fn, gen);
}
}
static class RecurExpr implements Expr{
final IPersistentArray args;
final IPersistentArray loopLocals;
public RecurExpr(IPersistentArray loopLocals, IPersistentArray args){
this.loopLocals = loopLocals;
this.args = args;
}
public Object eval() throws Exception{
throw new UnsupportedOperationException("Can't eval recur");
}
public void emit(C context, FnExpr fn, GeneratorAdapter gen){
Label loopLabel = (Label) LOOP_LABEL.get();
if(loopLabel == null)
throw new IllegalStateException();
for(int i = 0; i < loopLocals.count(); i++)
{
LocalBinding lb = (LocalBinding) loopLocals.nth(i);
Expr arg = (Expr) args.nth(i);
arg.emit(C.EXPRESSION, fn, gen);
gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), lb.idx);
}
gen.goTo(loopLabel);
}
public static Expr parse(C context, ISeq form) throws Exception{
IPersistentArray loopLocals = (IPersistentArray) LOOP_LOCALS.get();
if(context != C.RETURN || loopLocals == null)
throw new UnsupportedOperationException("Can only recur from tail position");
PersistentVector args = PersistentVector.EMPTY;
for(ISeq s = RT.seq(form.rest()); s != null; s = s.rest())
{
args = args.cons(analyze(C.EXPRESSION, s.first()));
}
if(args.count() != loopLocals.count())
throw new IllegalArgumentException(
String.format("Mismatched argument count to recur, expected: %d args, got: %d",
loopLocals.count(), args.count()));
return new RecurExpr(loopLocals, args);
}
}
private static LocalBinding registerLocal(Symbol sym, Symbol tag) throws Exception{
int num = getAndIncLocalNum();
LocalBinding b = new LocalBinding(num, sym, tag);
IPersistentMap localsMap = (IPersistentMap) LOCAL_ENV.get();
LOCAL_ENV.set(RT.assoc(localsMap, b.sym, b));
FnMethod method = (FnMethod) METHOD.get();
method.locals = (IPersistentMap) RT.assoc(method.locals, b, b);
return b;
}
private static int getAndIncLocalNum(){
int num = ((Number) NEXT_LOCAL_NUM.get()).intValue();
NEXT_LOCAL_NUM.set(num + 1);
return num;
}
private static Expr analyze(C context, Object form) throws Exception{
return analyze(context, form, null);
}
private static Expr analyze(C context, Object form, String name) throws Exception{
//todo symbol macro expansion
if(form == null)
return NIL_EXPR;
Class fclass = form.getClass();
if(fclass == Symbol.class)
return analyzeSymbol((Symbol) form);
else if(fclass == Keyword.class)
return registerKeyword((Keyword) form);
else if(form instanceof Num)
return new NumExpr((Num) form);
else if(fclass == String.class)
return new StringExpr((String) form);
else if(fclass == Character.class)
return new CharExpr((Character) form);
else if(form instanceof ISeq)
return analyzeSeq(context, (ISeq) form, name);
// else
throw new UnsupportedOperationException();
}
private static Expr analyzeSeq(C context, ISeq form, String name) throws Exception{
Object op = RT.first(form);
//macro expansion
if(op instanceof Symbol || op instanceof Var)
{
Var v = (op instanceof Var) ? (Var) op : lookupVar((Symbol) op, false);
if(v != null && v.isMacro())
{
return analyze(context, v.applyTo(form.rest()));
}
}
if(op.equals(DEF))
return DefExpr.parse(context, form);
else if(op.equals(IF))
return IfExpr.parse(context, form);
else if(op.equals(FN))
return FnExpr.parse(context, form, name);
else if(op.equals(DO))
return BodyExpr.parse(context, form.rest());
else if(op.equals(LET))
return LetExpr.parse(context, form, false);
else if(op.equals(LOOP))
return LetExpr.parse(context, form, true);
else if(op.equals(RECUR))
return RecurExpr.parse(context, form);
else if(op.equals(QUOTE))
return QuoteExpr.parse(context, form);
else if(op.equals(DOT))
return HostExpr.parse(context, form);
else if(op.equals(THE_VAR))
return TheVarExpr.parse(context, form);
else if(op.equals(ASSIGN))
return AssignExpr.parse(context, form);
else if(op.equals(TRY_FINALLY))
return TryFinallyExpr.parse(context, form);
else if(op.equals(THROW))
return ThrowExpr.parse(context, form);
else
return InvokeExpr.parse(context, form);
}
static Object eval(Object form) throws Exception{
Expr expr = analyze(C.EVAL, form);
return expr.eval();
}
private static KeywordExpr registerKeyword(Keyword keyword){
if(!KEYWORDS.isBound())
return new KeywordExpr(keyword);
IPersistentMap keywordsMap = (IPersistentMap) KEYWORDS.get();
KeywordExpr ke = (KeywordExpr) RT.get(keywordsMap, keyword);
if(ke == null)
KEYWORDS.set(RT.assoc(keywordsMap, keyword, ke = new KeywordExpr(keyword)));
return ke;
}
private static Expr analyzeSymbol(Symbol sym) throws Exception{
Symbol tag = tagOf(sym);
if(sym.ns == null) //ns-qualified syms are always Vars
{
LocalBinding b = referenceLocal(sym);
if(b != null)
return new LocalBindingExpr(b, tag);
}
Var v = lookupVar(sym, false);
if(v != null)
return new VarExpr(v, tag);
throw new Exception("Unable to resolve symbol: " + sym + " in this context");
}
static Var lookupVar(Symbol sym, boolean internNew) throws Exception{
Var var;
//note - ns-qualified vars must already exist
if(sym.ns != null)
{
var = Var.find(sym);
}
else
{
//is it an alias?
IPersistentMap uses = (IPersistentMap) RT.USES.get();
var = (Var) uses.valAt(sym);
if(var == null && sym.ns == null)
var = Var.find(Symbol.intern(currentNS(), sym.name));
if(var == null && internNew)
{
//introduce a new var in the current ns
String ns = currentNS();
var = Var.intern(Symbol.intern(ns, sym.name));
}
}
if(var != null)
registerVar(var);
return var;
}
private static void registerVar(Var var) throws Exception{
if(!VARS.isBound())
return;
IPersistentMap varsMap = (IPersistentMap) VARS.get();
if(varsMap != null && RT.get(varsMap, var) == null)
VARS.set(RT.assoc(varsMap, var, var));
}
private static String currentNS(){
return (String) RT.CURRENT_NS.get();
}
static void closeOver(LocalBinding b, FnMethod method){
if(b != null && method != null && RT.get(method.locals, b) == null)
{
method.fn.closes = (IPersistentMap) RT.assoc(method.fn.closes, b, b);
closeOver(b, method.parent);
}
}
static LocalBinding referenceLocal(Symbol sym) throws Exception{
if(!LOCAL_ENV.isBound())
return null;
LocalBinding b = (LocalBinding) RT.get(LOCAL_ENV.get(), sym);
if(b != null)
{
closeOver(b, (FnMethod) METHOD.get());
}
return b;
}
private static Symbol tagOf(Symbol sym){
if(sym.meta() != null)
return (Symbol) sym.meta().valAt(RT.TAG_KEY);
return null;
}
public static Object loadFile(String file) throws Exception{
return load(new FileInputStream(file));
}
public static Object load(InputStream s) throws Exception{
Object EOF = new Object();
try
{
Var.pushThreadBindings(
RT.map(LOADER, new DynamicClassLoader(),
RT.USES, RT.USES.get(),
RT.IMPORTS, RT.IMPORTS.get()));
LineNumberingPushbackReader rdr = new LineNumberingPushbackReader(new InputStreamReader(s));
for(Object r = LispReader.read(rdr, false, EOF, false); r != EOF; r = LispReader.read(rdr, false, EOF, false))
eval(r);
}
finally
{
Var.popThreadBindings();
}
return RT.T;
}
public static void main(String[] args){
//repl
LineNumberingPushbackReader rdr = new LineNumberingPushbackReader(new InputStreamReader(System.in));
OutputStreamWriter w = new OutputStreamWriter(System.out);
Object EOF = new Object();
try
{
Var.pushThreadBindings(
RT.map(RT.USES, RT.USES.get(),
RT.IMPORTS, RT.IMPORTS.get()));
for(; ;)
{
try
{
Var.pushThreadBindings(
RT.map(LOADER, new DynamicClassLoader()));
Object r = LispReader.read(rdr, false, EOF, false);
if(r == EOF)
break;
Object ret = eval(r);
RT.print(ret, w);
w.write('\n');
w.flush();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
Var.popThreadBindings();
}
}
}
finally
{
Var.popThreadBindings();
}
}
}
| false | false | null | null |
diff --git a/src/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java b/src/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java
index 65c0339c..aac000ad 100644
--- a/src/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java
+++ b/src/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java
@@ -1,1319 +1,1319 @@
package com.redhat.ceylon.compiler.js;
import static java.lang.Character.toUpperCase;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.NaturalVisitor;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AndOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnnotationList;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AssignOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeGetterDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeSetterDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseTypeExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BinaryOperatorExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Block;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Body;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CharLiteral;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompareOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.DifferenceOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.EqualOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ExecutableStatement;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ExtendedType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.FloatLiteral;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.IdenticalOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Import;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.InterfaceDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.InterfaceDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.InvocationExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.LargeAsOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.LargerOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.NamedArgument;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.NamedArgumentList;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.NaturalLiteral;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.NegativeOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.NotEqualOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.NotOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ObjectDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.OrOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Outer;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Parameter;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ParameterList;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositionalArgument;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositionalArgumentList;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositiveOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.PowerOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ProductOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedMemberExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedMemberOrTypeExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedTypeExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.QuotientOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.RemainderOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Return;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SatisfiedTypes;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SequencedArgument;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SequenceEnumeration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SimpleType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SmallAsOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SmallerOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierStatement;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Statement;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.StringLiteral;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SumOp;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Super;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.This;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
public class GenerateJsVisitor extends Visitor
implements NaturalVisitor {
private final Writer out;
boolean prototypeStyle;
@Override
public void handleException(Exception e, Node that) {
that.addUnexpectedError(that.getMessage(e, this));
}
public GenerateJsVisitor(Writer out, boolean prototypeStyle) {
this.out = out;
this.prototypeStyle=prototypeStyle;
}
private void out(String code) {
try {
out.write(code);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
int indentLevel = 0;
private void indent() {
for (int i=0;i<indentLevel;i++) {
out(" ");
}
}
private void endLine() {
out("\n");
indent();
}
private void beginBlock() {
indentLevel++;
out("{");
endLine();
}
private void endBlock() {
indentLevel--;
endLine();
out("}");
endLine();
}
private void location(Node node) {
out(" at ");
out(node.getUnit().getFilename());
out(" (");
out(node.getLocation());
out(")");
}
@Override
public void visit(CompilationUnit that) {
Module clm = that.getUnit().getPackage().getModule()
.getLanguageModule();
require(clm.getPackage(clm.getNameAsString()));
super.visit(that);
/*try {
out.flush();
}
catch (IOException ioe) {
ioe.printStackTrace();
}*/
}
@Override
public void visit(Import that) {
require(that.getImportList().getImportedPackage());
}
private void require(Package pkg) {
out("var ");
packageAlias(pkg);
out("=require('");
scriptPath(pkg);
out("');");
endLine();
}
private void packageAlias(Package pkg) {
out("$$$");
//out(pkg.getNameAsString().replace('.', '$'));
for (String s: pkg.getName()) {
out(s.substring(0,1));
}
out(Integer.toString(pkg.getQualifiedNameString().length()));
}
private void scriptPath(Package pkg) {
out(pkg.getModule().getNameAsString().replace('.', '/'));
out("/");
if (!pkg.getModule().isDefault()) {
out(pkg.getModule().getVersion());
out("/");
}
out(pkg.getNameAsString());
}
@Override
public void visit(Parameter that) {
out(that.getDeclarationModel().getName());
}
@Override
public void visit(ParameterList that) {
out("(");
boolean first=true;
for (Parameter param: that.getParameters()) {
if (!first) out(",");
out(param.getDeclarationModel().getName());
first = false;
}
out(")");
}
@Override
public void visit(Body that) {
List<Statement> stmnts = that.getStatements();
for (int i=0; i<stmnts.size(); i++) {
Statement s = stmnts.get(i);
s.visit(this);
if (s instanceof ExecutableStatement) {
endLine();
}
}
}
@Override
public void visit(Block that) {
List<Statement> stmnts = that.getStatements();
if (stmnts.isEmpty()) {
out("{}");
endLine();
}
else {
beginBlock();
for (int i=0; i<stmnts.size(); i++) {
Statement s = stmnts.get(i);
s.visit(this);
if (i<stmnts.size()-1 &&
s instanceof ExecutableStatement) {
endLine();
}
}
endBlock();
}
}
private void comment(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration that) {
endLine();
out("//");
out(that.getNodeType());
out(" ");
out(that.getDeclarationModel().getName());
location(that);
endLine();
}
private void var(Declaration d) {
out("var ");
out(d.getName());
out("=");
}
private void selfVar(Declaration d) {
out("var ");
self(d);
out("=");
}
private void share(Declaration d) {
if (d.isShared() ||
prototypeStyle && d.isCaptured()) {
outerSelf(d);
out(".");
out(d.getName());
out("=");
out(d.getName());
out(";");
endLine();
}
}
@Override
public void visit(ClassDeclaration that) {
Class d = that.getDeclarationModel();
comment(that);
var(d);
TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel()
.getDeclaration();
qualify(that,dec);
out(dec.getName());
out(";");
endLine();
share(d);
}
@Override
public void visit(InterfaceDeclaration that) {
Interface d = that.getDeclarationModel();
comment(that);
var(d);
TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel()
.getDeclaration();
qualify(that,dec);
out(";");
share(d);
}
private void newObject() {
out("new CeylonObject;");
}
private void function() {
out("function ");
}
@Override
public void visit(InterfaceDefinition that) {
Interface d = that.getDeclarationModel();
comment(that);
defineType(d);
copyInterfacePrototypes(that.getSatisfiedTypes(), d);
for (Statement s: that.getInterfaceBody().getStatements()) {
addToPrototype(d, s);
}
function();
out(d.getName());
out("()");
beginBlock();
declareSelf(d);
copyInterfaceMembers(that.getSatisfiedTypes(), d);
that.getInterfaceBody().visit(this);
returnSelf(d);
endBlock();
share(d);
}
@Override
public void visit(ClassDefinition that) {
Class d = that.getDeclarationModel();
comment(that);
defineType(d);
copySuperclassPrototype(that.getExtendedType(),d);
copyInterfacePrototypes(that.getSatisfiedTypes(), d);
for (Statement s: that.getClassBody().getStatements()) {
addToPrototype(d, s);
}
function();
out(d.getName());
that.getParameterList().visit(this);
beginBlock();
declareSelf(d);
copySuperclassMembers(that.getExtendedType(), d);
copyInterfaceMembers(that.getSatisfiedTypes(), d);
if (prototypeStyle) {
for (Parameter p: that.getParameterList().getParameters()) {
if (p.getDeclarationModel().isCaptured()) {
self(d);
out(".");
out(p.getDeclarationModel().getName());
out("=");
out(p.getDeclarationModel().getName());
out(";");
endLine();
}
}
}
that.getClassBody().visit(this);
returnSelf(d);
endBlock();
share(d);
}
private void defineType(ClassOrInterface d) {
if (prototypeStyle) {
function();
out("$");
out(d.getName());
out("(){}");
endLine();
}
}
private void addToPrototype(ClassOrInterface d, Statement s) {
if (s instanceof MethodDefinition) {
addMethodToPrototype(d, (MethodDefinition)s);
}
if (s instanceof AttributeGetterDefinition) {
addGetterToPrototype(d, (AttributeGetterDefinition)s);
}
if (s instanceof AttributeSetterDefinition) {
addSetterToPrototype(d, (AttributeSetterDefinition)s);
}
if (s instanceof AttributeDeclaration) {
addGetterAndSetterToPrototype(d, (AttributeDeclaration)s);
}
}
private void declareSelf(ClassOrInterface d) {
selfVar(d);
if (prototypeStyle) {
out("new $");
out(d.getName());
out(";");
}
else {
newObject();
}
endLine();
}
private void returnSelf(ClassOrInterface d) {
out("return ");
self(d);
out(";");
}
private void copyMembers(ClassOrInterface to, ClassOrInterface from) {
for (Declaration m: from.getMembers()) {
copyMember(to, from, m);
}
}
private void copyMember(Declaration to, ClassOrInterface from,
Declaration m) {
if (m instanceof Value) {
self(to);
out(".");
out(m.getName());
out("=");
if (prototypeStyle) {
self(to);
out(".");
}
- out("$super");
- out(from.getName());
+ self(from);
out(".");
out(m.getName());
out(";");
endLine();
}
if (!prototypeStyle) {
if (m instanceof Method) {
self(to);
out(".");
out(m.getName());
- out("=$super");
- out(from.getName());
+ out("=");
+ self(from);
out(".");
out(m.getName());
out(";");
endLine();
}
if (m instanceof Getter || m instanceof Value) {
self(to);
out(".");
out(getter(m));
- out("=$super");
- out(from.getName());
+ out("=");
+ self(from);
out(".");
out(getter(m));
out(";");
endLine();
}
if (m instanceof Setter || m instanceof Value
&& ((Value)m).isVariable()) {
self(to);
out(".");
out(setter(m));
- out("=$super");
- out(from.getName());
+ out("=");
+ self(from);
out(".");
out(setter(m));
out(";");
endLine();
}
}
}
private void copySuperclassMembers(ExtendedType that, Class d) {
if (that!=null) {
declareSuper(d, that);
copyMembers(d, d.getExtendedTypeDeclaration());
}
}
private void copyInterfaceMembers(SatisfiedTypes that, ClassOrInterface d) {
if (that!=null)
for (Tree.SimpleType st: that.getTypes()) {
Interface i = (Interface)st.getDeclarationModel();
declareSuperInterface(i);
copyMembers(d, i);
}
}
private void declareSuper(Class d, ExtendedType that) {
- if (!prototypeStyle) out("var ");
if (prototypeStyle) {
self(d);
out(".");
}
- out("$super");
- out(d.getExtendedTypeDeclaration().getName());
+ else {
+ out("var ");
+ }
+ self(d.getExtendedTypeDeclaration());
out("=");
out(d.getExtendedTypeDeclaration().getName());
that.getInvocationExpression().visit(this);
out(";");
endLine();
}
private void declareSuperInterface(Interface i) {
- out("var $super");
- out(i.getName());
+ out("var ");
+ self(i);
out("=");
out(i.getName());
out("();");
endLine();
}
private void copyMembersToPrototype(SimpleType that, Declaration d) {
copyMembersToPrototype("$"+that.getDeclarationModel().getName(), d);
}
private void copyMembersToPrototype(String from, Declaration d) {
out("for(var $ in ");
out(from);
out(".prototype){$");
out(d.getName());
out(".prototype[$]=");
out(from);
out(".prototype[$]}");
endLine();
}
private void copySuperclassPrototype(ExtendedType that, Declaration d) {
if (prototypeStyle) {
if (that==null) {
copyMembersToPrototype("CeylonObject", d);
}
else {
copyMembersToPrototype(that.getType(), d);
}
}
}
private void copyInterfacePrototypes(SatisfiedTypes that, Declaration d) {
if (prototypeStyle && that!=null) {
for (Tree.SimpleType st: that.getTypes()) {
copyMembersToPrototype(st, d);
}
}
}
@Override
public void visit(ObjectDefinition that) {
Value d = that.getDeclarationModel();
Class c = (Class) d.getTypeDeclaration();
comment(that);
defineType(c);
copySuperclassPrototype(that.getExtendedType(),d);
copyInterfacePrototypes(that.getSatisfiedTypes(),d);
for (Statement s: that.getClassBody().getStatements()) {
addToPrototype(c, s);
}
out("var $");
out(d.getName());
out("=");
function();
out(d.getName());
out("()");
beginBlock();
declareSelf(c);
copySuperclassMembers(that.getExtendedType(), c);
copyInterfaceMembers(that.getSatisfiedTypes(), c);
that.getClassBody().visit(this);
returnSelf(c);
indentLevel--;
endLine();
out("}();");
endLine();
if (d.isShared()) {
outerSelf(d);
out(".");
out(getter(d));
out("=");
}
function();
out(getter(d));
out("()");
beginBlock();
out("return $");
out(d.getName());
out(";");
endBlock();
}
@Override
public void visit(MethodDeclaration that) {}
@Override
public void visit(MethodDefinition that) {
Method d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
out(d.getName());
//TODO: if there are multiple parameter lists
// do the inner function declarations
super.visit(that);
share(d);
}
private void addMethodToPrototype(Declaration outer,
MethodDefinition that) {
Method d = that.getDeclarationModel();
if (!prototypeStyle||!d.isClassOrInterfaceMember()) return;
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
out(d.getName());
out("=");
function();
out(d.getName());
//TODO: if there are multiple parameter lists
// do the inner function declarations
super.visit(that);
}
@Override
public void visit(AttributeGetterDefinition that) {
Getter d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
out(getter(d));
out("()");
super.visit(that);
shareGetter(d);
}
private void addGetterToPrototype(Declaration outer,
AttributeGetterDefinition that) {
Getter d = that.getDeclarationModel();
if (!prototypeStyle||!d.isClassOrInterfaceMember()) return;
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
out(getter(d));
out("=");
function();
out(getter(d));
out("()");
super.visit(that);
}
private void shareGetter(MethodOrValue d) {
if (d.isShared() ||
prototypeStyle && d.isCaptured()) {
outerSelf(d);
out(".");
out(getter(d));
out("=");
out(getter(d));
out(";");
endLine();
}
}
@Override
public void visit(AttributeSetterDefinition that) {
Setter d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
out(setter(d));
out("(");
out(d.getName());
out(")");
super.visit(that);
shareSetter(d);
}
private void addSetterToPrototype(Declaration outer,
AttributeSetterDefinition that) {
Setter d = that.getDeclarationModel();
if (!prototypeStyle||!d.isClassOrInterfaceMember()) return;
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
out(setter(d));
out("=");
function();
out(setter(d));
out("(");
out(d.getName());
out(")");
super.visit(that);
}
private void shareSetter(MethodOrValue d) {
if (d.isShared() ||
prototypeStyle && d.isCaptured()) {
outerSelf(d);
out(".");
out(setter(d));
out("=");
out(setter(d));
out(";");
endLine();
}
}
@Override
public void visit(AttributeDeclaration that) {
Value d = that.getDeclarationModel();
if (!d.isFormal()) {
comment(that);
if (prototypeStyle&&d.isClassOrInterfaceMember()) {
if (that.getSpecifierOrInitializerExpression()!=null) {
outerSelf(d);
out(".");
out(d.getName());
out("=");
super.visit(that);
out(";");
endLine();
}
}
else {
out("var $");
out(d.getName());
if (that.getSpecifierOrInitializerExpression()!=null) {
out("=");
}
super.visit(that);
out(";");
endLine();
function();
out(getter(d));
out("()");
beginBlock();
out("return $");
out(d.getName());
out(";");
endBlock();
shareGetter(d);
if (d.isVariable()) {
function();
out(setter(d));
out("(");
out(d.getName());
out(")");
beginBlock();
out("$");
out(d.getName());
out("=");
out(d.getName());
out(";");
endBlock();
shareSetter(d);
}
}
}
}
private void addGetterAndSetterToPrototype(Declaration outer,
AttributeDeclaration that) {
Value d = that.getDeclarationModel();
if (!prototypeStyle||d.isToplevel()) return;
if (!d.isFormal()) {
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
out(getter(d));
out("=");
function();
out(getter(d));
out("()");
beginBlock();
out("return this.");
out(d.getName());
out(";");
endBlock();
if (d.isVariable()) {
out("$");
out(outer.getName());
out(".prototype.");
out(setter(d));
out("=");
function();
out(setter(d));
out("(");
out(d.getName());
out(")");
beginBlock();
out("this.");
out(d.getName());
out("=");
out(d.getName());
out(";");
endBlock();
}
}
}
private void clAlias() {
out("$$$cl15");
}
@Override
public void visit(CharLiteral that) {
clAlias();
out(".Character(");
out(that.getText().replace('`', '"'));
out(")");
}
@Override
public void visit(StringLiteral that) {
clAlias();
out(".String(");
out(that.getText());
out(")");
}
@Override
public void visit(FloatLiteral that) {
clAlias();
out(".Float(");
out(that.getText());
out(")");
}
@Override
public void visit(NaturalLiteral that) {
clAlias();
out(".Integer(");
out(that.getText());
out(")");
}
@Override
public void visit(This that) {
TypeDeclaration d = that.getTypeModel().getDeclaration();
if (prototypeStyle &&
!(that.getScope() instanceof ClassOrInterface)) {
out("this");
}
else {
self(d);
}
}
@Override
public void visit(Super that) {
TypeDeclaration d = that.getTypeModel().getDeclaration();
if (prototypeStyle) {
if (that.getScope() instanceof ClassOrInterface) {
self((ClassOrInterface)that.getScope());
}
else {
out("this");
}
out(".");
}
- out("$super");
- out(d.getName());
+ self(d);
}
@Override
public void visit(Outer that) {
self(that.getTypeModel().getDeclaration());
}
@Override
public void visit(BaseMemberExpression that) {
qualify(that, that.getDeclaration());
if (that.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter ||
that.getDeclaration() instanceof Method) {
out(that.getDeclaration().getName());
}
else {
out(getter(that.getDeclaration()));
out("()");
}
}
@Override
public void visit(QualifiedMemberExpression that) {
super.visit(that);
out(".");
if (that.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter ||
that.getDeclaration() instanceof Method) {
out(that.getDeclaration().getName());
}
else {
out(getter(that.getDeclaration()));
out("()");
}
}
@Override
public void visit(BaseTypeExpression that) {
qualify(that, that.getDeclaration());
out(that.getDeclaration().getName());
}
@Override
public void visit(QualifiedTypeExpression that) {
super.visit(that);
out(".");
out(that.getDeclaration().getName());
}
@Override
public void visit(InvocationExpression that) {
if (that.getNamedArgumentList()!=null) {
out("(function (){");
that.getNamedArgumentList().visit(this);
out("return ");
that.getPrimary().visit(this);
out("(");
if (that.getPrimary().getDeclaration() instanceof Functional) {
Functional f = (Functional) that.getPrimary().getDeclaration();
if (!f.getParameterLists().isEmpty()) {
boolean first=true;
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p:
f.getParameterLists().get(0).getParameters()) {
if (!first) out(",");
out("$");
out(p.getName());
first = false;
}
}
}
out(")}())");
}
else {
super.visit(that);
}
}
@Override
public void visit(PositionalArgumentList that) {
out("(");
boolean first=true;
boolean sequenced=false;
for (PositionalArgument arg: that.getPositionalArguments()) {
if (!first) out(",");
if (!sequenced && arg.getParameter().isSequenced()) {
sequenced=true;
clAlias();
out(".ArraySequence([");
}
arg.visit(this);
first = false;
}
if (sequenced) {
out("])");
}
out(")");
}
@Override
public void visit(NamedArgumentList that) {
for (NamedArgument arg: that.getNamedArguments()) {
out("var $");
out(arg.getParameter().getName());
out("=");
arg.visit(this);
out(";");
}
SequencedArgument sarg = that.getSequencedArgument();
if (sarg!=null) {
out("var $");
out(sarg.getParameter().getName());
out("=");
sarg.visit(this);
out(";");
}
}
@Override
public void visit(SequencedArgument that) {
clAlias();
out(".ArraySequence([");
boolean first=true;
for (Expression arg: that.getExpressionList().getExpressions()) {
if (!first) out(",");
arg.visit(this);
first = false;
}
out("])");
}
@Override
public void visit(SequenceEnumeration that) {
clAlias();
out(".ArraySequence([");
boolean first=true;
for (Expression arg: that.getExpressionList().getExpressions()) {
if (!first) out(",");
arg.visit(this);
first = false;
}
out("])");
}
@Override
public void visit(SpecifierStatement that) {
BaseMemberExpression bme = (Tree.BaseMemberExpression) that.getBaseMemberExpression();
qualify(that, bme.getDeclaration());
out(bme.getDeclaration().getName());
out("=");
that.getSpecifierExpression().visit(this);
}
@Override
public void visit(AssignOp that) {
BaseMemberExpression bme = (Tree.BaseMemberExpression) that.getLeftTerm();
qualify(that, bme.getDeclaration());
out(setter(bme.getDeclaration()));
out("(");
that.getRightTerm().visit(this);
if (bme.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter) {}
else {
out(")");
}
}
private void qualify(Node that, Declaration d) {
if (isImported(that, d)) {
packageAlias(d.getUnit().getPackage());
out(".");
}
else if (qualifyBaseMember(that, d)) {
TypeDeclaration id = that.getScope().getInheritingDeclaration(d);
if (prototypeStyle && id.equals(that.getScope().getContainer())) {
out("this");
}
else {
self(id);
}
out(".");
}
else if (prototypeStyle && d.isClassOrInterfaceMember()
&& d.isCaptured()) {
if (!isParameterOfContainingScope(that, d)) {
out("this");
out(".");
}
}
else if (prototypeStyle && d.isClassOrInterfaceMember() &&
- !(d instanceof Value)) {
+ !(d instanceof Value) &&
+ !(d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter)) {
outerSelf(d);
out(".");
}
}
private boolean isParameterOfContainingScope(Node that, Declaration d) {
return d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter &&
that.getScope().equals(((com.redhat.ceylon.compiler.typechecker.model.Parameter)d).getDeclaration());
}
private boolean isImported(Node that, Declaration d) {
return !d.getUnit().getPackage()
.equals(that.getUnit().getPackage());
}
private boolean qualifyBaseMember(Node that, Declaration d) {
return !d.isDefinedInScope(that.getScope());
/*return d.isClassOrInterfaceMember() &&
d.isShared() &&
that.getScope().isInherited(d);*/
}
@Override
public void visit(ExecutableStatement that) {
super.visit(that);
out(";");
}
@Override
public void visit(Expression that) {
if (prototypeStyle &&
that.getTerm() instanceof QualifiedMemberOrTypeExpression) {
QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm();
if (term.getDeclaration() instanceof Functional) {
out("function(){var $=");
term.getPrimary().visit(this);
out(";$.");
out(term.getDeclaration().getName());
out(".apply($,arguments)}");
return;
}
}
super.visit(that);
}
@Override
public void visit(Return that) {
out("return ");
super.visit(that);
}
@Override
public void visit(AnnotationList that) {}
private void self(Declaration d) {
out("$$");
out(d.getName().substring(0,1).toLowerCase());
out(d.getName().substring(1));
}
private void outerSelf(Declaration d) {
if (d.isToplevel()) {
out("this");
}
else {
//TODO: this is broken, since the container
// might not be the class ... we need
// to search up through the containers
self((Declaration) d.getContainer());
}
}
private String setter(Declaration d) {
return "set" + toUpperCase(d.getName().charAt(0)) +
d.getName().substring(1);
}
private String getter(Declaration d) {
return "get" + toUpperCase(d.getName().charAt(0)) +
d.getName().substring(1);
}
@Override
public void visit(SumOp that) {
that.getLeftTerm().visit(this);
out(".plus(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(DifferenceOp that) {
that.getLeftTerm().visit(this);
out(".minus(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(ProductOp that) {
that.getLeftTerm().visit(this);
out(".times(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(QuotientOp that) {
that.getLeftTerm().visit(this);
out(".divided(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(RemainderOp that) {
that.getLeftTerm().visit(this);
out(".remainder(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(PowerOp that) {
that.getLeftTerm().visit(this);
out(".power(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(NegativeOp that) {
that.getTerm().visit(this);
out(".negativeValue()");
}
@Override public void visit(PositiveOp that) {
that.getTerm().visit(this);
out(".positiveValue()");
}
@Override public void visit(EqualOp that) {
leftEqualsRight(that);
}
@Override public void visit(NotEqualOp that) {
leftEqualsRight(that);
equalsFalse();
}
@Override public void visit(NotOp that) {
that.getTerm().visit(this);
equalsFalse();
}
@Override public void visit(IdenticalOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
that.getRightTerm().visit(this);
thenTrueElseFalse();
out(")");
}
@Override public void visit(CompareOp that) {
leftCompareRight(that);
}
@Override public void visit(SmallerOp that) {
leftCompareRight(that);
out(".equals(");
clAlias();
out(".getSmaller())");
}
@Override public void visit(LargerOp that) {
leftCompareRight(that);
out(".equals(");
clAlias();
out(".getLarger())");
}
@Override public void visit(SmallAsOp that) {
out("(");
leftCompareRight(that);
out("!==");
clAlias();
out(".getLarger()");
thenTrueElseFalse();
out(")");
}
@Override public void visit(LargeAsOp that) {
out("(");
leftCompareRight(that);
out("!==");
clAlias();
out(".getSmaller()");
thenTrueElseFalse();
out(")");
}
private void leftEqualsRight(BinaryOperatorExpression that) {
that.getLeftTerm().visit(this);
out(".equals(");
that.getRightTerm().visit(this);
out(")");
}
private void clTrue() {
clAlias();
out(".getTrue()");
}
private void clFalse() {
clAlias();
out(".getFalse()");
}
private void equalsFalse() {
out(".equals(");
clFalse();
out(")");
}
private void thenTrueElseFalse() {
out("?");
clTrue();
out(":");
clFalse();
}
private void leftCompareRight(BinaryOperatorExpression that) {
that.getLeftTerm().visit(this);
out(".compare(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(AndOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
that.getRightTerm().visit(this);
out(":");
clFalse();
out(")");
}
@Override public void visit(OrOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
clTrue();
out(":");
that.getRightTerm().visit(this);
out(")");
}
}
| false | false | null | null |
diff --git a/src/main/java/com/salesforce/phoenix/compile/ExpressionCompiler.java b/src/main/java/com/salesforce/phoenix/compile/ExpressionCompiler.java
index 3029e314..3614abc9 100644
--- a/src/main/java/com/salesforce/phoenix/compile/ExpressionCompiler.java
+++ b/src/main/java/com/salesforce/phoenix/compile/ExpressionCompiler.java
@@ -1,1261 +1,1261 @@
/*******************************************************************************
* Copyright (c) 2013, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.salesforce.phoenix.compile;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import com.salesforce.phoenix.compile.GroupByCompiler.GroupBy;
import com.salesforce.phoenix.exception.SQLExceptionCode;
import com.salesforce.phoenix.exception.SQLExceptionInfo;
import com.salesforce.phoenix.expression.AndExpression;
import com.salesforce.phoenix.expression.CaseExpression;
import com.salesforce.phoenix.expression.CoerceExpression;
import com.salesforce.phoenix.expression.ComparisonExpression;
import com.salesforce.phoenix.expression.DateAddExpression;
import com.salesforce.phoenix.expression.DateSubtractExpression;
import com.salesforce.phoenix.expression.DecimalAddExpression;
import com.salesforce.phoenix.expression.DecimalDivideExpression;
import com.salesforce.phoenix.expression.DecimalMultiplyExpression;
import com.salesforce.phoenix.expression.DecimalSubtractExpression;
import com.salesforce.phoenix.expression.DoubleAddExpression;
import com.salesforce.phoenix.expression.DoubleDivideExpression;
import com.salesforce.phoenix.expression.DoubleMultiplyExpression;
import com.salesforce.phoenix.expression.DoubleSubtractExpression;
import com.salesforce.phoenix.expression.Expression;
import com.salesforce.phoenix.expression.InListExpression;
import com.salesforce.phoenix.expression.IsNullExpression;
import com.salesforce.phoenix.expression.LikeExpression;
import com.salesforce.phoenix.expression.LiteralExpression;
import com.salesforce.phoenix.expression.LongAddExpression;
import com.salesforce.phoenix.expression.LongDivideExpression;
import com.salesforce.phoenix.expression.LongMultiplyExpression;
import com.salesforce.phoenix.expression.LongSubtractExpression;
import com.salesforce.phoenix.expression.NotExpression;
import com.salesforce.phoenix.expression.OrExpression;
import com.salesforce.phoenix.expression.RowKeyColumnExpression;
import com.salesforce.phoenix.expression.RowValueConstructorExpression;
import com.salesforce.phoenix.expression.StringConcatExpression;
import com.salesforce.phoenix.expression.TimestampAddExpression;
import com.salesforce.phoenix.expression.TimestampSubtractExpression;
import com.salesforce.phoenix.expression.function.FunctionExpression;
import com.salesforce.phoenix.parse.AddParseNode;
import com.salesforce.phoenix.parse.AndParseNode;
import com.salesforce.phoenix.parse.ArithmeticParseNode;
import com.salesforce.phoenix.parse.BindParseNode;
import com.salesforce.phoenix.parse.CaseParseNode;
import com.salesforce.phoenix.parse.CastParseNode;
import com.salesforce.phoenix.parse.ColumnParseNode;
import com.salesforce.phoenix.parse.ComparisonParseNode;
import com.salesforce.phoenix.parse.DivideParseNode;
import com.salesforce.phoenix.parse.FunctionParseNode;
import com.salesforce.phoenix.parse.FunctionParseNode.BuiltInFunctionInfo;
import com.salesforce.phoenix.parse.InListParseNode;
import com.salesforce.phoenix.parse.IsNullParseNode;
import com.salesforce.phoenix.parse.LikeParseNode;
import com.salesforce.phoenix.parse.LiteralParseNode;
import com.salesforce.phoenix.parse.MultiplyParseNode;
import com.salesforce.phoenix.parse.NotParseNode;
import com.salesforce.phoenix.parse.OrParseNode;
import com.salesforce.phoenix.parse.ParseNode;
import com.salesforce.phoenix.parse.RowValueConstructorParseNode;
import com.salesforce.phoenix.parse.StringConcatParseNode;
import com.salesforce.phoenix.parse.SubtractParseNode;
import com.salesforce.phoenix.parse.UnsupportedAllParseNodeVisitor;
import com.salesforce.phoenix.schema.ColumnModifier;
import com.salesforce.phoenix.schema.ColumnRef;
import com.salesforce.phoenix.schema.DelegateDatum;
import com.salesforce.phoenix.schema.PDataType;
import com.salesforce.phoenix.schema.PDatum;
import com.salesforce.phoenix.schema.PTableType;
import com.salesforce.phoenix.schema.RowKeyValueAccessor;
import com.salesforce.phoenix.schema.TableRef;
import com.salesforce.phoenix.schema.TypeMismatchException;
import com.salesforce.phoenix.util.ByteUtil;
import com.salesforce.phoenix.util.SchemaUtil;
public class ExpressionCompiler extends UnsupportedAllParseNodeVisitor<Expression> {
private boolean isAggregate;
private ParseNode aggregateFunction;
protected final StatementContext context;
protected final GroupBy groupBy;
private int nodeCount;
ExpressionCompiler(StatementContext context) {
this(context,GroupBy.EMPTY_GROUP_BY);
}
ExpressionCompiler(StatementContext context, GroupBy groupBy) {
this.context = context;
this.groupBy = groupBy;
}
public boolean isAggregate() {
return isAggregate;
}
public boolean isTopLevel() {
return nodeCount == 0;
}
public void reset() {
this.isAggregate = false;
this.nodeCount = 0;
}
@Override
public boolean visitEnter(ComparisonParseNode node) {
return true;
}
private void addBindParamMetaData(ParseNode parentNode, ParseNode lhsNode, ParseNode rhsNode, Expression lhsExpr, Expression rhsExpr) throws SQLException {
if (lhsNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)lhsNode, rhsExpr);
}
if (rhsNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)rhsNode, lhsExpr);
}
}
private static void checkComparability(ParseNode node, PDataType lhsDataType, PDataType rhsDataType) throws TypeMismatchException {
if(lhsDataType != null && rhsDataType != null && !lhsDataType.isComparableTo(rhsDataType)) {
throw new TypeMismatchException(lhsDataType, rhsDataType, node.toString());
}
}
// TODO: this no longer needs to be recursive, as we flatten out rvc when we normalize the statement
private void checkComparability(ParseNode parentNode, ParseNode lhsNode, ParseNode rhsNode, Expression lhsExpr, Expression rhsExpr) throws SQLException {
if (lhsNode instanceof RowValueConstructorParseNode && rhsNode instanceof RowValueConstructorParseNode) {
int i = 0;
for (; i < Math.min(lhsExpr.getChildren().size(),rhsExpr.getChildren().size()); i++) {
checkComparability(parentNode, lhsNode.getChildren().get(i), rhsNode.getChildren().get(i), lhsExpr.getChildren().get(i), rhsExpr.getChildren().get(i));
}
for (; i < lhsExpr.getChildren().size(); i++) {
checkComparability(parentNode, lhsNode.getChildren().get(i), null, lhsExpr.getChildren().get(i), null);
}
for (; i < rhsExpr.getChildren().size(); i++) {
checkComparability(parentNode, null, rhsNode.getChildren().get(i), null, rhsExpr.getChildren().get(i));
}
} else if (lhsExpr instanceof RowValueConstructorExpression) {
checkComparability(parentNode, lhsNode.getChildren().get(0), rhsNode, lhsExpr.getChildren().get(0), rhsExpr);
for (int i = 1; i < lhsExpr.getChildren().size(); i++) {
checkComparability(parentNode, lhsNode.getChildren().get(i), null, lhsExpr.getChildren().get(i), null);
}
} else if (rhsExpr instanceof RowValueConstructorExpression) {
checkComparability(parentNode, lhsNode, rhsNode.getChildren().get(0), lhsExpr, rhsExpr.getChildren().get(0));
for (int i = 1; i < rhsExpr.getChildren().size(); i++) {
checkComparability(parentNode, null, rhsNode.getChildren().get(i), null, rhsExpr.getChildren().get(i));
}
} else if (lhsNode == null && rhsNode == null) { // null == null will end up making the query degenerate
} else if (lhsNode == null) { // AND rhs IS NULL
addBindParamMetaData(parentNode, lhsNode, rhsNode, lhsExpr, rhsExpr);
} else if (rhsNode == null) { // AND lhs IS NULL
addBindParamMetaData(parentNode, lhsNode, rhsNode, lhsExpr, rhsExpr);
} else { // AND lhs = rhs
checkComparability(parentNode, lhsExpr.getDataType(), rhsExpr.getDataType());
addBindParamMetaData(parentNode, lhsNode, rhsNode, lhsExpr, rhsExpr);
}
}
@Override
public Expression visitLeave(ComparisonParseNode node, List<Expression> children) throws SQLException {
ParseNode lhsNode = node.getChildren().get(0);
ParseNode rhsNode = node.getChildren().get(1);
Expression lhsExpr = children.get(0);
Expression rhsExpr = children.get(1);
PDataType lhsExprDataType = lhsExpr.getDataType();
PDataType rhsExprDataType = rhsExpr.getDataType();
checkComparability(node, lhsNode, rhsNode, lhsExpr, rhsExpr);
if (lhsExpr instanceof RowValueConstructorExpression || rhsExpr instanceof RowValueConstructorExpression) {
rhsExpr = RowValueConstructorExpression.coerce(lhsExpr, rhsExpr, node.getFilterOp());
// Always wrap both sides in row value constructor, so we don't have to consider comparing
// a non rvc with a rvc.
if ( ! ( lhsExpr instanceof RowValueConstructorExpression ) ) {
lhsExpr = new RowValueConstructorExpression(Collections.singletonList(lhsExpr), lhsExpr.isConstant());
}
children = Arrays.asList(lhsExpr, rhsExpr);
}
Object lhsValue = null;
// Can't use lhsNode.isConstant(), because we have cases in which we don't know
// in advance if a function evaluates to null (namely when bind variables are used)
if (lhsExpr instanceof LiteralExpression) {
lhsValue = ((LiteralExpression)lhsExpr).getValue();
if (lhsValue == null) {
return LiteralExpression.FALSE_EXPRESSION;
}
}
Object rhsValue = null;
if (rhsExpr instanceof LiteralExpression) {
rhsValue = ((LiteralExpression)rhsExpr).getValue();
if (rhsValue == null) {
return LiteralExpression.FALSE_EXPRESSION;
}
}
if (lhsValue != null && rhsValue != null) {
return LiteralExpression.newConstant(ByteUtil.compare(node.getFilterOp(),lhsExprDataType.compareTo(lhsValue, rhsValue, rhsExprDataType)));
}
// Coerce constant to match type of lhs so that we don't need to
// convert at filter time. Since we normalize the select statement
// to put constants on the LHS, we don't need to check the RHS.
if (rhsValue != null) {
// Comparing an unsigned int/long against a negative int/long would be an example. We just need to take
// into account the comparison operator.
if (rhsExprDataType != lhsExprDataType
|| rhsExpr.getColumnModifier() != lhsExpr.getColumnModifier()
|| (rhsExpr.getMaxLength() != null && lhsExpr.getMaxLength() != null && rhsExpr.getMaxLength() < lhsExpr.getMaxLength())) {
// TODO: if lengths are unequal and fixed width?
if (rhsExprDataType.isCoercibleTo(lhsExprDataType, rhsValue)) { // will convert 2.0 -> 2
children = Arrays.asList(children.get(0), LiteralExpression.newConstant(rhsValue, lhsExprDataType,
lhsExpr.getMaxLength(), null, lhsExpr.getColumnModifier()));
} else if (node.getFilterOp() == CompareOp.EQUAL) {
return LiteralExpression.FALSE_EXPRESSION;
} else if (node.getFilterOp() == CompareOp.NOT_EQUAL) {
return LiteralExpression.TRUE_EXPRESSION;
} else { // TODO: generalize this with PDataType.getMinValue(), PDataTypeType.getMaxValue() methods
switch(rhsExprDataType) {
case DECIMAL:
/*
* We're comparing an int/long to a constant decimal with a fraction part.
* We need the types to match in case this is used to form a key. To form the start/stop key,
* we need to adjust the decimal by truncating it or taking its ceiling, depending on the comparison
* operator, to get a whole number.
*/
int increment = 0;
switch (node.getFilterOp()) {
case GREATER_OR_EQUAL:
case LESS: // get next whole number
increment = 1;
default: // Else, we truncate the value
BigDecimal bd = (BigDecimal)rhsValue;
rhsValue = bd.longValue() + increment;
children = Arrays.asList(children.get(0), LiteralExpression.newConstant(rhsValue, lhsExprDataType, lhsExpr.getColumnModifier()));
break;
}
break;
case LONG:
/*
* We are comparing an int, unsigned_int to a long, or an unsigned_long to a negative long.
* int has range of -2147483648 to 2147483647, and unsigned_int has a value range of 0 to 4294967295.
*
* If lhs is int or unsigned_int, since we already determined that we cannot coerce the rhs
* to become the lhs, we know the value on the rhs is greater than lhs if it's positive, or smaller than
* lhs if it's negative.
*
* If lhs is an unsigned_long, then we know the rhs is definitely a negative long. rhs in this case
* will always be bigger than rhs.
*/
if (lhsExprDataType == PDataType.INTEGER ||
lhsExprDataType == PDataType.UNSIGNED_INT) {
switch (node.getFilterOp()) {
case LESS:
case LESS_OR_EQUAL:
if ((Long)rhsValue > 0) {
return LiteralExpression.TRUE_EXPRESSION;
} else {
return LiteralExpression.FALSE_EXPRESSION;
}
case GREATER:
case GREATER_OR_EQUAL:
if ((Long)rhsValue > 0) {
return LiteralExpression.FALSE_EXPRESSION;
} else {
return LiteralExpression.TRUE_EXPRESSION;
}
default:
break;
}
} else if (lhsExprDataType == PDataType.UNSIGNED_LONG) {
switch (node.getFilterOp()) {
case LESS:
case LESS_OR_EQUAL:
return LiteralExpression.FALSE_EXPRESSION;
case GREATER:
case GREATER_OR_EQUAL:
return LiteralExpression.TRUE_EXPRESSION;
default:
break;
}
}
children = Arrays.asList(children.get(0), LiteralExpression.newConstant(rhsValue, rhsExprDataType, lhsExpr.getColumnModifier()));
break;
}
}
}
// Determine if we know the expression must be TRUE or FALSE based on the max size of
// a fixed length expression.
if (children.get(1).getMaxLength() != null && lhsExpr.getMaxLength() != null && lhsExpr.getMaxLength() < children.get(1).getMaxLength()) {
switch (node.getFilterOp()) {
case EQUAL:
return LiteralExpression.FALSE_EXPRESSION;
case NOT_EQUAL:
return LiteralExpression.TRUE_EXPRESSION;
default:
break;
}
}
}
return new ComparisonExpression(node.getFilterOp(), children);
}
@Override
public boolean visitEnter(AndParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(AndParseNode node, List<Expression> children) throws SQLException {
Iterator<Expression> iterator = children.iterator();
while (iterator.hasNext()) {
Expression child = iterator.next();
if (child.getDataType() != PDataType.BOOLEAN) {
throw new TypeMismatchException(PDataType.BOOLEAN, child.getDataType(), child.toString());
}
if (child == LiteralExpression.FALSE_EXPRESSION) {
return child;
}
if (child == LiteralExpression.TRUE_EXPRESSION) {
iterator.remove();
}
}
if (children.size() == 0) {
return LiteralExpression.TRUE_EXPRESSION;
}
if (children.size() == 1) {
return children.get(0);
}
return new AndExpression(children);
}
@Override
public boolean visitEnter(OrParseNode node) throws SQLException {
return true;
}
private Expression orExpression(List<Expression> children) throws SQLException {
Iterator<Expression> iterator = children.iterator();
while (iterator.hasNext()) {
Expression child = iterator.next();
if (child.getDataType() != PDataType.BOOLEAN) {
throw new TypeMismatchException(PDataType.BOOLEAN, child.getDataType(), child.toString());
}
if (child == LiteralExpression.FALSE_EXPRESSION) {
iterator.remove();
}
if (child == LiteralExpression.TRUE_EXPRESSION) {
return child;
}
}
if (children.size() == 0) {
return LiteralExpression.TRUE_EXPRESSION;
}
if (children.size() == 1) {
return children.get(0);
}
return new OrExpression(children);
}
@Override
public Expression visitLeave(OrParseNode node, List<Expression> children) throws SQLException {
return orExpression(children);
}
@Override
public boolean visitEnter(FunctionParseNode node) throws SQLException {
// TODO: Oracle supports nested aggregate function while other DBs don't. Should we?
if (node.isAggregate()) {
if (aggregateFunction != null) {
throw new SQLFeatureNotSupportedException("Nested aggregate functions are not supported");
}
this.aggregateFunction = node;
this.isAggregate = true;
}
return true;
}
private Expression wrapGroupByExpression(Expression expression) {
// If we're in an aggregate function, don't wrap a group by expression,
// since in that case we're aggregating over the regular/ungrouped
// column.
if (aggregateFunction == null) {
int index = groupBy.getExpressions().indexOf(expression);
if (index >= 0) {
isAggregate = true;
RowKeyValueAccessor accessor = new RowKeyValueAccessor(groupBy.getKeyExpressions(), index);
expression = new RowKeyColumnExpression(expression, accessor, groupBy.getKeyExpressions().get(index).getDataType());
}
}
return expression;
}
/**
* Add a Function expression to the expression manager.
* Derived classes may use this as a hook to trap all function additions.
* @return a Function expression
* @throws SQLException if the arguments are invalid for the function.
*/
protected Expression addFunction(FunctionExpression func) {
return context.getExpressionManager().addIfAbsent(func);
}
@Override
/**
* @param node a function expression node
* @param children the child expression arguments to the function expression node.
*/
public Expression visitLeave(FunctionParseNode node, List<Expression> children) throws SQLException {
children = node.validate(children, context);
FunctionExpression func = node.create(children, context);
if (node.isConstant()) {
ImmutableBytesWritable ptr = context.getTempPtr();
Object value = null;
PDataType type = func.getDataType();
if (func.evaluate(null, ptr)) {
value = type.toObject(ptr);
}
return LiteralExpression.newConstant(value, type);
}
BuiltInFunctionInfo info = node.getInfo();
for (int i = 0; i < info.getRequiredArgCount(); i++) {
// Optimization to catch cases where a required argument is null resulting in the function
// returning null. We have to wait until after we create the function expression so that
// we can get the proper type to use.
if (node.evalToNullIfParamIsNull(context, i)) {
Expression child = children.get(i);
if (child instanceof LiteralExpression
&& ((LiteralExpression)child).getValue() == null) {
return LiteralExpression.newConstant(null, func.getDataType());
}
}
}
Expression expression = addFunction(func);
expression = wrapGroupByExpression(expression);
if (aggregateFunction == node) {
aggregateFunction = null; // Turn back off on the way out
}
return expression;
}
/**
* Called by visitor to resolve a column expression node into a column reference.
* Derived classes may use this as a hook to trap all column resolves.
* @param node a column expression node
* @return a resolved ColumnRef
* @throws SQLException if the column expression node does not refer to a known/unambiguous column
*/
protected ColumnRef resolveColumn(ColumnParseNode node) throws SQLException {
return context.getResolver().resolveColumn(node.getSchemaName(), node.getTableName(), node.getName());
}
@Override
public Expression visit(ColumnParseNode node) throws SQLException {
ColumnRef ref = resolveColumn(node);
TableRef tableRef = ref.getTableRef();
if (tableRef.equals(context.getCurrentTable())
&& !SchemaUtil.isPKColumn(ref.getColumn())) { // project only kv columns
context.getScan().addColumn(ref.getColumn().getFamilyName().getBytes(), ref.getColumn().getName().getBytes());
}
Expression expression = ref.newColumnExpression();
Expression wrappedExpression = wrapGroupByExpression(expression);
// If we're in an aggregate expression
// and we're not in the context of an aggregate function
// and we didn't just wrap our column reference
// then we're mixing aggregate and non aggregate expressions in the same expression.
// This catches cases like this: SELECT sum(a_integer) + a_integer FROM atable GROUP BY a_string
if (isAggregate && aggregateFunction == null && wrappedExpression == expression) {
throwNonAggExpressionInAggException(expression.toString());
}
return wrappedExpression;
}
@Override
public Expression visit(BindParseNode node) throws SQLException {
Object value = context.getBindManager().getBindValue(node);
return LiteralExpression.newConstant(value);
}
@Override
public Expression visit(LiteralParseNode node) throws SQLException {
return LiteralExpression.newConstant(node.getValue(), node.getType());
}
@Override
public List<Expression> newElementList(int size) {
nodeCount += size;
return new ArrayList<Expression>(size);
}
@Override
public void addElement(List<Expression> l, Expression element) {
nodeCount--;
l.add(element);
}
@Override
public boolean visitEnter(CaseParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(CaseParseNode node, List<Expression> l) throws SQLException {
final CaseExpression caseExpression = new CaseExpression(l);
for (int i = 0; i < node.getChildren().size(); i+=2) {
ParseNode childNode = node.getChildren().get(i);
if (childNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)childNode, new DelegateDatum(caseExpression));
}
}
if (node.isConstant()) {
ImmutableBytesWritable ptr = context.getTempPtr();
int index = caseExpression.evaluateIndexOf(null, ptr);
if (index < 0) {
return LiteralExpression.NULL_EXPRESSION;
}
return caseExpression.getChildren().get(index);
}
return wrapGroupByExpression(caseExpression);
}
@Override
public boolean visitEnter(LikeParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(LikeParseNode node, List<Expression> children) throws SQLException {
ParseNode lhsNode = node.getChildren().get(0);
ParseNode rhsNode = node.getChildren().get(1);
Expression lhs = children.get(0);
Expression rhs = children.get(1);
if ( rhs.getDataType() != null && lhs.getDataType() != null &&
!lhs.getDataType().isCoercibleTo(rhs.getDataType()) &&
!rhs.getDataType().isCoercibleTo(lhs.getDataType())) {
throw new TypeMismatchException(lhs.getDataType(), rhs.getDataType(), node.toString());
}
if (lhsNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)lhsNode, rhs);
}
if (rhsNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)rhsNode, lhs);
}
if (rhs instanceof LiteralExpression) {
String pattern = (String)((LiteralExpression)rhs).getValue();
if (pattern == null || pattern.length() == 0) {
return LiteralExpression.NULL_EXPRESSION;
}
// TODO: for pattern of '%' optimize to strlength(lhs) > 0
// We can't use lhs IS NOT NULL b/c if lhs is NULL we need
// to return NULL.
int index = LikeExpression.indexOfWildcard(pattern);
// Can't possibly be as long as the constant, then FALSE
Integer lhsByteSize = lhs.getByteSize();
if (lhsByteSize != null && lhsByteSize < index) {
return LiteralExpression.FALSE_EXPRESSION;
}
if (index == -1) {
String rhsLiteral = LikeExpression.unescapeLike(pattern);
if (lhsByteSize != null && lhsByteSize != rhsLiteral.length()) {
return LiteralExpression.FALSE_EXPRESSION;
}
CompareOp op = node.isNegate() ? CompareOp.NOT_EQUAL : CompareOp.EQUAL;
if (pattern.equals(rhsLiteral)) {
return new ComparisonExpression(op, children);
} else {
rhs = LiteralExpression.newConstant(rhsLiteral, PDataType.CHAR);
return new ComparisonExpression(op, Arrays.asList(lhs,rhs));
}
}
}
Expression expression = new LikeExpression(children);
if (node.isConstant()) {
ImmutableBytesWritable ptr = context.getTempPtr();
if (!expression.evaluate(null, ptr)) {
return LiteralExpression.NULL_EXPRESSION;
} else {
return LiteralExpression.newConstant(Boolean.TRUE.equals(PDataType.BOOLEAN.toObject(ptr)) ^ node.isNegate());
}
}
if (node.isNegate()) {
expression = new NotExpression(expression);
}
return expression;
}
@Override
public boolean visitEnter(NotParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(NotParseNode node, List<Expression> children) throws SQLException {
ParseNode childNode = node.getChildren().get(0);
Expression child = children.get(0);
if (!PDataType.BOOLEAN.isCoercibleTo(child.getDataType())) {
throw new TypeMismatchException(PDataType.BOOLEAN, child.getDataType(), node.toString());
}
if (childNode instanceof BindParseNode) { // TODO: valid/possibe?
context.getBindManager().addParamMetaData((BindParseNode)childNode, child);
}
Boolean value = null;
// Can't use child.isConstant(), because we have cases in which we don't know
// in advance if a function evaluates to null (namely when bind variables are used)
// TODO: review: have ParseNode.getValue()?
if (child instanceof LiteralExpression) {
value = (Boolean)((LiteralExpression)child).getValue();
if (value == null) {
return LiteralExpression.NULL_EXPRESSION;
}
}
if (value != null) {
return LiteralExpression.newConstant(!value);
}
return new NotExpression(child);
}
@Override
public boolean visitEnter(CastParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(CastParseNode node, List<Expression> children) throws SQLException {
final ParseNode childNode = node.getChildren().get(0);
final Expression child = children.get(0);
final PDataType dataType = child.getDataType();
final PDataType targetDataType = node.getDataType();
if (childNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)childNode, child);
}
if (dataType!= null && targetDataType != null && !dataType.isCoercibleTo(targetDataType)) {
// TODO: remove soon. Allow cast for indexes, as we know what we're doing :-)
if (context.getResolver().getTables().get(0).getTable().getType() != PTableType.INDEX) {
throw new TypeMismatchException(dataType, targetDataType, child.toString());
}
}
return wrapGroupByExpression(CoerceExpression.create(child, targetDataType));
}
@Override
public boolean visitEnter(InListParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(InListParseNode node, List<Expression> l) throws SQLException {
List<Expression> inChildren = l;
Expression firstChild = inChildren.get(0);
ImmutableBytesWritable ptr = context.getTempPtr();
PDataType firstChildType = firstChild.getDataType();
ParseNode firstChildNode = node.getChildren().get(0);
if (firstChildNode instanceof BindParseNode) {
PDatum datum = firstChild;
if (firstChildType == null) {
datum = inferBindDatum(inChildren);
}
context.getBindManager().addParamMetaData((BindParseNode)firstChildNode, datum);
}
for (int i = 1; i < l.size(); i++) {
ParseNode childNode = node.getChildren().get(i);
if (childNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)childNode, firstChild);
}
}
if (firstChildNode.isConstant() && firstChild.evaluate(null, ptr) && ptr.getLength() == 0) {
return LiteralExpression.newConstant(null, PDataType.BOOLEAN);
}
Expression e = InListExpression.create(inChildren, ptr);
if (node.isNegate()) {
e = new NotExpression(e);
}
if (node.isConstant()) {
if (!e.evaluate(null, ptr) || ptr.getLength() == 0) {
return LiteralExpression.newConstant(null, e.getDataType());
}
Object value = e.getDataType().toObject(ptr);
return LiteralExpression.newConstant(value, e.getDataType());
}
return e;
}
private static final PDatum DECIMAL_DATUM = new PDatum() {
@Override
public boolean isNullable() {
return true;
}
@Override
public PDataType getDataType() {
return PDataType.DECIMAL;
}
@Override
public Integer getByteSize() {
return null;
}
@Override
public Integer getMaxLength() {
return null;
}
@Override
public Integer getScale() {
return PDataType.DEFAULT_SCALE;
}
@Override
public ColumnModifier getColumnModifier() {
return null;
}
};
private static PDatum inferBindDatum(List<Expression> children) {
boolean isChildTypeUnknown = false;
PDatum datum = children.get(1);
for (int i = 2; i < children.size(); i++) {
Expression child = children.get(i);
PDataType childType = child.getDataType();
if (childType == null) {
isChildTypeUnknown = true;
} else if (datum.getDataType() == null) {
datum = child;
isChildTypeUnknown = true;
} else if (datum.getDataType() == childType || childType.isCoercibleTo(datum.getDataType())) {
continue;
} else if (datum.getDataType().isCoercibleTo(childType)) {
datum = child;
}
}
// If we found an "unknown" child type and the return type is a number
// make the return type be the most general number type of DECIMAL.
// TODO: same for TIMESTAMP for DATE/TIME?
if (isChildTypeUnknown && datum.getDataType() != null && datum.getDataType().isCoercibleTo(PDataType.DECIMAL)) {
return DECIMAL_DATUM;
}
return datum;
}
@Override
public boolean visitEnter(IsNullParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(IsNullParseNode node, List<Expression> children) throws SQLException {
ParseNode childNode = node.getChildren().get(0);
Expression child = children.get(0);
if (childNode instanceof BindParseNode) { // TODO: valid/possibe?
context.getBindManager().addParamMetaData((BindParseNode)childNode, child);
}
Boolean value = null;
// Can't use child.isConstant(), because we have cases in which we don't know
// in advance if a function evaluates to null (namely when bind variables are used)
// TODO: review: have ParseNode.getValue()?
if (child instanceof LiteralExpression) {
value = (Boolean)((LiteralExpression)child).getValue();
return node.isNegate() ^ value == null ? LiteralExpression.FALSE_EXPRESSION : LiteralExpression.TRUE_EXPRESSION;
}
if (!child.isNullable()) { // If child expression is not nullable, we can rewrite this
return node.isNegate() ? LiteralExpression.TRUE_EXPRESSION : LiteralExpression.FALSE_EXPRESSION;
}
return new IsNullExpression(child, node.isNegate());
}
private static interface ArithmeticExpressionFactory {
Expression create(ArithmeticParseNode node, List<Expression> children) throws SQLException;
}
private static interface ArithmeticExpressionBinder {
PDatum getBindMetaData(int i, List<Expression> children, Expression expression);
}
private Expression visitLeave(ArithmeticParseNode node, List<Expression> children, ArithmeticExpressionBinder binder, ArithmeticExpressionFactory factory)
throws SQLException {
boolean isLiteral = true;
boolean isNull = false;
for (Expression child : children) {
boolean isChildLiteral = (child instanceof LiteralExpression);
isNull |= isChildLiteral && ((LiteralExpression)child).getValue() == null;
isLiteral &= isChildLiteral;
}
Expression expression = factory.create(node, children);
for (int i = 0; i < node.getChildren().size(); i++) {
ParseNode childNode = node.getChildren().get(i);
if (childNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)childNode, binder == null ? expression : binder.getBindMetaData(i, children, expression));
}
}
ImmutableBytesWritable ptr = context.getTempPtr();
// If all children are literals, just evaluate now
if (isLiteral) {
// We can use null here because we don't need any row/tuple data when evaluating literals
expression.evaluate(null,ptr);
return LiteralExpression. newConstant(expression.getDataType().toObject(ptr), expression.getDataType());
} else if (isNull) {
return LiteralExpression. newConstant(null, expression.getDataType());
}
// Otherwise create and return the expression
return wrapGroupByExpression(expression);
}
@Override
public boolean visitEnter(SubtractParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(SubtractParseNode node,
List<Expression> children) throws SQLException {
return visitLeave(node, children, new ArithmeticExpressionBinder() {
@Override
public PDatum getBindMetaData(int i, List<Expression> children,
final Expression expression) {
final PDataType type;
// If we're binding the first parameter and the second parameter
// is a date
// we know that the first parameter must be a date type too.
if (i == 0 && (type = children.get(1).getDataType()) != null
&& type.isCoercibleTo(PDataType.DATE)) {
return new PDatum() {
@Override
public boolean isNullable() {
return expression.isNullable();
}
@Override
public PDataType getDataType() {
return type;
}
@Override
public Integer getByteSize() {
return type.getByteSize();
}
@Override
public Integer getMaxLength() {
return expression.getMaxLength();
}
@Override
public Integer getScale() {
return expression.getScale();
}
@Override
public ColumnModifier getColumnModifier() {
return expression.getColumnModifier();
}
};
} else if (expression.getDataType() != null
&& expression.getDataType().isCoercibleTo(
PDataType.DATE)) {
return new PDatum() { // Same as with addition
@Override
public boolean isNullable() {
return expression.isNullable();
}
@Override
public PDataType getDataType() {
return PDataType.DECIMAL;
}
@Override
public Integer getByteSize() {
return null;
}
@Override
public Integer getMaxLength() {
return expression.getMaxLength();
}
@Override
public Integer getScale() {
return expression.getScale();
}
@Override
public ColumnModifier getColumnModifier() {
return expression.getColumnModifier();
}
};
}
// Otherwise just go with what was calculated for the expression
return expression;
}
}, new ArithmeticExpressionFactory() {
@Override
public Expression create(ArithmeticParseNode node,
List<Expression> children) throws SQLException {
int i = 0;
PDataType theType = null;
PDataType type1 = children.get(0).getDataType();
PDataType type2 = children.get(1).getDataType();
// TODO: simplify this special case for DATE conversion
/**
* For date1-date2, we want to coerce to a LONG because this
* cannot be compared against another date. It has essentially
* become a number. For date1-5, we want to preserve the DATE
* type because this can still be compared against another date
* and cannot be multiplied or divided. Any other time occurs is
* an error. For example, 5-date1 is an error. The nulls occur if
* we have bind variables.
*/
boolean isType1Date =
type1 != null
&& type1 != PDataType.TIMESTAMP
&& type1.isCoercibleTo(PDataType.DATE);
boolean isType2Date =
type2 != null
&& type2 != PDataType.TIMESTAMP
&& type2.isCoercibleTo(PDataType.DATE);
if (isType1Date || isType2Date) {
if (isType1Date && isType2Date) {
i = 2;
theType = PDataType.LONG;
} else if (isType1Date && type2 != null
&& type2.isCoercibleTo(PDataType.DECIMAL)) {
i = 2;
theType = PDataType.DATE;
} else if (type1 == null || type2 == null) {
/*
* FIXME: Could be either a Date or BigDecimal, but we
* don't know if we're comparing to a date or a number
* which would be disambiguate it.
*/
i = 2;
theType = null;
}
} else if(type1 == PDataType.TIMESTAMP || type2 == PDataType.TIMESTAMP) {
i = 2;
theType = PDataType.TIMESTAMP;
}
for (; i < children.size(); i++) {
// This logic finds the common type to which all child types are coercible
// without losing precision.
PDataType type = children.get(i).getDataType();
if (type == null) {
continue;
} else if (type.isCoercibleTo(PDataType.LONG)) {
if (theType == null) {
theType = PDataType.LONG;
}
} else if (type == PDataType.DECIMAL) {
// Coerce return type to DECIMAL from LONG or DOUBLE if DECIMAL child found,
// unless we're doing date arithmetic.
if (theType == null
|| !theType.isCoercibleTo(PDataType.DATE)) {
theType = PDataType.DECIMAL;
}
} else if (type.isCoercibleTo(PDataType.DOUBLE)) {
// Coerce return type to DOUBLE from LONG if DOUBLE child found,
// unless we're doing date arithmetic or we've found another child of type DECIMAL
if (theType == null
|| (theType != PDataType.DECIMAL && !theType.isCoercibleTo(PDataType.DATE) )) {
theType = PDataType.DOUBLE;
}
} else {
throw new TypeMismatchException(type, node.toString());
}
}
if (theType == PDataType.DECIMAL) {
return new DecimalSubtractExpression(children);
} else if (theType == PDataType.LONG) {
return new LongSubtractExpression(children);
} else if (theType == PDataType.DOUBLE) {
return new DoubleSubtractExpression(children);
} else if (theType == null) {
return LiteralExpression.newConstant(null, theType);
} else if (theType == PDataType.TIMESTAMP) {
return new TimestampSubtractExpression(children);
} else if (theType.isCoercibleTo(PDataType.DATE)) {
return new DateSubtractExpression(children);
} else {
throw new TypeMismatchException(theType, node.toString());
}
}
});
}
@Override
public boolean visitEnter(AddParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(AddParseNode node, List<Expression> children) throws SQLException {
return visitLeave(node, children,
new ArithmeticExpressionBinder() {
@Override
public PDatum getBindMetaData(int i, List<Expression> children, final Expression expression) {
PDataType type = expression.getDataType();
if (type != null && type.isCoercibleTo(PDataType.DATE)) {
return new PDatum() {
@Override
public boolean isNullable() {
return expression.isNullable();
}
@Override
public PDataType getDataType() {
return PDataType.DECIMAL;
}
@Override
public Integer getByteSize() {
return null;
}
@Override
public Integer getMaxLength() {
return expression.getMaxLength();
}
@Override
public Integer getScale() {
return expression.getScale();
}
@Override
public ColumnModifier getColumnModifier() {
return expression.getColumnModifier();
}
};
}
return expression;
}
},
new ArithmeticExpressionFactory() {
@Override
public Expression create(ArithmeticParseNode node, List<Expression> children) throws SQLException {
boolean foundDate = false;
PDataType theType = null;
for(int i = 0; i < children.size(); i++) {
PDataType type = children.get(i).getDataType();
if (type == null) {
continue;
} else if (type.isCoercibleTo(PDataType.TIMESTAMP)) {
if (foundDate) {
throw new TypeMismatchException(type, node.toString());
}
if (theType == null || theType != PDataType.TIMESTAMP) {
theType = type;
}
foundDate = true;
}else if (type == PDataType.DECIMAL) {
- if (theType == null || !theType.isCoercibleTo(PDataType.DATE)) {
+ if (theType == null || !theType.isCoercibleTo(PDataType.TIMESTAMP)) {
theType = PDataType.DECIMAL;
}
} else if (type.isCoercibleTo(PDataType.LONG)) {
if (theType == null) {
theType = PDataType.LONG;
}
} else if (type.isCoercibleTo(PDataType.DOUBLE)) {
if (theType == null) {
theType = PDataType.DOUBLE;
}
} else {
throw new TypeMismatchException(type, node.toString());
}
}
if (theType == PDataType.DECIMAL) {
return new DecimalAddExpression(children);
} else if (theType == PDataType.LONG) {
return new LongAddExpression(children);
} else if (theType == PDataType.DOUBLE) {
return new DoubleAddExpression(children);
} else if (theType == null) {
return LiteralExpression.newConstant(null, theType);
} else if (theType == PDataType.TIMESTAMP) {
return new TimestampAddExpression(children);
} else if (theType.isCoercibleTo(PDataType.DATE)) {
return new DateAddExpression(children);
} else {
throw new TypeMismatchException(theType, node.toString());
}
}
});
}
@Override
public boolean visitEnter(MultiplyParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(MultiplyParseNode node, List<Expression> children) throws SQLException {
return visitLeave(node, children, null, new ArithmeticExpressionFactory() {
@Override
public Expression create(ArithmeticParseNode node, List<Expression> children) throws SQLException {
PDataType theType = null;
for(int i = 0; i < children.size(); i++) {
PDataType type = children.get(i).getDataType();
if (type == null) {
continue;
} else if (type == PDataType.DECIMAL) {
theType = PDataType.DECIMAL;
} else if (type.isCoercibleTo(PDataType.LONG)) {
if (theType == null) {
theType = PDataType.LONG;
}
} else if (type.isCoercibleTo(PDataType.DOUBLE)) {
if (theType == null) {
theType = PDataType.DOUBLE;
}
} else {
throw new TypeMismatchException(type, node.toString());
}
}
switch (theType) {
case DECIMAL:
return new DecimalMultiplyExpression( children);
case LONG:
return new LongMultiplyExpression( children);
case DOUBLE:
return new DoubleMultiplyExpression( children);
default:
return LiteralExpression.newConstant(null, theType);
}
}
});
}
@Override
public boolean visitEnter(DivideParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(DivideParseNode node, List<Expression> children) throws SQLException {
for (int i = 1; i < children.size(); i++) { // Compile time check for divide by zero and null
Expression child = children.get(i);
if (child.getDataType() != null && child instanceof LiteralExpression) {
LiteralExpression literal = (LiteralExpression)child;
if (literal.getDataType() == PDataType.DECIMAL) {
if (PDataType.DECIMAL.compareTo(literal.getValue(), BigDecimal.ZERO) == 0) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.DIVIDE_BY_ZERO).build().buildException();
}
} else {
if (literal.getDataType().compareTo(literal.getValue(), 0L, PDataType.LONG) == 0) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.DIVIDE_BY_ZERO).build().buildException();
}
}
}
}
return visitLeave(node, children, null, new ArithmeticExpressionFactory() {
@Override
public Expression create(ArithmeticParseNode node, List<Expression> children) throws SQLException {
PDataType theType = null;
for(int i = 0; i < children.size(); i++) {
PDataType type = children.get(i).getDataType();
if (type == null) {
continue;
} else if (type == PDataType.DECIMAL) {
theType = PDataType.DECIMAL;
} else if (type.isCoercibleTo(PDataType.LONG)) {
if (theType == null) {
theType = PDataType.LONG;
}
} else if (type.isCoercibleTo(PDataType.DOUBLE)) {
if (theType == null) {
theType = PDataType.DOUBLE;
}
} else {
throw new TypeMismatchException(type, node.toString());
}
}
switch (theType) {
case DECIMAL:
return new DecimalDivideExpression( children);
case LONG:
return new LongDivideExpression( children);
case DOUBLE:
return new DoubleDivideExpression(children);
default:
return LiteralExpression.newConstant(null, theType);
}
}
});
}
public static void throwNonAggExpressionInAggException(String nonAggregateExpression) throws SQLException {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.AGGREGATE_WITH_NOT_GROUP_BY_COLUMN)
.setMessage(nonAggregateExpression).build().buildException();
}
@Override
public Expression visitLeave(StringConcatParseNode node, List<Expression> children) throws SQLException {
final StringConcatExpression expression=new StringConcatExpression(children);
for (int i = 0; i < children.size(); i++) {
ParseNode childNode=node.getChildren().get(i);
if(childNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)childNode,expression);
}
PDataType type=children.get(i).getDataType();
if(type==PDataType.VARBINARY){
throw new SQLExceptionInfo.Builder(SQLExceptionCode.TYPE_NOT_SUPPORTED_FOR_OPERATOR)
.setMessage("Concatenation does not support "+ type +" in expression" + node).build().buildException();
}
}
boolean isLiteralExpression = true;
for (Expression child:children) {
isLiteralExpression&=(child instanceof LiteralExpression);
}
ImmutableBytesWritable ptr = context.getTempPtr();
if (isLiteralExpression) {
expression.evaluate(null,ptr);
return LiteralExpression.newConstant(expression.getDataType().toObject(ptr));
}
return wrapGroupByExpression(expression);
}
@Override
public boolean visitEnter(StringConcatParseNode node) throws SQLException {
return true;
}
@Override
public boolean visitEnter(RowValueConstructorParseNode node) throws SQLException {
return true;
}
@Override
public Expression visitLeave(RowValueConstructorParseNode node, List<Expression> l) throws SQLException {
// Don't trim trailing nulls here, as we'd potentially be dropping bind
// variables that aren't bound yet.
return new RowValueConstructorExpression(l, node.isConstant());
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/com/sun/gi/utils/nio/NIOSocketManager.java b/src/com/sun/gi/utils/nio/NIOSocketManager.java
index 642b1ec99..5ed80c593 100644
--- a/src/com/sun/gi/utils/nio/NIOSocketManager.java
+++ b/src/com/sun/gi/utils/nio/NIOSocketManager.java
@@ -1,350 +1,375 @@
package com.sun.gi.utils.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.Socket;
import java.net.DatagramSocket;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.ClosedChannelException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import static java.nio.channels.SelectionKey.*;
public class NIOSocketManager implements Runnable {
private static Logger log = Logger.getLogger("com.sun.gi.utils.nio");
private Selector selector;
private int tcpBufSize;
private int udpBufSize;
private Set<NIOSocketManagerListener> listeners =
new TreeSet<NIOSocketManagerListener>();
private List<NIOConnection> initiatorQueue =
new ArrayList<NIOConnection>();
private List<NIOConnection> receiverQueue =
new ArrayList<NIOConnection>();
private List<ServerSocketChannel> acceptorQueue =
new ArrayList<ServerSocketChannel>();
private List<SelectableChannel> writeQueue =
new ArrayList<SelectableChannel>();
public NIOSocketManager() throws IOException {
this(128 * 1024, // tcp buffer size
64 * 1024); // udp buffer size
}
public NIOSocketManager(int tcpBufferSize, int udpBufferSize)
throws IOException {
selector = Selector.open();
this.tcpBufSize = tcpBufferSize;
this.udpBufSize = udpBufferSize;
new Thread(this).start();
}
public void acceptConnectionsOn(SocketAddress addr)
throws IOException {
//log.entering("NIOSocketManager", "acceptConnectionsOn");
ServerSocketChannel channel = ServerSocketChannel.open();
channel.configureBlocking(false);
channel.socket().bind(addr);
synchronized (acceptorQueue) {
acceptorQueue.add(channel);
}
selector.wakeup();
//log.exiting("NIOSocketManager", "acceptConnectionsOn");
}
public NIOConnection makeConnectionTo(SocketAddress addr) {
//log.entering("NIOSocketManager", "makeConnectionTo");
try {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(addr);
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
- NIOConnection conn =
- new NIOConnection(this, sc, dc, tcpBufSize, udpBufSize);
+ NIOConnection conn = null;
+ try {
+ conn =
+ new NIOConnection(this, sc, dc, tcpBufSize, udpBufSize);
+ } catch (OutOfMemoryError e) {
+ e.printStackTrace();
+ log.severe("Can't allocate buffers for connection");
+ try {
+ sc.close();
+ dc.close();
+ } catch (IOException ie) {
+ // ignore
+ }
+ return null;
+ }
synchronized (initiatorQueue) {
initiatorQueue.add(conn);
}
selector.wakeup();
return conn;
}
catch (IOException ex) {
ex.printStackTrace();
return null;
//} finally {
//log.exiting("NIOSocketManager", "makeConnectionTo");
}
}
// This runs the actual polled input
public void run() {
//log.entering("NIOSocketManager", "run");
while (true) { // until shutdown() is called
synchronized (initiatorQueue) {
for (NIOConnection conn : initiatorQueue) {
try {
conn.registerConnect(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
initiatorQueue.clear();
}
synchronized (receiverQueue) {
for (NIOConnection conn : receiverQueue) {
try {
conn.open(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
receiverQueue.clear();
}
synchronized (acceptorQueue) {
for (ServerSocketChannel chan : acceptorQueue) {
try {
chan.register(selector, OP_ACCEPT);
}
catch (ClosedChannelException ex2) {
ex2.printStackTrace();
}
}
acceptorQueue.clear();
}
synchronized (writeQueue) {
for (SelectableChannel chan : writeQueue) {
SelectionKey key = chan.keyFor(selector);
if (key == null) { // XXX: DJE
log.warning("key is null");
continue;
}
if (key.isValid()) {
key.interestOps(key.interestOps() | OP_WRITE);
}
}
writeQueue.clear();
}
if (! selector.isOpen())
break;
try {
log.finest("Calling select");
int n = selector.select();
log.finer("selector: " + n + " ready handles");
if (n > 0) {
processSocketEvents(selector);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//log.exiting("NIOSocketManager", "run");
}
/**
* processSocketEvents
*
* @param selector Selector
*/
private void processSocketEvents(Selector selector) {
//log.entering("NIOSocketManager", "processSocketEvents");
Iterator<SelectionKey> i = selector.selectedKeys().iterator();
// Walk through set
while (i.hasNext()) {
// Get key from set
SelectionKey key = (SelectionKey) i.next();
// Remove current entry
i.remove();
if (key.isValid() && key.isAcceptable()) {
handleAccept(key);
}
if (key.isValid() && key.isConnectable()) {
handleConnect(key);
}
if (key.isValid() && key.isReadable()) {
handleRead(key);
}
if (key.isValid() && key.isWritable()) {
handleWrite(key);
}
}
//log.exiting("NIOSocketManager", "processSocketEvents");
}
private void handleRead(SelectionKey key) {
//log.entering("NIOSocketManager", "handleRead");
ReadWriteSelectorHandler h =
(ReadWriteSelectorHandler) key.attachment();
try {
h.handleRead(key);
} catch (IOException ex) {
h.handleClose();
//} finally {
//log.exiting("NIOSocketManager", "handleRead");
}
}
private void handleWrite(SelectionKey key) {
//log.entering("NIOSocketManager", "handleWrite");
ReadWriteSelectorHandler h =
(ReadWriteSelectorHandler) key.attachment();
try {
h.handleWrite(key);
} catch (IOException ex) {
h.handleClose();
//} finally {
//log.exiting("NIOSocketManager", "handleWrite");
}
}
private void handleAccept(SelectionKey key) {
//log.entering("NIOSocketManager", "handleAccept");
// Get channel
ServerSocketChannel serverChannel =
(ServerSocketChannel) key.channel();
NIOConnection conn = null;
// Accept request
try {
SocketChannel sc = serverChannel.accept();
if (sc == null) {
log.warning("accept returned null");
return;
}
sc.configureBlocking(false);
// Now create a UDP channel for this endpoint
DatagramChannel dc = DatagramChannel.open();
- conn =
- new NIOConnection(this, sc, dc, tcpBufSize, udpBufSize);
+ try {
+ conn =
+ new NIOConnection(this, sc, dc, tcpBufSize, udpBufSize);
+ } catch (OutOfMemoryError e) {
+ e.printStackTrace();
+ log.severe("Can't allocate buffers for connection");
+ try {
+ sc.close();
+ dc.close();
+ } catch (IOException ie) {
+ // ignore
+ }
+ return;
+ }
dc.socket().setReuseAddress(true);
dc.configureBlocking(false);
dc.socket().bind(sc.socket().getLocalSocketAddress());
// @@: Workaround for Windows JDK 1.5; it's unhappy with this
// call because it's trying to use the (null) hostname instead
// of the host address. So we explicitly pull out the host
// address and create a new InetSocketAddress with it.
//dc.connect(sc.socket().getRemoteSocketAddress());
dc.connect(new InetSocketAddress(
sc.socket().getInetAddress().getHostAddress(),
sc.socket().getPort()));
log.finest("udp local " +
dc.socket().getLocalSocketAddress() +
" remote " + dc.socket().getRemoteSocketAddress());
synchronized (receiverQueue) {
receiverQueue.add(conn);
}
for (NIOSocketManagerListener l : listeners) {
l.newConnection(conn);
}
} catch (IOException ex) {
ex.printStackTrace();
if (conn != null) {
conn.disconnect();
}
} finally {
//log.exiting("NIOSocketManager", "handleAccept");
}
}
public void enableWrite(SelectableChannel chan) {
synchronized(writeQueue) {
writeQueue.add(chan);
}
selector.wakeup();
}
private void handleConnect(SelectionKey key) {
//log.entering("NIOSocketManager", "handleConnect");
NIOConnection conn = (NIOConnection) key.attachment();
try {
conn.processConnect(key);
for (NIOSocketManagerListener l : listeners) {
l.connected(conn);
}
} catch (IOException ex) {
log.warning("NIO connect failure: "+ex.getMessage());
conn.disconnect();
for (NIOSocketManagerListener l : listeners) {
l.connectionFailed(conn);
}
//} finally {
//log.exiting("NIOSocketManager", "handleConnect");
}
}
/**
* addListener
*
* @param l NIOSocketManagerListener
*/
public void addListener(NIOSocketManagerListener l) {
listeners.add(l);
}
public void shutdown() {
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/hraven-core/src/main/java/com/twitter/hraven/JobDetails.java b/hraven-core/src/main/java/com/twitter/hraven/JobDetails.java
index b1b69d8..bded98b 100644
--- a/hraven-core/src/main/java/com/twitter/hraven/JobDetails.java
+++ b/hraven-core/src/main/java/com/twitter/hraven/JobDetails.java
@@ -1,502 +1,518 @@
/*
Copyright 2012 Twitter, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.twitter.hraven;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.NavigableMap;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
+import org.apache.commons.lang.NotImplementedException;
import com.twitter.hraven.datasource.JobHistoryService;
/**
* Represents the configuration, statistics, and counters from a single
* map reduce job. Individual task details are also nested, though may not
* be loaded in all cases.
*/
@JsonSerialize(
include= JsonSerialize.Inclusion.NON_NULL
)
public class JobDetails implements Comparable<JobDetails> {
@SuppressWarnings("unused")
private static Log LOG = LogFactory.getLog(JobDetails.class);
// job key -- maps to row key
private JobKey jobKey;
// unique job ID assigned by job tracker
private String jobId;
// job-level stats
private String jobName;
private String user;
private String priority;
private String status;
private String version;
private long submitTime;
private long launchTime;
private long finishTime;
private long totalMaps;
private long totalReduces;
private long finishedMaps;
private long finishedReduces;
private long failedMaps;
private long failedReduces;
private long mapFileBytesRead;
private long mapFileBytesWritten;
private long reduceFileBytesRead;
private long hdfsBytesRead;
private long hdfsBytesWritten;
private long mapSlotMillis;
private long reduceSlotMillis;
private long reduceShuffleBytes;
// job config
private Configuration config;
// job-level counters
private CounterMap counters = new CounterMap();
private CounterMap mapCounters = new CounterMap();
private CounterMap reduceCounters = new CounterMap();
// tasks
private List<TaskDetails> tasks = new ArrayList<TaskDetails>();
@JsonCreator
public JobDetails(@JsonProperty("jobKey") JobKey key) {
this.jobKey = key;
}
@Override
public boolean equals(Object other) {
if (other instanceof JobDetails) {
return compareTo((JobDetails)other) == 0;
}
return false;
}
/**
* Compares two JobDetails objects on the basis of their JobKey
*
* @param other
* @return 0 if this JobKey is equal to the other JobKey,
* 1 if this JobKey greater than other JobKey,
* -1 if this JobKey is less than other JobKey
*
*/
@Override
public int compareTo(JobDetails otherJob) {
if (otherJob == null) {
return -1;
}
return new CompareToBuilder().append(this.jobKey, otherJob.getJobKey())
.toComparison();
}
@Override
public int hashCode(){
return new HashCodeBuilder()
.append(this.jobKey)
.toHashCode();
}
public JobKey getJobKey() {
return this.jobKey;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public long getSubmitTime() {
return submitTime;
}
public void setSubmitTime(long submitTime) {
this.submitTime = submitTime;
}
public Date getSubmitDate() {
return new Date(this.submitTime);
}
public long getLaunchTime() {
return launchTime;
}
public void setLaunchTime(long launchTime) {
this.launchTime = launchTime;
}
public Date getLaunchDate() {
return new Date(this.launchTime);
}
public long getFinishTime() {
return finishTime;
}
public void setFinishTime(long finishTime) {
this.finishTime = finishTime;
}
public Date getFinishDate() {
return new Date(this.finishTime);
}
/**
* Returns the elapsed run time for this job (finish time minus launch time).
* @return
*/
public long getRunTime() {
return finishTime - launchTime;
}
public long getTotalMaps() {
return totalMaps;
}
public void setTotalMaps(long totalMaps) {
this.totalMaps = totalMaps;
}
public long getTotalReduces() {
return totalReduces;
}
public void setTotalReduces(long totalReduces) {
this.totalReduces = totalReduces;
}
public long getFinishedMaps() {
return finishedMaps;
}
public void setFinishedMaps(long finishedMaps) {
this.finishedMaps = finishedMaps;
}
public long getFinishedReduces() {
return finishedReduces;
}
public void setFinishedReduces(long finishedReduces) {
this.finishedReduces = finishedReduces;
}
public long getFailedMaps() {
return failedMaps;
}
public void setFailedMaps(long failedMaps) {
this.failedMaps = failedMaps;
}
public long getFailedReduces() {
return failedReduces;
}
public void setFailedReduces(long failedReduces) {
this.failedReduces = failedReduces;
}
public long getMapFileBytesRead() {
return mapFileBytesRead;
}
public void setMapFileBytesRead(long mapFileBytesRead) {
this.mapFileBytesRead = mapFileBytesRead;
}
public long getMapFileBytesWritten() {
return mapFileBytesWritten;
}
public void setMapFileBytesWritten(long mapBytesWritten) {
this.mapFileBytesWritten = mapBytesWritten;
}
public long getHdfsBytesRead() {
return hdfsBytesRead;
}
public long getMapSlotMillis() {
return mapSlotMillis;
}
public void setMapSlotMillis(long mapSlotMillis) {
this.mapSlotMillis = mapSlotMillis;
}
public long getReduceSlotMillis() {
return reduceSlotMillis;
}
public void setReduceSlotMillis(long reduceSlotMillis) {
this.reduceSlotMillis = reduceSlotMillis;
}
public long getReduceShuffleBytes() {
return reduceShuffleBytes;
}
public void setReduceShuffleBytes(long reduceShuffleBytes) {
this.reduceShuffleBytes = reduceShuffleBytes;
}
public long getReduceFileBytesRead() {
return reduceFileBytesRead;
}
public void setReduceFileBytesRead(long reduceFileBytesRead) {
this.reduceFileBytesRead = reduceFileBytesRead;
}
public long getHdfsBytesWritten() {
return hdfsBytesWritten;
}
public void setHdfsBytesWritten(long hdfsBytesWritten) {
this.hdfsBytesWritten = hdfsBytesWritten;
}
public void setHdfsBytesRead(long hdfsBytesRead) {
this.hdfsBytesRead = hdfsBytesRead;
}
public void addTask(TaskDetails task) {
this.tasks.add(task);
}
public List<TaskDetails> getTasks() {
return this.tasks;
}
public Configuration getConfiguration() {
return this.config;
}
public CounterMap getCounters() {
return this.counters;
}
public CounterMap getMapCounters() {
return this.mapCounters;
}
public CounterMap getReduceCounters() {
return this.reduceCounters;
}
// for JSON deserialization
void setConfiguration(Configuration config) { this.config = config; }
void setCounters(CounterMap counters) { this.counters = counters; }
void setMapCounters(CounterMap mapCounters) { this.mapCounters = mapCounters; }
void setReduceCounters(CounterMap reduceCounters) { this.reduceCounters = reduceCounters; }
+
+ /**
+ * Do not use, this is for JSON deserialization only.
+ * @param newTasks
+ */
+ @Deprecated
+ public void setTasks(List<TaskDetails> newTasks) {
+ if ((newTasks != null) && (newTasks.size() > 0)) {
+ throw new NotImplementedException("Expected to be invoked only during deserialization "
+ + "for empty/null TaskDetails. Deserialization of non-empty TaskDetails should not be done "
+ + "in this setter but by implementing a TaskDetails Custom Deserializer in ClientObjectMapper.");
+ }
+ this.tasks.clear();
+ }
/** TODO: refactor this out into a data access layer */
public void populate(Result result) {
// process job-level stats and properties
NavigableMap<byte[],byte[]> infoValues = result.getFamilyMap(Constants.INFO_FAM_BYTES);
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOBID))) {
this.jobId = Bytes.toString(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOBID)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.USER))) {
this.user = Bytes.toString(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.USER)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOBNAME))) {
this.jobName = Bytes.toString(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOBNAME)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOB_PRIORITY))) {
this.priority = Bytes.toString(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOB_PRIORITY)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOB_STATUS))) {
this.status = Bytes.toString(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOB_STATUS)));
}
if (infoValues.containsKey(Constants.VERSION_COLUMN_BYTES)) {
this.version = Bytes.toString(infoValues.get(Constants.VERSION_COLUMN_BYTES));
}
// times
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.SUBMIT_TIME))) {
this.submitTime = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.SUBMIT_TIME)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.LAUNCH_TIME))) {
this.launchTime = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.LAUNCH_TIME)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISH_TIME))) {
this.finishTime = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISH_TIME)));
}
// task counts
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_MAPS))) {
this.totalMaps = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_MAPS)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_REDUCES))) {
this.totalReduces = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_REDUCES)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_MAPS))) {
this.finishedMaps = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_MAPS)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_REDUCES))) {
this.finishedReduces = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_REDUCES)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_MAPS))) {
this.failedMaps = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_MAPS)));
}
if (infoValues.containsKey(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_REDUCES))) {
this.failedReduces = Bytes.toLong(
infoValues.get(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_REDUCES)));
}
this.config = JobHistoryService.parseConfiguration(infoValues);
this.counters = JobHistoryService.parseCounters(
Constants.COUNTER_COLUMN_PREFIX_BYTES, infoValues);
this.mapCounters = JobHistoryService.parseCounters(
Constants.MAP_COUNTER_COLUMN_PREFIX_BYTES, infoValues);
this.reduceCounters = JobHistoryService.parseCounters(
Constants.REDUCE_COUNTER_COLUMN_PREFIX_BYTES, infoValues);
// populate stats from counters for this job
// map file bytes read
if (this.mapCounters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_READ) != null) {
this.mapFileBytesRead =
this.mapCounters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_READ)
.getValue();
}
// map file bytes written
if (this.mapCounters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_WRITTEN) != null) {
this.mapFileBytesWritten =
this.mapCounters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_WRITTEN)
.getValue();
}
// reduce file bytes read
if (this.reduceCounters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_READ) != null) {
this.reduceFileBytesRead =
this.reduceCounters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_READ)
.getValue();
}
// hdfs bytes read
if (this.counters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.HDFS_BYTES_READ) != null) {
this.hdfsBytesRead =
this.counters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.HDFS_BYTES_READ)
.getValue();
}
// hdfs bytes written
if (this.counters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.HDFS_BYTES_WRITTEN) != null) {
this.hdfsBytesWritten =
this.counters.getCounter(Constants.FILESYSTEM_COUNTERS, Constants.HDFS_BYTES_WRITTEN)
.getValue();
}
// map slot millis
if (this.counters.getCounter(Constants.JOBINPROGRESS_COUNTER, Constants.SLOTS_MILLIS_MAPS) != null) {
this.mapSlotMillis =
this.counters.getCounter(Constants.JOBINPROGRESS_COUNTER, Constants.SLOTS_MILLIS_MAPS)
.getValue();
}
// reduce slot millis
if (this.counters.getCounter(Constants.JOBINPROGRESS_COUNTER, Constants.SLOTS_MILLIS_REDUCES) != null) {
this.reduceSlotMillis =
this.counters.getCounter(Constants.JOBINPROGRESS_COUNTER, Constants.SLOTS_MILLIS_REDUCES)
.getValue();
}
// reduce shuffle bytes
if (this.reduceCounters.getCounter(Constants.TASK_COUNTER, Constants.REDUCE_SHUFFLE_BYTES) != null) {
this.reduceShuffleBytes =
this.reduceCounters.getCounter(Constants.TASK_COUNTER, Constants.REDUCE_SHUFFLE_BYTES)
.getValue();
}
// populate the task-level data
+ // TODO: make sure to properly implement setTasks(...) before adding TaskDetails
//populateTasks(result.getFamilyMap(Constants.TASK_FAM_BYTES));
}
}
| false | false | null | null |
diff --git a/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java b/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java
index b29a9070..14104151 100644
--- a/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java
+++ b/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java
@@ -1,220 +1,220 @@
package com.atlassian.maven.plugins.amps;
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Build;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class TestMavenGoalsHomeZip
{
public static final String PROJECT_ID = "noplacelike";
public static final String TMP_RESOURCES = "tmp-resources";
public static final String GENERATED_HOME = "generated-home";
public static final String PLUGINS = "plugins";
public static final String BUNDLED_PLUGINS = "bundled-plugins";
public static final String ZIP_PREFIX = "generated-resources/" + PROJECT_ID + "-home";
private MavenContext ctx;
private MavenGoals goals;
private File tempDir;
private File productDir;
private File tempResourcesDir;
private File generatedHomeDir;
private File pluginsDir;
private File bundledPluginsDir;
private ZipFile zip;
@Before
public void setup(){
//Create the temp dir
- final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
+ final File sysTempDir = new File("target");
String dirName = UUID.randomUUID().toString();
tempDir = new File(sysTempDir, dirName);
productDir = new File(tempDir,PROJECT_ID);
tempResourcesDir = new File(productDir,TMP_RESOURCES);
generatedHomeDir = new File(tempResourcesDir,GENERATED_HOME);
pluginsDir = new File(generatedHomeDir,PLUGINS);
bundledPluginsDir = new File(generatedHomeDir,BUNDLED_PLUGINS);
//setup maven mocks
MavenProject project = mock(MavenProject.class);
Build build = mock(Build.class);
//Mockito throws NoClassDefFoundError: org/apache/maven/project/ProjectBuilderConfiguration
//when mocking the session
//MavenSession session = mock(MavenSession.class);
PluginManager pluginManager = mock(PluginManager.class);
List<MavenProject> reactor = Collections.<MavenProject>emptyList();
ctx = mock(MavenContext.class);
when(build.getDirectory()).thenReturn(tempDir.getAbsolutePath());
when(project.getBuild()).thenReturn(build);
when(ctx.getProject()).thenReturn(project);
when(ctx.getLog()).thenReturn(new SystemStreamLog());
when(ctx.getReactor()).thenReturn(reactor);
when(ctx.getSession()).thenReturn(null);
when(ctx.getPluginManager()).thenReturn(pluginManager);
goals = new MavenGoals(ctx);
}
@After
public void removeTempDir() throws IOException
{
//make sure zip is closed, else delete fails on windows
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
//ignore
}
zip = null;
}
FileUtils.deleteDirectory(tempDir);
}
@Test
public void skipNullHomeDir(){
File zip = new File(tempDir,"nullHomeZip.zip");
goals.createHomeResourcesZip(null,zip,PROJECT_ID);
assertFalse("zip for null home should not exist", zip.exists());
}
@Test
public void skipNonExistentHomeDir(){
File zip = new File(tempDir,"noExistHomeZip.zip");
File fakeHomeDir = new File(tempDir,"this-folder-does-not-exist");
goals.createHomeResourcesZip(fakeHomeDir,zip,PROJECT_ID);
assertFalse("zip for non-existent home should not exist", zip.exists());
}
@Test
public void existingGeneratedDirGetsDeleted() throws IOException
{
generatedHomeDir.mkdirs();
File deletedFile = new File(generatedHomeDir,"should-be-deleted.txt");
FileUtils.writeStringToFile(deletedFile,"This file should have been deleted!");
File zip = new File(tempDir,"deleteGenHomeZip.zip");
File homeDir = new File(tempDir,"deleteGenHomeDir");
homeDir.mkdirs();
goals.createHomeResourcesZip(homeDir,zip,PROJECT_ID);
assertFalse("generated text file should have been deleted",deletedFile.exists());
}
@Test
public void pluginsNotIncluded() throws IOException
{
pluginsDir.mkdirs();
File pluginFile = new File(pluginsDir,"plugin.txt");
FileUtils.writeStringToFile(pluginFile,"This file should have been deleted!");
File zip = new File(tempDir,"deletePluginsHomeZip.zip");
File homeDir = new File(tempDir,"deletePluginsHomeDir");
homeDir.mkdirs();
goals.createHomeResourcesZip(homeDir,zip,PROJECT_ID);
assertFalse("plugins file should have been deleted",pluginFile.exists());
}
@Test
public void bundledPluginsNotIncluded() throws IOException
{
bundledPluginsDir.mkdirs();
File pluginFile = new File(bundledPluginsDir,"bundled-plugin.txt");
FileUtils.writeStringToFile(pluginFile,"This file should have been deleted!");
File zip = new File(tempDir,"deleteBundledPluginsHomeZip.zip");
File homeDir = new File(tempDir,"deleteBundledPluginsHomeDir");
homeDir.mkdirs();
goals.createHomeResourcesZip(homeDir,zip,PROJECT_ID);
assertFalse("bundled-plugins file should have been deleted",pluginFile.exists());
}
@Test
public void zipContainsProperPrefix() throws IOException
{
File zipFile = new File(tempDir,"prefixedHomeZip.zip");
File homeDir = new File(tempDir,"prefixedHomeDir");
File dataDir = new File(homeDir,"data");
dataDir.mkdirs();
goals.createHomeResourcesZip(homeDir,zipFile,PROJECT_ID);
zip = new ZipFile(zipFile);
final Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements())
{
final ZipEntry zipEntry = entries.nextElement();
String zipPath = zipEntry.getName();
String[] segments = zipPath.split("/");
if(segments.length > 1) {
String testPrefix = segments[0] + "/" + segments[1];
assertEquals(ZIP_PREFIX,testPrefix);
}
}
}
@Test
public void zipContainsTestFile() throws IOException
{
File zipFile = new File(tempDir,"fileHomeZip.zip");
File homeDir = new File(tempDir,"fileHomeDir");
File dataDir = new File(homeDir,"data");
File dataFile = new File(dataDir,"data.txt");
dataDir.mkdirs();
FileUtils.writeStringToFile(dataFile,"This is some data.");
goals.createHomeResourcesZip(homeDir,zipFile,PROJECT_ID);
boolean dataFileFound = false;
zip = new ZipFile(zipFile);
final Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements())
{
final ZipEntry zipEntry = entries.nextElement();
String zipPath = zipEntry.getName();
String fileName = zipPath.substring(zipPath.lastIndexOf("/") + 1);
if(fileName.equals(dataFile.getName())) {
dataFileFound = true;
break;
}
}
assertTrue("data file not found in zip.",dataFileFound);
}
}
| true | true | public void setup(){
//Create the temp dir
final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
String dirName = UUID.randomUUID().toString();
tempDir = new File(sysTempDir, dirName);
productDir = new File(tempDir,PROJECT_ID);
tempResourcesDir = new File(productDir,TMP_RESOURCES);
generatedHomeDir = new File(tempResourcesDir,GENERATED_HOME);
pluginsDir = new File(generatedHomeDir,PLUGINS);
bundledPluginsDir = new File(generatedHomeDir,BUNDLED_PLUGINS);
//setup maven mocks
MavenProject project = mock(MavenProject.class);
Build build = mock(Build.class);
//Mockito throws NoClassDefFoundError: org/apache/maven/project/ProjectBuilderConfiguration
//when mocking the session
//MavenSession session = mock(MavenSession.class);
PluginManager pluginManager = mock(PluginManager.class);
List<MavenProject> reactor = Collections.<MavenProject>emptyList();
ctx = mock(MavenContext.class);
when(build.getDirectory()).thenReturn(tempDir.getAbsolutePath());
when(project.getBuild()).thenReturn(build);
when(ctx.getProject()).thenReturn(project);
when(ctx.getLog()).thenReturn(new SystemStreamLog());
when(ctx.getReactor()).thenReturn(reactor);
when(ctx.getSession()).thenReturn(null);
when(ctx.getPluginManager()).thenReturn(pluginManager);
goals = new MavenGoals(ctx);
}
| public void setup(){
//Create the temp dir
final File sysTempDir = new File("target");
String dirName = UUID.randomUUID().toString();
tempDir = new File(sysTempDir, dirName);
productDir = new File(tempDir,PROJECT_ID);
tempResourcesDir = new File(productDir,TMP_RESOURCES);
generatedHomeDir = new File(tempResourcesDir,GENERATED_HOME);
pluginsDir = new File(generatedHomeDir,PLUGINS);
bundledPluginsDir = new File(generatedHomeDir,BUNDLED_PLUGINS);
//setup maven mocks
MavenProject project = mock(MavenProject.class);
Build build = mock(Build.class);
//Mockito throws NoClassDefFoundError: org/apache/maven/project/ProjectBuilderConfiguration
//when mocking the session
//MavenSession session = mock(MavenSession.class);
PluginManager pluginManager = mock(PluginManager.class);
List<MavenProject> reactor = Collections.<MavenProject>emptyList();
ctx = mock(MavenContext.class);
when(build.getDirectory()).thenReturn(tempDir.getAbsolutePath());
when(project.getBuild()).thenReturn(build);
when(ctx.getProject()).thenReturn(project);
when(ctx.getLog()).thenReturn(new SystemStreamLog());
when(ctx.getReactor()).thenReturn(reactor);
when(ctx.getSession()).thenReturn(null);
when(ctx.getPluginManager()).thenReturn(pluginManager);
goals = new MavenGoals(ctx);
}
|
diff --git a/src/plugins/Freetalk/ui/NNTP/FreetalkNNTPHandler.java b/src/plugins/Freetalk/ui/NNTP/FreetalkNNTPHandler.java
index ccb63cdb..27a6aff5 100644
--- a/src/plugins/Freetalk/ui/NNTP/FreetalkNNTPHandler.java
+++ b/src/plugins/Freetalk/ui/NNTP/FreetalkNNTPHandler.java
@@ -1,983 +1,985 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.Freetalk.ui.NNTP;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import plugins.Freetalk.Board;
import plugins.Freetalk.FTOwnIdentity;
import plugins.Freetalk.Freetalk;
import plugins.Freetalk.IdentityManager;
import plugins.Freetalk.Message;
import plugins.Freetalk.MessageManager;
import plugins.Freetalk.MessageURI;
import plugins.Freetalk.OwnMessage;
import plugins.Freetalk.SubscribedBoard;
import plugins.Freetalk.exceptions.NoSuchBoardException;
import plugins.Freetalk.exceptions.NoSuchIdentityException;
import plugins.Freetalk.exceptions.NoSuchMessageException;
import freenet.support.CurrentTimeUTC;
import freenet.support.Logger;
/**
* Represents a connection to a single NNTP client.
*
* @author Benjamin Moody
* @author bback
* @author xor ([email protected])
*
* FIXME: allow board subscribe by NNTP server
*/
public final class FreetalkNNTPHandler implements Runnable {
private final IdentityManager mIdentityManager;
private final MessageManager mMessageManager;
private final Socket mSocket;
private BufferedWriter mOutput;
/** Current board (selected by the GROUP command) */
private FreetalkNNTPGroup mCurrentGroup;
/** Current message number within the group */
private int mCurrentMessageNum;
/** Authenticated FTOwnIdentity **/
private FTOwnIdentity mAuthenticatedUser = null;
/** Line ending required by NNTP **/
private static final String CRLF = "\r\n";
/** Date format used by the DATE command */
private static final SimpleDateFormat serverDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
private static final SimpleTimeZone utcTimeZone = new SimpleTimeZone(0, "UTC");
/** Pattern for matching valid "range" arguments. */
private static final Pattern rangePattern = Pattern.compile("(\\d+)(-(\\d+)?)?");
public FreetalkNNTPHandler(final Freetalk ft, final Socket socket) throws SocketException {
mIdentityManager = ft.getIdentityManager();
mMessageManager = ft.getMessageManager();
this.mSocket = socket;
}
/**
* Check if handler is still active.
*/
public boolean isAlive() {
return !mSocket.isClosed(); // This is synchronized
}
/**
* Close the connection to the client immediately.
*/
public synchronized void terminate() {
try {
mSocket.close();
}
catch (IOException e) {
// ignore
}
}
/**
* Print out a status response (numeric code plus additional
* information.)
*/
private void printStatusLine(final String line) throws IOException {
mOutput.write(line);
// NNTP spec requires all command and response lines end with CR+LF
mOutput.write(CRLF);
mOutput.flush();
}
/**
* Print out a text response line. The line will be "dot-stuffed"
* if necessary (any line beginning with a dot will have a second
* dot prepended.)
*/
private void printTextResponseLine(final String line) throws IOException {
if (line.length() > 0 && line.charAt(0) == '.') {
mOutput.write(".");
}
mOutput.write(line);
mOutput.write(CRLF);
}
/**
* Print a single dot to indicate the end of a text response.
*/
private void endTextResponse() throws IOException {
mOutput.write(".");
mOutput.write(CRLF);
mOutput.flush();
}
/**
* Print out a block of text (changing all line terminators to
* CR+LF and dot-stuffing as necessary.)
*/
private void printText(final String text) throws IOException {
String[] lines = FreetalkNNTPArticle.mEndOfLinePattern.split(text);
for (int i = 0; i < lines.length; i++) {
printTextResponseLine(lines[i]);
}
}
/**
* Get an iterator for the article or range of articles described
* by 'desc'. (The description may either be null, indicating the
* current article; a message ID, enclosed in angle brackets; a
* single number, indicating that message number; a number
* followed by a dash, indicating an unbounded range; or a number
* followed by a dash and a second number, indicating a bounded
* range.) Print an error message if it can't be found.
*
* You have to embed the call to this function and processing of the returned Iterator in a synchronized(mCurrentGroup.getBoard())!
*/
private Iterator<FreetalkNNTPArticle> getArticleRangeIterator(final String desc, final boolean single) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return null;
}
if (desc == null) {
if (mCurrentGroup == null) {
printStatusLine("412 No newsgroup selected");
return null;
}
try {
return mCurrentGroup.getMessageIterator(mCurrentMessageNum, mCurrentMessageNum);
}
catch (NoSuchMessageException e) {
printStatusLine("420 Current article number is invalid");
return null;
}
}
else if (desc.length() > 2 && desc.charAt(0) == '<' && desc.charAt(desc.length() - 1) == '>') {
final String msgid = desc.substring(1, desc.length() - 1);
try {
final Message msg = mMessageManager.get(msgid);
final ArrayList<FreetalkNNTPArticle> list = new ArrayList<FreetalkNNTPArticle>(2);
list.add(new FreetalkNNTPArticle(msg));
return list.iterator();
}
catch(NoSuchMessageException e) {
printStatusLine("430 No such article");
return null;
}
}
else {
try {
final Matcher matcher = rangePattern.matcher(desc);
if (!matcher.matches()) {
printStatusLine("501 Syntax error");
return null;
}
final String startStr = matcher.group(1);
final String dashStr = matcher.group(2);
final String endStr = matcher.group(3);
final int start = Integer.parseInt(startStr);
int end;
if (dashStr == null)
end = start;
else if (endStr == null)
end = -1;
else
end = Integer.parseInt(endStr);
if (dashStr != null && single) {
printStatusLine("501 Syntax error");
return null;
}
if (mCurrentGroup == null) {
printStatusLine("412 No newsgroup selected");
return null;
}
try {
return mCurrentGroup.getMessageIterator(start, end);
}
catch (NoSuchMessageException e) {
printStatusLine("423 No articles in that range");
return null;
}
}
catch (NumberFormatException e) {
printStatusLine("501 Syntax error");
return null;
}
}
}
/**
* Handle the ARTICLE / BODY / HEAD / STAT commands.
*/
private void selectArticle(final String desc, final boolean printHead, final boolean printBody) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
if (mCurrentGroup == null) {
printStatusLine("412 No newsgroup selected");
return;
}
synchronized(mCurrentGroup.getBoard()) {
final Iterator<FreetalkNNTPArticle> iter = getArticleRangeIterator(desc, true);
if (iter == null)
return;
final FreetalkNNTPArticle article = iter.next();
if (article.getMessageNum() != 0)
mCurrentMessageNum = article.getMessageNum();
if (printHead && printBody) {
printStatusLine("220 " + article.getMessageNum() + " <" + article.getMessage().getID() + ">");
printText(article.getHead());
printTextResponseLine("");
printText(article.getBody());
endTextResponse();
}
else if (printHead) {
printStatusLine("221 " + article.getMessageNum() + " <" + article.getMessage().getID() + ">");
printText(article.getHead());
endTextResponse();
}
else if (printBody) {
printStatusLine("222 " + article.getMessageNum() + " <" + article.getMessage().getID() + ">");
printText(article.getBody());
endTextResponse();
}
else {
printStatusLine("223 " + article.getMessageNum() + " <" + article.getMessage().getID() + ">");
}
}
}
/**
* Handle the GROUP command.
*/
private void selectGroup(final String name) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
try {
final String boardName = FreetalkNNTPGroup.groupToBoardName(name);
final SubscribedBoard board = mMessageManager.getSubscription(mAuthenticatedUser, boardName);
mCurrentGroup = new FreetalkNNTPGroup(board);
synchronized (board) {
mCurrentMessageNum = mCurrentGroup.firstMessage();
printStatusLine("211 " + mCurrentGroup.messageCount()
+ " " + mCurrentGroup.firstMessage()
+ " " + mCurrentGroup.lastMessage()
+ " " + mCurrentGroup.getGroupName());
}
}
catch(NoSuchBoardException e) {
printStatusLine("411 No such group");
}
}
/**
* Handle the LISTGROUP command.
*/
private void selectGroupWithList(final String name, final String range) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
final Matcher matcher = rangePattern.matcher(range);
if (!matcher.matches()) {
printStatusLine("501 Syntax error");
return;
}
final String startStr = matcher.group(1);
final String dashStr = matcher.group(2);
final String endStr = matcher.group(3);
int start, end;
try {
start = Integer.parseInt(startStr);
if (dashStr == null)
end = start;
else if (endStr == null)
end = -1;
else
end = Integer.parseInt(endStr);
}
catch (NumberFormatException e) {
printStatusLine("501 Syntax error");
return;
}
if (name != null) {
try {
final String boardName = FreetalkNNTPGroup.groupToBoardName(name);
final SubscribedBoard board = mMessageManager.getSubscription(mAuthenticatedUser, boardName);
mCurrentGroup = new FreetalkNNTPGroup(board);
}
catch (NoSuchBoardException e) {
printStatusLine("411 No such group");
return;
}
}
else if (mCurrentGroup == null) {
printStatusLine("412 No newsgroup selected");
return;
}
synchronized (mCurrentGroup.getBoard()) {
mCurrentMessageNum = mCurrentGroup.firstMessage();
printStatusLine("211 " + mCurrentGroup.messageCount()
+ " " + mCurrentGroup.firstMessage()
+ " " + mCurrentGroup.lastMessage()
+ " " + mCurrentGroup.getGroupName());
if (end == -1)
end = mCurrentGroup.lastMessage();
// TODO: Optimization: Write a getAllMessages() which allows the specification of a range!
for(final SubscribedBoard.MessageReference ref : mCurrentGroup.getBoard().getAllMessages(true)) {
final int index = ref.getIndex();
if (index > end)
break;
else if (index >= start)
printTextResponseLine(Integer.toString(index));
}
endTextResponse();
}
}
/**
* Handle the LIST / LIST ACTIVE command.
*/
private void listActiveGroups(final String pattern) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
// FIXME: filter by wildmat
printStatusLine("215 List of newsgroups follows:");
synchronized(mMessageManager) {
// TODO: Optimization: Use a non sorting function
for (final SubscribedBoard board : mMessageManager.subscribedBoardIteratorSortedByName(mAuthenticatedUser)) {
final FreetalkNNTPGroup group = new FreetalkNNTPGroup(board);
printTextResponseLine(group.getGroupName()
+ " " + group.lastMessage()
+ " " + group.firstMessage()
+ " " + group.postingStatus());
}
}
endTextResponse();
}
/**
* Handle the LIST NEWSGROUPS command.
*/
private void listGroupDescriptions(final String pattern) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
// FIXME: add filtering
printStatusLine("215 Information follows:");
synchronized(mMessageManager) {
for (final Board board : mMessageManager.boardIteratorSortedByName()) { // TODO: Optimization: Use a non-sorting function.
final String groupName = FreetalkNNTPGroup.boardToGroupName(board.getName());
printTextResponseLine(groupName + " " + board.getDescription(mAuthenticatedUser));
}
}
endTextResponse();
}
/**
* Handle the NEWGROUPS command.
*/
private void listNewGroupsSince(final String datestr, final String format, final boolean gmt) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
final SimpleDateFormat df = new SimpleDateFormat(format);
if (gmt)
df.setTimeZone(TimeZone.getTimeZone("UTC"));
printStatusLine("231 List of new newsgroups follows");
final Date date = df.parse(datestr, new ParsePosition(0));
synchronized(mMessageManager) {
for (SubscribedBoard board : mMessageManager.subscribedBoardIteratorSortedByDate(mAuthenticatedUser, date)) {
final FreetalkNNTPGroup group = new FreetalkNNTPGroup(board);
printTextResponseLine(board.getName()
+ " " + group.lastMessage()
+ " " + group.firstMessage()
+ " " + group.postingStatus());
}
}
endTextResponse();
}
/**
* Handle the HDR / XHDR command.
*/
private void printArticleHeader(final String header, final String articleDesc) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
if (mCurrentGroup == null) {
printStatusLine("412 No newsgroup selected");
return;
}
synchronized(mCurrentGroup.getBoard()) {
final Iterator<FreetalkNNTPArticle> iter = getArticleRangeIterator(articleDesc, false);
if (iter == null)
return;
printStatusLine("224 Header contents follow");
while (iter.hasNext()) {
final FreetalkNNTPArticle article = iter.next();
if (header.equalsIgnoreCase(":bytes"))
printTextResponseLine(article.getMessageNum() + " " + article.getByteCount());
else if (header.equalsIgnoreCase(":lines"))
printTextResponseLine(article.getMessageNum() + " " + article.getBodyLineCount());
else
printTextResponseLine(article.getMessageNum() + " " + article.getHeaderByName(header));
}
endTextResponse();
}
}
/**
* Handle the OVER / XOVER command.
*/
private void printArticleOverview(final String articleDesc) throws IOException {
if (mAuthenticatedUser == null) {
printStatusLine("480 Authentification required");
return;
}
if (mCurrentGroup == null) {
printStatusLine("412 No newsgroup selected");
return;
}
synchronized(mCurrentGroup.getBoard()) {
final Iterator<FreetalkNNTPArticle> iter = getArticleRangeIterator(articleDesc, false);
if (iter == null)
return;
printStatusLine("224 Overview follows");
while (iter.hasNext()) {
final FreetalkNNTPArticle article = iter.next();
printTextResponseLine(article.getMessageNum() + "\t" + article.getHeader(FreetalkNNTPArticle.Header.SUBJECT)
+ "\t" + article.getHeader(FreetalkNNTPArticle.Header.FROM)
+ "\t" + article.getHeader(FreetalkNNTPArticle.Header.DATE)
+ "\t" + article.getHeader(FreetalkNNTPArticle.Header.MESSAGE_ID)
+ "\t" + article.getHeader(FreetalkNNTPArticle.Header.REFERENCES)
+ "\t" + article.getByteCount()
+ "\t" + article.getBodyLineCount());
}
endTextResponse();
}
}
/**
* Handle the LIST HEADERS command.
*/
private void printHeaderList() throws IOException {
printStatusLine("215 Header list follows");
// We allow querying any header (:) as well as byte and line counts
printTextResponseLine(":");
printTextResponseLine(":bytes");
printTextResponseLine(":lines");
endTextResponse();
}
/**
* Handle the LIST OVERVIEW.FMT command.
*/
private void printOverviewFormat() throws IOException {
printStatusLine("215 Overview format follows");
printTextResponseLine("Subject:");
printTextResponseLine("From:");
printTextResponseLine("Date:");
printTextResponseLine("Message-ID:");
printTextResponseLine("References:");
printTextResponseLine(":bytes");
printTextResponseLine(":lines");
endTextResponse();
}
/**
* Handle the AUTHINFO command, authenticate provided own identity.
* For USER we expect the Freetalk address. We extract the identity ID and lookup it.
*
* @param subcmd Must be USER or PASS (PASS not yet supported!)
* @param value Value of subcmd
*/
private void handleAuthInfo(final String subcmd, final String value) throws IOException {
/*
* For AUTHINFO example see here: http://tools.ietf.org/html/rfc4643#section-2.3.3
*/
// For now, we don't require a PASS
if (!subcmd.equalsIgnoreCase("USER")) {
printStatusLine("502 Command unavailable");
return;
}
// already authenticated?
if (mAuthenticatedUser != null) {
printStatusLine("502 Command unavailable");
return;
}
FTOwnIdentity oi = null;
try {
final String id = extractIdFromFreetalkAddress(value);
oi = mIdentityManager.getOwnIdentity(id);
} catch (NoSuchIdentityException e) {
}
if (oi == null) {
printStatusLine("481 Authentication failed");
} else {
printStatusLine("281 Authentication accepted");
mAuthenticatedUser = oi; // assign authenticated id
}
}
/**
* Extracts the OwnIdentity ID from the input Freetalk address
* @param freetalkAddress freetalk address
* @return OwnIdentity ID or null on error
*/
private String extractIdFromFreetalkAddress(final String freetalkAddress) { // FIXME: Move to class FTIdentity
/*
* Format of input:
* nickname@_ID_.freetalk
* We want the _ID_
*/
final String trailing = ".freetalk";
try {
// sanity checks
if (!freetalkAddress.toLowerCase().endsWith(trailing)) {
return null;
}
int ix = freetalkAddress.indexOf('@');
if (ix < 0) {
return null;
}
final String id = freetalkAddress.substring(ix+1, freetalkAddress.length()-trailing.length());
return id;
} catch(Exception ex) {
return null;
}
}
/**
* Handle the CAPABILITIES command.
*/
private void printCapabilities() throws IOException {
printStatusLine("101 Capability list:");
printText("VERSION 2");
if (mAuthenticatedUser == null) {
printText("AUTHINFO USER"); // we allow this on unsecured connections
}
printText("READER");
printText("POST");
printText("HDR");
printText("OVER MSGID");
printText("LIST ACTIVE NEWSGROUPS HEADERS OVERVIEW.FMT");
endTextResponse();
}
/**
* Handle the DATE command.
*/
private void printDate() throws IOException {
final Date date = CurrentTimeUTC.get();
synchronized (serverDateFormat) {
serverDateFormat.setTimeZone(utcTimeZone);
printTextResponseLine("111 " + serverDateFormat.format(date));
}
}
/**
* Handle a command from the client. If the command requires a
* text data section, this function returns true (and
* finishCommand should be called after the text has been
* received.)
*/
private synchronized boolean beginCommand(final String line) throws IOException {
final String[] tokens = line.split("[ \t\r\n]+");
if (tokens.length == 0)
return false;
final String command = tokens[0];
if (command.equalsIgnoreCase("ARTICLE")) {
if (tokens.length == 2) {
selectArticle(tokens[1], true, true);
}
else if (tokens.length == 1) {
selectArticle(null, true, true);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("AUTHINFO")) {
if (tokens.length == 3) {
handleAuthInfo(tokens[1], tokens[2]);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("BODY")) {
if (tokens.length == 2) {
selectArticle(tokens[1], false, true);
}
else if (tokens.length == 1) {
selectArticle(null, false, true);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("CAPABILITIES")) {
printCapabilities();
}
else if (command.equalsIgnoreCase("DATE")) {
printDate();
}
else if (command.equalsIgnoreCase("GROUP")) {
if (tokens.length == 2) {
selectGroup(tokens[1]);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("HDR") || command.equalsIgnoreCase("XHDR")) {
if (tokens.length == 3) {
printArticleHeader(tokens[1], tokens[2]);
}
else if (tokens.length == 2) {
printArticleHeader(tokens[1], null);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("HEAD")) {
if (tokens.length == 2) {
selectArticle(tokens[1], true, false);
}
else if (tokens.length == 1) {
selectArticle(null, true, false);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("LIST")) {
if (tokens.length == 1 || tokens[1].equalsIgnoreCase("ACTIVE")) {
if (tokens.length > 2)
listActiveGroups(tokens[2]);
else
listActiveGroups(null);
}
else if (tokens[1].equalsIgnoreCase("NEWSGROUPS")) {
if (tokens.length > 2)
listGroupDescriptions(tokens[2]);
else
listGroupDescriptions(null);
}
else if (tokens[1].equalsIgnoreCase("HEADERS")) {
printHeaderList();
}
else if (tokens[1].equalsIgnoreCase("OVERVIEW.FMT")) {
printOverviewFormat();
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("LISTGROUP")) {
if (tokens.length == 1) {
selectGroupWithList(null, "1-");
}
else if (tokens.length == 2) {
selectGroupWithList(tokens[1], "1-");
}
else if (tokens.length == 3) {
selectGroupWithList(tokens[1], tokens[2]);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("NEWGROUPS")) {
boolean gmt = false;
if ((tokens.length == 4 && (gmt = tokens[3].equalsIgnoreCase("GMT"))) ||
(tokens.length == 3))
{
String date = tokens[1] + " " + tokens[2];
if (date.length() == 15) {
listNewGroupsSince(date, "yyyyMMdd HHmmss", gmt);
}
else if (date.length() == 13) {
listNewGroupsSince(date, "yyMMdd HHmmss", gmt);
}
else {
printStatusLine("501 Syntax error");
}
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("MODE")) {
if (tokens.length == 2 && tokens[1].equalsIgnoreCase("READER")) {
printStatusLine("200 Reader mode acknowledged, posting allowed");
}
else {
printStatusLine("501 Syntax error");
}
}
// We accept XOVER for OVER because a lot of (broken)
// newsreaders expect us to
else if (command.equalsIgnoreCase("OVER") || command.equalsIgnoreCase("XOVER")) {
if (tokens.length == 2) {
printArticleOverview(tokens[1]);
}
else if (tokens.length == 1) {
printArticleOverview(null);
}
else {
printStatusLine("501 Syntax error");
}
}
else if (command.equalsIgnoreCase("POST")) {
/* This happens when trying to send a reply to a message with Thunderbird */
/* Message arrives in finishCommand() */
printStatusLine("340 Please send article to be posted");
return true;
}
else if (command.equalsIgnoreCase("QUIT")) {
printStatusLine("205 Have a nice day.");
mSocket.close();
}
else if (command.equalsIgnoreCase("STAT")) {
if (tokens.length == 2) {
selectArticle(tokens[1], false, false);
}
else if (tokens.length == 1) {
selectArticle(null, false, false);
}
else {
printStatusLine("501 Syntax error");
}
}
else {
printStatusLine("500 Command not recognized");
}
return false;
}
/**
* Handle a command that includes a text data block.
*/
private synchronized void finishCommand(String line, ByteBuffer text) throws IOException {
final ArticleParser parser = new ArticleParser();
if (!parser.parseMessage(text)) {
printStatusLine("441 Unable to parse message");
}
else {
// Freetalk address used during AUTH must match the email provided with POST
String freetalkAddress = parser.getAuthorName() + "@" + parser.getAuthorDomain();
if (freetalkAddress == null || mAuthenticatedUser == null || !freetalkAddress.equals(mAuthenticatedUser.getFreetalkAddress())) {
Logger.normal(this, "Error posting message, invalid email address: " + freetalkAddress);
printStatusLine("441 Posting failed, invalid email address");
return;
}
synchronized(mMessageManager) {
try {
Message parentMessage;
try {
parentMessage = mMessageManager.get(parser.getParentID());
}
catch (NoSuchFieldException e) {
parentMessage = null;
}
catch (NoSuchMessageException e) {
parentMessage = null;
}
// FIXME: When replying to forked threads, this code will always sent the replies to the original thread. We need to find a way
// to figure out whether the user wanted to reply to a forked thread - does NNTP pass a thread ID?
MessageURI parentMessageURI = null;
if (parentMessage != null) {
parentMessageURI = parentMessage.isThread() ? parentMessage.getURI() : parentMessage.getThreadURI();
}
final HashSet<String> boardSet = new HashSet<String>(parser.getBoards());
final OwnMessage message = mMessageManager.postMessage(parentMessageURI,
parentMessage, boardSet, parser.getReplyToBoard(), mAuthenticatedUser, parser.getTitle(), null, parser.getText(), null);
printStatusLine("240 Message posted; ID is <" + message.getID() + ">");
}
catch (Exception e) {
Logger.error(this, "Error posting message: ", e);
printStatusLine("441 Posting failed");
}
}
}
}
/**
* Read an input line (terminated by the ASCII LF character) as a
* byte sequence.
*/
private ByteBuffer readLineBytes(final InputStream is) throws IOException {
+ // A minimal size > 0 is needed because is.available() might return 0.
ByteBuffer buf = ByteBuffer.allocate(Math.max(4096, Math.min(is.available(), 64*1024)));
int b;
do {
b = is.read();
if (b >= 0) {
if (!buf.hasRemaining()) {
// resize input buffer
ByteBuffer newbuf = ByteBuffer.allocate(buf.capacity() * 2);
buf.flip();
newbuf.put(buf);
buf = newbuf;
}
buf.put((byte) b);
}
} while (b >= 0 && b != '\n');
buf.flip();
return buf;
}
/**
* Read a complete text block (terminated by a '.' on a line by
* itself).
*/
private ByteBuffer readTextDataBytes(final InputStream is) throws IOException {
- ByteBuffer buf = ByteBuffer.allocate(Math.min(is.available(), 64*1024));
+ // A minimal size > 0 is needed because is.available() might return 0.
+ ByteBuffer buf = ByteBuffer.allocate(Math.max(4096, Math.min(is.available(), 64*1024)));
ByteBuffer line;
while (true) {
line = readLineBytes(is);
if (!line.hasRemaining())
return null; // text block not completed --
// consider message aborted.
if (line.get(0) == '.') {
if ((line.remaining() == 2 && line.get(1) == '\n')
|| (line.remaining() == 3 && line.get(1) == '\r' && line.get(2) == '\n')) {
buf.flip();
return buf;
}
else {
// Initial dot must always be skipped (even if the
// second character isn't a dot)
line.get();
}
}
// append line to the end of the buffer
if (line.remaining() > buf.remaining()) {
ByteBuffer newbuf = ByteBuffer.allocate((buf.position() + line.remaining()) * 2);
buf.flip();
newbuf.put(buf);
buf = newbuf;
}
buf.put(line);
}
}
/**
* Main command loop
*/
public void run() {
try {
final InputStream is = mSocket.getInputStream();
mOutput = new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8"), 8192);
Charset utf8 = Charset.forName("UTF-8");
printStatusLine("200 Welcome to Freetalk");
while (!mSocket.isClosed()) {
final String line = utf8.decode(readLineBytes(is)).toString();
synchronized(this) {
if (beginCommand(line)) {
finishCommand(line, readTextDataBytes(is));
}
}
}
}
catch (Throwable e) {
Logger.error(this, "Error in NNTP handler, closing socket: " + e.getMessage());
try {
mSocket.close();
} catch (IOException e1) {
}
}
}
}
| false | false | null | null |
diff --git a/api-backend/cloud-endpoints-java/src/com/sgzmd/examples/cloudendpoints/ApiBackend.java b/api-backend/cloud-endpoints-java/src/com/sgzmd/examples/cloudendpoints/ApiBackend.java
index 4cebe2b..a0813cf 100644
--- a/api-backend/cloud-endpoints-java/src/com/sgzmd/examples/cloudendpoints/ApiBackend.java
+++ b/api-backend/cloud-endpoints-java/src/com/sgzmd/examples/cloudendpoints/ApiBackend.java
@@ -1,293 +1,301 @@
package com.sgzmd.examples.cloudendpoints;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.labs.repackaged.com.google.common.annotations.VisibleForTesting;
import com.google.appengine.labs.repackaged.com.google.common.base.Predicate;
import com.google.appengine.labs.repackaged.com.google.common.base.Throwables;
import com.google.appengine.labs.repackaged.com.google.common.collect.Iterables;
import com.sgzmd.examples.utils.Clock;
import com.sgzmd.examples.utils.SystemClock;
/**
* API entry point.
*
* Local API explorer: {@link http://localhost:8888/_ah/api/explorer}
*
* @author [email protected] [Roman "sgzmd" Kirillov"]
*/
@Api(name = "monitoring", version = "v1")
public class ApiBackend {
private static final Logger logger = Logger.getLogger(ApiBackend.class.getSimpleName());
private final Clock clock;
public ApiBackend() {
this.clock = new SystemClock();
}
public ApiBackend(Clock clock) {
this.clock = clock;
}
/**
* Adds a {@link Room} to collection.
*
* @param room New {@link Room} to be added. Must not exist.
*
* @return an instance of {@link Room} added, with Key assigned.
*/
@ApiMethod(name = "addRoom", httpMethod = "POST", path = "rooms")
public Room addRoom(Room room) {
log("addRoom({0})", room);
Room created = getPM().makePersistent(room);
log("created: {0}", created);
return created;
}
/**
* Updates a room with specified ID.
*
* @param roomId {@link Room} ID to update
* @param updatedRoom Updated {@link Room} contents.
*
* @return updated {@link Room}.
*/
@ApiMethod(name = "updateRoom", httpMethod = "PUT", path = "rooms/{room}")
public Room updateRoom(@Named("room") Long roomId, Room updatedRoom) {
log("updateRoom({0}, {1})", roomId, updatedRoom);
PersistenceManager pm = getPM();
try {
Room room = (Room) pm.getObjectById(Room.class, roomId);
room.updateFrom(updatedRoom);
return room;
} finally {
pm.close();
}
}
/**
* Deletes {@link Room} from collection.
*
* @param roomId {@link Room} ID to be deleted.
*/
@ApiMethod(name = "deleteRoom", httpMethod = "DELETE", path = "rooms/{room}")
public void deleteRoom(@Named("room") Long roomId) {
log("deleteRoom({0})", roomId);
PersistenceManager pm = getPM();
Room room = (Room) pm.getObjectById(Room.class, roomId);
pm.deletePersistent(room);
}
/**
* Lists all {@link Room} in collection, along with their linked {@link Sensor}.
* @return {@link List} of {@link Room}.
*/
@SuppressWarnings("unchecked")
@ApiMethod(name = "listRooms", httpMethod = "GET", path = "rooms")
public List<Room> listRooms() {
log("list()");
PersistenceManager pm = getPM();
Query query = pm.newQuery(Room.class);
return (List<Room>) pm.newQuery(query).execute();
}
@ApiMethod(name = "getRoom", httpMethod = "GET", path="rooms/{room}")
public Room getRoom(@Named("room") Long roomId) {
log("getRoom({0})", roomId);
PersistenceManager pm = getPM();
Room room = null;
try {
room = (Room) pm.getObjectById(
Room.class,
KeyFactory.createKey(Room.class.getSimpleName(), roomId));
} finally {
pm.close();
}
return room;
}
/**
* Adds a new {@link Sensor} to an existing {@link Room}.
*
* @param roomId An identifier of a {@link Room} sensor should be added to.
* @param sensor New {@link Sensor} to be added.
*
* @return Updated {@link Room} with added {@link Sensor}.
*/
@ApiMethod(name = "addSensor", httpMethod = "POST", path = "rooms/{room}")
public Room addSensorToRoom(@Named("room") Long roomId, Sensor sensor) {
PersistenceManager pm = getPM();
log("addSensorToRoom({0}, {1})", roomId, sensor);
if (findSensorByNetworkId(sensor.getNetworkId(), pm) != null) {
throw new IllegalArgumentException("Duplicate sensor network id: " + sensor.getNetworkId());
}
Room room;
try {
room = (Room) pm.getObjectById(
Room.class,
KeyFactory.createKey(Room.class.getSimpleName(), roomId));
room.addSensor(sensor);
} finally {
pm.close();
}
return room;
}
@ApiMethod(name = "deleteSensor", httpMethod = "DELETE", path = "sensors/{sensor}")
- public void deleteSensor(@Named("room") Long roomId, @Named("sensor") Long sensorId) {
+ public List<Room> deleteSensor(@Named("room") Long roomId, @Named("sensor") Long sensorId) {
PersistenceManager pm = getPM();
log("deleteSensor(roomId={0}, sensorId={1}", roomId, sensorId);
try {
Room room = pm.getObjectById(Room.class, roomId);
room.deleteSensor(sensorId);
} finally {
pm.close();
}
+
+ return listRooms();
}
/**
* Will be called whenever {@link Sensor} fired and needs to be updated.
* Sensor's last active will be set to {@link #clock.now()}.
*
* @param sensorNetworkId {@link Sensor} to update.
* @throws NotFoundException
*/
@ApiMethod(name = "logSensorUpdate", httpMethod = "GET", path = "sensors/{network_id}")
public void sensorUpdated(@Named("network_id") String sensorNetworkId) throws NotFoundException {
log("sensorUpdated{0}", sensorNetworkId);
PersistenceManager pm = getPM();
try {
Sensor sensor = findSensorByNetworkId(sensorNetworkId, pm);
if (sensor != null) {
sensor.setLastActive(clock.now().getMillis());
log("Sensor updated: {0}", sensor);
} else {
log("Sensor with NetworkId = {0} not found", sensorNetworkId);
throw new NotFoundException("Sensor not found: network_id" + sensorNetworkId);
}
} finally {
pm.close();
}
}
/**
* Disables all sensors in all rooms of the household.
*/
@ApiMethod(name = "disarm", httpMethod = "GET", path = "disarm")
public void disarm() {
log("Disarming all sensors");
resetAllSensors(false);
}
/**
* Disables all sensors in all rooms of the household.
+ *
+ * In this and other methods you can see that we are returning full list of
+ * {@link Room} objects. This is an optimisation to avoid making a second
+ * query.
*/
@ApiMethod(name = "arm", httpMethod = "GET", path = "reset")
- public void reset(
+ public List<Room> reset(
@Nullable @Named("room") Long roomId,
@Nullable @Named("sensor") Long sensorId,
@Named("state") Boolean state) {
if (sensorId != null) {
resetSensor(sensorId, roomId, state);
} else if (roomId != null) {
resetRoom(roomId, state);
} else {
resetAllSensors(state);
}
+
+ return listRooms();
}
@VisibleForTesting void resetSensor(final Long sensorId, final Long roomId, final Boolean state) {
log("resetSensor({0}, {1})", sensorId, state);
PersistenceManager pm = getPM();
try {
Room room = pm.getObjectById(Room.class, roomId);
List<Sensor> sensors = room.getSensors();
for (Sensor sensor : sensors) {
if (sensor.getId() == sensorId) {
log("Setting sensor {0} to active={1}", sensor, state);
sensor.setActive(state);
break;
}
}
} finally {
pm.close();
}
}
@VisibleForTesting void resetRoom(Long roomId, Boolean state) {
log("resetRoom({0}, {1}", roomId, state);
PersistenceManager pm = getPM();
Room room;
try {
room = (Room) pm.getObjectById(
Room.class,
KeyFactory.createKey(Room.class.getSimpleName(), roomId));
if (room != null) {
for (Sensor sensor : room.getSensors()) {
log("Setting sensor {0} to {1}", sensor, state);
sensor.setActive(state);
}
}
} finally {
pm.close();
}
}
@VisibleForTesting void resetAllSensors(boolean state) {
PersistenceManager pm = getPM();
Query query = pm.newQuery(Sensor.class);
try {
@SuppressWarnings({"unchecked"})
List<Sensor> sensors = (List<Sensor>)pm.newQuery(query).execute();
for (Sensor sensor : sensors) {
log("Updating sensor {0}", sensor.toString());
sensor.setActive(state);
}
} finally {
query.closeAll();
pm.close();
}
}
@SuppressWarnings("unchecked")
private Sensor findSensorByNetworkId(String networkId, PersistenceManager pm) {
Query query = pm.newQuery(Sensor.class);
query.setFilter("networkId == networkIdParam");
query.declareParameters("String networkIdParam");
try {
return Iterables.getOnlyElement((List<Sensor>)query.execute(networkId), null);
} finally {
query.closeAll();
}
}
private void log(String format, Object... objects) {
logger.log(Level.INFO, format, objects);
}
private static PersistenceManager getPM() {
return PMF.get().getPersistenceManager();
}
}
| false | false | null | null |
diff --git a/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java b/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java
index ddca3c487..62a0cc4fc 100644
--- a/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java
+++ b/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java
@@ -1,429 +1,432 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.portal.webui.navigation;
import org.exoplatform.container.ExoContainer;
import org.exoplatform.portal.config.UserACL;
import org.exoplatform.portal.config.UserPortalConfigService;
import org.exoplatform.portal.config.model.PageNavigation;
import org.exoplatform.portal.config.model.PageNode;
import org.exoplatform.portal.config.model.PortalConfig;
import org.exoplatform.portal.mop.Visibility;
import org.exoplatform.services.resources.ResourceBundleManager;
import org.exoplatform.webui.application.WebuiRequestContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Created by The eXo Platform SARL
* Author : Nhu Dinh Thuan
* [email protected]
* Jun 27, 2007
*/
public class PageNavigationUtils
{
public static void removeNode(List<PageNode> list, String uri)
{
if (list == null)
return;
for (PageNode pageNode : list)
{
if (pageNode.getUri().equalsIgnoreCase(uri))
{
list.remove(pageNode);
return;
}
}
}
/**
* This method returns a pair of PageNode, one is the PageNode specified by the uri,
* another is its parent. Value return is 2-element array
*
* 1. The element indexed 1 is the page node specified by the uri
*
* 2. The element indexed 0 is its parent
*
* @deprecated Returning 2-element array would makes it difficult to understand, handle the code.
* Method searchParentChildPairByUri should be used instead.
*
* @param node
* @param uri
* @return
*/
@Deprecated
public static PageNode[] searchPageNodesByUri(PageNode node, String uri)
{
if (node.getUri().equals(uri))
return new PageNode[]{null, node};
if (node.getChildren() == null)
return null;
List<PageNode> children = node.getChildren();
for (PageNode ele : children)
{
PageNode[] returnNodes = searchPageNodesByUri(ele, uri);
if (returnNodes != null)
{
if (returnNodes[0] == null)
returnNodes[0] = node;
return returnNodes;
}
}
return null;
}
@Deprecated
public static PageNode[] searchPageNodesByUri(PageNavigation nav, String uri)
{
if (nav.getNodes() == null)
return null;
List<PageNode> nodes = nav.getNodes();
for (PageNode ele : nodes)
{
PageNode[] returnNodes = searchPageNodesByUri(ele, uri);
if (returnNodes != null)
return returnNodes;
}
return null;
}
/**
* This method returns a pair of a node matching the parsed uri and the parent of this node.
*
* @param nav
* @param uri
* @return
*/
public static ParentChildPair searchParentChildPairByUri(PageNavigation nav, String uri)
{
List<PageNode> nodes = nav.getNodes();
if(nodes == null)
{
return null;
}
for(PageNode ele : nodes)
{
ParentChildPair parentChildPair = searchParentChildPairUnderNode(ele, uri);
if(parentChildPair != null)
{
return parentChildPair;
}
}
return null;
}
public static ParentChildPair searchParentChildPairUnderNode(PageNode rootNode, String uri)
{
if(uri.equals(rootNode.getUri()))
{
return new ParentChildPair(null, rootNode);
}
List<PageNode> nodes = rootNode.getNodes();
if(nodes == null)
{
return null;
}
for(PageNode node : nodes)
{
ParentChildPair parentChildPair = searchParentChildPairUnderNode(node, uri);
if(parentChildPair != null)
{
- parentChildPair.setParentNode(node);
+ if(parentChildPair.getParentNode() == null)
+ {
+ parentChildPair.setParentNode(rootNode);
+ }
return parentChildPair;
}
}
return null;
}
public static PageNode searchPageNodeByUri(PageNode node, String uri)
{
if (node.getUri().equals(uri))
return node;
if (node.getChildren() == null)
return null;
List<PageNode> children = node.getChildren();
for (PageNode ele : children)
{
PageNode returnNode = searchPageNodeByUri(ele, uri);
if (returnNode != null)
return returnNode;
}
return null;
}
public static PageNode searchPageNodeByUri(PageNavigation nav, String uri)
{
if (nav.getNodes() == null)
return null;
List<PageNode> nodes = nav.getNodes();
for (PageNode ele : nodes)
{
PageNode returnNode = searchPageNodeByUri(ele, uri);
if (returnNode != null)
return returnNode;
}
return null;
}
public static Object searchParentNode(PageNavigation nav, String uri)
{
if (nav.getNodes() == null)
return null;
int last = uri.lastIndexOf("/");
String parentUri = "";
if (last > -1)
parentUri = uri.substring(0, uri.lastIndexOf("/"));
for (PageNode ele : nav.getNodes())
{
if (ele.getUri().equals(uri))
return nav;
}
if (parentUri.equals(""))
return null;
return searchPageNodeByUri(nav, parentUri);
}
// Still keep this method to have compatibility with legacy code
public static PageNavigation filter(PageNavigation nav, String userName) throws Exception
{
return filterNavigation(nav, userName, false, false);
}
/**
*
* @param nav
* @param userName
* @param acceptNonDisplayedNode
* @param acceptNodeWithoutPage
* @return
* @throws Exception
*/
public static PageNavigation filterNavigation(PageNavigation nav, String userName, boolean acceptNonDisplayedNode, boolean acceptNodeWithoutPage) throws Exception
{
PageNavigation filter = nav.clone();
filter.setNodes(new ArrayList<PageNode>());
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
ExoContainer container = context.getApplication().getApplicationServiceContainer();
UserPortalConfigService userService =
(UserPortalConfigService)container.getComponentInstanceOfType(UserPortalConfigService.class);
UserACL userACL = (UserACL)container.getComponentInstanceOfType(UserACL.class);
for (PageNode node : nav.getNodes())
{
PageNode newNode = filterNodeNavigation(node, userName, acceptNonDisplayedNode, acceptNodeWithoutPage, userService, userACL);
if (newNode != null)
filter.addNode(newNode);
}
return filter;
}
/**
* use {@link #filterNavigation(PageNavigation, String, boolean, boolean)}
*
* @param nav
* @param userName
* @param acceptNonDisplayedNode
* @return
* @throws Exception
*/
@Deprecated
public static PageNavigation filterNavigation(PageNavigation nav, String userName, boolean acceptNonDisplayedNode) throws Exception
{
return filterNavigation(nav, userName, acceptNonDisplayedNode, true);
}
/**
* Use {@link #filterNodeNavigation(PageNode, String, boolean, boolean, UserPortalConfigService, UserACL)}
* @param startNode
* @param userName
* @param acceptNonDisplayedNode
* @param userService
* @param userACL
* @return
* @throws Exception
*/
@Deprecated
private static PageNode filterNodeNavigation(PageNode startNode, String userName, boolean acceptNonDisplayedNode,
UserPortalConfigService userService, UserACL userACL) throws Exception {
PageNode cloneStartNode = filterNodeNavigation(startNode, userName, acceptNonDisplayedNode, false, userService, userACL);
return cloneStartNode;
}
/**
* PageNode won't be processed in following cases:
*
* Case 1: Node 's visibility is SYSTEM and the user is not superuser or he is superuser but acceptNonDisplayNode = false
*
* Case 2: Node 's visibility is not SYSTEM but the node is not display and the acceptNonDisplayedNode = false
*
* Case 3: Node has non null pageReference but the associated Page does not exist and not accept this node is without page
*
*
* @param startNode
* @param userName
* @param acceptNonDisplayedNode
* @param acceptNodeWithoutPage
* @param userService
* @param userACL
* @return
* @throws Exception
*/
private static PageNode filterNodeNavigation(PageNode startNode, String userName, boolean acceptNonDisplayedNode, boolean acceptNodeWithoutPage,
UserPortalConfigService userService, UserACL userACL) throws Exception
{
Visibility nodeVisibility = startNode.getVisibility();
String pageReference = startNode.getPageReference();
boolean doNothingCase_1 = nodeVisibility == Visibility.SYSTEM && (!userACL.getSuperUser().equals(userName) || !acceptNonDisplayedNode);
boolean doNothingCase_2 = nodeVisibility != Visibility.SYSTEM && !startNode.isDisplay() && !acceptNonDisplayedNode;
boolean doNothingCase_3 = (pageReference != null) && (userService.getPage(pageReference, userName) == null) && !acceptNodeWithoutPage;
if (doNothingCase_1 || doNothingCase_2 || doNothingCase_3)
{
return null;
}
PageNode cloneStartNode = startNode.clone();
ArrayList<PageNode> filteredChildren = new ArrayList<PageNode>();
List<PageNode> children = startNode.getChildren();
if (children != null)
{
for (PageNode child : children)
{
PageNode filteredChildNode = filterNodeNavigation(child, userName, acceptNonDisplayedNode, acceptNodeWithoutPage, userService, userACL);
if (filteredChildNode != null)
{
filteredChildren.add(filteredChildNode);
}
}
}
//If are only accepting displayed nodes and If the node has no child and it does not point to any Page, then null is return
if (!acceptNonDisplayedNode && filteredChildren.size() == 0 && cloneStartNode.getPageReference() == null)
{
return null;
}
cloneStartNode.setChildren(filteredChildren);
return cloneStartNode;
}
public static PageNode filter(PageNode node, String userName, boolean acceptNonDisplayedNode) throws Exception
{
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
ExoContainer container = context.getApplication().getApplicationServiceContainer();
UserPortalConfigService userService =
(UserPortalConfigService)container.getComponentInstanceOfType(UserPortalConfigService.class);
UserACL userACL = (UserACL)container.getComponentInstanceOfType(UserACL.class);
return filterNodeNavigation(node, userName, acceptNonDisplayedNode, userService, userACL);
}
public static void localizePageNavigation(PageNavigation nav, Locale locale, ResourceBundleManager i18nManager)
{
if (nav.getOwnerType().equals(PortalConfig.USER_TYPE))
return;
ResourceBundle res =
i18nManager.getNavigationResourceBundle(locale.getLanguage(), nav.getOwnerType(), nav.getOwnerId());
for (PageNode node : nav.getNodes())
{
resolveLabel(res, node);
}
}
private static void resolveLabel(ResourceBundle res, PageNode node)
{
node.setResolvedLabel(res);
if (node.getChildren() == null)
return;
for (PageNode childNode : node.getChildren())
{
resolveLabel(res, childNode);
}
}
public static PageNavigation findNavigationByID(List<PageNavigation> all_Navigations, int id)
{
for (PageNavigation nav : all_Navigations)
{
if (nav.getId() == id)
{
return nav;
}
}
return null;
}
public static void sortPageNavigation(List<PageNavigation> navigations)
{
Collections.sort(navigations, new PageNavigationComparator());
}
/**
*
* @author <a href="mailto:[email protected]">Minh Hoang TO</a>
* @version $Id$
*
*/
public static class PageNavigationComparator implements Comparator<PageNavigation>
{
public int compare(PageNavigation firstNav, PageNavigation secondNav)
{
int firstNavPriority = firstNav.getPriority();
int secondNavPriority = secondNav.getPriority();
if (firstNavPriority == secondNavPriority)
{
String firstNavId = firstNav.getOwnerId();
String secondNavId = secondNav.getOwnerId();
return firstNavId.compareTo(secondNavId);
}
else
{
if (firstNavPriority < secondNavPriority)
{
return -1;
}
else
{
return 1;
}
}
}
}
}
| true | false | null | null |
diff --git a/src/main/java/org/jasig/ssp/model/PlanCourse.java b/src/main/java/org/jasig/ssp/model/PlanCourse.java
index 21a2c7e32..4b9386053 100644
--- a/src/main/java/org/jasig/ssp/model/PlanCourse.java
+++ b/src/main/java/org/jasig/ssp/model/PlanCourse.java
@@ -1,97 +1,97 @@
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.ssp.model;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Formula;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name="map_plan_course")
public class PlanCourse extends AbstractPlanCourse<Plan> {
//Hibernate calculated attributes only support native sql and not hql :(
//tokens in all caps refer to map_plan_course COLUMNS not member attributes.
- private static final String IS_TRANSCRIPT_FORMULA = " ( select count(*) > 0 from external_student_transcript_course estc " +
+ private static final String IS_TRANSCRIPT_FORMULA = " ( select count(*) from external_student_transcript_course estc " +
" join person p on p.school_id = estc.school_id " +
" where p.id = PERSON_ID and estc.formatted_course = FORMATTED_COURSE ) ";
private static final long serialVersionUID = -6316130725863888876L;
@NotNull
@ManyToOne()
@JoinColumn(name = "plan_id", updatable = false, nullable = false)
private Plan plan;
@NotNull
@ManyToOne()
@JoinColumn(name = "person_id", updatable = false, nullable = false)
private Person person;
@Formula(IS_TRANSCRIPT_FORMULA)
- private Boolean isTranscript;
+ private Integer isTranscript;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Plan getPlan() {
return plan;
}
public void setPlan(Plan plan) {
this.plan = plan;
}
@Override
protected PlanCourse clone() throws CloneNotSupportedException {
PlanCourse clone = new PlanCourse();
clone.setPerson(this.getPerson());
cloneCommonFields(clone);
return clone;
}
@Override
public Plan getParent() {
return plan;
}
public Boolean getIsTranscript() {
- return isTranscript;
+ return isTranscript == null ? false : isTranscript > 0;
}
public void setIsTranscript(Boolean isTranscript) {
- this.isTranscript = isTranscript;
+ //NOOP since this is transient
}
}
| false | false | null | null |
diff --git a/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java b/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java
index 371818e..ab28c50 100644
--- a/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java
+++ b/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java
@@ -1,143 +1,143 @@
package org.pingles.cascading.protobuf;
import cascading.flow.Flow;
import cascading.flow.FlowConnector;
import cascading.operation.Identity;
import cascading.pipe.Each;
import cascading.pipe.Pipe;
import cascading.scheme.TextLine;
import cascading.tap.Lfs;
import cascading.tap.SinkMode;
import cascading.tap.Tap;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import cascading.tuple.TupleEntryIterator;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.mapred.JobConf;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static junit.framework.Assert.*;
public class ProtobufFlowTest {
private static final String TEST_DATA_ROOT = "./tmp/test";
private static Map<Object, Object> properties = new HashMap<Object, Object>();
private final JobConf conf = new JobConf();
@Before
public void setup() throws IOException {
File outputDir = new File(TEST_DATA_ROOT);
if (outputDir.exists()) {
outputDir.delete();
}
FileUtils.forceMkdir(new File(TEST_DATA_ROOT));
}
@Test
public void shouldKeepOnlyNames() throws IOException {
String inputFile = "./tmp/test/data/small.seq";
String outputDir = "./tmp/test/output/names-out";
writePersonToSequenceFile(personBuilder().setId(123).setName("Paul").setEmail("[email protected]").build(), inputFile);
Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email")), inputFile);
Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE);
Pipe pipe = new Each("Extract names", new Fields("name"), new Identity());
Flow flow = new FlowConnector(properties).connect(source, sink, pipe);
flow.complete();
List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000"));
assertEquals(1, lines.size());
assertEquals("Paul", lines.get(0));
}
@Test
public void shouldKeepNamesAndEmail() throws IOException {
String inputFile = "./tmp/test/data/small.seq";
String outputDir = "./tmp/test/output/names-out";
writePersonToSequenceFile(personBuilder().setId(123).setName("Paul").setEmail("[email protected]").build(), inputFile);
Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email")), inputFile);
Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE);
Pipe pipe = new Each("Extract names", new Fields("name", "email"), new Identity());
Flow flow = new FlowConnector(properties).connect(source, sink, pipe);
flow.complete();
List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000"));
assertEquals(1, lines.size());
assertEquals("Paul\[email protected]", lines.get(0));
}
@Test
public void shouldSetEmailFieldToEmptyStringWhenNotSetOnMessage() throws IOException {
String inputFile = "./tmp/test/data/small.seq";
String outputDir = "./tmp/test/output/names-out";
writePersonToSequenceFile(personBuilder().setId(123).setName("Paul").build(), inputFile);
Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email")), inputFile);
Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE);
Pipe pipe = new Each("Extract names", new Fields("name", "email"), new Identity());
Flow flow = new FlowConnector(properties).connect(source, sink, pipe);
flow.complete();
List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000"));
assertEquals(1, lines.size());
assertEquals("Paul\t", lines.get(0));
}
@Test
public void shouldHandleRepeatedFields() throws IOException {
String inputFile = "./tmp/test/data/small.seq";
String outputDir = "./tmp/test/output/names-out";
Messages.Person strongbad = personBuilder().setId(456).setName("strongbad").build();
Messages.Person homestar = personBuilder().setId(789).setName("homestar").build();
Messages.Person paul = personBuilder().setId(123).setName("Paul").addFriends(strongbad).addFriends(homestar).build();
writePersonToSequenceFile(paul, inputFile);
Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email", "friends")), inputFile);
Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE);
- Pipe pipe = new Each("Extract friends names", new Fields("friends"), new Identity());
+ Pipe pipe = new Each("Extract friends", new Fields("friends"), new Identity());
Flow flow = new FlowConnector(properties).connect(source, sink, pipe);
flow.complete();
List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000"));
assertEquals(1, lines.size());
assertEquals("456\tstrongbad\t\t\t789\thomestar\t\t", lines.get(0));
}
private Messages.Person.Builder personBuilder() {
return Messages.Person.newBuilder();
}
private void writePersonToSequenceFile(Messages.Person person, String path) throws IOException {
SequenceFile.Writer writer = SequenceFile.createWriter(FileSystem.getLocal(conf), conf, new Path(path), LongWritable.class, BytesWritable.class);
try {
writer.append(new LongWritable(1), new BytesWritable(person.toByteArray()));
} finally {
writer.close();
}
}
}
| true | true | public void shouldHandleRepeatedFields() throws IOException {
String inputFile = "./tmp/test/data/small.seq";
String outputDir = "./tmp/test/output/names-out";
Messages.Person strongbad = personBuilder().setId(456).setName("strongbad").build();
Messages.Person homestar = personBuilder().setId(789).setName("homestar").build();
Messages.Person paul = personBuilder().setId(123).setName("Paul").addFriends(strongbad).addFriends(homestar).build();
writePersonToSequenceFile(paul, inputFile);
Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email", "friends")), inputFile);
Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE);
Pipe pipe = new Each("Extract friends names", new Fields("friends"), new Identity());
Flow flow = new FlowConnector(properties).connect(source, sink, pipe);
flow.complete();
List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000"));
assertEquals(1, lines.size());
assertEquals("456\tstrongbad\t\t\t789\thomestar\t\t", lines.get(0));
}
| public void shouldHandleRepeatedFields() throws IOException {
String inputFile = "./tmp/test/data/small.seq";
String outputDir = "./tmp/test/output/names-out";
Messages.Person strongbad = personBuilder().setId(456).setName("strongbad").build();
Messages.Person homestar = personBuilder().setId(789).setName("homestar").build();
Messages.Person paul = personBuilder().setId(123).setName("Paul").addFriends(strongbad).addFriends(homestar).build();
writePersonToSequenceFile(paul, inputFile);
Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email", "friends")), inputFile);
Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE);
Pipe pipe = new Each("Extract friends", new Fields("friends"), new Identity());
Flow flow = new FlowConnector(properties).connect(source, sink, pipe);
flow.complete();
List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000"));
assertEquals(1, lines.size());
assertEquals("456\tstrongbad\t\t\t789\thomestar\t\t", lines.get(0));
}
|
diff --git a/src/info/ohgita/bincalc_android/MainActivity.java b/src/info/ohgita/bincalc_android/MainActivity.java
index 1ea4f60..996ca06 100644
--- a/src/info/ohgita/bincalc_android/MainActivity.java
+++ b/src/info/ohgita/bincalc_android/MainActivity.java
@@ -1,65 +1,76 @@
package info.ohgita.bincalc_android;
+/**
+ * Bin.Calc - MainActivity
+ * @author Masanori Ohgita
+ */
+
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends SherlockActivity {
-
+ int selectedBasetypeId = -1;
static int ID_BASETYPE_BIN = 100;
static int ID_BASETYPE_DEC = 200;
static int ID_BASETYPE_HEX = 300;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Event handler for Basetype toggles */
final ToggleButton tb_bin = (ToggleButton) findViewById(R.id.toggle_basetype_bin);
final ToggleButton tb_dec = (ToggleButton) findViewById(R.id.toggle_basetype_dec);
final ToggleButton tb_hex = (ToggleButton) findViewById(R.id.toggle_basetype_hex);
tb_bin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- switchBasetype(ID_BASETYPE_BIN);
+ if(isChecked == true){
+ switchBasetype(ID_BASETYPE_BIN);
+ }
}
});
tb_dec.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- switchBasetype(ID_BASETYPE_DEC);
+ if(isChecked == true){
+ switchBasetype(ID_BASETYPE_DEC);
+ }
}
});
tb_hex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- switchBasetype(ID_BASETYPE_HEX);
+ if(isChecked == true){
+ switchBasetype(ID_BASETYPE_HEX);
+ }
}
});
-
}
/**
* switch base-type
* @param basetypeId Base-type ID number
*/
public void switchBasetype(int basetypeId){
- Toast.makeText(MainActivity.this, "ID:"+basetypeId, Toast.LENGTH_SHORT).show();
+ selectedBasetypeId = basetypeId;
+
ToggleButton tb_bin = (ToggleButton) findViewById(R.id.toggle_basetype_bin);
ToggleButton tb_dec = (ToggleButton) findViewById(R.id.toggle_basetype_dec);
ToggleButton tb_hex = (ToggleButton) findViewById(R.id.toggle_basetype_hex);
tb_bin.setChecked(false);
tb_dec.setChecked(false);
tb_hex.setChecked(false);
if(basetypeId == ID_BASETYPE_BIN){
tb_bin.setChecked(true);
}else if(basetypeId == ID_BASETYPE_DEC){
tb_dec.setChecked(true);
}else{
tb_hex.setChecked(true);
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/Factory/src/factory/graphics/GraphicPanel.java b/Factory/src/factory/graphics/GraphicPanel.java
index e4d3bab..69fed7b 100644
--- a/Factory/src/factory/graphics/GraphicPanel.java
+++ b/Factory/src/factory/graphics/GraphicPanel.java
@@ -1,820 +1,820 @@
package factory.graphics;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import factory.Part;
import factory.client.*;
/**
* @author Minh La, Tobias Lee, George Li<p>
* <b>{@code GraphicPanel.java}</b> (*x720)<br>
* The superclass is what every Manager's graphical panel extends.<br>
* It contains every other graphical component as necessary.
*/
public abstract class GraphicPanel extends JPanel implements ActionListener{
public int WIDTH, HEIGHT;
public static final Image TILE_IMAGE = Toolkit.getDefaultToolkit().getImage("Images/Tiles/floorTileXGrill.png");
public static final int TILE_SIZE = 128;
public static final int DELAY = 10;
protected Client am; //The Client that holds this
protected boolean isLaneManager;
protected boolean isGantryRobotManager;
protected boolean isKitAssemblyManager;
protected boolean isFactoryProductionManager;
// LANE MANAGER
protected GraphicLaneManager [] lane;
// CAMERA
protected int flashCounter;
protected int flashFeederIndex;
protected static Image flashImage;
// KIT MANAGER
protected GraphicConveyorBelt belt; //The conveyer belt
protected GraphicKittingStation station; //The kitting station
protected GraphicKittingRobot kitRobot;
// PARTS MANAGER
protected ArrayList<GraphicNest> nests;
protected GraphicPartsRobot partsRobot;
// GANTRY
protected GraphicGantryRobot gantryRobot;
protected GraphicItem transferringItem;
public GraphicPanel(/*int offset/**/) {
WIDTH = 1100;
HEIGHT = 720;
am = null;
/*lane = null;
belt = null;
station = null;
kitRobot = null;
nests = null;
partsRobot = null;
gantryRobot = null;
isLaneManager = false;
isGantryRobotManager = false;
isKitAssemblyManager = false;
isFactoryProductionManager = false;*/
flashImage = Toolkit.getDefaultToolkit().getImage("Images/cameraFlash3x3.png");
transferringItem = null;
/*belt = new GraphicConveyorBelt(0-offset, 0, this);
station = new GraphicKittingStation(200-offset, 191, this);
kitRobot = new GraphicKittingRobot(this, 70-offset, 250);
// Parts robot client
// Add 8 nests
nests = new ArrayList<GraphicNest>();
for(int i = 0; i < 8; i++)
{
GraphicNest newNest = new GraphicNest(510-offset,i*80+50,0,0,0,0,75,75,"Images/nest3x3.png");
nests.add(newNest);
}
lane = new GraphicLaneManager [4];
for (int i = 0; i < lane.length; i++)
lane[i] = new GraphicLaneManager(510-offset, 160*i + 50, i, this);
partsRobot = new GraphicPartsRobot(350-offset,360,0,5,5,10,100,100,"Images/robot1.png");
gantryRobot = new GraphicGantryRobot(950-offset,360,0,5,5,10,100,100,"Images/robot2.png");*/
}
/**TODO: Kit Assembly Methods*/
/**
* Adds a Kit into the Factory via Conveyor Belt
* @see newEmptyKitDone()
*/
public void newEmptyKit() {
//if (!belt.kitin())
if (isKitAssemblyManager || isFactoryProductionManager)
belt.inKit();
}
/**
* Sends Kit Robot to pick up a Kit from the Conveyor Belt and move to the designated slot in the Kit Station
* @param target The targeted slot in the Kit Station
* @see moveEmptyKitToSlotDone()
*/
public void moveEmptyKitToSlot(int target) {
//if (belt.pickUp() && !kitRobot.kitted() && station.getKit(target) == null) {
if (isKitAssemblyManager || isFactoryProductionManager) {
kitRobot.setFromBelt(true);
kitRobot.setStationTarget(target);
}
}
/**
* Sends Kit Robot to move a Kit from the designated slot in the Kit Station to the Inspection Station
* @param target The targeted slot in the Kit Station
* @see moveKitToInspectionDone()
*/
public void moveKitToInspection(int target) {
//if (!kitRobot.kitted() && station.getKit(target) != null) {
if (isKitAssemblyManager || isFactoryProductionManager) {
kitRobot.setCheckKit(true);
kitRobot.setStationTarget(target);
}
}
/**
* Takes a picture of the Kit in the Inspection Station
* @see takePictureOfInspectionDone()
*/
public void takePictureOfInspectionSlot() {
//if (station.hasCheck())
if (isKitAssemblyManager || isFactoryProductionManager)
station.checkKit();
}
/**
* Dumps the Kit at the designated slot in the Kit Station
* @param target The targeted slot in the Kit Station
* @see dumpKitAtInspectionDone()
*/
public void dumpKitAtSlot(int target) {
if (isKitAssemblyManager || isFactoryProductionManager) {
kitRobot.setPurgeKit(true);
kitRobot.setStationTarget(target);
}
}
/**
* Dumps the Kit in the Inspection Station
* @see dumpKitAtInspectionDone()
*/
public void dumpKitAtInspection() {
//if (!kitRobot.kitted() && station.getCheck() != null)
if (isKitAssemblyManager || isFactoryProductionManager)
kitRobot.setPurgeInspectionKit(true);
}
/**
* Moves the Kit in the Inspection Station to the Conveyor Belt
* @see moveKitFromInspectionToConveyorDone()
*/
public void moveKitFromInspectionToConveyor() {
//if (station.getCheck() != null && !kitRobot.kitted())
if (isKitAssemblyManager || isFactoryProductionManager)
kitRobot.setFromCheck(true);
}
/**
* Sends a Kit out of the Factory via Conveyor Belt
* @see exportKitDone()
*/
public void exportKit() {
if (isKitAssemblyManager || isFactoryProductionManager)
belt.exportKit();
}
/**TODO: Gantry Robot methods*/
/**
* Moves Gantry Robot to pick up a Bin with the provided image
* @param path The image path to the desired Part image
* @see gantryRobotArrivedAtPickup()
*/
public void moveGantryRobotToPickup(String path)
{
if (isGantryRobotManager || isFactoryProductionManager) {
gantryRobot.setState(1);
gantryRobot.setPartPath(path);
gantryRobot.setDestination(WIDTH-100,-100,0);
}
}
/**
* Moves Gantry Robot to the designated Feeder to drop off Bin
* @param feederIndex The designated Feeder
* @see gantryRobotArrivedAtFeederForDropoff()
*/
public void moveGantryRobotToFeederForDropoff(int feederIndex)
{
// Error checking code has temporarily(?) been commented out as requested by Alfonso
//if(lane[feederIndex].hasBin())
//{
//System.err.println("Can't dropoff: feeder " + feederIndex + " (0-based index) already has a bin!");
//gantryRobotArrivedAtFeederForDropoff();
//}
//else if(!gantryRobot.hasBin())
//{
//System.err.println("Can't dropoff: gantry robot does not have a bin!");
//gantryRobotArrivedAtFeederForDropoff();
//}
//else
//{
if (isGantryRobotManager || isFactoryProductionManager) {
gantryRobot.setState(3);
gantryRobot.setDestinationFeeder(feederIndex);
gantryRobot.setDestination(lane[feederIndex].feederX+115, lane[feederIndex].feederY+15,180);
}
//gantryRobotArrivedAtFeederForDropoff();
//}
}
/**
* Moves Gantry Robot to the designated Feeder to pick up a purged Bin
* @param feederIndex The designated Feeder
* @see gantryRobotArrivedAtFeederForPickup()
*/
public void moveGantryRobotToFeederForPickup(int feederIndex)
{
// Error checking
//if(!lane[feederIndex].hasBin())
//{
// System.err.println("Can't pickup: no bin at feeder " + feederIndex + " (0-based index)!");
// gantryRobotArrivedAtFeederForPickup();
//}
//else
//{
if (isGantryRobotManager || isFactoryProductionManager) {
gantryRobot.setState(5);
gantryRobot.setDestinationFeeder(feederIndex);
gantryRobot.setDestination(lane[feederIndex].feederX+115, lane[feederIndex].feederY+15,180);
}
//}
}
/**TODO: Parts Robot and Nest methods*/
/**
* Takes a picture of the designated Lane pair
* @param nestIndex The designated Lane pair
* @see cameraFlashDone()
*/
public void cameraFlash(int nestIndex) {
if (isLaneManager || isFactoryProductionManager) {
flashCounter = 10;
flashFeederIndex = nestIndex;
}
}
//CHANGE TO 0 BASE
/**
* Moves Parts Robot to the designated Nest to pick up Part
* @param nestIndex The designated Nest
* @deprecated Use movePartsRobotToNest(int nestIndex, int itemIndex) instead
* @see partsRobotArrivedAtNest()
*/
public void movePartsRobotToNest(int nestIndex) {
if (isFactoryProductionManager) {
partsRobot.setState(1);
partsRobot.adjustShift(5);
partsRobot.setDestination(nests.get(nestIndex).getX()-nests.get(nestIndex).getImageWidth()-10,nests.get(nestIndex).getY()-15,0);
partsRobot.setDestinationNest(nestIndex);
}
}
/**
* Moves Parts Robot to the designated Nest to pick up the Part at the given index
* @param nestIndex The designated Nest
* @param itemIndex The designated Part
* @see partsRobotArrivedAtNest()
*/
public void movePartsRobotToNest(int nestIndex, int itemIndex) {
if (isFactoryProductionManager) {
partsRobot.setItemIndex(itemIndex);
partsRobot.setState(1);
partsRobot.adjustShift(5);
partsRobot.setDestination(nests.get(nestIndex).getX()-nests.get(nestIndex).getImageWidth()-10,nests.get(nestIndex).getY()-15,0);
partsRobot.setDestinationNest(nestIndex);
}
}
/**
* Moves Parts Robot to the designated slot in the Kit Station
* @param kitIndex The designated slot in the Kit Station
* @see partsRobotArrivedAtStation()
*/
public void movePartsRobotToStation(int kitIndex) {
if (isFactoryProductionManager) {
partsRobot.setState(3);
- partsRobot.setDestination(station.getX()+35,station.getY()-station.getY()%5,180);
+ partsRobot.setDestination(station.getX()+35,station.getY()+100*kitIndex-station.getY()%5,180);
partsRobot.setDestinationKit(kitIndex);
}
}
/**
* Adds Item from the Parts Robot to the Kit Station it's in front of
* @param itemIndex The index of the Item to remove
*/
public void partsRobotPopItemToCurrentKit(int itemIndex)
{
transferringItem = partsRobot.popItemAt(itemIndex);
station.addItem(transferringItem,partsRobot.getDestinationKit());
partsRobotPopItemToCurrentKitDone();
}
/**
* Moves Parts Robot to the center of the Factory
* @see partsRobotArrivedAtCenter()
*/
public void movePartsRobotToCenter() {
if (isFactoryProductionManager) {
partsRobot.setState(5);
partsRobot.setDestination(WIDTH/2-200, HEIGHT/2,0);
}
}
/**
* Drops whatever items the Parts Robot is holding
* @see dropPartsRobotsItemsDone()
*/
public void dropPartsRobotsItems() {
if (isFactoryProductionManager)
partsRobot.clearItems();
dropPartsRobotsItemsDone();
}
/**TODO: Lane methods*/
/**
* Begins feeding the designated Feeder
* @param feederNum The designated Feeder
* @see feedLaneDone(int feederNum)
*/
public void feedFeeder(int feederNum) {
//if(!lane[feederNum].lane1PurgeOn){ //If purging is on, cannot feed!
if (isLaneManager || isFactoryProductionManager) {
lane[feederNum].bin.getBinItems().clear();
for(int i = 0; i < lane[feederNum].bin.binSize;i++){ //unlimited items
lane[feederNum].bin.binItems.add(new GraphicItem(-40, 0, "Images/"+lane[feederNum].bin.partName+".png"));
}
if(lane[feederNum].hasBin() && lane[feederNum].bin.getBinItems().size() > 0){
lane[feederNum].laneStart = true;
lane[feederNum].feederOn = true;
}
}
}
/**
* Begins feeding the designated Lane
* @param laneNum The designated Lane
* @deprecated Use feedFeeder(int feederNum) instead
* @see feedLaneDone(int feederNum) Divide laneNum by 2
*/
public void feedLane(int laneNum){ //FEEDS THE LANE! Lane 0-7
//if(!lane[(laneNum) / 2].lane1PurgeOn){ //If purging is on, cannot feed!
if (isLaneManager || isFactoryProductionManager) {
lane[laneNum / 2].bin.getBinItems().clear();
for(int i = 0; i < lane[laneNum / 2].bin.binSize;i++){ //unlimited items
lane[laneNum / 2].bin.binItems.add(new GraphicItem(-40, 0, "Images/"+lane[laneNum / 2].bin.partName+".png"));
}
if(lane[(laneNum) / 2].hasBin() && lane[(laneNum) / 2].bin.getBinItems().size() > 0){
lane[(laneNum) / 2].laneStart = true;
lane[(laneNum) / 2].divergeUp = ((laneNum) % 2 == 0);
lane[(laneNum) / 2].feederOn = true;
}
}
//System.out.println("bin size " + lane[(laneNum) / 2].bin.getBinItems().size());
}
/**
* Starts the designated Lane
* @param laneNum The designated Lane
* @deprecated use startFeeder(int feederNum) instead
*/
public void startLane(int laneNum){
if (isLaneManager || isFactoryProductionManager) {
lane[(laneNum) / 2].laneStart = true;
}
}
/**
* Switches the Lane
* @param laneNum The designated Lane
* @deprecated use switchFeederLane(int feederNum) instead
*/
public void switchLane(int laneNum){
if (isLaneManager || isFactoryProductionManager) {
lane[(laneNum) / 2].divergeUp = !lane[(laneNum) / 2].divergeUp;
lane[(laneNum) / 2].vY = -(lane[(laneNum) / 2].vY);
}
}
/**
* Switches the Lane at the designated Feeder
* @param feederNum The designated Feeder
*/
public void switchFeederLane(int feederNum){
if (isLaneManager || isFactoryProductionManager) {
lane[feederNum].divergeUp = !lane[feederNum].divergeUp;
lane[feederNum].vY = -(lane[feederNum].vY);
switchFeederLaneDone(feederNum);
}
}
/**
* Stops the designated Lane
* @param laneNum The designated Lane
* @deprecated use turnFeederOff(int feederNum) instead
*/
public void stopLane(int laneNum){
if (isLaneManager || isFactoryProductionManager)
lane[(laneNum) / 2].laneStart = false;
}
/**
* Starts up the designated Feeder
* @param feederNum The designated Feeder
*/
public void turnFeederOn(int feederNum){
if (isLaneManager || isFactoryProductionManager) {
lane[feederNum].feederOn = true;
startFeederDone(feederNum);
}
}
/**
* Turns off the designated Feeder
* @param feederNum The designated Feeder
*/
public void turnFeederOff(int feederNum){
if (isLaneManager || isFactoryProductionManager) {
lane[feederNum].feederOn = false;
stopFeederDone(feederNum);
}
}
/**
* Purges the designated Feeder
* @param feederNum The designated Feeder
*/
public void purgeFeeder(int feederNum){ // takes in lane 0 - 4
// The following 2 lines were causing the bin to disappear, which is undesirable
// lane[(feederNum)].bin = null;
// lane[(feederNum)].binExists = false;
if (isLaneManager || isFactoryProductionManager) {
lane[(feederNum)].purgeFeeder();
purgeFeederDone(feederNum); // send the confirmation
}
}
/**
* Purges the Top Lane of the designated Feeder
* @param feederNum The designated Feeder
*/
public void purgeTopLane(int feederNum){
if (isLaneManager || isFactoryProductionManager) {
lane[feederNum].lane1PurgeOn = true;
lane[feederNum].feederOn = false;
lane[feederNum].laneStart = true;
}
}
/**
* Purges the Bottom Lane of the designated Feeder
* @param feederNum The designated Feeder
*/
public void purgeBottomLane(int feederNum){
if (isLaneManager || isFactoryProductionManager) {
lane[feederNum].lane2PurgeOn = true;
lane[feederNum].feederOn = false;
lane[feederNum].laneStart = true;
}
}
/**Movement methods*/
/**
* Moves the Parts Robot
*/
public void partsRobotStateCheck() {
// Has robot arrived at its destination?
//System.out.println(partsRobot.getState());
if (isFactoryProductionManager) {
if(partsRobot.getState() == 2) // partsRobot has arrived at nest
{
if (nests.get(partsRobot.getDestinationNest()).hasItem())
partsRobot.addItem(nests.get(partsRobot.getDestinationNest()).popItemAt(partsRobot.getItemIndex()));
partsRobot.setState(0);
partsRobotArrivedAtNest();
}
else if(partsRobot.getState() == 4) // partsRobot has arrived at kitting station
{
/*
System.out.println("Size:"+partsRobot.getSize());
int numberOfParts = partsRobot.getSize();
for(int i = 0; i < numberOfParts; i++)
{
System.out.println("Adding part to kit: " + i);
station.addItem(partsRobot.popItemAt(partsRobot.getItemIndex()),partsRobot.getDestinationKit());
}
*/
partsRobot.setState(0);
partsRobotArrivedAtStation();
}
else if(partsRobot.getState() == 6)
{
partsRobot.setState(0);
partsRobotArrivedAtCenter();
}
}
}
/**
* Moves the Gantry Robot
*/
public void gantryRobotStateCheck() {
if (isGantryRobotManager || isFactoryProductionManager) {
if(gantryRobot.getState() == 2) // gantry robot reached bin pickup point
{
gantryRobot.setState(0);
// Give gantry robot a bin
gantryRobot.giveBin(new GraphicBin(new Part(gantryRobot.getPartPath())));
gantryRobotArrivedAtPickup();
}
else if(gantryRobot.getState() == 4) // gantry robot reached feeder for dropoff
{
gantryRobot.setState(0);
lane[gantryRobot.getDestinationFeeder()].setBin(gantryRobot.popBin());
gantryRobotArrivedAtFeederForDropoff();
}
else if(gantryRobot.getState() == 6) // gantry robot reached feeder for pickup
{
gantryRobot.setState(0);
gantryRobot.giveBin(lane[gantryRobot.getDestinationFeeder()].popBin());
gantryRobotArrivedAtFeederForPickup();
}
}
}
/**
* Sets the Bin for the specified feeder
* @param feederNum
* @param bin
*/
public void setFeederBin(int feederNum, GraphicBin bin) {
lane[feederNum].setBin(bin);
}
/**
* Adds an Part to the specified Kit
* @param kitNum
* @param item
*/
public void setKitItem(int kitNum, GraphicItem item) {
station.addItem(item, kitNum);
}
/**
* Moves Parts down the Lanes
*/
public void moveLanes() {
if (isLaneManager || isFactoryProductionManager) {
for (int i = 0; i < lane.length; i++)
lane[i].moveLane();
}
}
/**
* Sends message to Server depending
* @param command The command to send
*/
public void sendMessage(String command) {
//if (am == null)
//return;
//asdfasd
String message;
if (isLaneManager)
message = "lm ";
else if (isGantryRobotManager)
message = "grm ";
else if (isKitAssemblyManager)
message = "kam ";
else if (isFactoryProductionManager)
message = "fpm ";
else
return;
if (am != null)
am.sendCommand(message + command);
else
System.out.println(message + command);
}
/**TODO: THIS IS SO I CAN FIND THE DONES*/
/**These are pretty self-explanatory*/
public void newEmptyKitDone() {
sendMessage("cca cnf");
}
public void moveEmptyKitToSlotDone() {
sendMessage("kra cnf");
}
public void moveKitToInspectionDone() {
sendMessage("kra cnf");
}
public void takePictureOfInspectionSlotDone() {
sendMessage("va cnf");
}
public void dumpKitAtInspectionDone() {
sendMessage("kra cnf");
}
public void moveKitFromInspectionToConveyorDone() {
sendMessage("kra cnf");
}
public void exportKitDone() {
sendMessage("ca cnf");
}
public void cameraFlashDone() {
sendMessage("va cnf");
}
public void gantryRobotArrivedAtPickup() {
sendMessage("ga cnf");
}
public void gantryRobotArrivedAtFeederForDropoff() {
sendMessage("lm set " + gantryRobot.getDestinationFeeder() + " "+ lane[gantryRobot.getDestinationFeeder()].getBin().getPartName());
sendMessage("ga cnf");
}
public void gantryRobotArrivedAtFeederForPickup()
{
sendMessage("ga cnf");
}
public void partsRobotArrivedAtNest() {
sendMessage("pra cnf");
}
public void partsRobotArrivedAtStation() {
sendMessage("pra cnf");
}
public void partsRobotArrivedAtCenter() {
sendMessage("pra cnf");
}
public void dropPartsRobotsItemsDone() {
sendMessage("pra cnf");
}
public void partsRobotPopItemToCurrentKitDone() {
if (isFactoryProductionManager)
sendMessage("kam set itemtype " + partsRobot.getDestinationKit() + " " + transferringItem.getImagePath());
sendMessage("pra cnf");
}
public void feedLaneDone(int feederNum){
sendMessage("fa cnf " + feederNum);
}
public void purgeTopLaneDone(int feederNum) {
sendMessage("fa cnf " + feederNum);
}
public void purgeBottomLaneDone(int feederNum) {
sendMessage("fa cnf " + feederNum);
}
public void purgeFeederDone(int feederNum) {
sendMessage("fa cnf " + feederNum);
}
public void startFeederDone(int feederNum) {
sendMessage("fa cnf " + feederNum);
}
public void stopFeederDone(int feederNum) {
sendMessage("fa cnf " + feederNum);
}
public void switchFeederLaneDone(int feederNum) {
sendMessage("fa cnf " + feederNum);
}
public GraphicKittingStation getStation() {
return station;
}
public GraphicConveyorBelt getBelt() {
return belt;
}
public ArrayList<GraphicNest> getNest(){
return nests;
}
public GraphicLaneManager getLane(int index) {
return lane[index];
}
/**TODO: Paint function*/
/**
* Paints all the applicable parts for the given panel
* @param g The specified graphics window
*/
public void paint(Graphics g) {
for(int j = 0; j < WIDTH; j += TILE_SIZE)
{
for(int k = 0; k < HEIGHT; k += TILE_SIZE)
{
g.drawImage(TILE_IMAGE, j, k, TILE_SIZE, TILE_SIZE, null);
}
}
//g.setColor(new Color(200, 200, 200));
//g.fillRect(0, 0, getWidth(), getHeight());
if (isKitAssemblyManager || isFactoryProductionManager) {
belt.paint(g);
station.paint(g);
kitRobot.paint(g);
}
if (isLaneManager || isFactoryProductionManager) {
for (int i = 0; i < lane.length; i++) {
//if (lane[i] != null)
lane[i].paintLane(g);
}
}
if (isLaneManager || isFactoryProductionManager || isGantryRobotManager) {
for (int i = 0; i < lane.length; i++) {
//if (lane[i] != null)
lane[i].paintFeeder(g);
}
}
// Parts robot client
// Draw the nests
if (isLaneManager || isFactoryProductionManager)
for(int i = 0; i < nests.size(); i++) {
GraphicNest currentNest = nests.get(i);
currentNest.paint(g);
}
if(isLaneManager || isFactoryProductionManager) {
if(flashCounter >= 0)
{
int flashX = nests.get(flashFeederIndex*2).getX()-20;
int flashY = nests.get(flashFeederIndex*2).getY()-12;
g.drawImage(flashImage, flashX, flashY, null);
flashX = nests.get(flashFeederIndex*2+1).getX()-20;
flashY = nests.get(flashFeederIndex*2+1).getY()-12;
g.drawImage(flashImage, flashX, flashY, null);
flashCounter --;
if(flashCounter == 1)
cameraFlashDone();
}
}
// Draw the parts robot
if (isFactoryProductionManager) {
final Graphics2D g3 = (Graphics2D)g.create();
g3.rotate(Math.toRadians(360-partsRobot.getAngle()), partsRobot.getX()+partsRobot.getImageWidth()/2, partsRobot.getY()+partsRobot.getImageHeight()/2);
// Draw items partsRobot is carrying
partsRobot.paint(g3);
g3.dispose();
}
// Draw the Gantry Robot
if (isGantryRobotManager || isFactoryProductionManager) {
final Graphics2D g4 = (Graphics2D)g.create();
g4.rotate(Math.toRadians(360-gantryRobot.getAngle()), gantryRobot.getX()+gantryRobot.getImageWidth()/2, gantryRobot.getY()+gantryRobot.getImageHeight()/2);
gantryRobot.paint(g4);
// Draw bin gantryRobot is carrying
g4.dispose();
}
}
public boolean isKitAssemblyManager() {
return isKitAssemblyManager;
}
public boolean isLaneManager() {
return isLaneManager;
}
public boolean isGantryRobotManager() {
return isGantryRobotManager;
}
public boolean isFactoryProductionManager() {
return isFactoryProductionManager;
}
/**
* Moves the components that need moving
*/
public void actionPerformed(ActionEvent arg0) {
}
}
| true | false | null | null |
diff --git a/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java b/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java
index e452c0162..7e57a138c 100644
--- a/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java
+++ b/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java
@@ -1,592 +1,598 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.data.util;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import com.itmill.toolkit.data.Container;
import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.data.Property;
/**
* <p>
* A wrapper class for adding external ordering to containers not implementing
* the {@link com.itmill.toolkit.data.Container.Ordered} interface.
* </p>
*
* <p>
* If the wrapped container is changed directly (that is, not through the
* wrapper), the ordering must be updated with the {@link #updateOrderWrapper()}
* method.
* </p>
*
* @author IT Mill Ltd.
* @version
* @VERSION@
* @since 3.0
*/
public class ContainerOrderedWrapper implements Container.Ordered,
Container.ItemSetChangeNotifier, Container.PropertySetChangeNotifier {
/**
* The wrapped container
*/
private final Container container;
/**
* Ordering information, ie. the mapping from Item ID to the next item ID
*/
private Hashtable next;
/**
* Reverse ordering information for convenience and performance reasons.
*/
private Hashtable prev;
/**
* ID of the first Item in the container.
*/
private Object first;
/**
* ID of the last Item in the container.
*/
private Object last;
/**
* Is the wrapped container ordered by itself, ie. does it implement the
* Container.Ordered interface by itself? If it does, this class will use
* the methods of the underlying container directly.
*/
private boolean ordered = false;
/**
* Constructs a new ordered wrapper for an existing Container. Works even if
* the to-be-wrapped container already implements the Container.Ordered
* interface.
*
* @param toBeWrapped
* the container whose contents need to be ordered.
*/
public ContainerOrderedWrapper(Container toBeWrapped) {
container = toBeWrapped;
ordered = container instanceof Container.Ordered;
// Checks arguments
if (container == null) {
throw new NullPointerException("Null can not be wrapped");
}
// Creates initial order if needed
updateOrderWrapper();
}
/**
* Removes the specified Item from the wrapper's internal hierarchy
* structure.
* <p>
* Note : The Item is not removed from the underlying Container.
* </p>
*
* @param id
* the ID of the Item to be removed from the ordering.
*/
private void removeFromOrderWrapper(Object id) {
if (id != null) {
final Object pid = prev.get(id);
final Object nid = next.get(id);
if (first.equals(id)) {
first = nid;
}
if (last.equals(id)) {
first = pid;
}
if (nid != null) {
prev.put(nid, pid);
}
if (pid != null) {
next.put(pid, nid);
}
next.remove(id);
prev.remove(id);
}
}
/**
* Registers the specified Item to the last position in the wrapper's
* internal ordering. The underlying container is not modified.
*
* @param id
* the ID of the Item to be added to the ordering.
*/
private void addToOrderWrapper(Object id) {
// Adds the if to tail
if (last != null) {
next.put(last, id);
prev.put(id, last);
last = id;
} else {
first = last = id;
}
}
/**
* Registers the specified Item after the specified itemId in the wrapper's
* internal ordering. The underlying container is not modified. Given item
* id must be in the container, or must be null.
*
* @param id
* the ID of the Item to be added to the ordering.
* @param previousItemId
* the Id of the previous item.
*/
private void addToOrderWrapper(Object id, Object previousItemId) {
if (last == previousItemId || last == null) {
addToOrderWrapper(id);
} else {
if (previousItemId == null) {
next.put(id, first);
prev.put(first, id);
first = id;
} else {
prev.put(id, previousItemId);
next.put(id, next.get(previousItemId));
prev.put(next.get(previousItemId), id);
next.put(previousItemId, id);
}
}
}
/**
* Updates the wrapper's internal ordering information to include all Items
* in the underlying container.
* <p>
* Note : If the contents of the wrapped container change without the
* wrapper's knowledge, this method needs to be called to update the
* ordering information of the Items.
* </p>
*/
public void updateOrderWrapper() {
if (!ordered) {
final Collection ids = container.getItemIds();
// Recreates ordering if some parts of it are missing
if (next == null || first == null || last == null || prev != null) {
first = null;
last = null;
next = new Hashtable();
prev = new Hashtable();
}
// Filter out all the missing items
final LinkedList l = new LinkedList(next.keySet());
for (final Iterator i = l.iterator(); i.hasNext();) {
final Object id = i.next();
if (!container.containsId(id)) {
removeFromOrderWrapper(id);
}
}
// Adds missing items
for (final Iterator i = ids.iterator(); i.hasNext();) {
final Object id = i.next();
if (!next.containsKey(id)) {
addToOrderWrapper(id);
}
}
}
}
/*
* Gets the first item stored in the ordered container Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
public Object firstItemId() {
if (ordered) {
return ((Container.Ordered) container).firstItemId();
}
return first;
}
/*
* Tests if the given item is the first item in the container Don't add a
* JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
public boolean isFirstId(Object itemId) {
if (ordered) {
return ((Container.Ordered) container).isFirstId(itemId);
}
return first != null && first.equals(itemId);
}
/*
* Tests if the given item is the last item in the container Don't add a
* JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
public boolean isLastId(Object itemId) {
if (ordered) {
return ((Container.Ordered) container).isLastId(itemId);
}
return last != null && last.equals(itemId);
}
/*
* Gets the last item stored in the ordered container Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
public Object lastItemId() {
if (ordered) {
return ((Container.Ordered) container).lastItemId();
}
return last;
}
/*
* Gets the item that is next from the specified item. Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
public Object nextItemId(Object itemId) {
if (ordered) {
return ((Container.Ordered) container).nextItemId(itemId);
}
+ if (itemId == null) {
+ return null;
+ }
return next.get(itemId);
}
/*
* Gets the item that is previous from the specified item. Don't add a
* JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
public Object prevItemId(Object itemId) {
if (ordered) {
return ((Container.Ordered) container).prevItemId(itemId);
}
+ if (itemId == null) {
+ return null;
+ }
return prev.get(itemId);
}
/**
* Registers a new Property to all Items in the Container.
*
* @param propertyId
* the ID of the new Property.
* @param type
* the Data type of the new Property.
* @param defaultValue
* the value all created Properties are initialized to.
* @return <code>true</code> if the operation succeeded,
* <code>false</code> if not
*/
public boolean addContainerProperty(Object propertyId, Class type,
Object defaultValue) throws UnsupportedOperationException {
return container.addContainerProperty(propertyId, type, defaultValue);
}
/**
* Creates a new Item into the Container, assigns it an automatic ID, and
* adds it to the ordering.
*
* @return the autogenerated ID of the new Item or <code>null</code> if
* the operation failed
* @throws UnsupportedOperationException
* if the addItem is not supported.
*/
public Object addItem() throws UnsupportedOperationException {
final Object id = container.addItem();
if (!ordered && id != null) {
addToOrderWrapper(id);
}
return id;
}
/**
* Registers a new Item by its ID to the underlying container and to the
* ordering.
*
* @param itemId
* the ID of the Item to be created.
* @return the added Item or <code>null</code> if the operation failed
* @throws UnsupportedOperationException
* if the addItem is not supported.
*/
public Item addItem(Object itemId) throws UnsupportedOperationException {
final Item item = container.addItem(itemId);
if (!ordered && item != null) {
addToOrderWrapper(itemId);
}
return item;
}
/**
* Removes all items from the underlying container and from the ordering.
*
* @return <code>true</code> if the operation succeeded, otherwise
* <code>false</code>
* @throws UnsupportedOperationException
* if the removeAllItems is not supported.
*/
public boolean removeAllItems() throws UnsupportedOperationException {
final boolean success = container.removeAllItems();
if (!ordered && success) {
first = last = null;
next.clear();
prev.clear();
}
return success;
}
/**
* Removes an Item specified by the itemId from the underlying container and
* from the ordering.
*
* @param itemId
* the ID of the Item to be removed.
* @return <code>true</code> if the operation succeeded,
* <code>false</code> if not
* @throws UnsupportedOperationException
* if the removeItem is not supported.
*/
public boolean removeItem(Object itemId)
throws UnsupportedOperationException {
final boolean success = container.removeItem(itemId);
if (!ordered && success) {
removeFromOrderWrapper(itemId);
}
return success;
}
/**
* Removes the specified Property from the underlying container and from the
* ordering.
* <p>
* Note : The Property will be removed from all the Items in the Container.
* </p>
*
* @param propertyId
* the ID of the Property to remove.
* @return <code>true</code> if the operation succeeded,
* <code>false</code> if not
* @throws UnsupportedOperationException
* if the removeContainerProperty is not supported.
*/
public boolean removeContainerProperty(Object propertyId)
throws UnsupportedOperationException {
return container.removeContainerProperty(propertyId);
}
/*
* Does the container contain the specified Item? Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
public boolean containsId(Object itemId) {
return container.containsId(itemId);
}
/*
* Gets the specified Item from the container. Don't add a JavaDoc comment
* here, we use the default documentation from implemented interface.
*/
public Item getItem(Object itemId) {
return container.getItem(itemId);
}
/*
* Gets the ID's of all Items stored in the Container Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
public Collection getItemIds() {
return container.getItemIds();
}
/*
* Gets the Property identified by the given itemId and propertyId from the
* Container Don't add a JavaDoc comment here, we use the default
* documentation from implemented interface.
*/
public Property getContainerProperty(Object itemId, Object propertyId) {
return container.getContainerProperty(itemId, propertyId);
}
/*
* Gets the ID's of all Properties stored in the Container Don't add a
* JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
public Collection getContainerPropertyIds() {
return container.getContainerPropertyIds();
}
/*
* Gets the data type of all Properties identified by the given Property ID.
* Don't add a JavaDoc comment here, we use the default documentation from
* implemented interface.
*/
public Class getType(Object propertyId) {
return container.getType(propertyId);
}
/*
* Gets the number of Items in the Container. Don't add a JavaDoc comment
* here, we use the default documentation from implemented interface.
*/
public int size() {
return container.size();
}
/*
* Registers a new Item set change listener for this Container. Don't add a
* JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
public void addListener(Container.ItemSetChangeListener listener) {
if (container instanceof Container.ItemSetChangeNotifier) {
((Container.ItemSetChangeNotifier) container)
.addListener(new PiggybackListener(listener));
}
}
/*
* Removes a Item set change listener from the object. Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
public void removeListener(Container.ItemSetChangeListener listener) {
if (container instanceof Container.ItemSetChangeNotifier) {
((Container.ItemSetChangeNotifier) container)
.removeListener(new PiggybackListener(listener));
}
}
/*
* Registers a new Property set change listener for this Container. Don't
* add a JavaDoc comment here, we use the default documentation from
* implemented interface.
*/
public void addListener(Container.PropertySetChangeListener listener) {
if (container instanceof Container.PropertySetChangeNotifier) {
((Container.PropertySetChangeNotifier) container)
.addListener(new PiggybackListener(listener));
}
}
/*
* Removes a Property set change listener from the object. Don't add a
* JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
public void removeListener(Container.PropertySetChangeListener listener) {
if (container instanceof Container.PropertySetChangeNotifier) {
((Container.PropertySetChangeNotifier) container)
.removeListener(new PiggybackListener(listener));
}
}
/*
* (non-Javadoc)
*
* @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(java.lang.Object,
* java.lang.Object)
*/
public Item addItemAfter(Object previousItemId, Object newItemId)
throws UnsupportedOperationException {
// If the previous item is not in the container, fail
if (previousItemId != null && !containsId(previousItemId)) {
return null;
}
// Adds the item to container
final Item item = container.addItem(newItemId);
// Puts the new item to its correct place
if (!ordered && item != null) {
addToOrderWrapper(newItemId, previousItemId);
}
return item;
}
/*
* (non-Javadoc)
*
* @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(java.lang.Object)
*/
public Object addItemAfter(Object previousItemId)
throws UnsupportedOperationException {
// If the previous item is not in the container, fail
if (previousItemId != null && !containsId(previousItemId)) {
return null;
}
// Adds the item to container
final Object id = container.addItem();
// Puts the new item to its correct place
if (!ordered && id != null) {
addToOrderWrapper(id, previousItemId);
}
return id;
}
/**
* This listener 'piggybacks' on the real listener in order to update the
* wrapper when needed. It proxies equals() and hashCode() to the real
* listener so that the correct listener gets removed.
*
*/
private class PiggybackListener implements
Container.PropertySetChangeListener,
Container.ItemSetChangeListener {
Object listener;
public PiggybackListener(Object realListener) {
listener = realListener;
}
public void containerItemSetChange(ItemSetChangeEvent event) {
updateOrderWrapper();
((Container.ItemSetChangeListener) listener)
.containerItemSetChange(event);
}
public void containerPropertySetChange(PropertySetChangeEvent event) {
updateOrderWrapper();
((Container.PropertySetChangeListener) listener)
.containerPropertySetChange(event);
}
public boolean equals(Object obj) {
return listener.equals(obj);
}
public int hashCode() {
return listener.hashCode();
}
}
}
| false | false | null | null |
diff --git a/dataobjects-spec/src/main/java/org/escidoc/core/domain/metadatarecords/MdRecordDatastreamHolderTO.java b/dataobjects-spec/src/main/java/org/escidoc/core/domain/metadatarecords/MdRecordDatastreamHolderTO.java
index a93a3701b..b77139703 100644
--- a/dataobjects-spec/src/main/java/org/escidoc/core/domain/metadatarecords/MdRecordDatastreamHolderTO.java
+++ b/dataobjects-spec/src/main/java/org/escidoc/core/domain/metadatarecords/MdRecordDatastreamHolderTO.java
@@ -1,36 +1,36 @@
package org.escidoc.core.domain.metadatarecords;
import org.escidoc.core.utils.io.Stream;
import org.escidoc.core.utils.xml.StreamHolder;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import static org.escidoc.core.utils.Preconditions.checkNotNull;
/**
* @author <a href="mailto:[email protected]">Eduard Hildebrandt</a>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "md-record", namespace = "http://www.escidoc.de/schemas/metadatarecords/0.5")
public class MdRecordDatastreamHolderTO extends MdRecordTO implements StreamHolder {
@XmlElement(namespace = NAMESPACE, name = ELEMENT_NAME)
private Stream stream;
public Stream getStream() {
if (this.stream == null) {
this.stream = new Stream();
}
return this.stream;
}
public void setContent(@NotNull final Stream datastream) {
- this.stream = stream;
+ this.stream = datastream;
}
}
diff --git a/dataobjects-spec/src/main/java/org/escidoc/core/domain/properties/ContentModelSpecificDatastreamHolderTO.java b/dataobjects-spec/src/main/java/org/escidoc/core/domain/properties/ContentModelSpecificDatastreamHolderTO.java
index 551c8f220..065db2a4e 100644
--- a/dataobjects-spec/src/main/java/org/escidoc/core/domain/properties/ContentModelSpecificDatastreamHolderTO.java
+++ b/dataobjects-spec/src/main/java/org/escidoc/core/domain/properties/ContentModelSpecificDatastreamHolderTO.java
@@ -1,36 +1,36 @@
package org.escidoc.core.domain.properties;
import org.escidoc.core.utils.io.Stream;
import org.escidoc.core.utils.xml.StreamHolder;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import static org.escidoc.core.utils.Preconditions.checkNotNull;
/**
* @author <a href="mailto:[email protected]">Eduard Hildebrandt</a>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "content-model-specific", namespace = "http://escidoc.de/core/01/properties/")
public class ContentModelSpecificDatastreamHolderTO extends ContentModelSpecificTO implements StreamHolder {
@XmlElement(namespace = NAMESPACE, name = ELEMENT_NAME)
private Stream stream;
public Stream getStream() {
if (this.stream == null) {
this.stream = new Stream();
}
return this.stream;
}
public void setContent(@NotNull final Stream datastream) {
- this.stream = stream;
+ this.stream = datastream;
}
}
| false | false | null | null |
diff --git a/src/main/java/org/basex/query/up/ContextModifier.java b/src/main/java/org/basex/query/up/ContextModifier.java
index 9fd4cb85e..fae66a95b 100644
--- a/src/main/java/org/basex/query/up/ContextModifier.java
+++ b/src/main/java/org/basex/query/up/ContextModifier.java
@@ -1,122 +1,125 @@
package org.basex.query.up;
import java.util.*;
import org.basex.data.*;
import org.basex.query.*;
import org.basex.query.up.primitives.*;
import org.basex.util.list.*;
/**
* Base class for the different context modifiers. A context modifier aggregates
* all updates for a specific context.
*
* @author BaseX Team 2005-12, BSD License
* @author Lukas Kircher
*/
public abstract class ContextModifier {
/** Update primitives, aggregated separately for each database which is
* referenced during a snapshot. */
private final Map<Data, DatabaseUpdates> pendingUpdates =
new HashMap<Data, DatabaseUpdates>();
/** Holds DBCreate primitives which are not associated with a database. */
private final Map<String, DBCreate> dbCreates = new HashMap<String, DBCreate>();
/** Temporary data reference, containing global . */
MemData tmp;
/**
* Adds an update primitive to this context modifier.
* @param p update primitive
* @param ctx query context
* @throws QueryException query exception
*/
abstract void add(final Operation p, final QueryContext ctx) throws QueryException;
/**
* Adds an update primitive to this context modifier.
* Will be called by {@link #add(Operation, QueryContext)}.
* @param p update primitive
* @throws QueryException query exception
*/
final void add(final Operation p) throws QueryException {
if(p instanceof DBCreate) {
final DBCreate c = (DBCreate) p;
final DBCreate o = dbCreates.get(c.name);
if(o != null) o.merge(c);
dbCreates.put(c.name, c);
return;
}
final Data data = p.getData();
DatabaseUpdates dbp = pendingUpdates.get(data);
if(dbp == null) {
dbp = new DatabaseUpdates(data);
pendingUpdates.put(data, dbp);
}
// create temporary mem data instance if not available yet
if(tmp == null) tmp = new MemData(data.meta.prop);
dbp.add(p, tmp);
}
/**
* Adds all databases to be updated to the specified list.
* @param db databases
*/
void databases(final StringList db) {
- for(final DatabaseUpdates du : pendingUpdates.values()) db.add(du.data().meta.name);
- for(final DBCreate du : dbCreates.values()) db.add(du.name);
+ for(final DatabaseUpdates du : pendingUpdates.values()) {
+ final Data d = du.data();
+ if(!d.inMemory()) db.add(d.meta.name);
+ }
+ for(final DBCreate dc : dbCreates.values()) db.add(dc.name);
}
/**
* Checks constraints and applies all update primitives to the databases if
* no constraints are hurt.
* @throws QueryException query exception
*/
final void apply() throws QueryException {
// checked constraints
final Collection<DatabaseUpdates> updates = pendingUpdates.values();
final Collection<DBCreate> creates = dbCreates.values();
// create temporary mem data instance if not available yet
if(tmp == null) {
for(final DatabaseUpdates c : updates) {
tmp = new MemData(c.data().meta.prop);
break;
}
}
for(final DatabaseUpdates c : updates) c.check(tmp);
for(final DBCreate c : creates) c.prepare(null);
int i = 0;
try {
// mark disk database instances as updating
for(final DatabaseUpdates c : updates) {
c.startUpdate();
i++;
}
// apply updates
for(final DatabaseUpdates c : updates) c.apply();
} finally {
// remove write locks and updating files
for(final DatabaseUpdates c : updates) {
if(i-- == 0) break;
c.finishUpdate();
}
}
// create databases
for(final DBCreate c : creates) c.apply();
}
/**
* Returns the total number of update operations.
* @return number of updates
*/
final int size() {
int s = 0;
for(final DatabaseUpdates c : pendingUpdates.values()) s += c.size();
for(final DBCreate c : dbCreates.values()) s += c.size();
return s;
}
}
| true | false | null | null |
diff --git a/src/org/jwildfire/create/tina/randomflame/SubFlameRandomFlameGenerator.java b/src/org/jwildfire/create/tina/randomflame/SubFlameRandomFlameGenerator.java
index 3ee2aff3..f9c1927d 100644
--- a/src/org/jwildfire/create/tina/randomflame/SubFlameRandomFlameGenerator.java
+++ b/src/org/jwildfire/create/tina/randomflame/SubFlameRandomFlameGenerator.java
@@ -1,139 +1,142 @@
/*
JWildfire - an image and animation processor written in Java
Copyright (C) 1995-2011 Andreas Maschke
This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this software;
if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jwildfire.create.tina.randomflame;
import org.jwildfire.base.Prefs;
import org.jwildfire.create.tina.base.Flame;
import org.jwildfire.create.tina.base.XForm;
import org.jwildfire.create.tina.io.Flam3Writer;
import org.jwildfire.create.tina.palette.RGBPalette;
import org.jwildfire.create.tina.palette.RandomRGBPaletteGenerator;
import org.jwildfire.create.tina.render.FlameRenderer;
import org.jwildfire.create.tina.transform.XFormTransformService;
import org.jwildfire.create.tina.variation.Linear3DFunc;
import org.jwildfire.create.tina.variation.SubFlameWFFunc;
import org.jwildfire.image.Pixel;
import org.jwildfire.image.SimpleImage;
public class SubFlameRandomFlameGenerator extends RandomFlameGenerator {
@Override
protected Flame createFlame() {
Prefs prefs = new Prefs();
try {
prefs.loadFromFile();
}
catch (Exception e) {
e.printStackTrace();
}
Flame flame = new Flame();
flame.setCentreX(0.0);
flame.setCentreY(0.0);
flame.setPixelsPerUnit(200);
flame.setSpatialFilterRadius(1.0);
flame.setFinalXForm(null);
flame.getXForms().clear();
int maxXForms = (int) (2.0 + Math.random() * 5.0);
double scl = 1.0;
for (int i = 0; i < maxXForms; i++) {
XForm xForm = new XForm();
flame.getXForms().add(xForm);
if (Math.random() < 0.5) {
XFormTransformService.rotate(xForm, 90.0 * Math.random());
}
else {
XFormTransformService.rotate(xForm, -90.0 * Math.random());
}
XFormTransformService.localTranslate(xForm, 2.0 * Math.random() - 1.0, 2.0 * Math.random() - 1.0);
scl *= 0.75 + Math.random() / 4;
XFormTransformService.scale(xForm, scl, true, true);
xForm.setColor(Math.random());
if (Math.random() < 0.7) {
SubFlameWFFunc var = new SubFlameWFFunc();
Flame subFlame;
while (true) {
double r = Math.random();
- if (r < 0.20) {
+ if (r < 0.15) {
subFlame = new LinearRandomFlameGenerator().createFlame();
}
- else if (r < 0.40) {
+ else if (r < 0.30) {
subFlame = new GnarlRandomFlameGenerator().createFlame();
}
- else if (r < 0.60) {
+ else if (r < 0.45) {
subFlame = new ExperimentalGnarlRandomFlameGenerator().createFlame();
}
- else if (r < 0.80) {
+ else if (r < 0.60) {
subFlame = new BubblesRandomFlameGenerator().createFlame();
}
- else {
+ else if (r < 0.75) {
subFlame = new ExperimentalSimpleRandomFlameGenerator().createFlame();
}
+ else {
+ subFlame = new SubFlameRandomFlameGenerator().createFlame();
+ }
final int IMG_WIDTH = 160;
final int IMG_HEIGHT = 100;
final double MIN_COVERAGE = 0.25;
subFlame.setWidth(IMG_WIDTH);
subFlame.setHeight(IMG_HEIGHT);
// subFlame.setPixelsPerUnit(10);
// render it
subFlame.setSampleDensity(50);
RGBPalette palette = new RandomRGBPaletteGenerator().generatePalette(11);
subFlame.setPalette(palette);
FlameRenderer renderer = new FlameRenderer(subFlame, prefs);
SimpleImage img = new SimpleImage(IMG_WIDTH, IMG_HEIGHT);
renderer.renderFlame(img, null);
renderer.renderFlame(img, null);
long maxCoverage = img.getImageWidth() * img.getImageHeight();
long coverage = 0;
Pixel pixel = new Pixel();
for (int k = 0; k < img.getImageHeight(); k++) {
for (int l = 0; l < img.getImageWidth(); l++) {
pixel.setARGBValue(img.getARGBValue(l, k));
if (pixel.r > 20 || pixel.g > 20 || pixel.b > 20) {
coverage++;
}
}
}
double fCoverage = (double) coverage / (double) maxCoverage;
if (fCoverage >= MIN_COVERAGE) {
break;
}
}
String flameXML = new Flam3Writer().getFlameXML(subFlame);
var.setRessource("flame", flameXML.getBytes());
xForm.addVariation(Math.random() * 0.8 + 0.2, var);
}
else {
xForm.addVariation(Math.random() * 0.8 + 0.2, new Linear3DFunc());
}
xForm.setWeight(0.5);
}
return flame;
}
@Override
public String getName() {
return "SubFlame";
}
}
diff --git a/src/org/jwildfire/create/tina/swing/TinaController.java b/src/org/jwildfire/create/tina/swing/TinaController.java
index 08c74c0f..86310fdb 100644
--- a/src/org/jwildfire/create/tina/swing/TinaController.java
+++ b/src/org/jwildfire/create/tina/swing/TinaController.java
@@ -1,3778 +1,3781 @@
/*
JWildfire - an image and animation processor written in Java
Copyright (C) 1995-2011 Andreas Maschke
This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this software;
if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jwildfire.create.tina.swing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.jwildfire.base.Prefs;
import org.jwildfire.base.Tools;
import org.jwildfire.create.tina.base.DrawMode;
import org.jwildfire.create.tina.base.Flame;
import org.jwildfire.create.tina.base.Shading;
import org.jwildfire.create.tina.base.ShadingInfo;
import org.jwildfire.create.tina.base.XForm;
import org.jwildfire.create.tina.batch.Job;
import org.jwildfire.create.tina.batch.JobRenderThread;
import org.jwildfire.create.tina.batch.JobRenderThreadController;
import org.jwildfire.create.tina.io.Flam3Reader;
import org.jwildfire.create.tina.io.Flam3Writer;
import org.jwildfire.create.tina.palette.RGBColor;
import org.jwildfire.create.tina.palette.RGBPalette;
import org.jwildfire.create.tina.palette.RGBPaletteRenderer;
import org.jwildfire.create.tina.palette.RandomRGBPaletteGenerator;
import org.jwildfire.create.tina.randomflame.RandomFlameGenerator;
import org.jwildfire.create.tina.randomflame.RandomFlameGeneratorList;
import org.jwildfire.create.tina.render.AffineZStyle;
import org.jwildfire.create.tina.render.FlameRenderer;
import org.jwildfire.create.tina.script.ScriptRunner;
import org.jwildfire.create.tina.script.ScriptRunnerEnvironment;
import org.jwildfire.create.tina.transform.AnimationService;
import org.jwildfire.create.tina.transform.AnimationService.GlobalScript;
import org.jwildfire.create.tina.transform.AnimationService.LightScript;
import org.jwildfire.create.tina.transform.AnimationService.XFormScript;
import org.jwildfire.create.tina.transform.FlameMorphService;
import org.jwildfire.create.tina.transform.XFormTransformService;
import org.jwildfire.create.tina.variation.Linear3DFunc;
import org.jwildfire.create.tina.variation.Variation;
import org.jwildfire.create.tina.variation.VariationFunc;
import org.jwildfire.create.tina.variation.VariationFuncList;
import org.jwildfire.image.Pixel;
import org.jwildfire.image.SimpleHDRImage;
import org.jwildfire.image.SimpleImage;
import org.jwildfire.io.ImageWriter;
import org.jwildfire.swing.ErrorHandler;
import org.jwildfire.swing.ImageFileChooser;
import org.jwildfire.swing.ImagePanel;
import org.jwildfire.swing.MainController;
public class TinaController implements FlameHolder, JobRenderThreadController, ScriptRunnerEnvironment {
private static final double SLIDER_SCALE_PERSPECTIVE = 100.0;
private static final double SLIDER_SCALE_CENTRE = 50.0;
private static final double SLIDER_SCALE_ZOOM = 10.0;
private static final double SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY = 100.0;
private static final double SLIDER_SCALE_GAMMA = 100.0;
private static final double SLIDER_SCALE_FILTER_RADIUS = 100.0;
private static final double SLIDER_SCALE_COLOR = 100.0;
private static final double SLIDER_SCALE_ZPOS = 50.0;
private static final double SLIDER_SCALE_DOF = 100.0;
private static final double SLIDER_SCALE_AMBIENT = 100.0;
private static final double SLIDER_SCALE_PHONGSIZE = 10.0;
private static final double SLIDER_SCALE_LIGHTPOS = 100.0;
private static final double SLIDER_SCALE_BLUR_FALLOFF = 10.0;
private final JPanel centerPanel;
private FlamePanel flamePanel;
private final Prefs prefs;
private final ErrorHandler errorHandler;
boolean gridRefreshing = false;
boolean cmbRefreshing = false;
boolean refreshing = false;
private final List<Job> batchRenderList = new ArrayList<Job>();
public static class NonlinearControlsRow {
private final JComboBox nonlinearVarCmb;
private final JComboBox nonlinearParamsCmb;
private final JTextField nonlinearVarREd;
private final JTextField nonlinearParamsREd;
private final JButton nonlinearVarLeftButton;
private final JButton nonlinearVarRightButton;
private final JButton nonlinearParamsLeftButton;
private final JButton nonlinearParamsRightButton;
public NonlinearControlsRow(JComboBox pNonlinearVarCmb, JComboBox pNonlinearParamsCmb, JTextField pNonlinearVarREd, JTextField pNonlinearParamsREd,
JButton pNonlinearVarLeftButton, JButton pNonlinearVarRightButton, JButton pNonlinearParamsLeftButton, JButton pNonlinearParamsRightButton) {
nonlinearVarCmb = pNonlinearVarCmb;
nonlinearParamsCmb = pNonlinearParamsCmb;
nonlinearVarREd = pNonlinearVarREd;
nonlinearParamsREd = pNonlinearParamsREd;
nonlinearVarLeftButton = pNonlinearVarLeftButton;
nonlinearVarRightButton = pNonlinearVarRightButton;
nonlinearParamsLeftButton = pNonlinearParamsLeftButton;
nonlinearParamsRightButton = pNonlinearParamsRightButton;
}
public void initControls() {
nonlinearVarCmb.removeAllItems();
List<String> nameList = new ArrayList<String>();
nameList.addAll(VariationFuncList.getNameList());
Collections.sort(nameList);
nonlinearVarCmb.addItem(null);
for (String name : nameList) {
nonlinearVarCmb.addItem(name);
}
nonlinearVarCmb.setSelectedIndex(-1);
nonlinearParamsCmb.removeAllItems();
nonlinearParamsCmb.setSelectedIndex(-1);
}
public JComboBox getNonlinearVarCmb() {
return nonlinearVarCmb;
}
public JComboBox getNonlinearParamsCmb() {
return nonlinearParamsCmb;
}
public JTextField getNonlinearVarREd() {
return nonlinearVarREd;
}
public JTextField getNonlinearParamsREd() {
return nonlinearParamsREd;
}
public JButton getNonlinearVarLeftButton() {
return nonlinearVarLeftButton;
}
public JButton getNonlinearVarRightButton() {
return nonlinearVarRightButton;
}
public JButton getNonlinearParamsLeftButton() {
return nonlinearParamsLeftButton;
}
public JButton getNonlinearParamsRightButton() {
return nonlinearParamsRightButton;
}
}
private MainController mainController;
private final JTabbedPane rootTabbedPane;
// script
private final JTextArea scriptTextArea;
// camera, coloring
private final JTextField cameraRollREd;
private final JSlider cameraRollSlider;
private final JTextField cameraPitchREd;
private final JSlider cameraPitchSlider;
private final JTextField cameraYawREd;
private final JSlider cameraYawSlider;
private final JTextField cameraPerspectiveREd;
private final JSlider cameraPerspectiveSlider;
private final JTextField previewQualityREd;
private final JTextField cameraCentreXREd;
private final JSlider cameraCentreXSlider;
private final JTextField cameraCentreYREd;
private final JSlider cameraCentreYSlider;
private final JTextField cameraZoomREd;
private final JSlider cameraZoomSlider;
private final JTextField cameraZPosREd;
private final JSlider cameraZPosSlider;
private final JTextField cameraDOFREd;
private final JSlider cameraDOFSlider;
private final JTextField pixelsPerUnitREd;
private final JSlider pixelsPerUnitSlider;
private final JTextField brightnessREd;
private final JSlider brightnessSlider;
private final JTextField contrastREd;
private final JSlider contrastSlider;
private final JTextField gammaREd;
private final JSlider gammaSlider;
private final JTextField vibrancyREd;
private final JSlider vibrancySlider;
private final JTextField filterRadiusREd;
private final JSlider filterRadiusSlider;
private final JTextField spatialOversampleREd;
private final JSlider spatialOversampleSlider;
private final JTextField colorOversampleREd;
private final JSlider colorOversampleSlider;
private final JTextField bgColorRedREd;
private final JSlider bgColorRedSlider;
private final JTextField bgColorGreenREd;
private final JSlider bgColorGreenSlider;
private final JTextField bgColorBlueREd;
private final JSlider bgColorBlueSlider;
// shading
private final JComboBox shadingCmb;
private final JTextField shadingAmbientREd;
private final JSlider shadingAmbientSlider;
private final JTextField shadingDiffuseREd;
private final JSlider shadingDiffuseSlider;
private final JTextField shadingPhongREd;
private final JSlider shadingPhongSlider;
private final JTextField shadingPhongSizeREd;
private final JSlider shadingPhongSizeSlider;
private final JComboBox shadingLightCmb;
private final JTextField shadingLightXREd;
private final JSlider shadingLightXSlider;
private final JTextField shadingLightYREd;
private final JSlider shadingLightYSlider;
private final JTextField shadingLightZREd;
private final JSlider shadingLightZSlider;
private final JTextField shadingLightRedREd;
private final JSlider shadingLightRedSlider;
private final JTextField shadingLightGreenREd;
private final JSlider shadingLightGreenSlider;
private final JTextField shadingLightBlueREd;
private final JSlider shadingLightBlueSlider;
private final JTextField shadingBlurRadiusREd;
private final JSlider shadingBlurRadiusSlider;
private final JTextField shadingBlurFadeREd;
private final JSlider shadingBlurFadeSlider;
private final JTextField shadingBlurFallOffREd;
private final JSlider shadingBlurFallOffSlider;
// palette -> create
private final JTextField paletteRandomPointsREd;
private final JPanel paletteImgPanel;
private ImagePanel palettePanel;
// palette -> transform
private final JTextField paletteShiftREd;
private final JSlider paletteShiftSlider;
private final JTextField paletteRedREd;
private final JSlider paletteRedSlider;
private final JTextField paletteGreenREd;
private final JSlider paletteGreenSlider;
private final JTextField paletteBlueREd;
private final JSlider paletteBlueSlider;
private final JTextField paletteHueREd;
private final JSlider paletteHueSlider;
private final JTextField paletteSaturationREd;
private final JSlider paletteSaturationSlider;
private final JTextField paletteContrastREd;
private final JSlider paletteContrastSlider;
private final JTextField paletteGammaREd;
private final JSlider paletteGammaSlider;
private final JTextField paletteBrightnessREd;
private final JSlider paletteBrightnessSlider;
private final JTextField paletteSwapRGBREd;
private final JSlider paletteSwapRGBSlider;
// Batch render
private final JTable renderBatchJobsTable;
private final JProgressBar batchRenderJobProgressBar;
private final JProgressBar batchRenderTotalProgressBar;
// Transformations
private final JToggleButton affineScaleXButton;
private final JToggleButton affineScaleYButton;
private final JTable transformationsTable;
private final JButton affineResetTransformButton;
private final JTextField affineC00REd;
private final JTextField affineC01REd;
private final JTextField affineC10REd;
private final JTextField affineC11REd;
private final JTextField affineC20REd;
private final JTextField affineC21REd;
private final JTextField affineRotateAmountREd;
private final JTextField affineScaleAmountREd;
private final JTextField affineMoveAmountREd;
private final JButton affineRotateLeftButton;
private final JButton affineRotateRightButton;
private final JButton affineEnlargeButton;
private final JButton affineShrinkButton;
private final JButton affineMoveUpButton;
private final JButton affineMoveLeftButton;
private final JButton affineMoveRightButton;
private final JButton affineMoveDownButton;
private final JButton affineFlipHorizontalButton;
private final JButton affineFlipVerticalButton;
private final JButton addTransformationButton;
private final JButton duplicateTransformationButton;
private final JButton deleteTransformationButton;
private final JButton addFinalTransformationButton;
private final JButton transformationWeightLeftButton;
private final JButton transformationWeightRightButton;
private final JToggleButton affineEditPostTransformButton;
private final JToggleButton affineEditPostTransformSmallButton;
private final JButton mouseEditZoomInButton;
private final JButton mouseEditZoomOutButton;
private final JToggleButton toggleTrianglesButton;
private final JToggleButton toggleDarkTrianglesButton;
// Random batch
private final JPanel randomBatchPanel;
private JScrollPane randomBatchScrollPane = null;
private final JCheckBox randomPostTransformCheckBox;
private final JCheckBox randomSymmetryCheckBox;
// Nonlinear transformations
private final NonlinearControlsRow[] nonlinearControlsRows;
// Color
private final JTextField xFormColorREd;
private final JSlider xFormColorSlider;
private final JTextField xFormSymmetryREd;
private final JSlider xFormSymmetrySlider;
private final JTextField xFormOpacityREd;
private final JSlider xFormOpacitySlider;
private final JComboBox xFormDrawModeCmb;
// Relative weights
private final JTable relWeightsTable;
private final JButton relWeightsLeftButton;
private final JButton relWeightsRightButton;
// Morphing
private final JButton setMorphFlame1Button;
private final JButton setMorphFlame2Button;
private final JTextField morphFrameREd;
private final JTextField morphFramesREd;
private final JCheckBox morphCheckBox;
private final JSlider morphFrameSlider;
private final JButton importMorphedFlameButton;
// Animate
private final JTextField animateOutputREd;
private final JTextField animateFramesREd;
private final JComboBox animateGlobalScriptCmb;
private final JComboBox animateXFormScriptCmb;
private final JComboBox animateLightScriptCmb;
private final JButton animationGenerateButton;
// misc
private final JComboBox zStyleCmb;
private Flame _currFlame;
private Flame morphFlame1, morphFlame2;
private boolean noRefresh;
private final ProgressUpdater mainProgressUpdater;
private final ProgressUpdater jobProgressUpdater;
private final JTable createPaletteColorsTable;
private List<RGBColor> paletteKeyFrames;
// mouse dragging
private final JToggleButton mouseTransformMoveButton;
private final JToggleButton mouseTransformRotateButton;
private final JToggleButton mouseTransformScaleButton;
private final JToggleButton mouseTransformSlowButton;
//
private final JButton batchRenderAddFilesButton;
private final JButton batchRenderFilesMoveDownButton;
private final JButton batchRenderFilesMoveUpButton;
private final JButton batchRenderFilesRemoveButton;
private final JButton batchRenderFilesRemoveAllButton;
private final JButton batchRenderStartButton;
public TinaController(ErrorHandler pErrorHandler, Prefs pPrefs, JPanel pCenterPanel, JTextField pCameraRollREd, JSlider pCameraRollSlider, JTextField pCameraPitchREd,
JSlider pCameraPitchSlider, JTextField pCameraYawREd, JSlider pCameraYawSlider, JTextField pCameraPerspectiveREd, JSlider pCameraPerspectiveSlider,
JTextField pPreviewQualityREd, JTextField pCameraCentreXREd, JSlider pCameraCentreXSlider, JTextField pCameraCentreYREd,
JSlider pCameraCentreYSlider, JTextField pCameraZoomREd, JSlider pCameraZoomSlider, JTextField pCameraZPosREd, JSlider pCameraZPosSlider,
JTextField pCameraDOFREd, JSlider pCameraDOFSlider, JTextField pPixelsPerUnitREd, JSlider pPixelsPerUnitSlider,
JTextField pBrightnessREd, JSlider pBrightnessSlider, JTextField pContrastREd, JSlider pContrastSlider, JTextField pGammaREd, JSlider pGammaSlider,
JTextField pVibrancyREd, JSlider pVibrancySlider, JTextField pFilterRadiusREd, JSlider pFilterRadiusSlider, JTextField pSpatialOversampleREd,
JSlider pSpatialOversampleSlider, JTextField pBGColorRedREd, JSlider pBGColorRedSlider, JTextField pBGColorGreenREd, JSlider pBGColorGreenSlider, JTextField pBGColorBlueREd,
JSlider pBGColorBlueSlider, JTextField pPaletteRandomPointsREd, JPanel pPaletteImgPanel, JTextField pPaletteShiftREd, JSlider pPaletteShiftSlider,
JTextField pPaletteRedREd, JSlider pPaletteRedSlider, JTextField pPaletteGreenREd, JSlider pPaletteGreenSlider, JTextField pPaletteBlueREd,
JSlider pPaletteBlueSlider, JTextField pPaletteHueREd, JSlider pPaletteHueSlider, JTextField pPaletteSaturationREd, JSlider pPaletteSaturationSlider,
JTextField pPaletteContrastREd, JSlider pPaletteContrastSlider, JTextField pPaletteGammaREd, JSlider pPaletteGammaSlider, JTextField pPaletteBrightnessREd,
JSlider pPaletteBrightnessSlider, JTextField pPaletteSwapRGBREd, JSlider pPaletteSwapRGBSlider, JTable pTransformationsTable, JTextField pAffineC00REd,
JTextField pAffineC01REd, JTextField pAffineC10REd, JTextField pAffineC11REd, JTextField pAffineC20REd, JTextField pAffineC21REd,
JTextField pAffineRotateAmountREd, JTextField pAffineScaleAmountREd, JTextField pAffineMoveAmountREd, JButton pAffineRotateLeftButton,
JButton pAffineRotateRightButton, JButton pAffineEnlargeButton, JButton pAffineShrinkButton, JButton pAffineMoveUpButton, JButton pAffineMoveLeftButton,
JButton pAffineMoveRightButton, JButton pAffineMoveDownButton, JButton pAddTransformationButton, JButton pDuplicateTransformationButton,
JButton pDeleteTransformationButton, JButton pAddFinalTransformationButton, JPanel pRandomBatchPanel, NonlinearControlsRow[] pNonlinearControlsRows,
JTextField pXFormColorREd, JSlider pXFormColorSlider, JTextField pXFormSymmetryREd, JSlider pXFormSymmetrySlider, JTextField pXFormOpacityREd,
JSlider pXFormOpacitySlider, JComboBox pXFormDrawModeCmb, JTable pRelWeightsTable, JButton pRelWeightsLeftButton, JButton pRelWeightsRightButton,
JButton pTransformationWeightLeftButton, JButton pTransformationWeightRightButton, JComboBox pZStyleCmb, JButton pSetMorphFlame1Button,
JButton pSetMorphFlame2Button, JTextField pMorphFrameREd, JTextField pMorphFramesREd, JCheckBox pMorphCheckBox, JSlider pMorphFrameSlider,
JButton pImportMorphedFlameButton, JTextField pAnimateOutputREd, JTextField pAnimateFramesREd, JComboBox pAnimateGlobalScriptCmb, JButton pAnimationGenerateButton,
JComboBox pAnimateXFormScriptCmb, JToggleButton pMouseTransformMoveButton, JToggleButton pMouseTransformRotateButton, JToggleButton pMouseTransformScaleButton,
JToggleButton pAffineEditPostTransformButton, JToggleButton pAffineEditPostTransformSmallButton, JButton pMouseEditZoomInButton, JButton pMouseEditZoomOutButton,
JToggleButton pToggleTrianglesButton, ProgressUpdater pMainProgressUpdater, JCheckBox pRandomPostTransformCheckBox, JCheckBox pRandomSymmetryCheckBox,
JButton pAffineResetTransformButton, JTextField pColorOversampleREd, JSlider pColorOversampleSlider, JTable pCreatePaletteColorsTable,
JComboBox pShadingCmb, JTextField pShadingAmbientREd, JSlider pShadingAmbientSlider, JTextField pShadingDiffuseREd, JSlider pShadingDiffuseSlider,
JTextField pShadingPhongREd, JSlider pShadingPhongSlider, JTextField pShadingPhongSizeREd, JSlider pShadingPhongSizeSlider,
JComboBox pShadingLightCmb, JTextField pShadingLightXREd, JSlider pShadingLightXSlider, JTextField pShadingLightYREd, JSlider pShadingLightYSlider,
JTextField pShadingLightZREd, JSlider pShadingLightZSlider, JTextField pShadingLightRedREd, JSlider pShadingLightRedSlider,
JTextField pShadingLightGreenREd, JSlider pShadingLightGreenSlider, JTextField pShadingLightBlueREd, JSlider pShadingLightBlueSlider,
JToggleButton pMouseTransformSlowButton, JTable pRenderBatchJobsTable, JProgressBar pBatchRenderJobProgressBar,
JProgressBar pBatchRenderTotalProgressBar, ProgressUpdater pJobProgressUpdater, JButton pBatchRenderAddFilesButton,
JButton pBatchRenderFilesMoveDownButton, JButton pBatchRenderFilesMoveUpButton, JButton pBatchRenderFilesRemoveButton,
JButton pBatchRenderFilesRemoveAllButton, JButton pBatchRenderStartButton, JTabbedPane pRootTabbedPane, JButton pAffineFlipHorizontalButton,
JButton pAffineFlipVerticalButton, JComboBox pAnimateLightScriptCmb, JToggleButton pToggleDarkTrianglesButton,
JTextField pShadingBlurRadiusREd, JSlider pShadingBlurRadiusSlider, JTextField pShadingBlurFadeREd, JSlider pShadingBlurFadeSlider,
JTextField pShadingBlurFallOffREd, JSlider pShadingBlurFallOffSlider, JTextArea pScriptTextArea, JToggleButton pAffineScaleXButton,
JToggleButton pAffineScaleYButton) {
errorHandler = pErrorHandler;
prefs = pPrefs;
centerPanel = pCenterPanel;
cameraRollREd = pCameraRollREd;
cameraRollSlider = pCameraRollSlider;
cameraPitchREd = pCameraPitchREd;
cameraPitchSlider = pCameraPitchSlider;
cameraYawREd = pCameraYawREd;
cameraYawSlider = pCameraYawSlider;
cameraPerspectiveREd = pCameraPerspectiveREd;
cameraPerspectiveSlider = pCameraPerspectiveSlider;
previewQualityREd = pPreviewQualityREd;
cameraCentreXREd = pCameraCentreXREd;
cameraCentreXSlider = pCameraCentreXSlider;
cameraCentreYREd = pCameraCentreYREd;
cameraCentreYSlider = pCameraCentreYSlider;
cameraZoomREd = pCameraZoomREd;
cameraZoomSlider = pCameraZoomSlider;
cameraZPosREd = pCameraZPosREd;
cameraZPosSlider = pCameraZPosSlider;
cameraDOFREd = pCameraDOFREd;
cameraDOFSlider = pCameraDOFSlider;
pixelsPerUnitREd = pPixelsPerUnitREd;
pixelsPerUnitSlider = pPixelsPerUnitSlider;
brightnessREd = pBrightnessREd;
brightnessSlider = pBrightnessSlider;
contrastREd = pContrastREd;
contrastSlider = pContrastSlider;
gammaREd = pGammaREd;
gammaSlider = pGammaSlider;
vibrancyREd = pVibrancyREd;
vibrancySlider = pVibrancySlider;
filterRadiusREd = pFilterRadiusREd;
filterRadiusSlider = pFilterRadiusSlider;
spatialOversampleREd = pSpatialOversampleREd;
spatialOversampleSlider = pSpatialOversampleSlider;
colorOversampleREd = pColorOversampleREd;
colorOversampleSlider = pColorOversampleSlider;
bgColorRedREd = pBGColorRedREd;
bgColorRedSlider = pBGColorRedSlider;
bgColorGreenREd = pBGColorGreenREd;
bgColorGreenSlider = pBGColorGreenSlider;
bgColorBlueREd = pBGColorBlueREd;
bgColorBlueSlider = pBGColorBlueSlider;
paletteRandomPointsREd = pPaletteRandomPointsREd;
paletteImgPanel = pPaletteImgPanel;
paletteShiftREd = pPaletteShiftREd;
paletteShiftSlider = pPaletteShiftSlider;
paletteRedREd = pPaletteRedREd;
paletteRedSlider = pPaletteRedSlider;
paletteGreenREd = pPaletteGreenREd;
paletteGreenSlider = pPaletteGreenSlider;
paletteBlueREd = pPaletteBlueREd;
paletteBlueSlider = pPaletteBlueSlider;
paletteHueREd = pPaletteHueREd;
paletteHueSlider = pPaletteHueSlider;
paletteSaturationREd = pPaletteSaturationREd;
paletteSaturationSlider = pPaletteSaturationSlider;
paletteContrastREd = pPaletteContrastREd;
paletteContrastSlider = pPaletteContrastSlider;
paletteGammaREd = pPaletteGammaREd;
paletteGammaSlider = pPaletteGammaSlider;
paletteBrightnessREd = pPaletteBrightnessREd;
paletteBrightnessSlider = pPaletteBrightnessSlider;
paletteSwapRGBREd = pPaletteSwapRGBREd;
paletteSwapRGBSlider = pPaletteSwapRGBSlider;
transformationsTable = pTransformationsTable;
affineC00REd = pAffineC00REd;
affineC01REd = pAffineC01REd;
affineC10REd = pAffineC10REd;
affineC11REd = pAffineC11REd;
affineC20REd = pAffineC20REd;
affineC21REd = pAffineC21REd;
affineRotateAmountREd = pAffineRotateAmountREd;
affineScaleAmountREd = pAffineScaleAmountREd;
affineMoveAmountREd = pAffineMoveAmountREd;
affineRotateLeftButton = pAffineRotateLeftButton;
affineRotateRightButton = pAffineRotateRightButton;
affineEnlargeButton = pAffineEnlargeButton;
affineShrinkButton = pAffineShrinkButton;
affineMoveUpButton = pAffineMoveUpButton;
affineMoveLeftButton = pAffineMoveLeftButton;
affineMoveRightButton = pAffineMoveRightButton;
affineMoveDownButton = pAffineMoveDownButton;
affineFlipHorizontalButton = pAffineFlipHorizontalButton;
affineFlipVerticalButton = pAffineFlipVerticalButton;
addTransformationButton = pAddTransformationButton;
duplicateTransformationButton = pDuplicateTransformationButton;
deleteTransformationButton = pDeleteTransformationButton;
addFinalTransformationButton = pAddFinalTransformationButton;
affineEditPostTransformButton = pAffineEditPostTransformButton;
affineEditPostTransformSmallButton = pAffineEditPostTransformSmallButton;
affineScaleXButton = pAffineScaleXButton;
affineScaleYButton = pAffineScaleYButton;
mouseEditZoomInButton = pMouseEditZoomInButton;
mouseEditZoomOutButton = pMouseEditZoomOutButton;
randomBatchPanel = pRandomBatchPanel;
nonlinearControlsRows = pNonlinearControlsRows;
xFormColorREd = pXFormColorREd;
xFormColorSlider = pXFormColorSlider;
xFormSymmetryREd = pXFormSymmetryREd;
xFormSymmetrySlider = pXFormSymmetrySlider;
xFormOpacityREd = pXFormOpacityREd;
xFormOpacitySlider = pXFormOpacitySlider;
xFormDrawModeCmb = pXFormDrawModeCmb;
relWeightsTable = pRelWeightsTable;
relWeightsLeftButton = pRelWeightsLeftButton;
relWeightsRightButton = pRelWeightsRightButton;
transformationWeightLeftButton = pTransformationWeightLeftButton;
transformationWeightRightButton = pTransformationWeightRightButton;
zStyleCmb = pZStyleCmb;
setMorphFlame1Button = pSetMorphFlame1Button;
setMorphFlame2Button = pSetMorphFlame2Button;
morphFrameREd = pMorphFrameREd;
morphFramesREd = pMorphFramesREd;
morphCheckBox = pMorphCheckBox;
morphFrameSlider = pMorphFrameSlider;
importMorphedFlameButton = pImportMorphedFlameButton;
animateOutputREd = pAnimateOutputREd;
animateFramesREd = pAnimateFramesREd;
animateGlobalScriptCmb = pAnimateGlobalScriptCmb;
animateXFormScriptCmb = pAnimateXFormScriptCmb;
animateLightScriptCmb = pAnimateLightScriptCmb;
animationGenerateButton = pAnimationGenerateButton;
mouseTransformMoveButton = pMouseTransformMoveButton;
mouseTransformRotateButton = pMouseTransformRotateButton;
mouseTransformScaleButton = pMouseTransformScaleButton;
toggleTrianglesButton = pToggleTrianglesButton;
toggleDarkTrianglesButton = pToggleDarkTrianglesButton;
mainProgressUpdater = pMainProgressUpdater;
jobProgressUpdater = pJobProgressUpdater;
randomPostTransformCheckBox = pRandomPostTransformCheckBox;
randomSymmetryCheckBox = pRandomSymmetryCheckBox;
affineResetTransformButton = pAffineResetTransformButton;
createPaletteColorsTable = pCreatePaletteColorsTable;
shadingCmb = pShadingCmb;
shadingAmbientREd = pShadingAmbientREd;
shadingAmbientSlider = pShadingAmbientSlider;
shadingDiffuseREd = pShadingDiffuseREd;
shadingDiffuseSlider = pShadingDiffuseSlider;
shadingPhongREd = pShadingPhongREd;
shadingPhongSlider = pShadingPhongSlider;
shadingPhongSizeREd = pShadingPhongSizeREd;
shadingPhongSizeSlider = pShadingPhongSizeSlider;
shadingLightCmb = pShadingLightCmb;
shadingLightXREd = pShadingLightXREd;
shadingLightXSlider = pShadingLightXSlider;
shadingLightYREd = pShadingLightYREd;
shadingLightYSlider = pShadingLightYSlider;
shadingLightZREd = pShadingLightZREd;
shadingLightZSlider = pShadingLightZSlider;
shadingLightRedREd = pShadingLightRedREd;
shadingLightRedSlider = pShadingLightRedSlider;
shadingLightGreenREd = pShadingLightGreenREd;
shadingLightGreenSlider = pShadingLightGreenSlider;
shadingLightBlueREd = pShadingLightBlueREd;
shadingLightBlueSlider = pShadingLightBlueSlider;
shadingBlurRadiusREd = pShadingBlurRadiusREd;
shadingBlurRadiusSlider = pShadingBlurRadiusSlider;
shadingBlurFadeREd = pShadingBlurFadeREd;
shadingBlurFadeSlider = pShadingBlurFadeSlider;
shadingBlurFallOffREd = pShadingBlurFallOffREd;
shadingBlurFallOffSlider = pShadingBlurFallOffSlider;
mouseTransformSlowButton = pMouseTransformSlowButton;
renderBatchJobsTable = pRenderBatchJobsTable;
batchRenderJobProgressBar = pBatchRenderJobProgressBar;
batchRenderTotalProgressBar = pBatchRenderTotalProgressBar;
batchRenderAddFilesButton = pBatchRenderAddFilesButton;
batchRenderFilesMoveDownButton = pBatchRenderFilesMoveDownButton;
batchRenderFilesMoveUpButton = pBatchRenderFilesMoveUpButton;
batchRenderFilesRemoveButton = pBatchRenderFilesRemoveButton;
batchRenderFilesRemoveAllButton = pBatchRenderFilesRemoveAllButton;
batchRenderStartButton = pBatchRenderStartButton;
rootTabbedPane = pRootTabbedPane;
scriptTextArea = pScriptTextArea;
animateFramesREd.setText(String.valueOf(prefs.getTinaRenderMovieFrames()));
previewQualityREd.setText(String.valueOf(prefs.getTinaRenderRealtimeQuality()));
refreshPaletteColorsTable();
refreshRenderBatchJobsTable();
initDefaultScript();
enableControls();
enableShadingUI();
enableXFormControls(null);
}
private void initDefaultScript() {
scriptTextArea.setText("import org.jwildfire.create.tina.base.Flame;\r\n" +
"import org.jwildfire.create.tina.base.XForm;\r\n" +
"import org.jwildfire.create.tina.variation.VariationFunc;\r\n" +
"import org.jwildfire.create.tina.script.ScriptRunnerEnvironment;\r\n" +
"\r\n" +
"import org.jwildfire.create.tina.variation.BubbleFunc;\r\n" +
"import org.jwildfire.create.tina.variation.HemisphereFunc;\r\n" +
"import org.jwildfire.create.tina.variation.Julia3DFunc;\r\n" +
"import org.jwildfire.create.tina.variation.LinearFunc;\r\n" +
"import org.jwildfire.create.tina.variation.PreBlurFunc;\r\n" +
"import org.jwildfire.create.tina.variation.SpirographFunc;\r\n" +
"import org.jwildfire.create.tina.variation.SplitsFunc;\r\n" +
"import org.jwildfire.create.tina.variation.ZTranslateFunc;\r\n" +
"\r\n" +
"// Bases on the Soft Julian Script by AsaLegault\r\n" +
"// http://asalegault.deviantart.com/art/Cloud-Julian-Script-84635709\r\n" +
"public void run(ScriptRunnerEnvironment pEnv) throws Exception {\r\n" +
" Flame currFlame = pEnv.getCurrFlame();\r\n" +
" if(currFlame==null) {\r\n" +
" throw new Exception(\"Please select a flame at first\");\r\n" +
" }\r\n" +
" // First transform\r\n" +
" {\r\n" +
" VariationFunc varFunc = new Julia3DFunc();\r\n" +
" varFunc.setParameter(\"power\", -2);\r\n" +
" XForm xForm = new XForm();\r\n" +
" xForm.addVariation(1.0, varFunc);\r\n" +
" xForm.setWeight(2.0);\r\n" +
" xForm.setColor(0.0);\r\n" +
" xForm.setColorSymmetry(0.01);\r\n" +
" xForm.setCoeff20(0.3); //o0 \r\n" +
" currFlame.getXForms().add(xForm);\r\n" +
" }\r\n" +
" // Second transform\r\n" +
" {\r\n" +
" XForm xForm = new XForm();\r\n" +
" xForm.addVariation(0.1, new BubbleFunc());\r\n" +
" xForm.addVariation(1.0, new PreBlurFunc());\r\n" +
" VariationFunc varFunc=new SpirographFunc();\r\n" +
" varFunc.setParameter(\"a\", 7.0);\r\n" +
" varFunc.setParameter(\"b\", 5.0);\r\n" +
" varFunc.setParameter(\"d\", 0.0);\r\n" +
" varFunc.setParameter(\"c1\", 5.0);\r\n" +
" varFunc.setParameter(\"c2\", -5.0);\r\n" +
" varFunc.setParameter(\"tmin\", 1.0);\r\n" +
" varFunc.setParameter(\"tmax\", 50.0);\r\n" +
" varFunc.setParameter(\"ymin\", -1.0);\r\n" +
" varFunc.setParameter(\"ymax\", 0.1);\r\n" +
" xForm.addVariation(0.03, varFunc);\r\n" +
" xForm.setWeight(1.0);\r\n" +
" xForm.setColor(0.844);\r\n" +
" currFlame.getXForms().add(xForm); \r\n" +
" }\r\n" +
" // Third transform\r\n" +
" {\r\n" +
" XForm xForm = new XForm();\r\n" +
" xForm.addVariation(0.18, new HemisphereFunc());\r\n" +
" xForm.addVariation(1.0, new PreBlurFunc());\r\n" +
" xForm.addVariation(-0.025, new ZTranslateFunc());\r\n" +
" xForm.setWeight(0.5);\r\n" +
" xForm.setColor(0.0);\r\n" +
" currFlame.getXForms().add(xForm); \r\n" +
" }\r\n" +
" //A fourth transform can be very useful when trying\r\n" +
" //to fill in the bubbles....But i'll let you figure\r\n" +
" //that out.//\r\n" +
" // ...\r\n" +
" // Final settings \r\n" +
" currFlame.setCamRoll(2.0);\r\n" +
" currFlame.setCamPitch(46.0);\r\n" +
" currFlame.setCamYaw(0.0);\r\n" +
" currFlame.setCamPerspective(0.30);\r\n" +
" currFlame.setPixelsPerUnit(96);\r\n" +
" // Refresh the UI\r\n" +
" pEnv.refreshUI();\r\n" +
"}\r\n");
}
private static boolean dragging = false;
private FlamePanel getFlamePanel() {
if (flamePanel == null) {
int width = centerPanel.getWidth();
int height = centerPanel.getHeight();
SimpleImage img = new SimpleImage(width, height);
img.fillBackground(0, 0, 0);
flamePanel = new FlamePanel(img, 0, 0, centerPanel.getWidth(), this, toggleTrianglesButton);
flamePanel.setRenderWidth(prefs.getTinaRenderImageWidth());
flamePanel.setRenderHeight(prefs.getTinaRenderImageHeight());
flamePanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
flamePanel_mouseDragged(e);
dragging = true;
}
});
flamePanel.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
flamePanel_mousePressed(e);
}
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
flamePanel_mouseClicked(e);
}
@Override
public void mouseReleased(MouseEvent e) {
if (dragging) {
refreshFlameImage(false);
}
dragging = false;
}
});
flamePanel.setSelectedXForm(getCurrXForm());
centerPanel.remove(0);
centerPanel.add(flamePanel, BorderLayout.CENTER);
centerPanel.getParent().validate();
centerPanel.repaint();
}
return flamePanel;
}
private ImagePanel getPalettePanel() {
if (palettePanel == null) {
int width = paletteImgPanel.getWidth();
int height = paletteImgPanel.getHeight();
SimpleImage img = new SimpleImage(width, height);
img.fillBackground(0, 0, 0);
palettePanel = new ImagePanel(img, 0, 0, paletteImgPanel.getWidth());
paletteImgPanel.add(palettePanel, BorderLayout.CENTER);
paletteImgPanel.getParent().validate();
}
return palettePanel;
}
public void refreshFlameImage(boolean pMouseDown) {
refreshFlameImage((AffineZStyle) zStyleCmb.getSelectedItem(), true, pMouseDown);
}
private Flame lastMorphedFlame = null;
private int lastMorphedFrame = -1;
@Override
public Flame getCurrFlame() {
if (morphFlame1 != null && morphFlame2 != null && morphCheckBox.isSelected()) {
int frame = Integer.parseInt(morphFrameREd.getText());
if (frame != lastMorphedFrame || lastMorphedFlame == null) {
lastMorphedFrame = frame;
lastMorphedFlame = FlameMorphService.morphFlames(morphFlame1, morphFlame2, frame, Integer.parseInt(morphFramesREd.getText()));
}
return lastMorphedFlame;
}
else {
return _currFlame;
}
}
public void refreshFlameImage(AffineZStyle pAffineZStyle, boolean pQuickRender, boolean pMouseDown) {
FlamePanel imgPanel = getFlamePanel();
Rectangle bounds = imgPanel.getImageBounds();
int renderScale = pQuickRender && pMouseDown ? 2 : 1;
int width = bounds.width / renderScale;
int height = bounds.height / renderScale;
if (width >= 16 && height >= 16) {
SimpleImage img = new SimpleImage(width, height);
Flame flame = getCurrFlame();
if (flame != null) {
double oldSpatialFilterRadius = flame.getSpatialFilterRadius();
int oldSpatialOversample = flame.getSpatialOversample();
int oldColorOversample = flame.getColorOversample();
double oldSampleDensity = flame.getSampleDensity();
try {
double wScl = (double) img.getImageWidth() / (double) flame.getWidth();
double hScl = (double) img.getImageHeight() / (double) flame.getHeight();
flame.setPixelsPerUnit((wScl + hScl) * 0.5 * flame.getPixelsPerUnit());
flame.setWidth(img.getImageWidth());
flame.setHeight(img.getImageHeight());
FlameRenderer renderer = new FlameRenderer(flame, prefs);
if (pQuickRender) {
renderer.setProgressUpdater(null);
flame.setSampleDensity(Integer.parseInt(previewQualityREd.getText()));
flame.setSpatialFilterRadius(0.0);
flame.setSpatialOversample(1);
flame.setColorOversample(1);
}
else {
renderer.setProgressUpdater(mainProgressUpdater);
flame.setSampleDensity(prefs.getTinaRenderPreviewQuality());
flame.setSpatialFilterRadius(prefs.getTinaRenderPreviewFilterRadius());
flame.setSpatialOversample(prefs.getTinaRenderPreviewSpatialOversample());
flame.setColorOversample(prefs.getTinaRenderPreviewColorOversample());
}
renderer.setAffineZStyle(pAffineZStyle);
renderer.setRenderScale(renderScale);
renderer.renderFlame(img, null);
}
finally {
flame.setSpatialFilterRadius(oldSpatialFilterRadius);
flame.setSpatialOversample(oldSpatialOversample);
flame.setColorOversample(oldColorOversample);
flame.setSampleDensity(oldSampleDensity);
}
}
imgPanel.setImage(img);
}
centerPanel.repaint();
}
@Override
public void refreshUI() {
noRefresh = true;
try {
Flame currFlame = getCurrFlame();
cameraRollREd.setText(Tools.doubleToString(currFlame.getCamRoll()));
cameraRollSlider.setValue(Tools.FTOI(currFlame.getCamRoll()));
cameraPitchREd.setText(Tools.doubleToString(currFlame.getCamPitch()));
cameraPitchSlider.setValue(Tools.FTOI(currFlame.getCamPitch()));
cameraYawREd.setText(Tools.doubleToString(currFlame.getCamYaw()));
cameraYawSlider.setValue(Tools.FTOI(currFlame.getCamYaw()));
cameraPerspectiveREd.setText(Tools.doubleToString(currFlame.getCamPerspective()));
cameraPerspectiveSlider.setValue(Tools.FTOI(currFlame.getCamPerspective() * SLIDER_SCALE_PERSPECTIVE));
cameraCentreXREd.setText(Tools.doubleToString(currFlame.getCentreX()));
cameraCentreXSlider.setValue(Tools.FTOI(currFlame.getCentreX() * SLIDER_SCALE_CENTRE));
cameraCentreYREd.setText(Tools.doubleToString(currFlame.getCentreY()));
cameraCentreYSlider.setValue(Tools.FTOI(currFlame.getCentreY() * SLIDER_SCALE_CENTRE));
cameraZoomREd.setText(Tools.doubleToString(currFlame.getCamZoom()));
cameraZoomSlider.setValue(Tools.FTOI(currFlame.getCamZoom() * SLIDER_SCALE_ZOOM));
cameraZPosREd.setText(Tools.doubleToString(currFlame.getCamZ()));
cameraZPosSlider.setValue(Tools.FTOI(currFlame.getCamZ() * SLIDER_SCALE_ZPOS));
cameraDOFREd.setText(Tools.doubleToString(currFlame.getCamDOF()));
cameraDOFSlider.setValue(Tools.FTOI(currFlame.getCamDOF() * SLIDER_SCALE_DOF));
pixelsPerUnitREd.setText(Tools.doubleToString(currFlame.getPixelsPerUnit()));
pixelsPerUnitSlider.setValue(Tools.FTOI(currFlame.getPixelsPerUnit()));
brightnessREd.setText(Tools.doubleToString(currFlame.getBrightness()));
brightnessSlider.setValue(Tools.FTOI(currFlame.getBrightness() * SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY));
contrastREd.setText(Tools.doubleToString(currFlame.getContrast()));
contrastSlider.setValue(Tools.FTOI(currFlame.getContrast() * SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY));
vibrancyREd.setText(Tools.doubleToString(currFlame.getVibrancy()));
vibrancySlider.setValue(Tools.FTOI(currFlame.getVibrancy() * SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY));
gammaREd.setText(Tools.doubleToString(currFlame.getGamma()));
gammaSlider.setValue(Tools.FTOI(currFlame.getGamma() * SLIDER_SCALE_GAMMA));
filterRadiusREd.setText(Tools.doubleToString(currFlame.getSpatialFilterRadius()));
filterRadiusSlider.setValue(Tools.FTOI(currFlame.getSpatialFilterRadius() * SLIDER_SCALE_FILTER_RADIUS));
spatialOversampleREd.setText(String.valueOf(currFlame.getSpatialOversample()));
spatialOversampleSlider.setValue(currFlame.getSpatialOversample());
colorOversampleREd.setText(String.valueOf(currFlame.getColorOversample()));
colorOversampleSlider.setValue(currFlame.getColorOversample());
bgColorRedREd.setText(String.valueOf(currFlame.getBGColorRed()));
bgColorRedSlider.setValue(currFlame.getBGColorRed());
bgColorGreenREd.setText(String.valueOf(currFlame.getBGColorGreen()));
bgColorGreenSlider.setValue(currFlame.getBGColorGreen());
bgColorBlueREd.setText(String.valueOf(currFlame.getBGColorBlue()));
bgColorBlueSlider.setValue(currFlame.getBGColorBlue());
gridRefreshing = true;
try {
refreshTransformationsTable();
}
finally {
gridRefreshing = false;
}
transformationTableClicked();
shadingLightCmb.setSelectedIndex(0);
refreshShadingUI();
enableShadingUI();
// refreshFlameImage();
refreshPaletteUI(currFlame.getPalette());
}
finally {
noRefresh = false;
}
}
private void refreshShadingUI() {
Flame currFlame = getCurrFlame();
ShadingInfo shadingInfo = currFlame != null ? currFlame.getShadingInfo() : null;
boolean pseudo3DEnabled;
boolean blurEnabled;
if (shadingInfo != null) {
shadingCmb.setSelectedItem(shadingInfo.getShading());
pseudo3DEnabled = shadingInfo.getShading().equals(Shading.PSEUDO3D);
blurEnabled = shadingInfo.getShading().equals(Shading.BLUR);
}
else {
shadingCmb.setSelectedIndex(0);
pseudo3DEnabled = false;
blurEnabled = false;
}
if (pseudo3DEnabled) {
shadingAmbientREd.setText(Tools.doubleToString(shadingInfo.getAmbient()));
shadingAmbientSlider.setValue(Tools.FTOI(shadingInfo.getAmbient() * SLIDER_SCALE_AMBIENT));
shadingDiffuseREd.setText(Tools.doubleToString(shadingInfo.getDiffuse()));
shadingDiffuseSlider.setValue(Tools.FTOI(shadingInfo.getDiffuse() * SLIDER_SCALE_AMBIENT));
shadingPhongREd.setText(Tools.doubleToString(shadingInfo.getPhong()));
shadingPhongSlider.setValue(Tools.FTOI(shadingInfo.getPhong() * SLIDER_SCALE_AMBIENT));
shadingPhongSizeREd.setText(Tools.doubleToString(shadingInfo.getPhongSize()));
shadingPhongSizeSlider.setValue(Tools.FTOI(shadingInfo.getPhongSize() * SLIDER_SCALE_PHONGSIZE));
int cIdx = shadingLightCmb.getSelectedIndex();
shadingLightXREd.setText(Tools.doubleToString(shadingInfo.getLightPosX()[cIdx]));
shadingLightXSlider.setValue(Tools.FTOI(shadingInfo.getLightPosX()[cIdx] * SLIDER_SCALE_LIGHTPOS));
shadingLightYREd.setText(Tools.doubleToString(shadingInfo.getLightPosY()[cIdx]));
shadingLightYSlider.setValue(Tools.FTOI(shadingInfo.getLightPosY()[cIdx] * SLIDER_SCALE_LIGHTPOS));
shadingLightZREd.setText(Tools.doubleToString(shadingInfo.getLightPosZ()[cIdx]));
shadingLightZSlider.setValue(Tools.FTOI(shadingInfo.getLightPosZ()[cIdx] * SLIDER_SCALE_LIGHTPOS));
shadingLightRedREd.setText(String.valueOf(shadingInfo.getLightRed()[cIdx]));
shadingLightRedSlider.setValue(shadingInfo.getLightRed()[cIdx]);
shadingLightGreenREd.setText(String.valueOf(shadingInfo.getLightGreen()[cIdx]));
shadingLightGreenSlider.setValue(shadingInfo.getLightGreen()[cIdx]);
shadingLightBlueREd.setText(String.valueOf(shadingInfo.getLightBlue()[cIdx]));
shadingLightBlueSlider.setValue(shadingInfo.getLightBlue()[cIdx]);
}
else {
shadingAmbientREd.setText("");
shadingAmbientSlider.setValue(0);
shadingDiffuseREd.setText("");
shadingDiffuseSlider.setValue(0);
shadingPhongREd.setText("");
shadingPhongSlider.setValue(0);
shadingPhongSizeREd.setText("");
shadingPhongSizeSlider.setValue(0);
shadingLightXREd.setText("");
shadingLightXSlider.setValue(0);
shadingLightYREd.setText("");
shadingLightYSlider.setValue(0);
shadingLightZREd.setText("");
shadingLightZSlider.setValue(0);
shadingLightRedREd.setText("");
shadingLightRedSlider.setValue(0);
shadingLightGreenREd.setText("");
shadingLightGreenSlider.setValue(0);
shadingLightBlueREd.setText("");
shadingLightBlueSlider.setValue(0);
}
if (blurEnabled) {
shadingBlurRadiusREd.setText(Tools.doubleToString(shadingInfo.getBlurRadius()));
shadingBlurRadiusSlider.setValue(shadingInfo.getBlurRadius());
shadingBlurFadeREd.setText(Tools.doubleToString(shadingInfo.getBlurFade()));
shadingBlurFadeSlider.setValue(Tools.FTOI(shadingInfo.getBlurFade() * SLIDER_SCALE_AMBIENT));
shadingBlurFallOffREd.setText(Tools.doubleToString(shadingInfo.getBlurFallOff()));
shadingBlurFallOffSlider.setValue(Tools.FTOI(shadingInfo.getBlurFallOff() * SLIDER_SCALE_BLUR_FALLOFF));
}
else {
shadingBlurRadiusREd.setText("");
shadingBlurRadiusSlider.setValue(0);
shadingBlurFadeREd.setText("");
shadingBlurFadeSlider.setValue(0);
shadingBlurFallOffREd.setText("");
shadingBlurFallOffSlider.setValue(0);
}
}
private void enableShadingUI() {
Flame currFlame = getCurrFlame();
ShadingInfo shadingInfo = currFlame != null ? currFlame.getShadingInfo() : null;
boolean pseudo3DEnabled;
boolean blurEnabled;
if (shadingInfo != null) {
shadingCmb.setEnabled(true);
pseudo3DEnabled = shadingInfo.getShading().equals(Shading.PSEUDO3D);
blurEnabled = shadingInfo.getShading().equals(Shading.BLUR);
}
else {
shadingCmb.setEnabled(false);
pseudo3DEnabled = false;
blurEnabled = false;
}
// pseudo3d
shadingAmbientREd.setEnabled(pseudo3DEnabled);
shadingAmbientSlider.setEnabled(pseudo3DEnabled);
shadingDiffuseREd.setEnabled(pseudo3DEnabled);
shadingDiffuseSlider.setEnabled(pseudo3DEnabled);
shadingPhongREd.setEnabled(pseudo3DEnabled);
shadingPhongSlider.setEnabled(pseudo3DEnabled);
shadingPhongSizeREd.setEnabled(pseudo3DEnabled);
shadingPhongSizeSlider.setEnabled(pseudo3DEnabled);
shadingLightCmb.setEnabled(pseudo3DEnabled);
shadingLightXREd.setEnabled(pseudo3DEnabled);
shadingLightXSlider.setEnabled(pseudo3DEnabled);
shadingLightYREd.setEnabled(pseudo3DEnabled);
shadingLightYSlider.setEnabled(pseudo3DEnabled);
shadingLightZREd.setEnabled(pseudo3DEnabled);
shadingLightZSlider.setEnabled(pseudo3DEnabled);
shadingLightRedREd.setEnabled(pseudo3DEnabled);
shadingLightRedSlider.setEnabled(pseudo3DEnabled);
shadingLightGreenREd.setEnabled(pseudo3DEnabled);
shadingLightGreenSlider.setEnabled(pseudo3DEnabled);
shadingLightBlueREd.setEnabled(pseudo3DEnabled);
shadingLightBlueSlider.setEnabled(pseudo3DEnabled);
// blur
shadingBlurRadiusREd.setEnabled(blurEnabled);
shadingBlurRadiusSlider.setEnabled(blurEnabled);
shadingBlurFadeREd.setEnabled(blurEnabled);
shadingBlurFadeSlider.setEnabled(blurEnabled);
shadingBlurFallOffREd.setEnabled(blurEnabled);
shadingBlurFallOffSlider.setEnabled(blurEnabled);
}
private void refreshTransformationsTable() {
final int COL_TRANSFORM = 0;
final int COL_VARIATIONS = 1;
final int COL_WEIGHT = 2;
transformationsTable.setModel(new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getRowCount() {
Flame currFlame = getCurrFlame();
return currFlame != null ? currFlame.getXForms().size() + (currFlame.getFinalXForm() != null ? 1 : 0) : 0;
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case COL_TRANSFORM:
return "Transform";
case COL_VARIATIONS:
return "Variations";
case COL_WEIGHT:
return "Weight";
}
return null;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Flame currFlame = getCurrFlame();
if (currFlame != null) {
XForm xForm = rowIndex < currFlame.getXForms().size() ? currFlame.getXForms().get(rowIndex) : currFlame.getFinalXForm();
switch (columnIndex) {
case COL_TRANSFORM:
return rowIndex < currFlame.getXForms().size() ? String.valueOf(rowIndex + 1) : "Final";
case COL_VARIATIONS:
{
String hs = "";
if (xForm.getVariationCount() > 0) {
for (int i = 0; i < xForm.getVariationCount() - 1; i++) {
hs += xForm.getVariation(i).getFunc().getName() + ", ";
}
hs += xForm.getVariation(xForm.getVariationCount() - 1).getFunc().getName();
}
return hs;
}
case COL_WEIGHT:
return rowIndex < currFlame.getXForms().size() ? Tools.doubleToString(xForm.getWeight()) : "";
}
}
return null;
}
@Override
public boolean isCellEditable(int row, int column) {
return column == COL_WEIGHT;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
Flame currFlame = getCurrFlame();
if (currFlame != null && column == COL_WEIGHT && row < currFlame.getXForms().size()) {
XForm xForm = currFlame.getXForms().get(row);
String valStr = (String) aValue;
if (valStr == null || valStr.length() == 0) {
valStr = "0";
}
xForm.setWeight(Tools.stringToDouble(valStr));
refreshFlameImage(false);
}
super.setValueAt(aValue, row, column);
}
});
transformationsTable.getTableHeader().setFont(transformationsTable.getFont());
transformationsTable.getColumnModel().getColumn(COL_TRANSFORM).setWidth(20);
transformationsTable.getColumnModel().getColumn(COL_VARIATIONS).setPreferredWidth(120);
transformationsTable.getColumnModel().getColumn(COL_WEIGHT).setWidth(16);
}
class PaletteTableCustomRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
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 (paletteKeyFrames != null && paletteKeyFrames.size() > row) {
RGBColor color = paletteKeyFrames.get(row);
c.setBackground(new java.awt.Color(color.getRed(), color.getGreen(), color.getBlue()));
}
return c;
}
}
private void refreshPaletteColorsTable() {
final int COL_COLOR = 0;
final int COL_RED = 1;
final int COL_GREEN = 2;
final int COL_BLUE = 3;
createPaletteColorsTable.setDefaultRenderer(Object.class, new PaletteTableCustomRenderer());
createPaletteColorsTable.setModel(new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getRowCount() {
return Integer.parseInt(paletteRandomPointsREd.getText());
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case COL_COLOR:
return "Color";
case COL_RED:
return "Red";
case COL_GREEN:
return "Green";
case COL_BLUE:
return "Blue";
}
return null;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (paletteKeyFrames != null && paletteKeyFrames.size() > rowIndex) {
switch (columnIndex) {
case COL_COLOR:
return String.valueOf(rowIndex + 1);
case COL_RED:
return String.valueOf(paletteKeyFrames.get(rowIndex).getRed());
case COL_GREEN:
return String.valueOf(paletteKeyFrames.get(rowIndex).getGreen());
case COL_BLUE:
return String.valueOf(paletteKeyFrames.get(rowIndex).getBlue());
}
}
return null;
}
@Override
public boolean isCellEditable(int row, int column) {
return column == COL_RED || column == COL_GREEN || column == COL_BLUE;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
Flame currFlame = getCurrFlame();
if (currFlame != null && paletteKeyFrames != null && paletteKeyFrames.size() > row) {
String valStr = (String) aValue;
if (valStr == null || valStr.length() == 0) {
valStr = "0";
}
switch (column) {
case COL_RED:
paletteKeyFrames.get(row).setRed(Tools.limitColor(Tools.stringToInt(valStr)));
break;
case COL_GREEN:
paletteKeyFrames.get(row).setGreen(Tools.limitColor(Tools.stringToInt(valStr)));
break;
case COL_BLUE:
paletteKeyFrames.get(row).setBlue(Tools.limitColor(Tools.stringToInt(valStr)));
break;
}
refreshPaletteColorsTable();
RGBPalette palette = new RandomRGBPaletteGenerator().generatePalette(paletteKeyFrames);
currFlame.setPalette(palette);
refreshPaletteUI(palette);
refreshFlameImage(false);
}
super.setValueAt(aValue, row, column);
}
});
createPaletteColorsTable.getTableHeader().setFont(transformationsTable.getFont());
createPaletteColorsTable.getColumnModel().getColumn(COL_COLOR).setWidth(20);
createPaletteColorsTable.getColumnModel().getColumn(COL_RED).setPreferredWidth(60);
createPaletteColorsTable.getColumnModel().getColumn(COL_GREEN).setPreferredWidth(60);
createPaletteColorsTable.getColumnModel().getColumn(COL_BLUE).setPreferredWidth(60);
}
private void refreshRelWeightsTable() {
final int COL_TRANSFORM = 0;
final int COL_WEIGHT = 1;
relWeightsTable.setModel(new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getRowCount() {
Flame currFlame = getCurrFlame();
XForm xForm = getCurrXForm();
return xForm != null && xForm != currFlame.getFinalXForm() ? currFlame.getXForms().size() : 0;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case COL_TRANSFORM:
return "Transform";
case COL_WEIGHT:
return "Weight";
}
return null;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Flame currFlame = getCurrFlame();
if (currFlame != null) {
switch (columnIndex) {
case COL_TRANSFORM:
return String.valueOf(rowIndex + 1);
case COL_WEIGHT: {
XForm xForm = getCurrXForm();
return xForm != null ? Tools.doubleToString(xForm.getModifiedWeights()[rowIndex]) : null;
}
}
}
return null;
}
@Override
public boolean isCellEditable(int row, int column) {
return column == COL_WEIGHT;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
XForm xForm = getCurrXForm();
Flame currFlame = getCurrFlame();
if (currFlame != null && column == COL_WEIGHT && xForm != null) {
String valStr = (String) aValue;
if (valStr == null || valStr.length() == 0) {
valStr = "0";
}
xForm.getModifiedWeights()[row] = Tools.stringToDouble(valStr);
refreshFlameImage(false);
}
super.setValueAt(aValue, row, column);
}
});
relWeightsTable.getTableHeader().setFont(relWeightsTable.getFont());
relWeightsTable.getColumnModel().getColumn(COL_TRANSFORM).setWidth(20);
relWeightsTable.getColumnModel().getColumn(COL_WEIGHT).setWidth(16);
}
private void refreshPaletteUI(RGBPalette pPalette) {
paletteRedREd.setText(String.valueOf(pPalette.getModRed()));
paletteRedSlider.setValue(pPalette.getModRed());
paletteGreenREd.setText(String.valueOf(pPalette.getModGreen()));
paletteGreenSlider.setValue(pPalette.getModGreen());
paletteBlueREd.setText(String.valueOf(pPalette.getModBlue()));
paletteBlueSlider.setValue(pPalette.getModBlue());
paletteContrastREd.setText(String.valueOf(pPalette.getModContrast()));
paletteContrastSlider.setValue(pPalette.getModContrast());
paletteHueREd.setText(String.valueOf(pPalette.getModHue()));
paletteHueSlider.setValue(pPalette.getModHue());
paletteBrightnessREd.setText(String.valueOf(pPalette.getModBrightness()));
paletteBrightnessSlider.setValue(pPalette.getModBrightness());
paletteSwapRGBREd.setText(String.valueOf(pPalette.getModSwapRGB()));
paletteSwapRGBSlider.setValue(pPalette.getModSwapRGB());
paletteGammaREd.setText(String.valueOf(pPalette.getModGamma()));
paletteGammaSlider.setValue(pPalette.getModGamma());
paletteShiftREd.setText(String.valueOf(pPalette.getModShift()));
paletteShiftSlider.setValue(pPalette.getModShift());
paletteSaturationREd.setText(String.valueOf(pPalette.getModSaturation()));
paletteSaturationSlider.setValue(pPalette.getModSaturation());
refreshPaletteImg();
}
private void refreshPaletteImg() {
Flame currFlame = getCurrFlame();
if (currFlame != null) {
ImagePanel imgPanel = getPalettePanel();
int width = imgPanel.getWidth();
int height = imgPanel.getHeight();
if (width >= 16 && height >= 16) {
SimpleImage img = new RGBPaletteRenderer().renderHorizPalette(currFlame.getPalette(), width, height);
imgPanel.setImage(img);
}
palettePanel.getParent().validate();
}
}
private void flameSliderChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale) {
Flame currFlame = getCurrFlame();
if (noRefresh || currFlame == null)
return;
noRefresh = true;
try {
double propValue = pSlider.getValue() / pSliderScale;
pTextField.setText(Tools.doubleToString(propValue));
Class<?> cls = currFlame.getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(currFlame, propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(currFlame, Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
private void paletteSliderChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale) {
Flame currFlame = getCurrFlame();
if (noRefresh || currFlame == null)
return;
noRefresh = true;
try {
double propValue = pSlider.getValue() / pSliderScale;
pTextField.setText(Tools.doubleToString(propValue));
Class<?> cls = currFlame.getPalette().getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(currFlame.getPalette(), propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(currFlame.getPalette(), Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
field = cls.getDeclaredField("modified");
field.setAccessible(true);
field.setBoolean(currFlame.getPalette(), true);
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshPaletteImg();
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
private void shadingInfoTextFieldChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale, int pIdx) {
Flame currFlame = getCurrFlame();
if (noRefresh || currFlame == null)
return;
ShadingInfo shadingInfo = currFlame.getShadingInfo();
noRefresh = true;
try {
double propValue = Tools.stringToDouble(pTextField.getText());
pSlider.setValue(Tools.FTOI(propValue * pSliderScale));
Class<?> cls = shadingInfo.getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(shadingInfo, propValue);
}
else if (fieldCls == double[].class) {
double[] arr = (double[]) field.get(shadingInfo);
Array.set(arr, pIdx, propValue);
}
else if (fieldCls == Double[].class) {
Double[] arr = (Double[]) field.get(shadingInfo);
Array.set(arr, pIdx, propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(shadingInfo, Tools.FTOI(propValue));
}
else if (fieldCls == int[].class) {
int[] arr = (int[]) field.get(shadingInfo);
Array.set(arr, pIdx, Tools.FTOI(propValue));
}
else if (fieldCls == Integer[].class) {
Integer[] arr = (Integer[]) field.get(shadingInfo);
Array.set(arr, pIdx, Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
private void shadingInfoSliderChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale, int pIdx) {
Flame currFlame = getCurrFlame();
if (noRefresh || currFlame == null)
return;
ShadingInfo shadingInfo = currFlame.getShadingInfo();
noRefresh = true;
try {
double propValue = pSlider.getValue() / pSliderScale;
pTextField.setText(Tools.doubleToString(propValue));
Class<?> cls = shadingInfo.getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(shadingInfo, propValue);
}
else if (fieldCls == double[].class) {
double[] arr = (double[]) field.get(shadingInfo);
Array.set(arr, pIdx, propValue);
}
else if (fieldCls == Double[].class) {
Double[] arr = (Double[]) field.get(shadingInfo);
Array.set(arr, pIdx, propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(shadingInfo, Tools.FTOI(propValue));
}
else if (fieldCls == int[].class) {
int[] arr = (int[]) field.get(shadingInfo);
Array.set(arr, pIdx, Tools.FTOI(propValue));
}
else if (fieldCls == Integer[].class) {
Integer[] arr = (Integer[]) field.get(shadingInfo);
Array.set(arr, pIdx, Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
private void xFormSliderChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale) {
if (noRefresh) {
return;
}
Flame currFlame = getCurrFlame();
if (currFlame == null) {
return;
}
XForm xForm = getCurrXForm();
if (xForm == null) {
return;
}
noRefresh = true;
try {
double propValue = pSlider.getValue() / pSliderScale;
pTextField.setText(Tools.doubleToString(propValue));
Class<?> cls = xForm.getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(xForm, propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(xForm, Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
private void flameTextFieldChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale) {
if (noRefresh) {
return;
}
Flame currFlame = getCurrFlame();
if (currFlame == null) {
return;
}
noRefresh = true;
try {
double propValue = Tools.stringToDouble(pTextField.getText());
pSlider.setValue(Tools.FTOI(propValue * pSliderScale));
Class<?> cls = currFlame.getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(currFlame, propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(currFlame, Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
private void paletteTextFieldChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale) {
Flame currFlame = getCurrFlame();
if (noRefresh || currFlame == null)
return;
noRefresh = true;
try {
double propValue = Tools.stringToDouble(pTextField.getText());
pSlider.setValue(Tools.FTOI(propValue * pSliderScale));
Class<?> cls = currFlame.getPalette().getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(currFlame.getPalette(), propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(currFlame.getPalette(), Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
field = cls.getDeclaredField("modified");
field.setAccessible(true);
field.setBoolean(currFlame.getPalette(), true);
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshPaletteImg();
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
private void xFormTextFieldChanged(JSlider pSlider, JTextField pTextField, String pProperty, double pSliderScale) {
if (noRefresh) {
return;
}
XForm xForm = getCurrXForm();
if (xForm == null) {
return;
}
noRefresh = true;
try {
double propValue = Tools.stringToDouble(pTextField.getText());
pSlider.setValue(Tools.FTOI(propValue * pSliderScale));
Class<?> cls = xForm.getClass();
Field field;
try {
field = cls.getDeclaredField(pProperty);
field.setAccessible(true);
Class<?> fieldCls = field.getType();
if (fieldCls == double.class || fieldCls == Double.class) {
field.setDouble(xForm, propValue);
}
else if (fieldCls == int.class || fieldCls == Integer.class) {
field.setInt(xForm, Tools.FTOI(propValue));
}
else {
throw new IllegalStateException();
}
}
catch (Throwable ex) {
ex.printStackTrace();
}
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
public void cameraRollSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraRollSlider, cameraRollREd, "camRoll", 1.0);
}
public void cameraRollREd_changed() {
flameTextFieldChanged(cameraRollSlider, cameraRollREd, "camRoll", 1.0);
}
public void cameraPitchREd_changed() {
flameTextFieldChanged(cameraPitchSlider, cameraPitchREd, "camPitch", 1.0);
}
public void cameraPitchSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraPitchSlider, cameraPitchREd, "camPitch", 1.0);
}
public void cameraYawREd_changed() {
flameTextFieldChanged(cameraYawSlider, cameraYawREd, "camYaw", 1.0);
}
public void cameraPerspectiveREd_changed() {
flameTextFieldChanged(cameraPerspectiveSlider, cameraPerspectiveREd, "camPerspective", SLIDER_SCALE_PERSPECTIVE);
}
public void cameraYawSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraYawSlider, cameraYawREd, "camYaw", 1.0);
}
public void cameraPerspectiveSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraPerspectiveSlider, cameraPerspectiveREd, "camPerspective", SLIDER_SCALE_PERSPECTIVE);
}
public void renderFlameButton_actionPerformed(ActionEvent e) {
// refreshing = true;
// try {
// toggleTrianglesButton.setSelected(false);
// flamePanel.setDrawFlame(false);
// }
// finally {
// refreshing = false;
// }
refreshFlameImage((AffineZStyle) zStyleCmb.getSelectedItem(), false, false);
}
public void loadFlameButton_actionPerformed(ActionEvent e) {
try {
JFileChooser chooser = new FlameFileChooser(prefs);
if (prefs.getInputFlamePath() != null) {
try {
chooser.setCurrentDirectory(new File(prefs.getInputFlamePath()));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
if (chooser.showOpenDialog(centerPanel) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
List<Flame> flames = new Flam3Reader().readFlames(file.getAbsolutePath());
Flame flame = flames.get(0);
prefs.setLastInputFlameFile(file);
_currFlame = flame;
for (int i = flames.size() - 1; i >= 0; i--) {
randomBatch.add(0, flames.get(i));
}
updateThumbnails(null);
refreshUI();
}
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
public void previewQualityREd_changed() {
if (noRefresh)
return;
refreshFlameImage(false);
}
public void cameraCentreYSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraCentreYSlider, cameraCentreYREd, "centreY", SLIDER_SCALE_CENTRE);
}
public void cameraCentreYREd_changed() {
flameTextFieldChanged(cameraCentreYSlider, cameraCentreYREd, "centreY", SLIDER_SCALE_CENTRE);
}
public void cameraCentreXSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraCentreXSlider, cameraCentreXREd, "centreX", SLIDER_SCALE_CENTRE);
}
public void cameraZoomSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraZoomSlider, cameraZoomREd, "camZoom", SLIDER_SCALE_ZOOM);
}
public void cameraCentreXREd_changed() {
flameTextFieldChanged(cameraCentreXSlider, cameraCentreXREd, "centreX", SLIDER_SCALE_CENTRE);
}
public void cameraZoomREd_changed() {
flameTextFieldChanged(cameraZoomSlider, cameraZoomREd, "camZoom", SLIDER_SCALE_ZOOM);
}
public void brightnessSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(brightnessSlider, brightnessREd, "brightness", SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY);
}
public void filterRadiusREd_changed() {
flameTextFieldChanged(filterRadiusSlider, filterRadiusREd, "spatialFilterRadius", SLIDER_SCALE_FILTER_RADIUS);
}
public void bgColorGreenSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(bgColorGreenSlider, bgColorGreenREd, "bgColorGreen", 1.0);
}
public void gammaREd_changed() {
flameTextFieldChanged(gammaSlider, gammaREd, "gamma", SLIDER_SCALE_GAMMA);
}
public void bgColorRedSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(bgColorRedSlider, bgColorRedREd, "bgColorRed", 1.0);
}
public void bgColorBlueSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(bgColorBlueSlider, bgColorBlueREd, "bgColorBlue", 1.0);
}
public void spatialOversampleREd_changed() {
flameTextFieldChanged(spatialOversampleSlider, spatialOversampleREd, "spatialOversample", 1.0);
}
public void colorOversampleREd_changed() {
flameTextFieldChanged(colorOversampleSlider, colorOversampleREd, "colorOversample", 1.0);
}
public void contrastREd_changed() {
flameTextFieldChanged(contrastSlider, contrastREd, "contrast", SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY);
}
public void vibrancySlider_stateChanged(ChangeEvent e) {
flameSliderChanged(vibrancySlider, vibrancyREd, "vibrancy", SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY);
}
public void filterRadiusSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(filterRadiusSlider, filterRadiusREd, "spatialFilterRadius", SLIDER_SCALE_FILTER_RADIUS);
}
public void spatialOversampleSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(spatialOversampleSlider, spatialOversampleREd, "spatialOversample", 1.0);
}
public void colorOversampleSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(colorOversampleSlider, colorOversampleREd, "colorOversample", 1.0);
}
public void vibrancyREd_changed() {
flameTextFieldChanged(vibrancySlider, vibrancyREd, "vibrancy", SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY);
}
public void pixelsPerUnitSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(pixelsPerUnitSlider, pixelsPerUnitREd, "pixelsPerUnit", 1.0);
}
public void bgColorGreenREd_changed() {
flameTextFieldChanged(bgColorGreenSlider, bgColorGreenREd, "bgColorGreen", 1.0);
}
public void gammaSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(gammaSlider, gammaREd, "gamma", SLIDER_SCALE_GAMMA);
}
public void bgColorRedREd_changed() {
flameTextFieldChanged(bgColorRedSlider, bgColorRedREd, "bgColorRed", 1.0);
}
public void bgBGColorBlueREd_changed() {
flameTextFieldChanged(bgColorBlueSlider, bgColorBlueREd, "bgColorBlue", 1.0);
}
public void pixelsPerUnitREd_changed() {
flameTextFieldChanged(pixelsPerUnitSlider, pixelsPerUnitREd, "pixelsPerUnit", 1.0);
}
public void brightnessREd_changed() {
flameTextFieldChanged(brightnessSlider, brightnessREd, "brightness", SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY);
}
public void contrastSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(contrastSlider, contrastREd, "contrast", SLIDER_SCALE_BRIGHTNESS_CONTRAST_VIBRANCY);
}
public void randomPaletteButton_actionPerformed(ActionEvent e) {
Flame currFlame = getCurrFlame();
if (currFlame != null) {
RandomRGBPaletteGenerator generator = new RandomRGBPaletteGenerator();
paletteKeyFrames = generator.generateKeyFrames(Integer.parseInt(paletteRandomPointsREd.getText()));
refreshPaletteColorsTable();
RGBPalette palette = new RandomRGBPaletteGenerator().generatePalette(paletteKeyFrames);
currFlame.setPalette(palette);
refreshPaletteUI(palette);
refreshFlameImage(false);
}
}
public void grabPaletteFromFlameButton_actionPerformed(ActionEvent e) {
JFileChooser chooser = new FlameFileChooser(prefs);
if (prefs.getInputFlamePath() != null) {
try {
chooser.setCurrentDirectory(new File(prefs.getInputFlamePath()));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
if (chooser.showOpenDialog(centerPanel) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
List<Flame> flames = new Flam3Reader().readFlames(file.getAbsolutePath());
Flame flame = flames.get(0);
prefs.setLastInputFlameFile(file);
RGBPalette palette = flame.getPalette();
paletteKeyFrames = null;
Flame currFlame = getCurrFlame();
currFlame.setPalette(palette);
refreshPaletteColorsTable();
refreshPaletteUI(palette);
refreshFlameImage(false);
}
}
public void paletteRedREd_changed() {
paletteTextFieldChanged(paletteRedSlider, paletteRedREd, "modRed", 1.0);
}
public void paletteSaturationREd_changed() {
paletteTextFieldChanged(paletteSaturationSlider, paletteSaturationREd, "modSaturation", 1.0);
}
public void paletteBlueREd_changed() {
paletteTextFieldChanged(paletteBlueSlider, paletteBlueREd, "modBlue", 1.0);
}
public void paletteBlueSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteBlueSlider, paletteBlueREd, "modBlue", 1.0);
}
public void paletteBrightnessSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteBrightnessSlider, paletteBrightnessREd, "modBrightness", 1.0);
}
public void paletteBrightnessREd_changed() {
paletteTextFieldChanged(paletteBrightnessSlider, paletteBrightnessREd, "modBrightness", 1.0);
}
public void paletteContrastREd_changed() {
paletteTextFieldChanged(paletteContrastSlider, paletteContrastREd, "modContrast", 1.0);
}
public void paletteGreenREd_changed() {
paletteTextFieldChanged(paletteGreenSlider, paletteGreenREd, "modGreen", 1.0);
}
public void paletteGreenSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteGreenSlider, paletteGreenREd, "modGreen", 1.0);
}
public void paletteHueREd_changed() {
paletteTextFieldChanged(paletteHueSlider, paletteHueREd, "modHue", 1.0);
}
public void paletteGammaSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteGammaSlider, paletteGammaREd, "modGamma", 1.0);
}
public void paletteGammaREd_changed() {
paletteTextFieldChanged(paletteGammaSlider, paletteGammaREd, "modGamma", 1.0);
}
public void paletteRedSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteRedSlider, paletteRedREd, "modRed", 1.0);
}
public void paletteContrastSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteContrastSlider, paletteContrastREd, "modContrast", 1.0);
}
public void paletteSaturationSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteSaturationSlider, paletteSaturationREd, "modSaturation", 1.0);
}
public void paletteShiftREd_changed() {
paletteTextFieldChanged(paletteShiftSlider, paletteShiftREd, "modShift", 1.0);
}
public void paletteHueSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteHueSlider, paletteHueREd, "modHue", 1.0);
}
public void paletteShiftSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteShiftSlider, paletteShiftREd, "modShift", 1.0);
}
public void renderImageButton_actionPerformed(boolean pHighQuality) {
Flame currFlame = getCurrFlame();
if (currFlame != null) {
try {
JFileChooser chooser = new ImageFileChooser();
if (prefs.getOutputImagePath() != null) {
try {
chooser.setCurrentDirectory(new File(prefs.getOutputImagePath()));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
if (chooser.showSaveDialog(centerPanel) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
prefs.setLastOutputImageFile(file);
int width = prefs.getTinaRenderImageWidth();
int height = prefs.getTinaRenderImageHeight();
SimpleImage img = new SimpleImage(width, height);
Flame flame = getCurrFlame();
double wScl = (double) img.getImageWidth() / (double) flame.getWidth();
double hScl = (double) img.getImageHeight() / (double) flame.getHeight();
flame.setPixelsPerUnit((wScl + hScl) * 0.5 * flame.getPixelsPerUnit());
flame.setWidth(img.getImageWidth());
flame.setHeight(img.getImageHeight());
boolean renderHDR = pHighQuality ? prefs.isTinaRenderHighHDR() : prefs.isTinaRenderNormalHDR();
SimpleHDRImage hdrImg = renderHDR ? new SimpleHDRImage(width, height) : null;
double oldSampleDensity = flame.getSampleDensity();
int oldSpatialOversample = flame.getSpatialOversample();
int oldColorOversample = flame.getColorOversample();
double oldFilterRadius = flame.getSpatialFilterRadius();
try {
if (pHighQuality) {
flame.setSampleDensity(prefs.getTinaRenderHighQuality());
flame.setSpatialOversample(prefs.getTinaRenderHighSpatialOversample());
flame.setColorOversample(prefs.getTinaRenderHighColorOversample());
flame.setSpatialFilterRadius(prefs.getTinaRenderHighSpatialOversample());
}
else {
flame.setSampleDensity(prefs.getTinaRenderNormalQuality());
flame.setSpatialOversample(prefs.getTinaRenderNormalSpatialOversample());
flame.setColorOversample(prefs.getTinaRenderNormalColorOversample());
flame.setSpatialFilterRadius(prefs.getTinaRenderNormalSpatialOversample());
}
long t0 = Calendar.getInstance().getTimeInMillis();
FlameRenderer renderer = new FlameRenderer(flame, prefs);
renderer.setProgressUpdater(mainProgressUpdater);
renderer.setAffineZStyle((AffineZStyle) zStyleCmb.getSelectedItem());
renderer.renderFlame(img, hdrImg);
long t1 = Calendar.getInstance().getTimeInMillis();
System.err.println("RENDER TIME: " + ((double) (t1 - t0) / 1000.0) + "s");
new ImageWriter().saveImage(img, file.getAbsolutePath());
if (renderHDR) {
new ImageWriter().saveImage(hdrImg, file.getAbsolutePath() + ".hdr");
}
}
finally {
flame.setSampleDensity(oldSampleDensity);
flame.setSpatialOversample(oldSpatialOversample);
flame.setColorOversample(oldColorOversample);
flame.setSpatialFilterRadius(oldFilterRadius);
}
mainController.loadImage(file.getAbsolutePath(), false);
// JOptionPane.showMessageDialog(centerPanel, "Image was successfully saved", "Operation successful", JOptionPane.OK_OPTION);
}
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
}
public void saveFlameButton_actionPerformed(ActionEvent e) {
try {
Flame currFlame = getCurrFlame();
if (currFlame != null) {
JFileChooser chooser = new FlameFileChooser(prefs);
if (prefs.getOutputFlamePath() != null) {
try {
chooser.setCurrentDirectory(new File(prefs.getOutputFlamePath()));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
if (chooser.showSaveDialog(centerPanel) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
new Flam3Writer().writeFlame(currFlame, file.getAbsolutePath());
prefs.setLastOutputFlameFile(file);
}
}
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
public XForm getCurrXForm() {
XForm xForm = null;
Flame currFlame = getCurrFlame();
if (currFlame != null) {
int row = transformationsTable.getSelectedRow();
if (row >= 0 && row < currFlame.getXForms().size()) {
xForm = currFlame.getXForms().get(row);
}
else if (row == currFlame.getXForms().size()) {
xForm = currFlame.getFinalXForm();
}
}
return xForm;
}
public void transformationTableClicked() {
if (!gridRefreshing) {
gridRefreshing = cmbRefreshing = true;
try {
XForm xForm = getCurrXForm();
if (flamePanel != null) {
flamePanel.setSelectedXForm(xForm);
}
refreshXFormUI(xForm);
enableXFormControls(xForm);
refreshFlameImage(false);
}
finally {
cmbRefreshing = gridRefreshing = false;
}
}
}
private void enableControls() {
enableJobRenderControls();
setMorphFlame1Button.setEnabled(true);
setMorphFlame2Button.setEnabled(true);
importMorphedFlameButton.setEnabled(true);
animationGenerateButton.setEnabled(true);
morphCheckBox.setEnabled(morphFlame1 != null && morphFlame2 != null);
}
private void enableJobRenderControls() {
boolean idle = jobRenderThread == null;
batchRenderAddFilesButton.setEnabled(idle);
batchRenderFilesMoveDownButton.setEnabled(idle);
batchRenderFilesMoveUpButton.setEnabled(idle);
batchRenderFilesRemoveButton.setEnabled(idle);
batchRenderFilesRemoveAllButton.setEnabled(idle);
batchRenderStartButton.setText(idle ? "Render" : "Stop");
batchRenderStartButton.invalidate();
batchRenderStartButton.validate();
rootTabbedPane.setEnabled(idle);
}
private void enableXFormControls(XForm xForm) {
Flame currFlame = getCurrFlame();
boolean enabled = xForm != null;
affineRotateLeftButton.setEnabled(enabled);
affineRotateRightButton.setEnabled(enabled);
affineEnlargeButton.setEnabled(enabled);
affineShrinkButton.setEnabled(enabled);
affineMoveUpButton.setEnabled(enabled);
affineMoveLeftButton.setEnabled(enabled);
affineMoveRightButton.setEnabled(enabled);
affineMoveDownButton.setEnabled(enabled);
affineFlipHorizontalButton.setEnabled(enabled);
affineFlipVerticalButton.setEnabled(enabled);
addTransformationButton.setEnabled(currFlame != null);
duplicateTransformationButton.setEnabled(enabled);
deleteTransformationButton.setEnabled(enabled);
addFinalTransformationButton.setEnabled(currFlame != null && currFlame.getFinalXForm() == null);
affineEditPostTransformButton.setEnabled(currFlame != null);
affineEditPostTransformSmallButton.setEnabled(currFlame != null);
mouseEditZoomInButton.setEnabled(currFlame != null);
mouseEditZoomOutButton.setEnabled(currFlame != null);
toggleTrianglesButton.setEnabled(currFlame != null);
affineC20REd.setEditable(enabled);
affineC21REd.setEditable(enabled);
affineResetTransformButton.setEnabled(enabled);
transformationWeightLeftButton.setEnabled(enabled);
transformationWeightRightButton.setEnabled(enabled);
for (NonlinearControlsRow rows : nonlinearControlsRows) {
rows.getNonlinearVarCmb().setEnabled(enabled);
rows.getNonlinearVarREd().setEnabled(enabled);
rows.getNonlinearVarLeftButton().setEnabled(enabled);
rows.getNonlinearVarRightButton().setEnabled(enabled);
rows.getNonlinearParamsCmb().setEnabled(enabled);
rows.getNonlinearParamsREd().setEnabled(enabled);
// refreshing occurs in refreshXFormUI():
// rows.getNonlinearParamsLeftButton().setEnabled(enabled);
// rows.getNonlinearParamsRightButton().setEnabled(enabled);
}
xFormColorREd.setEnabled(enabled);
xFormColorSlider.setEnabled(enabled);
xFormSymmetryREd.setEnabled(enabled);
xFormSymmetrySlider.setEnabled(enabled);
xFormOpacityREd.setEnabled(enabled && xForm.getDrawMode() == DrawMode.OPAQUE);
xFormOpacitySlider.setEnabled(xFormOpacityREd.isEnabled());
xFormDrawModeCmb.setEnabled(enabled);
relWeightsTable.setEnabled(enabled);
relWeightsLeftButton.setEnabled(enabled);
relWeightsRightButton.setEnabled(enabled);
}
private void refreshXFormUI(XForm pXForm) {
boolean oldRefreshing = refreshing;
boolean oldGridRefreshing = gridRefreshing;
boolean oldCmbRefreshing = cmbRefreshing;
boolean oldNoRefresh = noRefresh;
gridRefreshing = cmbRefreshing = refreshing = noRefresh = true;
try {
if (pXForm != null) {
if (affineEditPostTransformButton.isSelected()) {
affineC00REd.setText(Tools.doubleToString(pXForm.getPostCoeff00()));
affineC01REd.setText(Tools.doubleToString(pXForm.getPostCoeff01()));
affineC10REd.setText(Tools.doubleToString(pXForm.getPostCoeff10()));
affineC11REd.setText(Tools.doubleToString(pXForm.getPostCoeff11()));
affineC20REd.setText(Tools.doubleToString(pXForm.getPostCoeff20()));
affineC21REd.setText(Tools.doubleToString(pXForm.getPostCoeff21()));
}
else {
affineC00REd.setText(Tools.doubleToString(pXForm.getCoeff00()));
affineC01REd.setText(Tools.doubleToString(pXForm.getCoeff01()));
affineC10REd.setText(Tools.doubleToString(pXForm.getCoeff10()));
affineC11REd.setText(Tools.doubleToString(pXForm.getCoeff11()));
affineC20REd.setText(Tools.doubleToString(pXForm.getCoeff20()));
affineC21REd.setText(Tools.doubleToString(pXForm.getCoeff21()));
}
xFormColorREd.setText(Tools.doubleToString(pXForm.getColor()));
xFormColorSlider.setValue(Tools.FTOI(pXForm.getColor() * SLIDER_SCALE_COLOR));
xFormSymmetryREd.setText(Tools.doubleToString(pXForm.getColorSymmetry()));
xFormSymmetrySlider.setValue(Tools.FTOI(pXForm.getColorSymmetry() * SLIDER_SCALE_COLOR));
xFormOpacityREd.setText(Tools.doubleToString(pXForm.getOpacity()));
xFormOpacitySlider.setValue(Tools.FTOI(pXForm.getOpacity() * SLIDER_SCALE_COLOR));
xFormDrawModeCmb.setSelectedItem(pXForm.getDrawMode());
}
else {
affineC00REd.setText(null);
affineC01REd.setText(null);
affineC10REd.setText(null);
affineC11REd.setText(null);
affineC20REd.setText(null);
affineC21REd.setText(null);
xFormColorREd.setText(null);
xFormColorSlider.setValue(0);
xFormSymmetryREd.setText(null);
xFormSymmetrySlider.setValue(0);
xFormOpacityREd.setText(null);
xFormOpacitySlider.setValue(0);
xFormDrawModeCmb.setSelectedIndex(-1);
}
{
int idx = 0;
for (NonlinearControlsRow row : nonlinearControlsRows) {
if (pXForm == null || idx >= pXForm.getVariationCount()) {
refreshParamCmb(row, null, null);
row.getNonlinearParamsLeftButton().setEnabled(false);
row.getNonlinearParamsRightButton().setEnabled(false);
}
else {
Variation var = pXForm.getVariation(idx);
refreshParamCmb(row, pXForm, var);
}
idx++;
}
}
refreshRelWeightsTable();
}
finally {
gridRefreshing = oldGridRefreshing;
refreshing = oldRefreshing;
cmbRefreshing = oldCmbRefreshing;
noRefresh = oldNoRefresh;
}
}
public void refreshParamCmb(NonlinearControlsRow pRow, XForm pXForm, Variation pVar) {
if (pXForm == null || pVar == null) {
pRow.getNonlinearVarCmb().setSelectedIndex(-1);
pRow.getNonlinearVarREd().setText(null);
pRow.getNonlinearParamsCmb().setSelectedIndex(-1);
pRow.getNonlinearParamsREd().setText(null);
}
else {
VariationFunc varFunc = pVar.getFunc();
pRow.getNonlinearVarCmb().setSelectedItem(varFunc.getName());
pRow.getNonlinearVarREd().setText(Tools.doubleToString(pVar.getAmount()));
pRow.getNonlinearParamsCmb().removeAllItems();
// ressources
int resCount = 0;
String[] resNames = varFunc.getRessourceNames();
if (resNames != null) {
for (String name : resNames) {
pRow.getNonlinearParamsCmb().addItem(name);
resCount++;
}
}
// params
String[] paramNames = varFunc.getParameterNames();
if (paramNames != null) {
for (String name : paramNames) {
pRow.getNonlinearParamsCmb().addItem(name);
}
}
// preselection
if (resCount > 0) {
pRow.getNonlinearParamsCmb().setSelectedIndex(0);
enableNonlinearControls(pRow, true);
}
else if (varFunc.getParameterNames().length > 0) {
pRow.getNonlinearParamsCmb().setSelectedIndex(0);
Object val = varFunc.getParameterValues()[0];
if (val instanceof Double) {
pRow.getNonlinearParamsREd().setText(Tools.doubleToString((Double) val));
}
else {
pRow.getNonlinearParamsREd().setText(val.toString());
}
enableNonlinearControls(pRow, false);
}
else {
pRow.getNonlinearParamsCmb().setSelectedIndex(-1);
pRow.getNonlinearParamsREd().setText(null);
}
}
}
public void addXForm() {
XForm xForm = new XForm();
xForm.addVariation(1.0, new Linear3DFunc());
xForm.setWeight(0.5);
Flame currFlame = getCurrFlame();
currFlame.getXForms().add(xForm);
gridRefreshing = true;
try {
refreshTransformationsTable();
}
finally {
gridRefreshing = false;
}
int row = currFlame.getXForms().size() - 1;
transformationsTable.getSelectionModel().setSelectionInterval(row, row);
refreshFlameImage(false);
}
public void duplicateXForm() {
XForm xForm = new XForm();
xForm.assign(getCurrXForm());
Flame currFlame = getCurrFlame();
currFlame.getXForms().add(xForm);
gridRefreshing = true;
try {
refreshTransformationsTable();
}
finally {
gridRefreshing = false;
}
int row = currFlame.getXForms().size() - 1;
transformationsTable.getSelectionModel().setSelectionInterval(row, row);
refreshFlameImage(false);
}
public void deleteXForm() {
int row = transformationsTable.getSelectedRow();
Flame currFlame = getCurrFlame();
if (currFlame.getFinalXForm() != null && row == currFlame.getXForms().size()) {
currFlame.setFinalXForm(null);
}
else {
currFlame.getXForms().remove(getCurrXForm());
}
gridRefreshing = true;
try {
refreshTransformationsTable();
}
finally {
gridRefreshing = false;
}
refreshFlameImage(false);
}
public void addFinalXForm() {
XForm xForm = new XForm();
xForm.addVariation(1.0, new Linear3DFunc());
Flame currFlame = getCurrFlame();
currFlame.setFinalXForm(xForm);
gridRefreshing = true;
try {
refreshTransformationsTable();
}
finally {
gridRefreshing = false;
}
int row = currFlame.getXForms().size();
transformationsTable.getSelectionModel().setSelectionInterval(row, row);
refreshFlameImage(false);
}
public void xForm_moveRight() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = Tools.stringToDouble(affineMoveAmountREd.getText());
XFormTransformService.globalTranslate(getCurrXForm(), amount, 0, affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_rotateRight() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = Tools.stringToDouble(affineRotateAmountREd.getText());
XFormTransformService.rotate(getCurrXForm(), -amount, affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_moveLeft() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = Tools.stringToDouble(affineMoveAmountREd.getText());
XFormTransformService.globalTranslate(getCurrXForm(), -amount, 0, affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_flipHorizontal() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
XFormTransformService.flipHorizontal(getCurrXForm(), affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_flipVertical() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
XFormTransformService.flipVertical(getCurrXForm(), affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_enlarge() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = Tools.stringToDouble(affineScaleAmountREd.getText()) / 100.0;
XFormTransformService.scale(getCurrXForm(), amount, affineScaleXButton.isSelected(), affineScaleYButton.isSelected(), affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_shrink() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = 100.0 / Tools.stringToDouble(affineScaleAmountREd.getText());
XFormTransformService.scale(getCurrXForm(), amount, affineScaleXButton.isSelected(), affineScaleYButton.isSelected(), affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_rotateLeft() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = Tools.stringToDouble(affineRotateAmountREd.getText());
XFormTransformService.rotate(getCurrXForm(), amount, affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_moveUp() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = Tools.stringToDouble(affineMoveAmountREd.getText());
XFormTransformService.globalTranslate(getCurrXForm(), 0, -amount, affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
public void xForm_moveDown() {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
double amount = Tools.stringToDouble(affineMoveAmountREd.getText());
XFormTransformService.globalTranslate(getCurrXForm(), 0, amount, affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
private List<Flame> randomBatch = new ArrayList<Flame>();
private final int IMG_WIDTH = 80;
private final int IMG_HEIGHT = 60;
private final int BORDER_SIZE = 10;
public void updateThumbnails(List<SimpleImage> pImages) {
if (randomBatchScrollPane != null) {
randomBatchPanel.remove(randomBatchScrollPane);
randomBatchScrollPane = null;
}
int panelWidth = (IMG_WIDTH + BORDER_SIZE) * randomBatch.size();
int panelHeight = IMG_HEIGHT + 2 * BORDER_SIZE;
JPanel batchPanel = new JPanel();
batchPanel.setLayout(null);
batchPanel.setSize(panelWidth, panelHeight);
batchPanel.setPreferredSize(new Dimension(panelWidth, panelHeight));
for (int i = 0; i < randomBatch.size(); i++) {
SimpleImage img;
if (pImages != null) {
img = pImages.get(i);
}
else {
img = new SimpleImage(IMG_WIDTH, IMG_HEIGHT);
Flame flame = randomBatch.get(i).makeCopy();
double wScl = (double) img.getImageWidth() / (double) flame.getWidth();
double hScl = (double) img.getImageHeight() / (double) flame.getHeight();
flame.setPixelsPerUnit((wScl + hScl) * 0.5 * flame.getPixelsPerUnit());
flame.setWidth(IMG_WIDTH);
flame.setHeight(IMG_HEIGHT);
FlameRenderer renderer = new FlameRenderer(flame, prefs);
renderer.renderFlame(img, null);
}
// add it to the main panel
ImagePanel imgPanel = new ImagePanel(img, 0, 0, img.getImageWidth());
imgPanel.setImage(img);
imgPanel.setLocation(i * IMG_WIDTH + (i + 1) * BORDER_SIZE, BORDER_SIZE);
final int idx = i;
imgPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
if (e.getClickCount() > 1) {
importFromRandomBatch(idx);
}
}
});
batchPanel.add(imgPanel);
}
randomBatchScrollPane = new JScrollPane(batchPanel);
randomBatchScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
randomBatchScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
randomBatchPanel.add(randomBatchScrollPane, BorderLayout.CENTER);
randomBatchPanel.validate();
}
public void createRandomBatch(int pCount, String pGeneratorname) {
randomBatch.clear();
final int IMG_COUNT = 24;
final int MAX_IMG_SAMPLES = 10;
final double MIN_COVERAGE = 0.33;
List<SimpleImage> imgList = new ArrayList<SimpleImage>();
int maxCount = (pCount > 0 ? pCount : IMG_COUNT);
mainProgressUpdater.initProgress(maxCount);
for (int i = 0; i < maxCount; i++) {
SimpleImage img = new SimpleImage(IMG_WIDTH, IMG_HEIGHT);
Flame bestFlame = null;
double bestCoverage = 0.0;
for (int j = 0; j < MAX_IMG_SAMPLES; j++) {
// create flame
RandomFlameGenerator randGen = RandomFlameGeneratorList.getRandomFlameGeneratorInstance(pGeneratorname, true);
Flame flame = randGen.createFlame(randomSymmetryCheckBox.isSelected(), randomPostTransformCheckBox.isSelected());
flame.setWidth(IMG_WIDTH);
flame.setHeight(IMG_HEIGHT);
flame.setPixelsPerUnit(10);
RGBPalette palette = new RandomRGBPaletteGenerator().generatePalette(Integer.parseInt(paletteRandomPointsREd.getText()));
flame.setPalette(palette);
// render it
if (j > 0) {
img.fillBackground(0, 0, 0);
}
flame.setSampleDensity(50);
FlameRenderer renderer = new FlameRenderer(flame, prefs);
renderer.renderFlame(img, null);
if (j == MAX_IMG_SAMPLES - 1) {
randomBatch.add(bestFlame);
new FlameRenderer(bestFlame, prefs).renderFlame(img, null);
imgList.add(img);
}
else {
long maxCoverage = img.getImageWidth() * img.getImageHeight();
long coverage = 0;
Pixel pixel = new Pixel();
for (int k = 0; k < img.getImageHeight(); k++) {
for (int l = 0; l < img.getImageWidth(); l++) {
pixel.setARGBValue(img.getARGBValue(l, k));
if (pixel.r > 20 || pixel.g > 20 || pixel.b > 20) {
coverage++;
}
}
}
double fCoverage = (double) coverage / (double) maxCoverage;
if (fCoverage >= MIN_COVERAGE) {
randomBatch.add(flame);
imgList.add(img);
break;
}
else {
if (bestFlame == null || fCoverage > bestCoverage) {
bestFlame = flame;
bestCoverage = fCoverage;
}
}
}
}
// add it to the main panel
ImagePanel imgPanel = new ImagePanel(img, 0, 0, img.getImageWidth());
imgPanel.setImage(img);
imgPanel.setLocation(i * IMG_WIDTH + (i + 1) * BORDER_SIZE, BORDER_SIZE);
final int idx = i;
imgPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
if (e.getClickCount() > 1) {
importFromRandomBatch(idx);
}
}
});
mainProgressUpdater.updateProgress(i + 1);
}
updateThumbnails(imgList);
}
public void importFromRandomBatch(int pIdx) {
if (pIdx >= 0 && pIdx < randomBatch.size()) {
_currFlame = randomBatch.get(pIdx);
refreshUI();
transformationsTable.getSelectionModel().setSelectionInterval(0, 0);
}
}
public void nonlinearVarCmbChanged(int pIdx) {
if (cmbRefreshing) {
return;
}
+ boolean oldCmbRefreshing = cmbRefreshing;
cmbRefreshing = true;
try {
XForm xForm = getCurrXForm();
if (xForm != null) {
String fName = (String) nonlinearControlsRows[pIdx].getNonlinearVarCmb().getSelectedItem();
Variation var;
if (pIdx < xForm.getVariationCount()) {
var = xForm.getVariation(pIdx);
if (fName == null || fName.length() == 0) {
xForm.removeVariation(var);
}
else {
- var.setFunc(VariationFuncList.getVariationFuncInstance(fName));
+ if (var.getFunc() == null || !var.getFunc().getName().equals(fName)) {
+ var.setFunc(VariationFuncList.getVariationFuncInstance(fName));
+ }
}
}
else {
var = new Variation();
String varStr = nonlinearControlsRows[pIdx].getNonlinearVarREd().getText();
if (varStr == null || varStr.length() == 0) {
varStr = "0";
}
var.setFunc(VariationFuncList.getVariationFuncInstance(fName));
var.setAmount(Tools.stringToDouble(varStr));
xForm.addVariation(var);
}
refreshParamCmb(nonlinearControlsRows[pIdx], xForm, var);
refreshXFormUI(xForm);
// String selected = (String) nonlinearControlsRows[pIdx].getNonlinearParamsCmb().getSelectedItem();
// boolean enabled = selected != null && selected.length() > 0;
// nonlinearControlsRows[pIdx].getNonlinearParamsLeftButton().setEnabled(enabled);
// nonlinearControlsRows[pIdx].getNonlinearParamsRightButton().setEnabled(enabled);
refreshFlameImage(false);
}
}
finally {
- cmbRefreshing = false;
+ cmbRefreshing = oldCmbRefreshing;
}
}
public void nonlinearVarREdChanged(int pIdx) {
nonlinearVarREdChanged(pIdx, 0.0);
}
public void nonlinearVarREdChanged(int pIdx, double pDelta) {
if (cmbRefreshing) {
return;
}
cmbRefreshing = true;
try {
XForm xForm = getCurrXForm();
if (xForm != null) {
if (pIdx < xForm.getVariationCount()) {
Variation var = xForm.getVariation(pIdx);
String varStr = nonlinearControlsRows[pIdx].getNonlinearVarREd().getText();
if (varStr == null || varStr.length() == 0) {
varStr = "0";
}
var.setAmount(Tools.stringToDouble(varStr) + pDelta);
nonlinearControlsRows[pIdx].getNonlinearVarREd().setText(Tools.doubleToString(var.getAmount()));
refreshFlameImage(false);
}
}
}
finally {
cmbRefreshing = false;
}
}
public void nonlinearParamsREdChanged(int pIdx) {
nonlinearParamsREdChanged(pIdx, 0.0);
}
public void nonlinearParamsREdChanged(int pIdx, double pDelta) {
if (cmbRefreshing) {
return;
}
cmbRefreshing = true;
try {
String selected = (String) nonlinearControlsRows[pIdx].getNonlinearParamsCmb().getSelectedItem();
XForm xForm = getCurrXForm();
if (xForm != null && selected != null && selected.length() > 0) {
if (pIdx < xForm.getVariationCount()) {
Variation var = xForm.getVariation(pIdx);
int idx;
if ((idx = var.getFunc().getParameterIndex(selected)) >= 0) {
String valStr = nonlinearControlsRows[pIdx].getNonlinearParamsREd().getText();
if (valStr == null || valStr.length() == 0) {
valStr = "0";
}
// round the delta to whole numbers if the parameter is of type integer
if (Math.abs(pDelta) > Tools.EPSILON) {
Object val = var.getFunc().getParameterValues()[idx];
if (val != null && val instanceof Integer) {
if (Math.abs(pDelta) < 1.0) {
pDelta = pDelta < 0 ? -1 : 1;
}
else {
pDelta = Math.round(pDelta);
}
}
}
double val = Tools.stringToDouble(valStr) + pDelta;
var.getFunc().setParameter(selected, val);
nonlinearControlsRows[pIdx].getNonlinearParamsREd().setText(Tools.doubleToString(val));
}
else if ((idx = var.getFunc().getRessourceIndex(selected)) >= 0) {
RessourceDialog dlg = new RessourceDialog(SwingUtilities.getWindowAncestor(centerPanel));
String rName = var.getFunc().getRessourceNames()[idx];
dlg.setRessourceName(rName);
byte val[] = var.getFunc().getRessourceValues()[idx];
if (val != null) {
dlg.setRessourceValue(new String(val));
}
dlg.setModal(true);
dlg.setVisible(true);
if (dlg.isConfirmed()) {
try {
String valStr = dlg.getRessourceValue();
byte[] valByteArray = valStr != null ? valStr.getBytes() : null;
var.getFunc().setRessource(rName, valByteArray);
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
}
refreshFlameImage(false);
}
}
}
finally {
cmbRefreshing = false;
}
}
public void nonlinearParamsCmbChanged(int pIdx) {
if (cmbRefreshing) {
return;
}
cmbRefreshing = true;
try {
String selected = (String) nonlinearControlsRows[pIdx].getNonlinearParamsCmb().getSelectedItem();
XForm xForm = getCurrXForm();
if (xForm != null && selected != null && selected.length() > 0) {
if (pIdx < xForm.getVariationCount()) {
Variation var = xForm.getVariation(pIdx);
// params
int idx;
if ((idx = var.getFunc().getParameterIndex(selected)) >= 0) {
enableNonlinearControls(nonlinearControlsRows[pIdx], false);
Object val = var.getFunc().getParameterValues()[idx];
if (val instanceof Double) {
nonlinearControlsRows[pIdx].getNonlinearParamsREd().setText(Tools.doubleToString((Double) val));
}
else {
nonlinearControlsRows[pIdx].getNonlinearParamsREd().setText(val.toString());
}
}
// ressources
else if ((idx = var.getFunc().getRessourceIndex(selected)) >= 0) {
enableNonlinearControls(nonlinearControlsRows[pIdx], true);
nonlinearControlsRows[pIdx].getNonlinearParamsREd().setText(null);
}
// empty
else {
nonlinearControlsRows[pIdx].getNonlinearParamsREd().setText(null);
}
}
}
}
finally {
cmbRefreshing = false;
}
}
private void enableNonlinearControls(NonlinearControlsRow pRow, boolean pRessource) {
String selected = (String) pRow.getNonlinearParamsCmb().getSelectedItem();
boolean enabled = selected != null && selected.length() > 0;
pRow.getNonlinearParamsLeftButton().setEnabled(enabled);
pRow.getNonlinearParamsRightButton().setEnabled(enabled && !pRessource);
pRow.getNonlinearParamsREd().setEnabled(!pRessource);
}
private final double DELTA_VAR = 0.05;
private final double DELTA_PARAM = 0.1;
public void nonlinearVarLeftButtonClicked(int pIdx) {
nonlinearVarREdChanged(pIdx, -DELTA_VAR);
}
public void nonlinearVarRightButtonClicked(int pIdx) {
nonlinearVarREdChanged(pIdx, DELTA_VAR);
}
public void nonlinearParamsLeftButtonClicked(int pIdx) {
nonlinearParamsREdChanged(pIdx, -DELTA_PARAM);
}
public void nonlinearParamsRightButtonClicked(int pIdx) {
nonlinearParamsREdChanged(pIdx, DELTA_PARAM);
}
public void xFormSymmetrySlider_changed() {
xFormSliderChanged(xFormSymmetrySlider, xFormSymmetryREd, "colorSymmetry", SLIDER_SCALE_COLOR);
}
public void xFormOpacityREd_changed() {
xFormTextFieldChanged(xFormOpacitySlider, xFormOpacityREd, "opacity", SLIDER_SCALE_COLOR);
}
public void xFormOpacitySlider_changed() {
xFormSliderChanged(xFormOpacitySlider, xFormOpacityREd, "opacity", SLIDER_SCALE_COLOR);
}
public void xFormDrawModeCmb_changed() {
if (!cmbRefreshing) {
XForm xForm = getCurrXForm();
if (xForm != null && xFormDrawModeCmb.getSelectedItem() != null) {
xForm.setDrawMode((DrawMode) xFormDrawModeCmb.getSelectedItem());
refreshFlameImage(false);
enableXFormControls(xForm);
}
}
}
public void xFormColorSlider_changed() {
xFormSliderChanged(xFormColorSlider, xFormColorREd, "color", SLIDER_SCALE_COLOR);
}
public void xFormSymmetryREd_changed() {
xFormTextFieldChanged(xFormSymmetrySlider, xFormSymmetryREd, "colorSymmetry", SLIDER_SCALE_COLOR);
}
public void xFormColorREd_changed() {
xFormTextFieldChanged(xFormColorSlider, xFormColorREd, "color", SLIDER_SCALE_COLOR);
}
private void relWeightsChanged(double pDelta) {
XForm xForm = getCurrXForm();
Flame currFlame = getCurrFlame();
if (xForm != null && currFlame != null && xForm != currFlame.getFinalXForm()) {
int row = relWeightsTable.getSelectedRow();
if (row >= 0 && row < currFlame.getXForms().size()) {
xForm.getModifiedWeights()[row] += pDelta;
gridRefreshing = true;
try {
refreshRelWeightsTable();
relWeightsTable.getSelectionModel().setSelectionInterval(row, row);
refreshFlameImage(false);
}
finally {
gridRefreshing = false;
}
}
}
}
private void transformationWeightChanged(double pDelta) {
XForm xForm = getCurrXForm();
Flame currFlame = getCurrFlame();
if (xForm != null && currFlame != null && xForm != currFlame.getFinalXForm()) {
xForm.setWeight(xForm.getWeight() + pDelta);
gridRefreshing = true;
try {
int row = transformationsTable.getSelectedRow();
refreshTransformationsTable();
transformationsTable.getSelectionModel().setSelectionInterval(row, row);
refreshFlameImage(false);
}
finally {
gridRefreshing = false;
}
}
}
public void relWeightsLeftButton_clicked() {
relWeightsChanged(-DELTA_PARAM);
}
public void relWeightsRightButton_clicked() {
relWeightsChanged(DELTA_PARAM);
}
public void transformationWeightRightButton_clicked() {
transformationWeightChanged(DELTA_PARAM);
}
public void transformationWeightLeftButton_clicked() {
transformationWeightChanged(-DELTA_PARAM);
}
public void newFlameButton_clicked() {
Flame flame = new Flame();
flame.setWidth(800);
flame.setHeight(600);
flame.setPixelsPerUnit(50);
RGBPalette palette = new RandomRGBPaletteGenerator().generatePalette(Integer.parseInt(paletteRandomPointsREd.getText()));
flame.setPalette(palette);
_currFlame = flame;
refreshUI();
}
public void renderModeCmb_changed() {
if (!refreshing && !cmbRefreshing) {
refreshFlameImage(false);
}
}
public void zStyleCmb_changed() {
if (!refreshing && !cmbRefreshing) {
refreshFlameImage(false);
}
}
public void setMorphFlame1() {
if (_currFlame != null) {
morphFlame1 = _currFlame.makeCopy();
lastMorphedFrame = -1;
enableControls();
refreshFlameImage(false);
}
}
public void setMorphFlame2() {
if (_currFlame != null) {
morphFlame2 = _currFlame.makeCopy();
lastMorphedFrame = -1;
enableControls();
refreshFlameImage(false);
}
}
public void morphFramesREd_changed() {
int frame = Integer.parseInt(morphFramesREd.getText());
if (!refreshing) {
refreshing = true;
try {
morphFrameSlider.setMaximum(frame);
lastMorphedFrame = -1;
}
finally {
refreshing = false;
}
}
}
public void morphFrameREd_changed() {
int frame = Integer.parseInt(morphFramesREd.getText());
if (!refreshing) {
refreshing = true;
try {
morphFrameSlider.setValue(frame);
lastMorphedFrame = -1;
refreshFlameImage(false);
}
finally {
refreshing = false;
}
}
}
public void morphCheckBox_changed() {
lastMorphedFrame = -1;
refreshFlameImage(false);
}
public void morphFrameSlider_changed() {
int frame = morphFrameSlider.getValue();
if (!refreshing) {
refreshing = true;
try {
morphFrameREd.setText(String.valueOf(frame));
lastMorphedFrame = -1;
refreshFlameImage(false);
}
finally {
refreshing = false;
}
}
}
public void importMorphedFlameButton_clicked() {
if (morphCheckBox.isSelected()) {
Flame flame = getCurrFlame();
if (flame != null) {
randomBatch.add(0, flame);
updateThumbnails(null);
}
}
}
public void animationGenerateButton_clicked() {
try {
int frames = Integer.parseInt(animateFramesREd.getText());
boolean doMorph = morphCheckBox.isSelected();
GlobalScript globalScript = (GlobalScript) animateGlobalScriptCmb.getSelectedItem();
XFormScript xFormScript = (XFormScript) animateXFormScriptCmb.getSelectedItem();
LightScript lightScript = (LightScript) animateLightScriptCmb.getSelectedItem();
String imagePath = animateOutputREd.getText();
int width = prefs.getTinaRenderMovieWidth();
int height = prefs.getTinaRenderMovieHeight();
int quality = prefs.getTinaRenderMovieQuality();
AffineZStyle affineZStyle = (AffineZStyle) zStyleCmb.getSelectedItem();
for (int frame = 1; frame <= frames; frame++) {
Flame flame1 = doMorph ? morphFlame1.makeCopy() : _currFlame.makeCopy();
Flame flame2 = doMorph ? morphFlame2.makeCopy() : null;
flame1.setSpatialOversample(prefs.getTinaRenderMovieSpatialOversample());
flame1.setColorOversample(prefs.getTinaRenderMovieColorOversample());
flame1.setSpatialFilterRadius(prefs.getTinaRenderMovieFilterRadius());
AnimationService.renderFrame(frame, frames, flame1, flame2, doMorph, globalScript, xFormScript, lightScript, imagePath, width, height, quality, affineZStyle, prefs);
}
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
@Override
public Flame getFlame() {
return getCurrFlame();
}
private void flamePanel_mouseDragged(MouseEvent e) {
if (flamePanel != null) {
if (flamePanel.mouseDragged(e.getX(), e.getY())) {
refreshXFormUI(getCurrXForm());
refreshFlameImage(true);
}
}
}
private void flamePanel_mousePressed(MouseEvent e) {
if (flamePanel != null) {
flamePanel.mousePressed(e.getX(), e.getY());
}
}
private void flamePanel_mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
renderFlameButton_actionPerformed(null);
}
else if (e.getClickCount() == 1) {
Flame flame = getCurrFlame();
if (flame != null && flamePanel != null) {
XForm xForm = flamePanel.mouseClicked(e.getX(), e.getY());
if (xForm != null) {
for (int i = 0; i < flame.getXForms().size(); i++) {
if (xForm == flame.getXForms().get(i)) {
transformationsTable.getSelectionModel().setSelectionInterval(i, i);
return;
}
}
if (xForm == flame.getFinalXForm()) {
int row = flame.getXForms().size();
transformationsTable.getSelectionModel().setSelectionInterval(row, row);
return;
}
}
}
}
}
public void mouseTransformMoveButton_clicked() {
if (!refreshing) {
refreshing = true;
try {
mouseTransformRotateButton.setSelected(false);
mouseTransformScaleButton.setSelected(false);
if (flamePanel != null) {
flamePanel.setMouseDragOperation(mouseTransformMoveButton.isSelected() ? MouseDragOperation.MOVE : MouseDragOperation.NONE);
}
}
finally {
refreshing = false;
}
}
}
public void mouseTransformRotateButton_clicked() {
if (!refreshing) {
refreshing = true;
try {
mouseTransformMoveButton.setSelected(false);
mouseTransformScaleButton.setSelected(false);
if (flamePanel != null) {
flamePanel.setMouseDragOperation(mouseTransformRotateButton.isSelected() ? MouseDragOperation.ROTATE : MouseDragOperation.NONE);
}
}
finally {
refreshing = false;
}
}
}
public void mouseTransformScaleButton_clicked() {
if (!refreshing) {
refreshing = true;
try {
mouseTransformMoveButton.setSelected(false);
mouseTransformRotateButton.setSelected(false);
if (flamePanel != null) {
flamePanel.setMouseDragOperation(mouseTransformScaleButton.isSelected() ? MouseDragOperation.SCALE : MouseDragOperation.NONE);
}
}
finally {
refreshing = false;
}
}
}
public void setMainController(MainController pMainController) {
mainController = pMainController;
}
public void affineEditPostTransformButton_clicked() {
if (refreshing) {
return;
}
refreshing = true;
try {
if (!toggleTrianglesButton.isSelected()) {
flamePanel.setDrawFlame(true);
toggleTrianglesButton.setSelected(true);
}
XForm xForm = getCurrXForm();
if (flamePanel != null) {
flamePanel.setEditPostTransform(affineEditPostTransformButton.isSelected());
}
refreshXFormUI(xForm);
refreshFlameImage(false);
affineEditPostTransformSmallButton.setSelected(affineEditPostTransformButton.isSelected());
}
finally {
refreshing = false;
}
}
public void affineEditPostTransformSmallButton_clicked() {
refreshing = true;
try {
affineEditPostTransformButton.setSelected(affineEditPostTransformSmallButton.isSelected());
}
finally {
refreshing = false;
}
affineEditPostTransformButton_clicked();
}
public void mouseTransformZoomInButton_clicked() {
if (flamePanel != null) {
flamePanel.zoomIn();
refreshFlameImage(false);
}
}
public void mouseTransformZoomOutButton_clicked() {
if (flamePanel != null) {
flamePanel.zoomOut();
refreshFlameImage(false);
}
}
public void toggleTrianglesButton_clicked() {
if (refreshing) {
return;
}
if (flamePanel != null) {
flamePanel.setDrawFlame(toggleTrianglesButton.isSelected());
refreshFlameImage(false);
}
}
public void affineC21REd_changed() {
XForm xForm = getCurrXForm();
if (xForm != null) {
double value = Tools.stringToDouble(affineC21REd.getText());
if (affineEditPostTransformButton.isSelected()) {
xForm.setPostCoeff21(value);
}
else {
xForm.setCoeff21(value);
}
transformationTableClicked();
// refreshFlameImage();
}
}
public void affineC20REd_changed() {
XForm xForm = getCurrXForm();
if (xForm != null) {
double value = Tools.stringToDouble(affineC20REd.getText());
if (affineEditPostTransformButton.isSelected()) {
xForm.setPostCoeff20(value);
}
else {
xForm.setCoeff20(value);
}
transformationTableClicked();
// refreshFlameImage();
}
}
public void affineResetTransformButton_clicked() {
XForm xForm = getCurrXForm();
if (xForm != null) {
XFormTransformService.reset(xForm, affineEditPostTransformButton.isSelected());
transformationTableClicked();
// refreshFlameImage();
}
}
public void switchFrameMode(boolean pMovieMode) {
if (pMovieMode) {
flamePanel.setRenderWidth(prefs.getTinaRenderMovieWidth());
flamePanel.setRenderHeight(prefs.getTinaRenderMovieHeight());
}
else {
flamePanel.setRenderWidth(prefs.getTinaRenderImageWidth());
flamePanel.setRenderHeight(prefs.getTinaRenderImageHeight());
}
refreshFlameImage(false);
}
public void cameraZPosSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraZPosSlider, cameraZPosREd, "camZ", SLIDER_SCALE_ZPOS);
}
public void cameraDOFSlider_stateChanged(ChangeEvent e) {
flameSliderChanged(cameraDOFSlider, cameraDOFREd, "camDOF", SLIDER_SCALE_DOF);
}
public void cameraZPosREd_changed() {
flameTextFieldChanged(cameraZPosSlider, cameraZPosREd, "camZ", SLIDER_SCALE_ZPOS);
}
public void cameraDOFREd_changed() {
flameTextFieldChanged(cameraDOFSlider, cameraDOFREd, "camDOF", SLIDER_SCALE_DOF);
}
public void shadingAmbientREd_changed() {
shadingInfoTextFieldChanged(shadingAmbientSlider, shadingAmbientREd, "ambient", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingDiffuseREd_changed() {
shadingInfoTextFieldChanged(shadingDiffuseSlider, shadingDiffuseREd, "diffuse", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingPhongREd_changed() {
shadingInfoTextFieldChanged(shadingPhongSlider, shadingPhongREd, "phong", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingPhongSizeREd_changed() {
shadingInfoTextFieldChanged(shadingPhongSizeSlider, shadingPhongSizeREd, "phongSize", SLIDER_SCALE_PHONGSIZE, 0);
}
public void shadingLightXREd_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoTextFieldChanged(shadingLightXSlider, shadingLightXREd, "lightPosX", SLIDER_SCALE_LIGHTPOS, cIdx);
}
public void shadingLightYREd_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoTextFieldChanged(shadingLightYSlider, shadingLightYREd, "lightPosY", SLIDER_SCALE_LIGHTPOS, cIdx);
}
public void shadingLightZREd_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoTextFieldChanged(shadingLightZSlider, shadingLightZREd, "lightPosZ", SLIDER_SCALE_LIGHTPOS, cIdx);
}
public void shadingLightRedREd_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoTextFieldChanged(shadingLightRedSlider, shadingLightRedREd, "lightRed", 1.0, cIdx);
}
public void shadingLightGreenREd_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoTextFieldChanged(shadingLightGreenSlider, shadingLightGreenREd, "lightGreen", 1.0, cIdx);
}
public void shadingLightBlueREd_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoTextFieldChanged(shadingLightBlueSlider, shadingLightBlueREd, "lightBlue", 1.0, cIdx);
}
public void shadingLightBlueSlider_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoSliderChanged(shadingLightBlueSlider, shadingLightBlueREd, "lightBlue", 1.0, cIdx);
}
public void shadingLightGreenSlider_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoSliderChanged(shadingLightGreenSlider, shadingLightGreenREd, "lightGreen", 1.0, cIdx);
}
public void shadingAmbientSlider_changed() {
shadingInfoSliderChanged(shadingAmbientSlider, shadingAmbientREd, "ambient", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingDiffuseSlider_changed() {
shadingInfoSliderChanged(shadingDiffuseSlider, shadingDiffuseREd, "diffuse", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingPhongSlider_changed() {
shadingInfoSliderChanged(shadingPhongSlider, shadingPhongREd, "phong", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingCmb_changed() {
if (noRefresh) {
return;
}
Flame currFlame = getCurrFlame();
if (currFlame == null) {
return;
}
noRefresh = true;
try {
currFlame.getShadingInfo().setShading((Shading) shadingCmb.getSelectedItem());
refreshShadingUI();
enableShadingUI();
refreshFlameImage(false);
}
finally {
noRefresh = false;
}
}
public void shadingLightXSlider_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoSliderChanged(shadingLightXSlider, shadingLightXREd, "lightPosX", SLIDER_SCALE_LIGHTPOS, cIdx);
}
public void shadingLightYSlider_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoSliderChanged(shadingLightYSlider, shadingLightYREd, "lightPosY", SLIDER_SCALE_LIGHTPOS, cIdx);
}
public void shadingLightZSlider_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoSliderChanged(shadingLightZSlider, shadingLightZREd, "lightPosZ", SLIDER_SCALE_LIGHTPOS, cIdx);
}
public void shadingLightRedSlider_changed() {
int cIdx = shadingLightCmb.getSelectedIndex();
shadingInfoSliderChanged(shadingLightRedSlider, shadingLightRedREd, "lightRed", 1.0, cIdx);
}
public void shadingLightCmb_changed() {
if (noRefresh) {
return;
}
noRefresh = true;
try {
refreshShadingUI();
}
finally {
noRefresh = false;
}
}
public void shadingPhongSizeSlider_changed() {
shadingInfoSliderChanged(shadingPhongSizeSlider, shadingPhongSizeREd, "phongSize", SLIDER_SCALE_PHONGSIZE, 0);
}
public void loadFlameFromClipboard() {
try {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable clipData = clipboard.getContents(clipboard);
if (clipData != null) {
if (clipData.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String xml = (String) (clipData.getTransferData(
DataFlavor.stringFlavor));
List<Flame> flames = new Flam3Reader().readFlamesfromXML(xml);
Flame flame = flames.get(0);
_currFlame = flame;
for (int i = flames.size() - 1; i >= 0; i--) {
randomBatch.add(0, flames.get(i));
}
updateThumbnails(null);
refreshUI();
}
}
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
public void saveFlameToClipboard() {
try {
Flame currFlame = getCurrFlame();
if (currFlame != null) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String xml = new Flam3Writer().getFlameXML(currFlame);
StringSelection data = new StringSelection(xml);
clipboard.setContents(data, data);
}
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
public void mouseTransformSlowButton_clicked() {
if (flamePanel != null) {
flamePanel.setFineMovement(mouseTransformSlowButton.isSelected());
}
}
@Override
public void refreshRenderBatchJobsTable() {
final int COL_FLAME_FILE = 0;
final int COL_FINISHED = 1;
final int COL_ELAPSED = 2;
final int COL_LAST_ERROR = 3;
renderBatchJobsTable.setModel(new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getRowCount() {
return batchRenderList.size();
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case COL_FLAME_FILE:
return "Flame file";
case COL_FINISHED:
return "Finished";
case COL_ELAPSED:
return "Elapsed time (ms)";
case COL_LAST_ERROR:
return "Last error";
}
return null;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Job job = rowIndex < batchRenderList.size() ? batchRenderList.get(rowIndex) : null;
if (job != null) {
switch (columnIndex) {
case COL_FLAME_FILE:
return new File(job.getFlameFilename()).getName();
case COL_FINISHED:
return job.isFinished() ? String.valueOf(job.isFinished()) : "";
case COL_ELAPSED:
return job.isFinished() ? Tools.doubleToString(job.getElapsedSeconds()) : "";
case COL_LAST_ERROR:
return job.getLastErrorMsg();
}
}
return null;
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
renderBatchJobsTable.getTableHeader().setFont(transformationsTable.getFont());
renderBatchJobsTable.getColumnModel().getColumn(COL_FLAME_FILE).setWidth(120);
renderBatchJobsTable.getColumnModel().getColumn(COL_FINISHED).setPreferredWidth(10);
renderBatchJobsTable.getColumnModel().getColumn(COL_ELAPSED).setWidth(10);
renderBatchJobsTable.getColumnModel().getColumn(COL_LAST_ERROR).setWidth(120);
}
public void batchRenderAddFilesButton_clicked() {
if (jobRenderThread != null) {
return;
}
try {
JFileChooser chooser = new FlameFileChooser(prefs);
if (prefs.getInputFlamePath() != null) {
try {
chooser.setCurrentDirectory(new File(prefs.getInputFlamePath()));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
int jobCount = batchRenderList.size();
chooser.setMultiSelectionEnabled(true);
if (chooser.showOpenDialog(centerPanel) == JFileChooser.APPROVE_OPTION) {
for (File file : chooser.getSelectedFiles()) {
String filename = file.getPath();
boolean hasFile = false;
for (Job job : batchRenderList) {
if (job.getFlameFilename().equals(filename)) {
hasFile = true;
break;
}
}
if (!hasFile) {
Job job = new Job();
job.setFlameFilename(filename);
batchRenderList.add(job);
}
}
}
if (jobCount != batchRenderList.size()) {
refreshRenderBatchJobsTable();
}
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
public void batchRenderFilesMoveUpButton_clicked() {
if (jobRenderThread != null) {
return;
}
int row = renderBatchJobsTable.getSelectedRow();
if (row < 0 && batchRenderList.size() > 0) {
row = 0;
renderBatchJobsTable.getSelectionModel().setSelectionInterval(row, row);
}
else if (row > 0 && row < batchRenderList.size()) {
Job t = batchRenderList.get(row - 1);
batchRenderList.set(row - 1, batchRenderList.get(row));
batchRenderList.set(row, t);
refreshRenderBatchJobsTable();
renderBatchJobsTable.getSelectionModel().setSelectionInterval(row - 1, row - 1);
}
}
public void batchRenderFilesMoveDownButton_clicked() {
if (jobRenderThread != null) {
return;
}
int row = renderBatchJobsTable.getSelectedRow();
if (row < 0 && batchRenderList.size() > 0) {
row = 0;
renderBatchJobsTable.getSelectionModel().setSelectionInterval(row, row);
}
else if (row >= 0 && row < batchRenderList.size() - 1) {
Job t = batchRenderList.get(row + 1);
batchRenderList.set(row + 1, batchRenderList.get(row));
batchRenderList.set(row, t);
refreshRenderBatchJobsTable();
renderBatchJobsTable.getSelectionModel().setSelectionInterval(row + 1, row + 1);
}
}
private JobRenderThread jobRenderThread = null;
public void batchRenderStartButton_clicked() {
if (jobRenderThread != null) {
jobRenderThread.setCancelSignalled(true);
return;
}
List<Job> activeJobList = new ArrayList<Job>();
for (Job job : batchRenderList) {
if (!job.isFinished()) {
activeJobList.add(job);
}
}
if (activeJobList.size() > 0) {
jobRenderThread = new JobRenderThread(this, activeJobList);
new Thread(jobRenderThread).start();
}
enableJobRenderControls();
}
public void batchRenderFilesRemoveAllButton_clicked() {
if (jobRenderThread != null) {
return;
}
batchRenderList.clear();
refreshRenderBatchJobsTable();
}
public void batchRenderFilesRemoveButton_clicked() {
if (jobRenderThread != null) {
return;
}
int row = renderBatchJobsTable.getSelectedRow();
if (row >= 0 && row < batchRenderList.size()) {
batchRenderList.remove(row);
refreshRenderBatchJobsTable();
if (row >= batchRenderList.size()) {
row--;
}
if (row >= 0 && row < batchRenderList.size()) {
renderBatchJobsTable.getSelectionModel().setSelectionInterval(row, row);
}
}
}
@Override
public Prefs getPrefs() {
return prefs;
}
@Override
public JProgressBar getTotalProgressBar() {
return batchRenderTotalProgressBar;
}
@Override
public JProgressBar getJobProgressBar() {
return batchRenderJobProgressBar;
}
@Override
public ProgressUpdater getJobProgressUpdater() {
return jobProgressUpdater;
}
@Override
public void onJobFinished() {
jobRenderThread = null;
System.err.println("JOB FINISHED");
enableJobRenderControls();
}
@Override
public AffineZStyle getZStyle() {
return (AffineZStyle) zStyleCmb.getSelectedItem();
}
@Override
public JTable getRenderBatchJobsTable() {
return renderBatchJobsTable;
}
public void toggleDarkTriangles() {
if (refreshing) {
return;
}
if (flamePanel != null) {
flamePanel.setDarkTriangles(toggleDarkTrianglesButton.isSelected());
refreshFlameImage(false);
}
}
public void shadingBlurFadeREd_changed() {
shadingInfoTextFieldChanged(shadingBlurFadeSlider, shadingBlurFadeREd, "blurFade", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingBlurFallOffREd_changed() {
shadingInfoTextFieldChanged(shadingBlurFallOffSlider, shadingBlurFallOffREd, "blurFallOff", SLIDER_SCALE_BLUR_FALLOFF, 0);
}
public void shadingBlurRadiusREd_changed() {
shadingInfoTextFieldChanged(shadingBlurRadiusSlider, shadingBlurRadiusREd, "blurRadius", 1.0, 0);
}
public void shadingBlurFallOffSlider_changed() {
shadingInfoSliderChanged(shadingBlurFallOffSlider, shadingBlurFallOffREd, "blurFallOff", SLIDER_SCALE_BLUR_FALLOFF, 0);
}
public void shadingBlurFadeSlider_changed() {
shadingInfoSliderChanged(shadingBlurFadeSlider, shadingBlurFadeREd, "blurFade", SLIDER_SCALE_AMBIENT, 0);
}
public void shadingBlurRadiusSlider_changed() {
shadingInfoSliderChanged(shadingBlurRadiusSlider, shadingBlurRadiusREd, "blurRadius", 1.0, 0);
}
private ScriptRunner compileScript() throws Exception {
return ScriptRunner.compile(scriptTextArea.getText());
}
public void runScriptButton_clicked() {
try {
ScriptRunner script = compileScript();
script.run(this);
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
public void compileScriptButton_clicked() {
try {
compileScript();
}
catch (Throwable ex) {
errorHandler.handleError(ex);
}
}
public void affineScaleXButton_stateChanged() {
if (flamePanel != null) {
flamePanel.setAllowScaleX(affineScaleXButton.isSelected());
}
}
public void affineScaleYButton_stateChanged() {
if (flamePanel != null) {
flamePanel.setAllowScaleY(affineScaleYButton.isSelected());
}
}
public void distributeColorsBtn_clicked() {
Flame flame = getCurrFlame();
if (flame != null) {
flame.distributeColors();
transformationTableClicked();
}
}
public void randomizeColorsBtn_clicked() {
Flame flame = getCurrFlame();
if (flame != null) {
flame.randomizeColors();
transformationTableClicked();
}
}
public void paletteSwapRGBREd_changed() {
paletteTextFieldChanged(paletteSwapRGBSlider, paletteSwapRGBREd, "modSwapRGB", 1.0);
}
public void paletteSwapRGBSlider_stateChanged(ChangeEvent e) {
paletteSliderChanged(paletteSwapRGBSlider, paletteSwapRGBREd, "modSwapRGB", 1.0);
}
}
diff --git a/src/org/jwildfire/create/tina/variation/Variation.java b/src/org/jwildfire/create/tina/variation/Variation.java
index f8c853a2..1a4a0904 100644
--- a/src/org/jwildfire/create/tina/variation/Variation.java
+++ b/src/org/jwildfire/create/tina/variation/Variation.java
@@ -1,84 +1,85 @@
/*
JWildfire - an image and animation processor written in Java
Copyright (C) 1995-2011 Andreas Maschke
This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this software;
if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jwildfire.create.tina.variation;
import org.jwildfire.create.tina.base.XForm;
import org.jwildfire.create.tina.base.XYZPoint;
public class Variation {
private double amount;
private VariationFunc func;
public double getAmount() {
return amount;
}
public void setAmount(double pAmount) {
this.amount = pAmount;
}
public VariationFunc getFunc() {
return func;
}
public void setFunc(VariationFunc func) {
this.func = func;
}
public void transform(FlameTransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP) {
func.transform(pContext, pXForm, pAffineTP, pVarTP, amount);
}
@Override
public String toString() {
return func.getName() + "(" + amount + ")";
}
public void assign(Variation var) {
amount = var.amount;
func = VariationFuncList.getVariationFuncInstance(var.func.getName());
+
// params
{
String[] paramNames = var.func.getParameterNames();
if (paramNames != null) {
for (int i = 0; i < paramNames.length; i++) {
Object val = var.func.getParameterValues()[i];
if (val instanceof Double) {
func.setParameter(paramNames[i], (Double) val);
}
else if (val instanceof Integer) {
func.setParameter(paramNames[i], Double.valueOf(((Integer) val)));
}
else {
throw new IllegalStateException();
}
}
}
}
// ressources
{
String[] ressNames = var.func.getRessourceNames();
if (ressNames != null) {
for (int i = 0; i < ressNames.length; i++) {
byte[] val = var.func.getRessourceValues()[i];
func.setRessource(ressNames[i], val);
}
}
}
}
}
| false | false | null | null |
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/sync/UnchangedTeamContainer.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/sync/UnchangedTeamContainer.java
index 95c8002c0..46c85c794 100644
--- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/sync/UnchangedTeamContainer.java
+++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/sync/UnchangedTeamContainer.java
@@ -1,65 +1,60 @@
package org.eclipse.team.ui.sync;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.compare.CompareUI;
import org.eclipse.compare.ITypedElement;
+import org.eclipse.compare.ResourceNode;
import org.eclipse.compare.structuremergeviewer.DiffNode;
import org.eclipse.compare.structuremergeviewer.Differencer;
import org.eclipse.compare.structuremergeviewer.IDiffContainer;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.graphics.Image;
/**
* A node in a diff tree that represents a folder with no changes
* to itself, it is only a placeholder for changes in its children.
*/
public class UnchangedTeamContainer extends DiffNode implements ITeamNode {
private IResource resource;
public UnchangedTeamContainer(IDiffContainer parent, IResource resource) {
this(parent, resource, Differencer.NO_CHANGE);
}
public UnchangedTeamContainer(IDiffContainer parent, IResource resource, int description) {
super(parent, description);
+ setLeft(new ResourceNode(resource));
this.resource = resource;
}
/*
* Method declared on ITeamNode
*/
public int getChangeDirection() {
return ITeamNode.NO_CHANGE;
}
public Image getImage() {
return CompareUI.getImage(getType());
}
public String getName() {
return resource.getName();
}
/**
* Returns the resource underlying this diff node.
*/
public IResource getResource() {
return resource;
}
public String getType() {
return ITypedElement.FOLDER_TYPE;
}
-
- /**
- * For debugging purposes only.
- */
- public String toString() {
- return "UnchangedTeamContainer(" + resource.getName() + ")";
- }
}
| false | false | null | null |
diff --git a/jython/org/python/core/PyBuiltinFunctionSet.java b/jython/org/python/core/PyBuiltinFunctionSet.java
index addae502..a4dc7f8e 100644
--- a/jython/org/python/core/PyBuiltinFunctionSet.java
+++ b/jython/org/python/core/PyBuiltinFunctionSet.java
@@ -1,121 +1,120 @@
// Copyright � Corporation for National Research Initiatives
package org.python.core;
public class PyBuiltinFunctionSet extends PyObject
{
// part of the public interface for built-in functions
public PyObject __name__;
public PyObject __doc__;
public PyObject __self__;
public static PyObject __members__;
// internal implementation
protected String name;
protected int minargs, maxargs;
protected boolean isMethod;
// used as an index into a big switch statement in the various derived
// class's __call__() methods.
protected int index;
static {
PyString[] members = new PyString[3];
members[0] = new PyString("__doc__");
members[1] = new PyString("__name__");
members[2] = new PyString("__self__");
__members__ = new PyList(members);
}
// full-blown constructor, specifying everything
public PyBuiltinFunctionSet(String name, int index, int minargs,
int maxargs, boolean isMethod, String doc)
{
this.name = name;
this.index = index;
this.minargs = minargs;
this.maxargs = maxargs;
this.isMethod = isMethod;
__name__ = new PyString(name);
if (doc == null)
__doc__ = Py.None;
else
__doc__ = new PyString(doc);
__self__ = Py.None;
}
public PyObject _doget(PyObject container) {
return _doget(container, null);
}
public PyObject _doget(PyObject container, PyObject wherefound) {
if (isMethod)
- return new PyMethod(container, this, wherefound);
- else
- return this;
+ __self__ = container;
+ return this;
}
public String toString() {
if (isMethod) {
return "<builtin method '"+name+"'>";
} else {
return "<builtin function '"+name+"'>";
}
}
public PyException argCountError(int nargs) {
if (minargs == maxargs) {
return Py.TypeError(name+"(): expected "+minargs+" args; got "+
nargs);
} else {
return Py.TypeError(name+"(): expected "+minargs+"-"+maxargs+
" args; got "+nargs);
}
}
public PyObject fancyCall(PyObject[] args) {
throw Py.TypeError("surprising call");
}
public PyObject __call__(PyObject[] args) {
int nargs = args.length;
if (minargs != -1 && nargs > minargs || nargs < minargs) {
throw argCountError(nargs);
}
switch (nargs) {
case 0:
return __call__();
case 1:
return __call__(args[0]);
case 2:
return __call__(args[0], args[1]);
case 3:
return __call__(args[0], args[1], args[2]);
case 4:
return __call__(args[0], args[1], args[2], args[3]);
default:
return fancyCall(args);
}
}
public PyObject __call__() {
throw argCountError(0);
}
public PyObject __call__(PyObject arg1) {
throw argCountError(1);
}
public PyObject __call__(PyObject arg1, PyObject arg2) {
throw argCountError(2);
}
public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) {
throw argCountError(3);
}
public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3,
PyObject arg4)
{
throw argCountError(4);
}
}
| true | false | null | null |
diff --git a/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommandLineManager.java b/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommandLineManager.java
index e6c0efe..0c4ecef 100644
--- a/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommandLineManager.java
+++ b/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommandLineManager.java
@@ -1,209 +1,206 @@
package org.jaggeryjs.jaggery.core.manager;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaggeryjs.jaggery.core.ScriptReader;
import org.jaggeryjs.scriptengine.cache.CacheManager;
-import org.jaggeryjs.scriptengine.engine.JaggeryContext;
-import org.jaggeryjs.scriptengine.engine.JavaScriptHostObject;
-import org.jaggeryjs.scriptengine.engine.JavaScriptMethod;
-import org.jaggeryjs.scriptengine.engine.RhinoEngine;
+import org.jaggeryjs.scriptengine.engine.*;
import org.jaggeryjs.scriptengine.exceptions.ScriptException;
import org.jaggeryjs.scriptengine.security.RhinoSecurityController;
import org.jaggeryjs.scriptengine.util.HostObjectUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
/**
* Shares the common functionality, of initialization of functions, and Host Objects
*/
public final class CommandLineManager {
private static final Log log = LogFactory.getLog(CommandLineManager.class);
private static final RhinoEngine RHINO_ENGINE;
public static final int ENV_COMMAND_LINE = 1;
public static final String JAGGERY_CONTEXT = "jaggeryContext";
private CommandLineManager(String jaggeryDir) throws ScriptException {
CommonManager.getInstance().initialize(jaggeryDir, null);
}
static {
- RHINO_ENGINE = new RhinoEngine(new CacheManager(null), new RhinoSecurityController());
+ RHINO_ENGINE = new RhinoEngine(new CacheManager(null), new RhinoContextFactory(new RhinoSecurityController()));
initEngine();
}
public static RhinoEngine getCommandLineEngine() {
return RHINO_ENGINE;
}
protected static void initEngine() {
try {
InputStream inputStream = CommandLineManager.class.
getClassLoader().getResourceAsStream("META-INF/hostobjects.xml");
StAXOMBuilder builder = new StAXOMBuilder(inputStream);
OMElement document = builder.getDocumentElement();
Iterator itr = document.getChildrenWithLocalName("hostObject");
String msg = "Error while registering HostObject : ";
while (itr.hasNext()) {
OMElement hostObject = (OMElement) itr.next();
String name = hostObject.getFirstChildWithName(new QName(null, "name")).getText();
String className = hostObject.getFirstChildWithName(new QName(null, "className")).getText();
JavaScriptHostObject ho = new JavaScriptHostObject(name);
try {
ho.setClazz(Class.forName(className));
RHINO_ENGINE.defineHostObject(ho);
} catch (ClassNotFoundException e) {
msg += name + " " + e.getMessage();
log.error(msg, e);
}
}
} catch (XMLStreamException e) {
log.error("Error while reading the hostobjects.xml", e);
}
initGlobalProperties();
//engine.sealEngine();
}
private static void initGlobalProperties() {
JavaScriptMethod method = new JavaScriptMethod("print");
method.setMethodName("print");
method.setClazz(CommandLineManager.class);
RHINO_ENGINE.defineMethod(method);
}
/**
* Method responsible of writing to the output stream
*/
public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
String functionName = "print";
JaggeryContext jaggeryContext = CommandLineManager.getJaggeryContext();
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs("RhinoTopLevel", functionName, argsCount, false);
}
PrintWriter writer = new PrintWriter((OutputStream) jaggeryContext.getProperty(
CommonManager.JAGGERY_OUTPUT_STREAM));
writer.write(HostObjectUtil.serializeObject(args[0]));
writer.flush();
}
public static JaggeryContext getJaggeryContext() {
return (JaggeryContext) RhinoEngine.getContextProperty(CommandLineManager.JAGGERY_CONTEXT);
}
public static void setJaggeryContext(JaggeryContext jaggeryContext) {
RhinoEngine.putContextProperty(CommandLineManager.JAGGERY_CONTEXT, jaggeryContext);
}
public static void include(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "include";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(CommonManager.HOST_OBJECT_NAME, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(CommonManager.HOST_OBJECT_NAME, functionName, "1", "string", args[0], false);
}
JaggeryContext jaggeryContext = CommonManager.getJaggeryContext();
Stack<String> includesCallstack = CommonManager.getCallstack(jaggeryContext);
Map<String, Boolean> includedScripts = CommonManager.getIncludes(jaggeryContext);
String parent = includesCallstack.lastElement();
String fileURL = (String) args[0];
if (CommonManager.isHTTP(fileURL) || CommonManager.isHTTP(parent)) {
CommonManager.include(cx, thisObj, args, funObj);
return;
}
ScriptableObject scope = jaggeryContext.getScope();
RhinoEngine engine = jaggeryContext.getEngine();
if (fileURL.startsWith("/")) {
fileURL = includesCallstack.firstElement() + fileURL;
} else {
fileURL = FilenameUtils.getFullPath(parent) + fileURL;
}
fileURL = FilenameUtils.normalize(fileURL);
if (includesCallstack.search(fileURL) != -1) {
return;
}
ScriptReader source = null;
try {
source = new ScriptReader(new FileInputStream(fileURL));
includedScripts.put(fileURL, true);
includesCallstack.push(fileURL);
engine.exec(source, scope, null);
includesCallstack.pop();
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
}
}
public static void include_once(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "include_once";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(CommonManager.HOST_OBJECT_NAME, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(CommonManager.HOST_OBJECT_NAME, functionName, "1", "string", args[0], false);
}
JaggeryContext jaggeryContext = CommonManager.getJaggeryContext();
Stack<String> includesCallstack = CommonManager.getCallstack(jaggeryContext);
Map<String, Boolean> includedScripts = CommonManager.getIncludes(jaggeryContext);
String parent = includesCallstack.lastElement();
String fileURL = (String) args[0];
if (CommonManager.isHTTP(fileURL) || CommonManager.isHTTP(parent)) {
CommonManager.include_once(cx, thisObj, args, funObj);
return;
}
ScriptableObject scope = jaggeryContext.getScope();
RhinoEngine engine = jaggeryContext.getEngine();
if (fileURL.startsWith("/")) {
fileURL = includesCallstack.firstElement() + fileURL;
} else {
fileURL = FilenameUtils.getFullPath(parent) + fileURL;
}
fileURL = FilenameUtils.normalize(fileURL);
if (includesCallstack.search(fileURL) != -1) {
return;
}
if (includedScripts.get(fileURL) != null) {
return;
}
try {
ScriptReader source = new ScriptReader(new FileInputStream(fileURL));
includedScripts.put(fileURL, true);
includesCallstack.push(fileURL);
engine.exec(source, scope, null);
includesCallstack.pop();
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
}
}
}
diff --git a/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommonManager.java b/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommonManager.java
index ea1a6ad..b1b6ded 100644
--- a/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommonManager.java
+++ b/components/jaggery-core/org.jaggeryjs.jaggery.core/src/main/java/org/jaggeryjs/jaggery/core/manager/CommonManager.java
@@ -1,332 +1,332 @@
package org.jaggeryjs.jaggery.core.manager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaggeryjs.hostobjects.stream.StreamHostObject;
import org.jaggeryjs.hostobjects.web.Constants;
import org.jaggeryjs.jaggery.core.ScriptReader;
import org.jaggeryjs.scriptengine.EngineConstants;
import org.jaggeryjs.scriptengine.cache.CacheManager;
import org.jaggeryjs.scriptengine.engine.*;
import org.jaggeryjs.scriptengine.exceptions.ScriptException;
import org.jaggeryjs.scriptengine.security.RhinoSecurityController;
import org.jaggeryjs.scriptengine.util.HostObjectUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.wso2.carbon.context.CarbonContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Shares the common functionality, of initialization of functions, and Host Objects
*/
public class CommonManager {
private static final int BYTE_BUFFER_SIZE = 1024;
private static final Log log = LogFactory.getLog(CommonManager.class);
public static final String JAGGERY_URLS_MAP = "jaggery.urls.map";
public static final String JAGGERY_OUTPUT_STREAM = "jaggery.output.stream";
public static final String HOST_OBJECT_NAME = "RhinoTopLevel";
private static CommonManager manager;
private RhinoEngine engine = null;
private ModuleManager moduleManager = null;
private CommonManager() throws ScriptException {
}
public static CommonManager getInstance() throws ScriptException {
if (manager == null) {
manager = new CommonManager();
}
return manager;
}
public RhinoEngine getEngine() {
return this.engine;
}
public ModuleManager getModuleManager() {
return this.moduleManager;
}
public void initialize(String modulesDir, RhinoSecurityController securityController)
throws ScriptException {
- this.engine = new RhinoEngine(new CacheManager(null), securityController);
+ this.engine = new RhinoEngine(new CacheManager(null), new RhinoContextFactory(securityController));
this.moduleManager = new ModuleManager(modulesDir);
exposeDefaultModules(this.engine, this.moduleManager.getModules());
}
public static void initContext(JaggeryContext context) throws ScriptException {
context.setEngine(manager.engine);
context.setScope(manager.engine.getRuntimeScope());
context.setTenantId(Integer.toString(CarbonContext.getCurrentContext().getTenantId()));
context.addProperty(Constants.JAGGERY_CORE_MANAGER, manager);
context.addProperty(Constants.JAGGERY_INCLUDED_SCRIPTS, new HashMap<String, Boolean>());
context.addProperty(Constants.JAGGERY_INCLUDES_CALLSTACK, new Stack<String>());
}
private static void exposeDefaultModules(RhinoEngine engine, Map<String, JavaScriptModule> modules)
throws ScriptException {
for (JavaScriptModule module : modules.values()) {
if (module.isExpose()) {
String namespace = module.getNamespace();
if (namespace == null || namespace.equals("")) {
//expose globally
exposeModule(engine, module);
} else {
engine.defineModule(module);
}
}
}
}
public static void include(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "include";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(HOST_OBJECT_NAME, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(HOST_OBJECT_NAME, functionName, "1", "string", args[0], false);
}
JaggeryContext jaggeryContext = getJaggeryContext();
RhinoEngine engine = jaggeryContext.getEngine();
if (engine == null) {
log.error("Rhino Engine in Jaggery context is null");
throw new ScriptException("Rhino Engine in Jaggery context is null");
}
Stack<String> includesCallstack = getCallstack(jaggeryContext);
Map<String, Boolean> includedScripts = getIncludes(jaggeryContext);
String parent = includesCallstack.lastElement();
String fileURL = (String) args[0];
if (isHTTP(fileURL) || isHTTP(parent)) {
if (!isHTTP(fileURL)) {
fileURL = parent + fileURL;
}
if (includesCallstack.search(fileURL) != -1) {
return;
}
ScriptReader source;
ScriptableObject scope = jaggeryContext.getScope();
//this is a remote file url
try {
URL url = new URL(fileURL);
url.openConnection();
source = new ScriptReader(url.openStream());
includedScripts.put(fileURL, true);
includesCallstack.push(fileURL);
engine.exec(source, scope, null);
includesCallstack.pop();
} catch (MalformedURLException e) {
String msg = "Malformed URL. function : import, url : " + fileURL;
log.warn(msg, e);
throw new ScriptException(msg, e);
} catch (IOException e) {
String msg = "IO exception while importing content from url : " + fileURL;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
} else {
String msg = "Unsupported file include : " + fileURL;
throw new ScriptException(msg);
}
}
public static void include_once(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "include_once";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(HOST_OBJECT_NAME, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(HOST_OBJECT_NAME, functionName, "1", "string", args[0], false);
}
JaggeryContext jaggeryContext = getJaggeryContext();
RhinoEngine engine = jaggeryContext.getEngine();
if (engine == null) {
log.error("Rhino Engine in Jaggery context is null");
throw new ScriptException("Rhino Engine in Jaggery context is null");
}
Stack<String> includesCallstack = getCallstack(jaggeryContext);
String parent = includesCallstack.lastElement();
String fileURL = (String) args[0];
if (isHTTP(fileURL) || isHTTP(parent)) {
if (!isHTTP(fileURL)) {
fileURL = parent + fileURL;
}
if (includesCallstack.search(fileURL) != -1) {
return;
}
Map<String, Boolean> includedScripts = getIncludes(jaggeryContext);
if (includedScripts.get(fileURL)) {
return;
}
ScriptReader source;
ScriptableObject scope = jaggeryContext.getScope();
//this is a remote file url
try {
URL url = new URL(fileURL);
url.openConnection();
source = new ScriptReader(url.openStream());
includedScripts.put(fileURL, true);
includesCallstack.push(fileURL);
engine.exec(source, scope, null);
includesCallstack.pop();
} catch (MalformedURLException e) {
String msg = "Malformed URL. function : import, url : " + fileURL;
log.warn(msg, e);
throw new ScriptException(msg, e);
} catch (IOException e) {
String msg = "IO exception while importing content from url : " + fileURL;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
} else {
String msg = "Unsupported file include : " + fileURL;
throw new ScriptException(msg);
}
}
public static boolean isHTTP(String url) {
return url.matches("^[hH][tT][tT][pP][sS]?.*");
}
public static ScriptableObject require(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException, IOException {
String functionName = "require";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(HOST_OBJECT_NAME, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(HOST_OBJECT_NAME, functionName, "1", "string", args[0], false);
}
String moduleName = (String) args[0];
JaggeryContext context = getJaggeryContext();
//RhinoEngine engine = context.getEngine();
//ScriptableObject scope = context.getScope();
CommonManager manager = (CommonManager) context.getProperty(Constants.JAGGERY_CORE_MANAGER);
ModuleManager moduleManager = manager.getModuleManager();
JavaScriptModule module = moduleManager.getModule(moduleName);
if (module == null) {
String msg = "A module cannot be found with the specified name : " + moduleName;
log.error(msg);
throw new ScriptException(msg);
}
ScriptableObject object = (ScriptableObject) cx.newObject(thisObj);
object.setPrototype(thisObj);
object.setParentScope(null);
exposeModule(cx, object, module);
return object;
}
private static void exposeModule(Context cx, ScriptableObject object, JavaScriptModule module)
throws ScriptException {
for (JavaScriptHostObject hostObject : module.getHostObjects()) {
RhinoEngine.defineHostObject(object, hostObject);
}
for (JavaScriptMethod method : module.getMethods()) {
RhinoEngine.defineMethod(object, method);
}
for (JavaScriptScript script : module.getScripts()) {
script.getScript().exec(cx, object);
}
}
private static void exposeModule(RhinoEngine engine, JavaScriptModule module) {
for (JavaScriptHostObject hostObject : module.getHostObjects()) {
engine.defineHostObject(hostObject);
}
for (JavaScriptMethod method : module.getMethods()) {
engine.defineMethod(method);
}
for (JavaScriptScript script : module.getScripts()) {
engine.defineScript(script);
}
}
/**
* JaggeryMethod responsible of writing to the output stream
*/
public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "print";
JaggeryContext jaggeryContext = getJaggeryContext();
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs("RhinoTopLevel", functionName, argsCount, false);
}
OutputStream out = (OutputStream) jaggeryContext.getProperty(CommonManager.JAGGERY_OUTPUT_STREAM);
if (args[0] instanceof StreamHostObject) {
InputStream in = ((StreamHostObject) args[0]).getStream();
try {
byte[] buffer = new byte[BYTE_BUFFER_SIZE];
int count;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
in.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
} else {
try {
out.write(HostObjectUtil.serializeObject(args[0]).getBytes());
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
}
}
}
public static JaggeryContext getJaggeryContext() {
return (JaggeryContext) RhinoEngine.getContextProperty(EngineConstants.JAGGERY_CONTEXT);
}
public static void setJaggeryContext(JaggeryContext jaggeryContext) {
RhinoEngine.putContextProperty(EngineConstants.JAGGERY_CONTEXT, jaggeryContext);
}
public static Map<String, Boolean> getIncludes(JaggeryContext jaggeryContext) {
return (Map<String, Boolean>) jaggeryContext.getProperty(Constants.JAGGERY_INCLUDED_SCRIPTS);
}
public static Stack<String> getCallstack(JaggeryContext jaggeryContext) {
return (Stack<String>) jaggeryContext.getProperty(Constants.JAGGERY_INCLUDES_CALLSTACK);
}
}
diff --git a/components/script-engine/org.jaggeryjs.scriptengine/src/main/java/org/jaggeryjs/scriptengine/engine/RhinoEngine.java b/components/script-engine/org.jaggeryjs.scriptengine/src/main/java/org/jaggeryjs/scriptengine/engine/RhinoEngine.java
index ef4c038..4aa0f82 100644
--- a/components/script-engine/org.jaggeryjs.scriptengine/src/main/java/org/jaggeryjs/scriptengine/engine/RhinoEngine.java
+++ b/components/script-engine/org.jaggeryjs.scriptengine/src/main/java/org/jaggeryjs/scriptengine/engine/RhinoEngine.java
@@ -1,621 +1,614 @@
package org.jaggeryjs.scriptengine.engine;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.wst.jsdt.debug.internal.rhino.debugger.RhinoDebuggerImpl;
import org.eclipse.wst.jsdt.debug.internal.rhino.transport.RhinoTransportService;
import org.jaggeryjs.scriptengine.cache.CacheManager;
import org.jaggeryjs.scriptengine.cache.ScriptCachingContext;
import org.jaggeryjs.scriptengine.exceptions.ScriptException;
import org.jaggeryjs.scriptengine.security.RhinoSecurityController;
import org.jaggeryjs.scriptengine.util.HostObjectUtil;
-import org.mozilla.javascript.Context;
-import org.mozilla.javascript.ContextFactory;
-import org.mozilla.javascript.Function;
-import org.mozilla.javascript.FunctionObject;
-import org.mozilla.javascript.Script;
-import org.mozilla.javascript.Scriptable;
-import org.mozilla.javascript.ScriptableObject;
-import org.mozilla.javascript.SecurityController;
+import org.mozilla.javascript.*;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* The <code>RhinoEngine</code> class acts as a global engine for executing JavaScript codes using Mozilla Rhino.
* Each engine instance associates a scope and a caching manager.
* <p/>
* During the class initialization time, it creates a static global scope, which will be cloned upon request. This also
* has a constructor which accepts class object itself as a parameter. So, it allows you to keep customised versions of
* RhinoEngine instances.
* <p/>
* It also has several util methods to register hostobjects, methods, properties with the engine's scope.
*/
@SuppressWarnings({"UnusedDeclaration"})
public class RhinoEngine {
private static final Log log = LogFactory.getLog(RhinoEngine.class);
private static ContextFactory globalContextFactory;
private CacheManager cacheManager;
private ContextFactory contextFactory;
//private SecurityController securityController;
private List<JavaScriptModule> modules = new ArrayList<JavaScriptModule>();
private JavaScriptModule globalModule = new JavaScriptModule("global");
private static boolean debugMode = false;
private static String debugPort = "-1";
static {
globalContextFactory = new RhinoContextFactory(
RhinoSecurityController.isSecurityEnabled() ? new RhinoSecurityController() : null);
ContextFactory.initGlobal(globalContextFactory);
String property = System.getProperty("jsDebug");
if (property != null) {
debugPort = property;
debugMode = true;
}
}
/**
* This constructor gets an existing <code>CacheManager</code> instance and returns a new engine instance with the
* new cache manager.
* <p/>
* Scope of the engine will be a clone of the static global scope associates with the <code>RhinoEngine</code>
* class.
*
* @param cacheManager A {@code CacheManager} instance to be used as the cache manager of the engine
*/
- public RhinoEngine(CacheManager cacheManager, SecurityController securityController) {
+ public RhinoEngine(CacheManager cacheManager, RhinoContextFactory contextFactory) {
this.cacheManager = cacheManager;
- if (securityController != null) {
- this.contextFactory = new RhinoContextFactory(securityController);
+ if (contextFactory != null) {
+ this.contextFactory = contextFactory;
} else {
this.contextFactory = globalContextFactory;
}
//If the server is started in debug mode create a debugger with the given port
if (debugMode) {
RhinoDebuggerImpl debugger = new RhinoDebuggerImpl(new RhinoTransportService(), debugPort, true, true);
debugger.start();
this.contextFactory.addListener(debugger);
}
}
/**
* This method registers a hostobject in the given scope.
*
* @param scope The scope where hostobject will be defined
* @param hostObject HostObject to be defined
*/
public static void defineHostObject(ScriptableObject scope, JavaScriptHostObject hostObject)
throws ScriptException {
String msg = "Error while registering the hostobject : ";
Class clazz = hostObject.getClazz();
String className = clazz.getName();
try {
ScriptableObject.defineClass(scope, clazz);
} catch (InvocationTargetException e) {
log.error(msg + className, e);
} catch (InstantiationException e) {
log.error(msg + className, e);
} catch (IllegalAccessException e) {
log.error(msg + className, e);
}
}
/**
* This method registers a hostobject in the engine scope.
*
* @param hostObject HostObject to be defined
*/
public void defineHostObject(JavaScriptHostObject hostObject) {
globalModule.addHostObject(hostObject);
}
/**
* This method registers the specified property in the specified scope.
*
* @param scope The scope to register the bean object
* @param property Property to be defined
*/
public static void defineProperty(ScriptableObject scope, JavaScriptProperty property) {
String name = property.getName();
Object object = property.getValue();
if ((object instanceof Number) ||
(object instanceof String) ||
(object instanceof Boolean)) {
scope.defineProperty(name, object, property.getAttribute());
} else {
// Must wrap non-scriptable objects before presenting to Rhino
Scriptable wrapped = Context.toObject(object, scope);
scope.defineProperty(name, wrapped, property.getAttribute());
}
}
/**
* This method registers the specified property in the engine scope.
*
* @param property Property to be defined
*/
public void defineProperty(JavaScriptProperty property) {
globalModule.addProperty(property);
}
/**
* This method executes the given script in the specified scope.
*
* @param scope The scope to register the bean object
* @param script Script to be defined
*/
public static void defineScript(ScriptableObject scope, JavaScriptScript script) {
Context cx = enterGlobalContext();
script.getScript().exec(cx, scope);
exitContext();
}
/**
* This method executes the given script in the engine scope.
*
* @param script Script to be defined
*/
public void defineScript(JavaScriptScript script) {
globalModule.addScript(script);
}
/**
* This method registers the given method in the specified scope.
*
* @param scope The scope to register the bean object
* @param method Method to be defined
*/
public static void defineMethod(ScriptableObject scope, JavaScriptMethod method)
throws ScriptException {
String name = method.getName();
FunctionObject f = new FunctionObject(name, method.getMethod(), scope);
scope.defineProperty(name, f, method.getAttribute());
}
/**
* This method registers the given method in the engine scope.
*
* @param method Method to be defined
*/
public void defineMethod(JavaScriptMethod method) {
globalModule.addMethod(method);
}
/**
* This method registers the given module in the specified scope.
*
* @param module Module to be defined
*/
public void defineModule(JavaScriptModule module) {
modules.add(module);
}
/**
* Evaluates the specified script and the result is returned. If the <code>sctx</code> is provided and cache is
* upto date, cached script will be evaluated instead of the original one. Otherwise, a either cache will be
* updated or evaluated the script directly without caching.
* <p/>
* A clone of the engine scope will be used as the scope during the evaluation.
*
* @param scriptReader Reader object to read the script when ever needed
* @param sctx Script caching context which contains caching data. When null is passed for this, caching
* will be disabled.
* @return Returns the resulting object after evaluating script
* @throws ScriptException If error occurred while evaluating
*/
public Object eval(Reader scriptReader, ScriptCachingContext sctx) throws ScriptException {
return evalScript(scriptReader, getRuntimeScope(), sctx);
}
/**
* Evaluates the specified script and the result is returned. If the <code>sctx</code> is provided and cache is
* upto date, cached script will be evaluated instead of the original one. Otherwise, either the cache will be
* updated or evaluated the script directly without caching.
* <p/>
* The specified scope will be used as the scope during the evaluation.
*
* @param scriptReader Reader object to read the script when ever needed
* @param scope Scope to be used during the evaluation
* @param sctx Script caching context which contains caching data. When null is passed for this, caching
* will be disabled.
* @return Returns the resulting object after evaluating script
* @throws ScriptException If error occurred while evaluating
*/
public Object eval(Reader scriptReader, ScriptableObject scope, ScriptCachingContext sctx)
throws ScriptException {
if (scope == null) {
String msg = "ScriptableObject value for scope, can not be null.";
log.error(msg);
throw new ScriptException(msg);
}
return evalScript(scriptReader, scope, sctx);
}
/**
* Executes the script on a clone of the engine scope and the scope is returned.
* <p/>
* If the <code>sctx</code> is provided and cache is upto date, cached script
* will be evaluated instead of the original one. Otherwise, either the cache will be updated or evaluated the
* script directly without caching.
*
* @param scriptReader Reader object to read the script when ever needed
* @param sctx Script caching context which contains caching data. When null is passed for this, caching
* will be disabled.
* @return Modified clone of the engine scope
* @throws ScriptException If error occurred while evaluating
*/
public ScriptableObject exec(Reader scriptReader, ScriptCachingContext sctx)
throws ScriptException {
return execScript(scriptReader, getRuntimeScope(), sctx);
}
/**
* Executes the script on the specified scope.
* <p/>
* If the <code>sctx</code> is provided and cache is upto date, cached script
* will be evaluated instead of the original one. Otherwise, either the cache will be updated or evaluated the
* script directly without caching.
*
* @param scriptReader Reader object to read the script when ever needed
* @param scope Scope to be used during the execution
* @param sctx Script caching context which contains caching data. When null is passed for this, caching
* will be disabled.
* @throws ScriptException If error occurred while evaluating
*/
public void exec(Reader scriptReader, ScriptableObject scope, ScriptCachingContext sctx)
throws ScriptException {
if (scope == null) {
String msg = "ScriptableObject value for scope, can not be null.";
log.error(msg);
throw new ScriptException(msg);
}
execScript(scriptReader, scope, sctx);
}
/**
* Executes a particular JavaScript function from a script on a clone of engine's scope and returns the result.
*
* @param scriptReader Reader object to read the script when ever needed
* @param funcName Name of the function to be invoked
* @param args Arguments for the functions as an array of objects
* @param sctx Script caching context which contains caching data. When null is passed for this, caching
* will be disabled.
* @return Returns the resulting object after invoking the function
* @throws ScriptException If error occurred while invoking the function
*/
public Object call(Reader scriptReader, String funcName, Object[] args,
ScriptCachingContext sctx)
throws ScriptException {
return execFunc(scriptReader, funcName, args, getRuntimeScope(), getRuntimeScope(), sctx);
}
/**
* Executes a particular JavaScript function from a script on a clone of engine's scope and returns the result.
*
* @param scriptReader Reader object to read the script when ever needed
* @param funcName Name of the function to be invoked
* @param args Arguments for the functions as an array of objects
* @param thiz {@code this} object for the function
* @param sctx Script caching context which contains caching data. When null is passed for this, caching
* will be disabled.
* @return Returns the resulting object after invoking the function
* @throws ScriptException If error occurred while invoking the function
*/
public Object call(Reader scriptReader, String funcName, Object[] args, ScriptableObject thiz,
ScriptCachingContext sctx) throws ScriptException {
if (thiz == null) {
String msg = "ScriptableObject value for thiz, can not be null.";
log.error(msg);
throw new ScriptException(msg);
}
return execFunc(scriptReader, funcName, args, thiz, getRuntimeScope(), sctx);
}
/**
* Executes a particular JavaScript function from a script on the specified scope and returns the result.
*
* @param scriptReader Reader object to read the script when ever needed
* @param funcName Name of the function to be invoked
* @param args Arguments for the functions as an array of objects
* @param thiz {@code this} object for the function
* @param scope The scope where function will be executed
* @param sctx Script caching context which contains caching data. When null is passed for this, caching
* will be disabled.
* @return Returns the resulting object after invoking the function
* @throws ScriptException If error occurred while invoking the function
*/
public Object call(Reader scriptReader, String funcName, Object[] args, ScriptableObject thiz,
ScriptableObject scope, ScriptCachingContext sctx) throws ScriptException {
if (scope == null) {
String msg = "ScriptableObject value for scope, can not be null.";
log.error(msg);
throw new ScriptException(msg);
}
if (thiz == null) {
String msg = "ScriptableObject value for thiz, can not be null.";
log.error(msg);
throw new ScriptException(msg);
}
return execFunc(scriptReader, funcName, args, thiz, scope, sctx);
}
/**
* This clones the engine scope and returns.
*
* @return Cloned scope
*/
public ScriptableObject getRuntimeScope() throws ScriptException {
Context cx = enterContext();
ScriptableObject scope = removeUnsafeObjects(new RhinoTopLevel(cx, false));
exposeModule(cx, scope, globalModule);
for (JavaScriptModule module : modules) {
String name = module.getName();
ScriptableObject object = (ScriptableObject) cx.newObject(scope);
exposeModule(cx, object, module);
JavaScriptProperty property = new JavaScriptProperty(name);
property.setValue(object);
property.setAttribute(ScriptableObject.PERMANENT);
defineProperty(scope, property);
}
exitContext();
return scope;
}
/**
* Unloads all the resources associated with a particular tenant
*
* @param tenantId Tenant to be unloaded
*/
public void unloadTenant(String tenantId) {
this.cacheManager.unloadTenant(tenantId);
RhinoTopLevel.removeTasks(tenantId);
}
/**
* Creates a new JavaScript object in the given scope
*
* @param scope Scope for the object constructor lookup
* @return Newly created object
*/
public static Scriptable newObject(ScriptableObject scope) {
Context cx = enterGlobalContext();
Scriptable obj = cx.newObject(scope);
exitContext();
return obj;
}
/**
* Puts a property in the Context of the current thread
*
* @param key Property name
* @param value Property value
*/
public static void putContextProperty(Object key, Object value) {
Context cx = Context.getCurrentContext();
cx.putThreadLocal(key, value);
}
/**
* Gets a property from the Context of the current thread
*
* @param key Property name
* @return Property value
*/
public static Object getContextProperty(Object key) {
Context cx = Context.getCurrentContext();
return cx.getThreadLocal(key);
}
/**
* Creates a Rhino Context in the current thread or returned the already created one
*
* @return Rhino Context instance
*/
public Context enterContext() {
return contextFactory.enterContext();
}
/**
* Creates a Rhino Context in the current thread using the specified ContextFactory or returned the already
* created one
*
* @return Rhino Context instance
*/
public static Context enterContext(ContextFactory factory) {
return factory.enterContext();
}
/**
* Creates a Rhino Context in the current thread using the global ContextFactory or returned the already
* created one
*
* @return Rhino Context instance
*/
public static Context enterGlobalContext() {
return globalContextFactory.enterContext();
}
/**
* Exists from the context associated in the current thread
*/
public static void exitContext() {
Context.exit();
}
private void defineClass(ScriptableObject scope, Class clazz) {
try {
ScriptableObject.defineClass(scope, clazz);
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
} catch (InstantiationException e) {
log.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
log.error(e.getMessage(), e);
}
}
private void defineMethod(ScriptableObject scope, String name, Method method, int attribute) {
FunctionObject f = new FunctionObject(name, method, scope);
scope.defineProperty(name, f, attribute);
}
private void exposeModule(Context cx, ScriptableObject scope, JavaScriptModule module)
throws ScriptException {
for (JavaScriptHostObject hostObject : module.getHostObjects()) {
defineClass(scope, hostObject.getClazz());
}
for (JavaScriptMethod method : module.getMethods()) {
defineMethod(scope, method.getName(), method.getMethod(), method.getAttribute());
}
for (JavaScriptScript script : module.getScripts()) {
script.getScript().exec(cx, scope);
}
}
private CacheManager getCacheManager() {
return cacheManager;
}
private Object execFunc(Reader scriptReader, String funcName, Object[] args,
ScriptableObject thiz,
ScriptableObject scope, ScriptCachingContext sctx)
throws ScriptException {
Context cx = enterContext();
try {
if (sctx == null) {
cx.evaluateString(scope, HostObjectUtil.readerToString(scriptReader), "wso2js", 1, null);
} else if (debugMode) { //If the server is started to debug scripts
String scriptPath = sctx.getContext() + sctx.getPath() + sctx.getCacheKey();
cx.evaluateString(scope, HostObjectUtil.readerToString(scriptReader), scriptPath, 1, null);
} else {
Script script = cacheManager.getScriptObject(scriptReader, sctx);
if (script == null) {
cacheManager.cacheScript(scriptReader, sctx);
script = cacheManager.getScriptObject(scriptReader, sctx);
}
script.exec(cx, scope);
}
return execFunc(funcName, args, thiz, scope, cx);
} catch (Exception e) {
log.error(e);
throw new ScriptException(e);
} finally {
exitContext();
}
}
private static Object execFunc(String funcName, Object[] args, ScriptableObject thiz,
ScriptableObject scope, Context cx) throws ScriptException {
Object object = scope.get(funcName, scope);
if (!(object instanceof Function)) {
String msg = "Function cannot be found with the name '" + funcName + "', but a " + object.toString();
log.error(msg);
throw new ScriptException(msg);
}
try {
return ((Function) object).call(cx, scope, thiz, args);
} catch (Exception e) {
log.error(e);
throw new ScriptException(e);
}
}
private Object evalScript(Reader scriptReader, ScriptableObject scope,
ScriptCachingContext sctx)
throws ScriptException {
Context cx = enterContext();
Object result;
try {
if (sctx == null) {
result = cx.evaluateString(scope, HostObjectUtil.readerToString(scriptReader), "wso2js", 1, null);
} else if (debugMode) { //If the server is started to debug scripts
String scriptPath = sctx.getContext() + sctx.getPath() + sctx.getCacheKey();
result = cx.evaluateString(scope, HostObjectUtil.readerToString(scriptReader), scriptPath, 1, null);
} else {
Script script = cacheManager.getScriptObject(scriptReader, sctx);
if (script == null) {
cacheManager.cacheScript(scriptReader, sctx);
script = cacheManager.getScriptObject(scriptReader, sctx);
}
result = script.exec(cx, scope);
}
return result;
} catch (Exception e) {
log.error(e);
throw new ScriptException(e);
} finally {
exitContext();
}
}
private ScriptableObject execScript(Reader scriptReader, ScriptableObject scope,
ScriptCachingContext sctx)
throws ScriptException {
Context cx = enterContext();
try {
if (sctx == null) {
cx.evaluateString(scope, HostObjectUtil.readerToString(scriptReader), "wso2js", 1, null);
} else if (debugMode) { //If the server is started to debug scripts
String scriptPath = sctx.getContext() + sctx.getPath() + sctx.getCacheKey();
cx.evaluateString(scope, HostObjectUtil.readerToString(scriptReader), scriptPath, 1, null);
} else {
Script script = cacheManager.getScriptObject(scriptReader, sctx);
if (script == null) {
cacheManager.cacheScript(scriptReader, sctx);
script = cacheManager.getScriptObject(scriptReader, sctx);
}
script.exec(cx, scope);
}
return scope;
} catch (Exception e) {
log.error(e);
throw new ScriptException(e);
} finally {
exitContext();
}
}
private static ScriptableObject removeUnsafeObjects(ScriptableObject scope) {
/**
* TODO : go through ECMAScript and E4X specs and remove unwanted objects from following values
* QName, TypeError, isNaN, isFinite, ConversionError, EvalError, encodeURI, Boolean, Call, Iterator, Array,
* XML, unescape, URIError, decodeURI, Infinity, SyntaxError, Date, String, encodeURIComponent, RangeError,
* ReferenceError, RegExp, With, Function, InternalError, NaN, Number, escape, XMLList, Math, JavaException,
* parseFloat, Error, undefined, parseInt, Object, Continuation, decodeURIComponent, StopIteration, log,
* Namespace, isXMLName, global, eval
*/
/*scope.delete("JavaAdapter");
scope.delete("org");
scope.delete("java");
scope.delete("JavaImporter");
scope.delete("Script");
scope.delete("edu");
scope.delete("uneval");
scope.delete("javax");
scope.delete("getClass");
scope.delete("com");
scope.delete("net");
scope.delete("Packages");
scope.delete("importClass");
scope.delete("importPackage");*/
return scope;
}
private static void copyEngineScope(ScriptableObject engineScope, ScriptableObject scope) {
Object[] objs = engineScope.getAllIds();
for (Object obj : objs) {
String id = (String) obj;
scope.put(id, scope, engineScope.get(id, engineScope));
}
}
}
| false | false | null | null |
diff --git a/src/poker/Window.java b/src/poker/Window.java
index 4574d81..f4a28de 100644
--- a/src/poker/Window.java
+++ b/src/poker/Window.java
@@ -1,281 +1,288 @@
package poker;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class Window {
private JTextArea community;
private JTextArea score;
private JTextArea playcards;
private JTextArea terminal;
private JTextField bidfield;
private JButton bid;
private JButton call;
private JButton fold;
private Poker caller; //used to see who called this window
private JMenuItem play;
private JMenuItem how;
private JMenuItem about;
private JMenuItem exit;
private JMenu menu;
private JMenuBar menubar;
private JFrame window;
private Thread background;
public Window() {
//Creates the Main Window and sets settings
final Window win = this;
window = new JFrame("Texas Hold 'em");
window.setSize(640, 480);
window.setMinimumSize(new Dimension(640,480));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates main panel and sets settings
JPanel full = new JPanel();
full.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
//create sub panels and sets settings
JPanel interaction = new JPanel();
interaction.setLayout(new BoxLayout(interaction, BoxLayout.Y_AXIS));
interaction.setBorder(BorderFactory.createMatteBorder(5,0,5,5, Color.black));
JPanel first = new JPanel();
first.setLayout(new BoxLayout(first, BoxLayout.X_AXIS));
JPanel second = new JPanel();
second.setLayout(new BoxLayout(second, BoxLayout.X_AXIS));
JPanel third = new JPanel();
third.setLayout(new BoxLayout(third, BoxLayout.X_AXIS));
JPanel fourth = new JPanel();
fourth.setLayout(new BoxLayout(fourth, BoxLayout.X_AXIS));
JPanel top = new JPanel();
top.setLayout(new BoxLayout(top,BoxLayout.X_AXIS));
//initialize the text areas
community = new JTextArea();
community.setLineWrap(true);
community.setEditable(false);
community.setBorder(BorderFactory.createLineBorder(Color.black, 5));
score = new JTextArea();
score.setLineWrap(true);
score.setEditable(false);
score.setBorder(BorderFactory.createMatteBorder(5,0,5,5, Color.black));
playcards = new JTextArea();
playcards.setLineWrap(true);
playcards.setEditable(false);
playcards.setBorder(BorderFactory.createMatteBorder(0,5,5,5, Color.black));
terminal = new JTextArea();
terminal.setLineWrap(true);
terminal.setEditable(false);
DefaultCaret caret = (DefaultCaret)terminal.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(640, 500));
scrollPane.setViewportView(terminal);
scrollPane.setBorder(BorderFactory.createMatteBorder(0,5,5,5, Color.black));
//Initializes interactive widgets
bidfield = new JTextField();
bidfield.setMaximumSize(new Dimension(80,35));
bid = new JButton("Bid");
bid.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent ae){
String entered = bidfield.getText();
int ent;
try {
ent = Integer.parseInt(entered);
Poker.dropbox = ent;
synchronized (Poker.getLock()){
Poker.getLock().notify();
}
}
catch (NumberFormatException e){
print("Invalid Number, please enter again");
}
finally {
bidfield.setText(null);
}
}
});
call = new JButton("Call");
call.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent ae) {
synchronized (Poker.getLock()) {
Poker.dropbox = "call";
Poker.getLock().notify();
}
}
});
fold = new JButton("Fold");
fold.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent ae) {
synchronized (Poker.getLock()){
Poker.dropbox = "folding";
Poker.getLock().notify();
}
}
});
//menu bar editing
menu = new JMenu("File");
play = new JMenuItem("Play new game");
play.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent ae) {
boolean start = true;
boolean okay = false;
int playerNum = 0;
String message = "How many players?";
while(!okay){
String numberAI = JOptionPane.showInputDialog(null,message,"New Game", JOptionPane.QUESTION_MESSAGE);
if (numberAI == null){
start = false;
break;
}
try {
playerNum = Integer.parseInt(numberAI);
+ if (playerNum < 3 )
+ throw new NumberFormatException("Not enough players");
+ if (playerNum > 24)
+ throw new NumberFormatException("Too many players");
okay = true;
+
}
catch (NumberFormatException e){
message = "Invalid number. Try again";
+ if (e.getMessage().equals("Not enough players") || e.getMessage().equals("Too many players"))
+ message = e.getMessage();
}
}
if (start){
if (background != null){
background.interrupt();
}
//Actual Creation
caller = new Poker(playerNum);
caller.passWindow(win);
win.redrawScore();
background = new Thread(caller);
background.start();
}
}
});
how = new JMenuItem("How to play");
how.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent ae) {
}
});
about = new JMenuItem("About");
about.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, "Programmed by: Paul Steele\nCheck out paul-steele.com", "About",JOptionPane.PLAIN_MESSAGE);
}
});
exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent ae) {
int reallyExit = JOptionPane.showConfirmDialog(null, "Do you really want to exit?");
if (reallyExit == 0){
System.exit(0);
}
}
});
//Initializes MenuBar
menubar = new JMenuBar();
menu.add(play);
menu.add(how);
menu.add(about);
menu.add(exit);
menubar.add(menu);
//Set up Interactions pane
first.add(Box.createRigidArea(new Dimension(10,0)));
first.add(bidfield);
first.add(Box.createRigidArea(new Dimension(10,0)));
second.add(Box.createGlue());
second.add(bid);
second.add(Box.createGlue());
third.add(Box.createGlue());
third.add(call);
third.add(Box.createGlue());
fourth.add(Box.createGlue());
fourth.add(fold);
fourth.add(Box.createGlue());
interaction.add(Box.createGlue());
interaction.add(first);
interaction.add(Box.createGlue());
interaction.add(second);
interaction.add(Box.createGlue());
interaction.add(third);
interaction.add(Box.createGlue());
interaction.add(fourth);
interaction.add(Box.createGlue());
//add widgets to full
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx =0;
constraints.gridy = 0;
constraints.gridwidth = 2;
constraints.weightx = .7;
constraints.weighty = 0.0;
full.add(community, constraints);
constraints.gridx = 2;
constraints.gridwidth = 1;
constraints.weightx = .3;
full.add(score, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.weighty = 0.0;
constraints.weightx =.7;
full.add(playcards, constraints);
constraints.gridx= 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.weighty = 1.0;
full.add(scrollPane, constraints);
constraints.gridx =2;
constraints.gridwidth = 1;
constraints.weightx = .3;
full.add(interaction, constraints);
//add main panel to window
window.add(full);
//add the menubar
window.setJMenuBar(menubar);
//start off buttons disabled
buttonsEnabled(false);
//display window
window.setResizable(true);
window.setVisible(true);
}
public void redrawScore(){
score.setText("-----Cash Amounts-----\n"); //clears out the text
if (caller != null){
for (int i = 1; i < caller.PLAYERS + 1; i++){
score.append(caller.getPlayer(i).getName()+": $"+caller.getPlayer(i).getCash() + "\n");
}
score.append("\nCash in pot: " + caller.getPot());
}
}
public void print(String str){
terminal.append(str + "\n");
}
public void printToCommunity(String str) {
community.append(str);
}
public void clearCommunity(){
community.setText("-----Community Cards-----\n");
}
public void buttonsEnabled(boolean desired){
bid.setEnabled(desired);
call.setEnabled(desired);
fold.setEnabled(desired);
}
public void printToPlayerCards(String str){
playcards.append(str);
}
public void clearPlayerCards(){
playcards.setText("-----Your Hand-----\n");
}
}
| false | false | null | null |
diff --git a/kundera-rest/src/test/java/com/impetus/kundera/rest/common/Book.java b/kundera-rest/src/test/java/com/impetus/kundera/rest/common/Book.java
index 9683c6b38..4434eba98 100644
--- a/kundera-rest/src/test/java/com/impetus/kundera/rest/common/Book.java
+++ b/kundera-rest/src/test/java/com/impetus/kundera/rest/common/Book.java
@@ -1,104 +1,104 @@
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.rest.common;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Entity class for Book
*
* @author amresh.singh
*/
@Entity
@Table(name = "BOOK", schema = "KunderaExamples@twissandra")
@NamedQueries(value = { @NamedQuery(name = "findByAuthor", query = "Select b from Book b where b.author = :author"),
@NamedQuery(name = "findByPublication", query = "Select b from Book b where b.publication = ?1"),
@NamedQuery(name = "findAllBooks", query = "Select b from Book b") })
-@NamedNativeQueries(value = { @NamedNativeQuery(name = "findAllBooksNative", query = "select * from " + "\"BOOK\"") })
+@NamedNativeQueries(value = { @NamedNativeQuery(name = "findAllBooksNative", query = "select * from " + "BOOK") })
@XmlRootElement
public class Book
{
@Id
@Column(name = "ISBN")
String isbn;
@Column(name = "AUTHOR")
String author;
@Column(name = "PUBLICATION")
String publication;
/**
* @return the isbn
*/
public String getIsbn()
{
return isbn;
}
/**
* @param isbn
* the isbn to set
*/
public void setIsbn(String isbn)
{
this.isbn = isbn;
}
/**
* @return the author
*/
public String getAuthor()
{
return author;
}
/**
* @param author
* the author to set
*/
public void setAuthor(String author)
{
this.author = author;
}
/**
* @return the publication
*/
public String getPublication()
{
return publication;
}
/**
* @param publication
* the publication to set
*/
public void setPublication(String publication)
{
this.publication = publication;
}
}
diff --git a/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java b/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java
index ac9c8d9d3..af09f79bd 100644
--- a/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java
+++ b/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java
@@ -1,515 +1,515 @@
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.rest.resources;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.MediaType;
import junit.framework.Assert;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.ColumnDef;
import org.apache.cassandra.thrift.IndexType;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.TException;
import org.databene.contiperf.PerfTest;
import org.databene.contiperf.junit.ContiPerfRule;
import org.databene.contiperf.report.CSVSummaryReportModule;
import org.databene.contiperf.report.HtmlReportModule;
import org.databene.contiperf.report.ReportModule;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import com.impetus.kundera.rest.common.Book;
import com.impetus.kundera.rest.common.CassandraCli;
import com.impetus.kundera.rest.common.Constants;
import com.impetus.kundera.rest.common.HabitatUni1ToM;
import com.impetus.kundera.rest.common.JAXBUtils;
import com.impetus.kundera.rest.common.PersonnelUni1ToM;
import com.impetus.kundera.rest.dao.RESTClient;
import com.impetus.kundera.rest.dao.RESTClientImpl;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.test.framework.JerseyTest;
/**
* Test case for {@link CRUDResource} Cassandra-CLI Commands to run for
* non-embedded mode: create keyspace KunderaExamples; use KunderaExamples; drop
* column family BOOK; drop column family PERSONNEL; drop column family ADDRESS;
* create column family BOOK with comparator=UTF8Type and
* default_validation_class=UTF8Type and key_validation_class=UTF8Type and
* column_metadata=[{column_name: AUTHOR, validation_class:UTF8Type, index_type:
* KEYS},{column_name: PUBLICATION, validation_class:UTF8Type, index_type:
* KEYS}]; create column family PERSONNEL with comparator=UTF8Type and
* default_validation_class=UTF8Type and key_validation_class=UTF8Type and
* column_metadata=[{column_name: PERSON_NAME, validation_class:UTF8Type,
* index_type: KEYS},{column_name: ADDRESS_ID, validation_class:UTF8Type,
* index_type: KEYS}]; create column family ADDRESS with comparator=UTF8Type and
* default_validation_class=UTF8Type and key_validation_class=UTF8Type and
* column_metadata=[{column_name: STREET, validation_class:UTF8Type, index_type:
* KEYS},{column_name: PERSON_ID, validation_class:UTF8Type, index_type: KEYS}];
* describe KunderaExamples;
*
* @author amresh
*
*/
public class CRUDResourceTest extends JerseyTest
{
private static final String _KEYSPACE = "KunderaExamples";
private static Log log = LogFactory.getLog(CRUDResourceTest.class);
static String mediaType = MediaType.APPLICATION_XML;
static RESTClient restClient;
String applicationToken = null;
String sessionToken = null;
String bookStr1;
String bookStr2;
String pk1;
String pk2;
@Rule
public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),
new HtmlReportModule() });
private final static boolean USE_EMBEDDED_SERVER = true;
private final static boolean AUTO_MANAGE_SCHEMA = true;
WebResource webResource = resource();
public CRUDResourceTest() throws Exception
{
super(Constants.KUNDERA_REST_RESOURCES_PACKAGE);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
if (USE_EMBEDDED_SERVER)
{
CassandraCli.cassandraSetUp();
}
if (AUTO_MANAGE_SCHEMA)
{
loadData();
}
// Initialize REST Client
restClient = new RESTClientImpl();
}
@Before
public void setup() throws Exception
{
restClient.initialize(webResource, mediaType);
}
@After
public void tearDown() throws Exception
{
super.tearDown();
}
@AfterClass
public static void tearDownAfterClass() throws Exception
{
if (AUTO_MANAGE_SCHEMA)
{
CassandraCli.dropKeySpace(_KEYSPACE);
}
if (USE_EMBEDDED_SERVER)
{
}
}
@Test
@PerfTest(invocations = 10)
public void testCRUD()
{
if (MediaType.APPLICATION_XML.equals(mediaType))
{
bookStr1 = "<book><isbn>1111111111111</isbn><author>Amresh</author><publication>Willey</publication></book>";
bookStr2 = "<book><isbn>2222222222222</isbn><author>Vivek</author><publication>OReilly</publication></book>";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else if (MediaType.APPLICATION_JSON.equals(mediaType))
{
bookStr1 = "{book:{\"isbn\":\"1111111111111\",\"author\":\"Amresh\", \"publication\":\"Willey\"}}";
bookStr2 = "{book:{\"isbn\":\"2222222222222\",\"author\":\"Vivek\", \"publication\":\"Oreilly\"}}";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else
{
Assert.fail("Incorrect Media Type:" + mediaType);
return;
}
// Get Application Token
applicationToken = restClient.getApplicationToken("twissandra");
Assert.assertNotNull(applicationToken);
Assert.assertTrue(applicationToken.startsWith("AT_"));
// Get Session Token
sessionToken = restClient.getSessionToken(applicationToken);
Assert.assertNotNull(sessionToken);
Assert.assertTrue(sessionToken.startsWith("ST_"));
// Insert Record
String insertResponse1 = restClient.insertEntity(sessionToken, bookStr1, "Book");
String insertResponse2 = restClient.insertEntity(sessionToken, bookStr2, "Book");
Assert.assertNotNull(insertResponse1);
Assert.assertNotNull(insertResponse2);
Assert.assertTrue(insertResponse1.indexOf("201") > 0);
Assert.assertTrue(insertResponse2.indexOf("201") > 0);
// Find Record
String foundBook = restClient.findEntity(sessionToken, pk1, "Book");
Assert.assertNotNull(foundBook);
if (MediaType.APPLICATION_JSON.equals(mediaType))
{
foundBook = "{book:" + foundBook + "}";
}
Assert.assertTrue(foundBook.indexOf("Amresh") > 0);
// Update Record
foundBook = foundBook.replaceAll("Amresh", "Saurabh");
String updatedBook = restClient.updateEntity(sessionToken, foundBook, "Book");
Assert.assertNotNull(updatedBook);
Assert.assertTrue(updatedBook.indexOf("Saurabh") > 0);
/** JPA Query - Select */
// Get All books
String jpaQuery = "select b from Book b";
String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>());
log.debug("Query Result:" + queryResult);
/** JPA Query - Select All */
// Get All Books
String allBooks = restClient.getAllEntities(sessionToken, "Book");
Assert.assertNotNull(allBooks);
Assert.assertTrue(allBooks.indexOf("books") > 0);
Assert.assertTrue(allBooks.indexOf("Saurabh") > 0);
Assert.assertTrue(allBooks.indexOf("Vivek") > 0);
log.debug(allBooks);
/** Named JPA Query - Select */
// Get books for a specific author
Map<String, Object> params = new HashMap<String, Object>();
params.put("author", "Saurabh");
String booksByAuthor = restClient.runNamedJPAQuery(sessionToken, Book.class.getSimpleName(), "findByAuthor",
params);
Assert.assertNotNull(booksByAuthor);
Assert.assertTrue(booksByAuthor.indexOf("books") > 0);
Assert.assertTrue(booksByAuthor.indexOf("Saurabh") > 0);
Assert.assertFalse(booksByAuthor.indexOf("Vivek") > 0);
log.debug(booksByAuthor);
/** Named JPA Query - Select */
// Get books for a specific publication
Map<String, Object> paramsPublication = new HashMap<String, Object>();
paramsPublication.put("1", "Willey");
String booksByPublication = restClient.runNamedJPAQuery(sessionToken, Book.class.getSimpleName(),
"findByPublication", paramsPublication);
Assert.assertNotNull(booksByPublication);
Assert.assertTrue(booksByAuthor.indexOf("books") > 0);
Assert.assertTrue(booksByAuthor.indexOf("Saurabh") > 0);
Assert.assertFalse(booksByAuthor.indexOf("Vivek") > 0);
Assert.assertTrue(booksByAuthor.indexOf("Willey") > 0);
log.debug(booksByAuthor);
/** Native Query - Select */
// Get All books
- String nativeQuery = "Select * from " + "\"BOOK\"";
+ String nativeQuery = "Select * from " + "BOOK";
String nativeQueryResult = restClient.runNativeQuery(sessionToken, "Book", nativeQuery,
new HashMap<String, Object>());
log.debug("Native Query Select Result:" + nativeQueryResult);
Assert.assertNotNull(nativeQueryResult);
Assert.assertTrue(nativeQueryResult.indexOf("books") > 0);
Assert.assertTrue(nativeQueryResult.indexOf("Saurabh") > 0);
Assert.assertTrue(nativeQueryResult.indexOf("Vivek") > 0);
/** Named Native Query - Select */
String namedNativeQuerySelectResult = restClient.runNamedNativeQuery(sessionToken, "Book",
"findAllBooksNative", new HashMap<String, Object>());
log.debug("Named Native Query Select Result:" + namedNativeQuerySelectResult);
Assert.assertNotNull(namedNativeQuerySelectResult);
Assert.assertTrue(namedNativeQuerySelectResult.indexOf("books") > 0);
Assert.assertTrue(namedNativeQuerySelectResult.indexOf("Saurabh") > 0);
Assert.assertTrue(namedNativeQuerySelectResult.indexOf("Vivek") > 0);
// Delete Records
restClient.deleteEntity(sessionToken, updatedBook, pk1, "Book");
restClient.deleteEntity(sessionToken, updatedBook, pk2, "Book");
// Close Session
restClient.closeSession(sessionToken);
// Close Application
restClient.closeApplication(applicationToken);
if (AUTO_MANAGE_SCHEMA)
{
truncateColumnFamily();
}
}
@Test
@PerfTest(invocations = 10)
public void testCRUDOnAssociation()
{
String personStr;
String personStr1;
String personPk = "1234567";
String person1Pk = "1234568";
String addressPk = "201001";
Set<HabitatUni1ToM> addresses = new HashSet<HabitatUni1ToM>();
HabitatUni1ToM add1 = new HabitatUni1ToM();
add1.setAddressId(addressPk);
add1.setStreet("XXXXXXXXX");
HabitatUni1ToM add = new HabitatUni1ToM();
add.setAddressId(addressPk);
add.setStreet("XXXXXXXXX");
addresses.add(add1);
addresses.add(add);
PersonnelUni1ToM p = new PersonnelUni1ToM();
p.setPersonId(personPk);
p.setPersonName("kuldeep");
p.setAddresses(addresses);
PersonnelUni1ToM p1 = new PersonnelUni1ToM();
p1.setPersonId(person1Pk);
p1.setPersonName("kuldeep");
p1.setAddresses(addresses);
personStr = JAXBUtils.toString(PersonnelUni1ToM.class, p, mediaType);
personStr1 = JAXBUtils.toString(PersonnelUni1ToM.class, p1, mediaType);
// Get Application Token
applicationToken = restClient.getApplicationToken("twissandra");
Assert.assertNotNull(applicationToken);
Assert.assertTrue(applicationToken.startsWith("AT_"));
// Get Session Token
sessionToken = restClient.getSessionToken(applicationToken);
Assert.assertNotNull(sessionToken);
Assert.assertTrue(sessionToken.startsWith("ST_"));
// Insert person.
String insertResponse = restClient.insertPerson(sessionToken, personStr);
String insertResponse1 = restClient.insertPerson(sessionToken, personStr1);
Assert.assertNotNull(insertResponse);
Assert.assertTrue(insertResponse.indexOf("201") > 0);
Assert.assertNotNull(insertResponse1);
Assert.assertTrue(insertResponse1.indexOf("201") > 0);
// Find person.
String foundPerson = restClient.findPerson(sessionToken, personPk);
Assert.assertNotNull(foundPerson);
if (MediaType.APPLICATION_JSON.equals(mediaType))
{
foundPerson = "{personnelUni1ToM:" + foundPerson + "}";
}
Assert.assertTrue(foundPerson.indexOf(addressPk) > 0);
Assert.assertTrue(foundPerson.indexOf("XXXXXXXXX") > 0);
Assert.assertTrue(foundPerson.indexOf("kuldeep") > 0);
// Update Record
String updatedPerson = restClient.updatePerson(sessionToken, foundPerson);
Assert.assertNotNull(updatedPerson);
Assert.assertTrue(updatedPerson.indexOf("YYYYYYYYY") > 0);
// Find all persons.
String allPersons = restClient.getAllPersons(sessionToken);
Assert.assertNotNull(allPersons);
Assert.assertTrue(allPersons.indexOf("personneluni1toms") > 0);
log.debug(allPersons);
// Run Query.
String jpaQuery = "select p from PersonnelUni1ToM p where p.personId >= " + person1Pk;
String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>());
log.debug("Query Result:" + queryResult);
// Delete person.
restClient.deletePerson(sessionToken, updatedPerson, personPk);
foundPerson = restClient.findPerson(sessionToken, personPk);
Assert.assertEquals("", foundPerson);
// Close Session
restClient.closeSession(sessionToken);
// Close Application
restClient.closeApplication(applicationToken);
if (AUTO_MANAGE_SCHEMA)
{
truncateColumnFamily();
}
}
/**
* Load cassandra specific data.
*
* @throws TException
* the t exception
* @throws InvalidRequestException
* the invalid request exception
* @throws UnavailableException
* the unavailable exception
* @throws TimedOutException
* the timed out exception
* @throws SchemaDisagreementException
* the schema disagreement exception
*/
private static void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,
SchemaDisagreementException
{
KsDef ksDef = null;
CfDef user_Def = new CfDef();
user_Def.name = "BOOK";
user_Def.keyspace = _KEYSPACE;
user_Def.setComparator_type("UTF8Type");
user_Def.setKey_validation_class("UTF8Type");
ColumnDef authorDef = new ColumnDef(ByteBuffer.wrap("AUTHOR".getBytes()), "UTF8Type");
authorDef.index_type = IndexType.KEYS;
ColumnDef publicationDef = new ColumnDef(ByteBuffer.wrap("PUBLICATION".getBytes()), "UTF8Type");
publicationDef.index_type = IndexType.KEYS;
user_Def.addToColumn_metadata(authorDef);
user_Def.addToColumn_metadata(publicationDef);
CfDef person_Def = new CfDef();
person_Def.name = "PERSONNEL";
person_Def.keyspace = _KEYSPACE;
person_Def.setComparator_type("UTF8Type");
person_Def.setKey_validation_class("UTF8Type");
person_Def.setComparator_type("UTF8Type");
person_Def.setDefault_validation_class("UTF8Type");
ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap("PERSON_NAME".getBytes()), "UTF8Type");
person_Def.addToColumn_metadata(columnDef);
CfDef address_Def = new CfDef();
address_Def.name = "ADDRESS";
address_Def.keyspace = _KEYSPACE;
address_Def.setKey_validation_class("UTF8Type");
address_Def.setComparator_type("UTF8Type");
ColumnDef street = new ColumnDef(ByteBuffer.wrap("STREET".getBytes()), "UTF8Type");
street.index_type = IndexType.KEYS;
address_Def.addToColumn_metadata(street);
ColumnDef personId = new ColumnDef(ByteBuffer.wrap("PERSON_ID".getBytes()), "UTF8Type");
personId.index_type = IndexType.KEYS;
address_Def.addToColumn_metadata(personId);
List<CfDef> cfDefs = new ArrayList<CfDef>();
cfDefs.add(user_Def);
cfDefs.add(person_Def);
cfDefs.add(address_Def);
try
{
ksDef = CassandraCli.client.describe_keyspace(_KEYSPACE);
CassandraCli.client.set_keyspace(_KEYSPACE);
List<CfDef> cfDefn = ksDef.getCf_defs();
for (CfDef cfDef1 : cfDefn)
{
if (cfDef1.getName().equalsIgnoreCase("BOOK"))
{
CassandraCli.client.system_drop_column_family("BOOK");
}
if (cfDef1.getName().equalsIgnoreCase("PERSONNEL"))
{
CassandraCli.client.system_drop_column_family("PERSONNEL");
}
if (cfDef1.getName().equalsIgnoreCase("ADDRESS"))
{
CassandraCli.client.system_drop_column_family("ADDRESS");
}
}
CassandraCli.client.system_add_column_family(user_Def);
CassandraCli.client.system_add_column_family(person_Def);
CassandraCli.client.system_add_column_family(address_Def);
}
catch (NotFoundException e)
{
ksDef = new KsDef(_KEYSPACE, "org.apache.cassandra.locator.SimpleStrategy", cfDefs);
Map<String, String> strategy_options = new HashMap<String, String>();
strategy_options.put("replication_factor", "1");
ksDef.setStrategy_options(strategy_options);
CassandraCli.client.system_add_keyspace(ksDef);
}
CassandraCli.client.set_keyspace(_KEYSPACE);
}
private void truncateColumnFamily()
{
String[] columnFamily = new String[] { "BOOK", "PERSONNEL", "ADDRESS" };
CassandraCli.truncateColumnFamily(_KEYSPACE, columnFamily);
}
}
| false | false | null | null |
diff --git a/Main.java b/Main.java
index 5a46076..95299e5 100755
--- a/Main.java
+++ b/Main.java
@@ -1,110 +1,110 @@
-package com.sec.android.allshare.devicediscovery;
+package com.sec.android.devicediscovery;
import java.util.ArrayList;
import com.sec.android.allshare.Device;
import com.sec.android.allshare.Device.DeviceDomain;
import com.sec.android.allshare.Device.DeviceType;
import com.sec.android.allshare.DeviceFinder;
import com.sec.android.allshare.DeviceFinder.IDeviceFinderEventListener;
import com.sec.android.allshare.ERROR;
import com.sec.android.allshare.ServiceConnector;
import com.sec.android.allshare.ServiceConnector.IServiceConnectEventListener;
import com.sec.android.allshare.ServiceConnector.ServiceState;
import com.sec.android.allshare.ServiceProvider;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
ServiceProvider mServiceProvider = null;
TextView mText = null;
Handler mHandler = new Handler();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText = (TextView) findViewById(R.id.txtLog);
mText.append("\n\n" + "Creating service provider!" + "\r\n\n");
ERROR err = ServiceConnector.createServiceProvider(this, new IServiceConnectEventListener()
{
@Override
public void onCreated(ServiceProvider sprovider, ServiceState state)
{
mServiceProvider = sprovider;
showDeviceList();
}
@Override
public void onDeleted(ServiceProvider sprovider)
{
mServiceProvider = null;
}
});
if (err == ERROR.FRAMEWORK_NOT_INSTALLED)
{
// AllShare Framework Service is not installed.
}
else if (err == ERROR.INVALID_ARGUMENT)
{
// Input argement is invalid. Check and try again
}
else
{
// Success on calling the function.
}
}
private final DeviceFinder.IDeviceFinderEventListener mDeviceDiscoveryListener = new IDeviceFinderEventListener()
{
@Override
public void onDeviceRemoved(DeviceType deviceType, Device device, ERROR err)
{
- mText.append("AVPlayer: " + device.getName() + " [" + device.getIPAdress() + "] is removed" + "\r\n");
+ mText.append("AVPlayer: " + device.getName() + " [" + device.getIPAddress() + "] is removed" + "\r\n");
}
@Override
public void onDeviceAdded(DeviceType deviceType, Device device, ERROR err)
{
- mText.append("AVPlayer: " + device.getName() + " [" + device.getIPAdress() + "] is found" + "\r\n");
+ mText.append("AVPlayer: " + device.getName() + " [" + device.getIPAddress() + "] is found" + "\r\n");
}
};
private void showDeviceList()
{
if (mServiceProvider == null)
return;
DeviceFinder mDeviceFinder = mServiceProvider.getDeviceFinder();
mDeviceFinder.setDeviceFinderEventListener(DeviceType.DEVICE_AVPLAYER, mDeviceDiscoveryListener);
ArrayList<Device> mDeviceList = mDeviceFinder.getDevices(DeviceDomain.LOCAL_NETWORK, DeviceType.DEVICE_AVPLAYER);
if (mDeviceList != null)
{
for (int i = 0; i < mDeviceList.size(); i++)
{
- mText.append("AVPlayer: " + mDeviceList.get(i).getName() + " [" + mDeviceList.get(i).getIPAdress() + "] is found" + "\r\n");
+ mText.append("AVPlayer: " + mDeviceList.get(i).getName() + " [" + mDeviceList.get(i).getIPAddress() + "] is found" + "\r\n");
}
}
}
@Override
protected void onDestroy()
{
if (mServiceProvider != null)
ServiceConnector.deleteServiceProvider(mServiceProvider);
super.onDestroy();
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/ch/amana/android/cputuner/view/activity/ProfileEditor.java b/src/ch/amana/android/cputuner/view/activity/ProfileEditor.java
index 62314d20..bcf686e6 100644
--- a/src/ch/amana/android/cputuner/view/activity/ProfileEditor.java
+++ b/src/ch/amana/android/cputuner/view/activity/ProfileEditor.java
@@ -1,483 +1,470 @@
package ch.amana.android.cputuner.view.activity;
import android.content.Context;
import android.content.Intent;
-import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ch.amana.android.cputuner.R;
import ch.amana.android.cputuner.helper.CpuFrequencyChooser;
import ch.amana.android.cputuner.helper.CpuFrequencyChooser.FrequencyChangeCallback;
import ch.amana.android.cputuner.helper.EditorActionbarHelper;
import ch.amana.android.cputuner.helper.EditorActionbarHelper.EditorCallback;
import ch.amana.android.cputuner.helper.EditorActionbarHelper.ExitStatus;
import ch.amana.android.cputuner.helper.GeneralMenuHelper;
import ch.amana.android.cputuner.helper.GovernorConfigHelper;
import ch.amana.android.cputuner.helper.GovernorConfigHelper.GovernorConfig;
import ch.amana.android.cputuner.helper.GuiUtils;
import ch.amana.android.cputuner.helper.Logger;
import ch.amana.android.cputuner.helper.SettingsStorage;
import ch.amana.android.cputuner.hw.CpuHandler;
import ch.amana.android.cputuner.model.ModelAccess;
import ch.amana.android.cputuner.model.ProfileModel;
import ch.amana.android.cputuner.view.fragments.GovernorBaseFragment;
import ch.amana.android.cputuner.view.fragments.GovernorFragment;
import ch.amana.android.cputuner.view.fragments.GovernorFragmentCallback;
import ch.amana.android.cputuner.view.fragments.VirtualGovernorFragment;
import ch.amana.android.cputuner.view.widget.CputunerActionBar;
import com.markupartist.android.widget.ActionBar;
public class ProfileEditor extends FragmentActivity implements GovernorFragmentCallback, FrequencyChangeCallback, EditorCallback {
private ProfileModel profile;
private CpuHandler cpuHandler;
private SeekBar sbCpuFreqMax;
private Spinner spCpuFreqMax;
private SeekBar sbCpuFreqMin;
private Spinner spCpuFreqMin;
private int[] availCpuFreqsMax;
private int[] availCpuFreqsMin;
private Spinner spWifi;
private Spinner spGps;
private Spinner spBluetooth;
private TextView labelCpuFreqMin;
private TextView labelCpuFreqMax;
private EditText etName;
private Spinner spMobileData3G;
private Spinner spSync;
private boolean hasDeviceStatesBeta;
private Spinner spMobileDataConnection;
// private LinearLayout llTop;
private GovernorBaseFragment governorFragment;
private TableRow trMinFreq;
private TableRow trMaxFreq;
private Spinner spAirplaneMode;
private CpuFrequencyChooser cpuFrequencyChooser;
private ExitStatus exitStatus = ExitStatus.save;
private ModelAccess modelAccess;
private ProfileModel origProfile;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_editor);
modelAccess = ModelAccess.getInstace(this);
String action = getIntent().getAction();
if (Intent.ACTION_EDIT.equals(action)) {
profile = modelAccess.getProfile(getIntent().getData());
}
if (profile == null) {
profile = new ProfileModel();
}
Bundle bundle = new Bundle();
profile.saveToBundle(bundle);
origProfile = new ProfileModel(bundle);
CputunerActionBar actionBar = (CputunerActionBar) findViewById(R.id.abCpuTuner);
actionBar.setHomeAction(new ActionBar.Action() {
@Override
public void performAction(View view) {
}
@Override
public int getDrawable() {
return R.drawable.icon;
}
});
actionBar.setTitle(getString(R.string.title_profile_editor) + " " + profile.getProfileName());
EditorActionbarHelper.addActions(this, actionBar);
cpuHandler = CpuHandler.getInstance();
availCpuFreqsMax = cpuHandler.getAvailCpuFreq(false);
availCpuFreqsMin = cpuHandler.getAvailCpuFreq(true);
SettingsStorage settings = SettingsStorage.getInstance();
governorFragment = getFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.llGovernorFragmentAncor, governorFragment);
fragmentTransaction.commit();
if (profile.getMinFreq() < cpuHandler.getMinimumSensibleFrequency() && settings.isBeginnerUser()) {
if (availCpuFreqsMin != null && availCpuFreqsMin.length > 0) {
profile.setMinFreq(availCpuFreqsMin[0]);
}
}
if (ProfileModel.NO_VALUE_INT == profile.getMinFreq() && availCpuFreqsMin.length > 0) {
profile.setMinFreq(cpuHandler.getMinCpuFreq());
}
if (ProfileModel.NO_VALUE_INT == profile.getMaxFreq() && availCpuFreqsMax.length > 0) {
profile.setMaxFreq(cpuHandler.getMaxCpuFreq());
}
// TODO make generic
hasDeviceStatesBeta = 3 == Math.max(profile.getWifiState(),
Math.max(profile.getGpsState(),
Math.max(profile.getMobiledata3GState(),
Math.max(profile.getBluetoothState(),
Math.max(profile.getBackgroundSyncState(),
profile.getWifiState())))));
// llTop = (LinearLayout) findViewById(R.id.llTop);
etName = (EditText) findViewById(R.id.etName);
spCpuFreqMax = (Spinner) findViewById(R.id.spCpuFreqMax);
spCpuFreqMin = (Spinner) findViewById(R.id.spCpuFreqMin);
labelCpuFreqMin = (TextView) findViewById(R.id.labelCpuFreqMin);
labelCpuFreqMax = (TextView) findViewById(R.id.labelCpuFreqMax);
sbCpuFreqMax = (SeekBar) findViewById(R.id.SeekBarCpuFreqMax);
sbCpuFreqMin = (SeekBar) findViewById(R.id.SeekBarCpuFreqMin);
spWifi = (Spinner) findViewById(R.id.spWifi);
spGps = (Spinner) findViewById(R.id.spGps);
spBluetooth = (Spinner) findViewById(R.id.spBluetooth);
spMobileData3G = (Spinner) findViewById(R.id.spMobileData3G);
spMobileDataConnection = (Spinner) findViewById(R.id.spMobileDataConnection);
spAirplaneMode = (Spinner) findViewById(R.id.spAirplaneMode);
spSync = (Spinner) findViewById(R.id.spSync);
trMaxFreq = (TableRow) findViewById(R.id.TableRowMaxFreq);
trMinFreq = (TableRow) findViewById(R.id.TableRowMinFreq);
cpuFrequencyChooser = new CpuFrequencyChooser(this, sbCpuFreqMin, spCpuFreqMin, sbCpuFreqMax, spCpuFreqMax);
TableLayout tlServices = (TableLayout) findViewById(R.id.TableLayoutServices);
if (settings.isEnableSwitchWifi()) {
spWifi.setAdapter(getSystemsAdapter());
spWifi.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
profile.setWifiState(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} else {
tlServices.removeView(findViewById(R.id.TableRowWifi));
}
if (settings.isEnableSwitchGps()) {
spGps.setAdapter(getSystemsAdapter());
spGps.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
profile.setGpsState(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} else {
tlServices.removeView(findViewById(R.id.TableRowGps));
}
if (settings.isEnableSwitchBluetooth()) {
spBluetooth.setAdapter(getSystemsAdapter());
spBluetooth.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
profile.setBluetoothState(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} else {
tlServices.removeView(findViewById(R.id.TableRowBluetooth));
}
if (settings.isEnableSwitchMobiledata3G()) {
int mobiledatastates = R.array.mobiledataStates;
if (settings.isEnableBeta()) {
mobiledatastates = R.array.mobiledataStatesBeta;
}
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, mobiledatastates, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMobileData3G.setAdapter(adapter);
spMobileData3G.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
profile.setMobiledata3GState(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} else {
tlServices.removeView(findViewById(R.id.TableRowMobileData3G));
}
if (settings.isEnableSwitchMobiledataConnection()) {
spMobileDataConnection.setAdapter(getSystemsAdapter());
spMobileDataConnection.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
profile.setMobiledataConnectionState(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} else {
tlServices.removeView(findViewById(R.id.TableRowMobiledataConnection));
}
if (settings.isEnableSwitchBackgroundSync()) {
spSync.setAdapter(getSystemsAdapter());
spSync.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
profile.setBackgroundSyncState(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} else {
tlServices.removeView(findViewById(R.id.TableRowSync));
}
if (settings.isEnableAirplaneMode()) {
spAirplaneMode.setAdapter(getSystemsAdapter());
spAirplaneMode.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
profile.setAirplainemodeState(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} else {
tlServices.removeView(findViewById(R.id.TableRowAirplaneMode));
}
// hide keyboard
etName.setInputType(InputType.TYPE_NULL);
etName.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
etName.setInputType(InputType.TYPE_CLASS_TEXT);
return false;
}
});
// updateView();
}
private GovernorBaseFragment getFragment() {
GovernorBaseFragment gf;
if (SettingsStorage.getInstance().isUseVirtualGovernors()) {
gf = new VirtualGovernorFragment(this, profile);
} else {
gf = new GovernorFragment(this, profile);
}
return gf;
}
private ArrayAdapter<CharSequence> getSystemsAdapter() {
int devicestates = R.array.deviceStates;
if (SettingsStorage.getInstance().isEnableBeta() || hasDeviceStatesBeta) {
devicestates = R.array.deviceStatesBeta;
}
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, devicestates, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
if (exitStatus != ExitStatus.discard) {
updateModel();
profile.saveToBundle(outState);
} else {
origProfile.saveToBundle(outState);
}
super.onSaveInstanceState(outState);
}
@Override
public void updateModel() {
profile.setProfileName(etName.getText().toString());
governorFragment.updateModel();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (profile == null) {
profile = new ProfileModel(savedInstanceState);
} else {
profile.readFromBundle(savedInstanceState);
}
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
updateView();
}
@Override
protected void onPause() {
super.onPause();
updateModel();
try {
String action = getIntent().getAction();
if (exitStatus == ExitStatus.save) {
if (Intent.ACTION_INSERT.equals(action)) {
modelAccess.insertProfile(profile);
} else if (Intent.ACTION_EDIT.equals(action)) {
modelAccess.updateProfile(profile);
}
}
} catch (Exception e) {
Logger.w("Cannot insert or update", e);
}
}
@Override
public void updateView() {
String profileName = profile.getProfileName();
if (!ProfileModel.NO_VALUE_STR.equals(profileName)) {
etName.setText(profileName);
}
cpuFrequencyChooser.setMaxCpuFreq(profile.getMaxFreq());
cpuFrequencyChooser.setMinCpuFreq(profile.getMinFreq());
spWifi.setSelection(profile.getWifiState());
spGps.setSelection(profile.getGpsState());
spBluetooth.setSelection(profile.getBluetoothState());
spMobileData3G.setSelection(profile.getMobiledata3GState());
spMobileDataConnection.setSelection(profile.getMobiledataConnectionState());
spSync.setSelection(profile.getBackgroundSyncState());
spAirplaneMode.setSelection(profile.getAirplainemodeState());
GovernorConfig governorConfig = GovernorConfigHelper.getGovernorConfig(profile.getGov());
if (governorConfig.hasNewLabelCpuFreqMax()) {
labelCpuFreqMax.setText(governorConfig.getNewLabelCpuFreqMax(this));
} else {
labelCpuFreqMax.setText(R.string.labelMax);
}
if (governorConfig.hasMinFrequency()) {
GuiUtils.showViews(trMinFreq, new View[] { labelCpuFreqMin, spCpuFreqMin, sbCpuFreqMin });
} else {
GuiUtils.hideViews(trMinFreq, new View[] { labelCpuFreqMin, spCpuFreqMin, sbCpuFreqMin });
}
if (governorConfig.hasMaxFrequency()) {
GuiUtils.showViews(trMaxFreq, new View[] { labelCpuFreqMax, spCpuFreqMax, sbCpuFreqMax });
} else {
GuiUtils.hideViews(trMaxFreq, new View[] { labelCpuFreqMax, spCpuFreqMax, sbCpuFreqMax });
}
governorFragment.updateView();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.gerneral_help_menu, menu);
getMenuInflater().inflate(R.menu.edit_option, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuItemCancel:
discard();
return true;
case R.id.menuItemSave:
save();
return true;
default:
if (GeneralMenuHelper.onOptionsItemSelected(this, item, HelpActivity.PAGE_PROFILE)) {
return true;
}
}
return false;
}
@Override
public Context getContext() {
return this;
}
@Override
public void setMaxCpuFreq(int val) {
profile.setMaxFreq(val);
}
@Override
public void setMinCpuFreq(int val) {
profile.setMinFreq(val);
}
@Override
public void discard() {
exitStatus = ExitStatus.discard;
profile = origProfile;
// updateView();
finish();
}
@Override
public void save() {
exitStatus = ExitStatus.save;
finish();
}
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- FragmentManager fragmentManager = getSupportFragmentManager();
- FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
- fragmentTransaction.detach(governorFragment);
- fragmentTransaction.commit();
- super.onConfigurationChanged(newConfig);
- fragmentTransaction = fragmentManager.beginTransaction();
- fragmentTransaction.attach(governorFragment);
- fragmentTransaction.commit();
- }
-
// @Override
// public void onBackPressed() {
// updateModel();
// EditorActionbarHelper.onBackPressed(this, exitStatus, !origProfile.equals(profile));
// }
}
diff --git a/src/ch/amana/android/cputuner/view/fragments/CurInfoFragment.java b/src/ch/amana/android/cputuner/view/fragments/CurInfoFragment.java
index 690dd299..c9211249 100644
--- a/src/ch/amana/android/cputuner/view/fragments/CurInfoFragment.java
+++ b/src/ch/amana/android/cputuner/view/fragments/CurInfoFragment.java
@@ -1,545 +1,533 @@
package ch.amana.android.cputuner.view.fragments;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import ch.amana.android.cputuner.R;
import ch.amana.android.cputuner.helper.CpuFrequencyChooser;
import ch.amana.android.cputuner.helper.CpuFrequencyChooser.FrequencyChangeCallback;
import ch.amana.android.cputuner.helper.GovernorConfigHelper;
import ch.amana.android.cputuner.helper.GovernorConfigHelper.GovernorConfig;
import ch.amana.android.cputuner.helper.GuiUtils;
import ch.amana.android.cputuner.helper.Logger;
import ch.amana.android.cputuner.helper.Notifier;
import ch.amana.android.cputuner.helper.PulseHelper;
import ch.amana.android.cputuner.helper.SettingsStorage;
import ch.amana.android.cputuner.hw.BatteryHandler;
import ch.amana.android.cputuner.hw.CpuHandler;
import ch.amana.android.cputuner.hw.CpuHandlerMulticore;
import ch.amana.android.cputuner.hw.PowerProfiles;
import ch.amana.android.cputuner.model.IGovernorModel;
import ch.amana.android.cputuner.model.ProfileModel;
import ch.amana.android.cputuner.model.VirtualGovernorModel;
import ch.amana.android.cputuner.provider.db.DB;
import ch.amana.android.cputuner.provider.db.DB.VirtualGovernor;
import ch.amana.android.cputuner.view.adapter.ProfileAdaper;
import ch.amana.android.cputuner.view.preference.ConfigurationManageActivity;
public class CurInfoFragment extends PagerFragment implements GovernorFragmentCallback, FrequencyChangeCallback {
private static final int[] lock = new int[1];
private CpuTunerReceiver receiver;
private CpuHandler cpuHandler;
private SeekBar sbCpuFreqMax;
private Spinner spCpuFreqMax;
private SeekBar sbCpuFreqMin;
private Spinner spCpuFreqMin;
private TextView tvBatteryLevel;
private TextView tvAcPower;
private TextView tvCurrentTrigger;
private TextView labelCpuFreqMin;
private TextView labelCpuFreqMax;
private TextView tvBatteryCurrent;
private PowerProfiles powerProfiles;
private Spinner spProfiles;
private TextView labelBatteryCurrent;
private GovernorBaseFragment governorFragment;
private GovernorHelperCurInfo governorHelper;
private TextView tvPulse;
private TableRow trPulse;
private TextView spacerPulse;
private TableRow trMaxFreq;
private TableRow trMinFreq;
private TableRow trBatteryCurrent;
private TableRow trConfig;
private TextView labelConfig;
private TextView tvConfig;
private CpuFrequencyChooser cpuFrequencyChooser;
private TableRow trBattery;
private TableRow trPower;
protected class CpuTunerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
acPowerChanged();
batteryLevelChanged();
if (Notifier.BROADCAST_TRIGGER_CHANGED.equals(action) || Notifier.BROADCAST_PROFILE_CHANGED.equals(action)) {
profileChanged();
}
}
}
public void registerReceiver() {
synchronized (lock) {
final Activity act = getActivity();
IntentFilter deviceStatusFilter = new IntentFilter(Notifier.BROADCAST_DEVICESTATUS_CHANGED);
IntentFilter triggerFilter = new IntentFilter(Notifier.BROADCAST_TRIGGER_CHANGED);
IntentFilter profileFilter = new IntentFilter(Notifier.BROADCAST_PROFILE_CHANGED);
receiver = new CpuTunerReceiver();
act.registerReceiver(receiver, deviceStatusFilter);
act.registerReceiver(receiver, triggerFilter);
act.registerReceiver(receiver, profileFilter);
Logger.i("Registered CpuTunerReceiver");
}
}
public void unregisterReceiver() {
synchronized (lock) {
if (receiver != null) {
try {
getActivity().unregisterReceiver(receiver);
receiver = null;
} catch (Throwable e) {
Logger.w("Could not unregister BatteryReceiver", e);
}
}
}
}
private class GovernorHelperCurInfo implements IGovernorModel {
@Override
public int getGovernorThresholdUp() {
return cpuHandler.getGovThresholdUp();
}
@Override
public int getGovernorThresholdDown() {
return cpuHandler.getGovThresholdDown();
}
@Override
public void setGov(String gov) {
cpuHandler.setCurGov(gov);
}
@Override
public void setGovernorThresholdUp(String string) {
try {
setGovernorThresholdUp(Integer.parseInt(string));
} catch (Exception e) {
Logger.w("Cannot parse " + string + " as int");
}
}
@Override
public void setGovernorThresholdDown(String string) {
try {
setGovernorThresholdDown(Integer.parseInt(string));
} catch (Exception e) {
Logger.w("Cannot parse " + string + " as int");
}
}
@Override
public void setScript(String string) {
// not used
}
@Override
public String getGov() {
return cpuHandler.getCurCpuGov();
}
@Override
public String getScript() {
// not used
return "";
}
@Override
public void setGovernorThresholdUp(int i) {
cpuHandler.setGovThresholdUp(i);
}
@Override
public void setGovernorThresholdDown(int i) {
cpuHandler.setGovThresholdDown(i);
}
@Override
public void setVirtualGovernor(long id) {
Cursor c = getActivity().managedQuery(VirtualGovernor.CONTENT_URI, VirtualGovernor.PROJECTION_DEFAULT, DB.SELECTION_BY_ID, new String[] { id + "" },
VirtualGovernor.SORTORDER_DEFAULT);
if (c.moveToFirst()) {
VirtualGovernorModel vgm = new VirtualGovernorModel(c);
cpuHandler.applyGovernorSettings(vgm);
powerProfiles.getCurrentProfile().setVirtualGovernor(id);
}
}
@Override
public long getVirtualGovernor() {
if (powerProfiles == null || powerProfiles.getCurrentProfile() == null) {
return -1;
}
return powerProfiles.getCurrentProfile().getVirtualGovernor();
}
@Override
public void setPowersaveBias(int powersaveBias) {
cpuHandler.setPowersaveBias(powersaveBias);
}
@Override
public int getPowersaveBias() {
return cpuHandler.getPowersaveBias();
}
@Override
public boolean hasScript() {
return false;
}
@Override
public void setUseNumberOfCpus(int position) {
cpuHandler.setNumberOfActiveCpus(position);
}
@Override
public int getUseNumberOfCpus() {
return cpuHandler.getNumberOfActiveCpus();
}
@Override
public CharSequence getDescription(Context ctx) {
if (ctx == null) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(ctx.getString(R.string.labelGovernor)).append(" ").append(getGov());
int governorThresholdUp = getGovernorThresholdUp();
if (governorThresholdUp > 0) {
sb.append("\n").append(ctx.getString(R.string.labelThreshsUp)).append(" ").append(governorThresholdUp);
}
int governorThresholdDown = getGovernorThresholdDown();
if (governorThresholdDown > 0) {
sb.append(" ").append(ctx.getString(R.string.labelDown)).append(" ").append(governorThresholdDown);
}
if (cpuHandler instanceof CpuHandlerMulticore) {
int useNumberOfCpus = getUseNumberOfCpus();
int numberOfCpus = cpuHandler.getNumberOfCpus();
if (useNumberOfCpus < 1 || useNumberOfCpus > numberOfCpus) {
useNumberOfCpus = numberOfCpus;
}
sb.append("\n").append(ctx.getString(R.string.labelActiveCpus)).append(" ").append(useNumberOfCpus);
sb.append("/").append(numberOfCpus);
}
return sb.toString();
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.cur_info, container, false);
tvCurrentTrigger = (TextView) v.findViewById(R.id.tvCurrentTrigger);
spProfiles = (Spinner) v.findViewById(R.id.spProfiles);
tvBatteryLevel = (TextView) v.findViewById(R.id.tvBatteryLevel);
tvAcPower = (TextView) v.findViewById(R.id.tvAcPower);
tvBatteryCurrent = (TextView) v.findViewById(R.id.tvBatteryCurrent);
tvBatteryLevel = (TextView) v.findViewById(R.id.tvBatteryLevel);
spCpuFreqMax = (Spinner) v.findViewById(R.id.spCpuFreqMax);
spCpuFreqMin = (Spinner) v.findViewById(R.id.spCpuFreqMin);
labelCpuFreqMin = (TextView) v.findViewById(R.id.labelCpuFreqMin);
labelCpuFreqMax = (TextView) v.findViewById(R.id.labelCpuFreqMax);
sbCpuFreqMax = (SeekBar) v.findViewById(R.id.SeekBarCpuFreqMax);
sbCpuFreqMin = (SeekBar) v.findViewById(R.id.SeekBarCpuFreqMin);
labelBatteryCurrent = (TextView) v.findViewById(R.id.labelBatteryCurrent);
trPulse = (TableRow) v.findViewById(R.id.TableRowPulse);
tvPulse = (TextView) v.findViewById(R.id.tvPulse);
spacerPulse = (TextView) v.findViewById(R.id.spacerPulse);
trMaxFreq = (TableRow) v.findViewById(R.id.TableRowMaxFreq);
trMinFreq = (TableRow) v.findViewById(R.id.TableRowMinFreq);
trBatteryCurrent = (TableRow) v.findViewById(R.id.TableRowBatteryCurrent);
trConfig = (TableRow) v.findViewById(R.id.TableRowConfig);
labelConfig = (TextView) v.findViewById(R.id.labelConfig);
tvConfig = (TextView) v.findViewById(R.id.tvConfig);
trBattery = (TableRow) v.findViewById(R.id.TableRowBattery);
trPower = (TableRow) v.findViewById(R.id.TableRowPower);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final SettingsStorage settings = SettingsStorage.getInstance();
final Activity act = getActivity();
cpuHandler = CpuHandler.getInstance();
powerProfiles = PowerProfiles.getInstance();
cpuFrequencyChooser = new CpuFrequencyChooser(this, sbCpuFreqMin, spCpuFreqMin, sbCpuFreqMax, spCpuFreqMax);
governorHelper = new GovernorHelperCurInfo();
if (settings.isUseVirtualGovernors()) {
governorFragment = new VirtualGovernorFragment(this, governorHelper);
} else {
governorFragment = new GovernorFragment(this, governorHelper, true);
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.llGovernorFragmentAncor, governorFragment);
fragmentTransaction.commit();
Cursor cursor = act.managedQuery(DB.CpuProfile.CONTENT_URI, DB.CpuProfile.PROJECTION_PROFILE_NAME, null, null, DB.CpuProfile.SORTORDER_DEFAULT);
// SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
// android.R.layout.simple_spinner_item, cursor, new String[] {
// DB.CpuProfile.NAME_PROFILE_NAME },
// new int[] { android.R.id.text1 });
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ProfileAdaper adapter = new ProfileAdaper(act, cursor);
spProfiles.setAdapter(adapter);
spProfiles.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
ProfileModel currentProfile = powerProfiles.getCurrentProfile();
if (pos > 0) {
// let us change the profile
String profile = parent.getItemAtPosition(pos).toString();
if (profile != null) {
powerProfiles.setManualProfile(id);
powerProfiles.applyProfile(id);
governorFragment.updateView();
}
} else {
powerProfiles.setManualProfile(PowerProfiles.AUTOMATIC_PROFILE);
powerProfiles.applyProfile(currentProfile.getDbId());
governorFragment.updateView();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
OnClickListener startBattery = new OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent i = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
startActivity(i);
} catch (Throwable e) {
// 'old' -> fallback
try {
Intent i = new Intent();
i.setClassName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
startActivity(i);
} catch (Throwable e1) {
}
}
}
};
trBattery.setOnClickListener(startBattery);
trBatteryCurrent.setOnClickListener(startBattery);
trPower.setOnClickListener(startBattery);
trConfig.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Context ctx = getActivity();
Intent intent = new Intent(ctx, ConfigurationManageActivity.class);
intent.putExtra(ConfigurationManageActivity.EXTRA_CLOSE_ON_LOAD, true);
intent.putExtra(ConfigurationManageActivity.EXTRA_NEW_LAYOUT, true);
ctx.startActivity(intent);
}
});
}
@Override
public void onResume() {
super.onResume();
registerReceiver();
// updateView();
governorFragment.updateVirtGov(true);
}
@Override
public void onPause() {
super.onPause();
governorFragment.updateVirtGov(false);
unregisterReceiver();
}
@Override
public void updateView() {
batteryLevelChanged();
profileChanged();
acPowerChanged();
}
private void batteryLevelChanged() {
StringBuilder bat = new StringBuilder();
bat.append(powerProfiles.getBatteryLevel()).append("%");
bat.append(" (");
if (powerProfiles.isBatteryHot()) {
bat.append(R.string.label_hot).append(" ");
}
bat.append(powerProfiles.getBatteryTemperature()).append(" °C)");
tvBatteryLevel.setText(bat.toString());
StringBuilder currentText = new StringBuilder();
BatteryHandler batteryHandler = BatteryHandler.getInstance();
int currentNow = batteryHandler.getBatteryCurrentNow();
if (currentNow > 0) {
currentText.append(batteryHandler.getBatteryCurrentNow()).append(" mA/h");
}
if (batteryHandler.hasAvgCurrent()) {
int currentAvg = batteryHandler.getBatteryCurrentAverage();
if (currentAvg != BatteryHandler.NO_VALUE_INT) {
currentText.append(" (").append(getString(R.string.label_avgerage)).append(" ").append(batteryHandler.getBatteryCurrentAverage()).append(" mA/h)");
}
}
if (currentText.length() > 0) {
GuiUtils.showViews(trBatteryCurrent, new View[] { labelBatteryCurrent, tvBatteryCurrent });
tvBatteryCurrent.setText(currentText.toString());
} else {
GuiUtils.hideViews(trBatteryCurrent, new View[] { labelBatteryCurrent, tvBatteryCurrent });
}
}
private void profileChanged() {
final Activity act = getActivity();
SettingsStorage settings = SettingsStorage.getInstance();
if (PulseHelper.getInstance(act).isPulsing()) {
GuiUtils.showViews(trPulse, new View[] { spacerPulse, tvPulse });
int res = PulseHelper.getInstance(act).isOn() ? R.string.labelPulseOn : R.string.labelPulseOff;
tvPulse.setText(res);
} else {
GuiUtils.hideViews(trPulse, new View[] { spacerPulse, tvPulse });
}
if (settings.hasCurrentConfiguration()) {
GuiUtils.showViews(trConfig, new View[] { labelConfig, tvConfig });
tvConfig.setText(settings.getCurrentConfiguration());
} else {
GuiUtils.hideViews(trConfig, new View[] { labelConfig, tvConfig });
}
if (settings.isEnableProfiles()) {
ProfileModel currentProfile = powerProfiles.getCurrentProfile();
if (currentProfile != null) {
if (powerProfiles.isManualProfile()) {
GuiUtils.setSpinner(spProfiles, currentProfile.getDbId());
} else {
spProfiles.setSelection(0);
}
spProfiles.setEnabled(true);
} else {
spProfiles.setEnabled(false);
}
tvCurrentTrigger.setText(powerProfiles.getCurrentTriggerName());
} else {
// Does this work now?
// spProfiles.setEnabled(false);
tvCurrentTrigger.setText(R.string.notEnabled);
}
cpuFrequencyChooser.setMinCpuFreq(cpuHandler.getMinCpuFreq());
cpuFrequencyChooser.setMaxCpuFreq(cpuHandler.getMaxCpuFreq());
GovernorConfig governorConfig = GovernorConfigHelper.getGovernorConfig(cpuHandler.getCurCpuGov());
if (governorConfig.hasNewLabelCpuFreqMax()) {
labelCpuFreqMax.setText(governorConfig.getNewLabelCpuFreqMax(act));
} else {
labelCpuFreqMax.setText(R.string.labelMax);
}
if (governorConfig.hasMinFrequency()) {
GuiUtils.showViews(trMinFreq, new View[] { labelCpuFreqMin, spCpuFreqMin, sbCpuFreqMin });
} else {
GuiUtils.hideViews(trMinFreq, new View[] { labelCpuFreqMin, spCpuFreqMin, sbCpuFreqMin });
}
if (governorConfig.hasMaxFrequency()) {
GuiUtils.showViews(trMaxFreq, new View[] { labelCpuFreqMax, spCpuFreqMax, sbCpuFreqMax });
} else {
GuiUtils.hideViews(trMaxFreq, new View[] { labelCpuFreqMax, spCpuFreqMax, sbCpuFreqMax });
}
governorFragment.updateView();
}
private void acPowerChanged() {
tvAcPower.setText(getText(powerProfiles.isAcPower() ? R.string.yes : R.string.no));
}
@Override
public void updateModel() {
// not used
}
@Override
public void setMaxCpuFreq(int val) {
if (val != cpuHandler.getMaxCpuFreq()) {
if (cpuHandler.setMaxCpuFreq(val)) {
Toast.makeText(getContext(), getString(R.string.msg_setting_cpu_max_freq, val), Toast.LENGTH_LONG).show();
}
updateView();
}
}
@Override
public void setMinCpuFreq(int val) {
if (val != cpuHandler.getMinCpuFreq()) {
if (cpuHandler.setMinCpuFreq(val)) {
Toast.makeText(getContext(), getString(R.string.setting_cpu_min_freq, val), Toast.LENGTH_LONG).show();
}
updateView();
}
}
@Override
public Context getContext() {
return getActivity();
};
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- FragmentManager fragmentManager = getFragmentManager();
- FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
- fragmentTransaction.detach(governorFragment);
- fragmentTransaction.commit();
- super.onConfigurationChanged(newConfig);
- fragmentTransaction = fragmentManager.beginTransaction();
- fragmentTransaction.attach(governorFragment);
- fragmentTransaction.commit();
- }
}
| false | false | null | null |
diff --git a/android/src/com/google/zxing/client/android/PreferencesFragment.java b/android/src/com/google/zxing/client/android/PreferencesFragment.java
index 2d95eba1..95b387bc 100644
--- a/android/src/com/google/zxing/client/android/PreferencesFragment.java
+++ b/android/src/com/google/zxing/client/android/PreferencesFragment.java
@@ -1,123 +1,126 @@
/*
* Copyright (C) 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
public final class PreferencesFragment
extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener {
private CheckBoxPreference[] checkBoxPrefs;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.preferences);
PreferenceScreen preferences = getPreferenceScreen();
preferences.getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
checkBoxPrefs = findDecodePrefs(preferences,
PreferencesActivity.KEY_DECODE_1D_PRODUCT,
PreferencesActivity.KEY_DECODE_1D_INDUSTRIAL,
PreferencesActivity.KEY_DECODE_QR,
PreferencesActivity.KEY_DECODE_DATA_MATRIX,
PreferencesActivity.KEY_DECODE_AZTEC,
PreferencesActivity.KEY_DECODE_PDF417);
disableLastCheckedPref();
EditTextPreference customProductSearch = (EditTextPreference)
preferences.findPreference(PreferencesActivity.KEY_CUSTOM_PRODUCT_SEARCH);
customProductSearch.setOnPreferenceChangeListener(new CustomSearchURLValidator());
}
private static CheckBoxPreference[] findDecodePrefs(PreferenceScreen preferences, String... keys) {
CheckBoxPreference[] prefs = new CheckBoxPreference[keys.length];
for (int i = 0; i < keys.length; i++) {
prefs[i] = (CheckBoxPreference) preferences.findPreference(keys[i]);
}
return prefs;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
disableLastCheckedPref();
}
private void disableLastCheckedPref() {
Collection<CheckBoxPreference> checked = new ArrayList<>(checkBoxPrefs.length);
for (CheckBoxPreference pref : checkBoxPrefs) {
if (pref.isChecked()) {
checked.add(pref);
}
}
boolean disable = checked.size() <= 1;
for (CheckBoxPreference pref : checkBoxPrefs) {
pref.setEnabled(!(disable && checked.contains(pref)));
}
}
private class CustomSearchURLValidator implements Preference.OnPreferenceChangeListener {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!isValid(newValue)) {
AlertDialog.Builder builder =
new AlertDialog.Builder(PreferencesFragment.this.getActivity());
builder.setTitle(R.string.msg_error);
builder.setMessage(R.string.msg_invalid_value);
builder.setCancelable(true);
builder.show();
return false;
}
return true;
}
private boolean isValid(Object newValue) {
// Allow empty/null value
if (newValue == null) {
return true;
}
String valueString = newValue.toString();
if (valueString.isEmpty()) {
return true;
}
// Before validating, remove custom placeholders, which will not
// be considered valid parts of the URL in some locations:
- valueString = valueString.replaceAll("%[sdf]", "");
+ // Blank %d and %s:
+ valueString = valueString.replaceAll("%[sd]", "");
+ // Blank %f but not if followed by digit or a-f as it may be a hex sequence
+ valueString = valueString.replaceAll("%f(?![0-9a-f])", "");
// Require a scheme otherwise:
try {
URI uri = new URI(valueString);
return uri.getScheme() != null;
} catch (URISyntaxException use) {
return false;
}
}
}
}
diff --git a/android/src/com/google/zxing/client/android/result/ResultHandler.java b/android/src/com/google/zxing/client/android/result/ResultHandler.java
index ef1a6e94..07b15688 100644
--- a/android/src/com/google/zxing/client/android/result/ResultHandler.java
+++ b/android/src/com/google/zxing/client/android/result/ResultHandler.java
@@ -1,478 +1,482 @@
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.result;
import com.google.zxing.Result;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.LocaleManager;
import com.google.zxing.client.android.PreferencesActivity;
import com.google.zxing.client.android.R;
import com.google.zxing.client.android.book.SearchBookContentsActivity;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ParsedResultType;
import com.google.zxing.client.result.ResultParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;
/**
* A base class for the Android-specific barcode handlers. These allow the app to polymorphically
* suggest the appropriate actions for each data type.
*
* This class also contains a bunch of utility methods to take common actions like opening a URL.
* They could easily be moved into a helper object, but it can't be static because the Activity
* instance is needed to launch an intent.
*
* @author [email protected] (Daniel Switkin)
* @author Sean Owen
*/
public abstract class ResultHandler {
private static final String TAG = ResultHandler.class.getSimpleName();
private static final String[] EMAIL_TYPE_STRINGS = {"home", "work", "mobile"};
private static final String[] PHONE_TYPE_STRINGS = {"home", "work", "mobile", "fax", "pager", "main"};
private static final String[] ADDRESS_TYPE_STRINGS = {"home", "work"};
private static final int[] EMAIL_TYPE_VALUES = {
ContactsContract.CommonDataKinds.Email.TYPE_HOME,
ContactsContract.CommonDataKinds.Email.TYPE_WORK,
ContactsContract.CommonDataKinds.Email.TYPE_MOBILE,
};
private static final int[] PHONE_TYPE_VALUES = {
ContactsContract.CommonDataKinds.Phone.TYPE_HOME,
ContactsContract.CommonDataKinds.Phone.TYPE_WORK,
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK,
ContactsContract.CommonDataKinds.Phone.TYPE_PAGER,
ContactsContract.CommonDataKinds.Phone.TYPE_MAIN,
};
private static final int[] ADDRESS_TYPE_VALUES = {
ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME,
ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK,
};
private static final int NO_TYPE = -1;
public static final int MAX_BUTTON_COUNT = 4;
private final ParsedResult result;
private final Activity activity;
private final Result rawResult;
private final String customProductSearch;
ResultHandler(Activity activity, ParsedResult result) {
this(activity, result, null);
}
ResultHandler(Activity activity, ParsedResult result, Result rawResult) {
this.result = result;
this.activity = activity;
this.rawResult = rawResult;
this.customProductSearch = parseCustomSearchURL();
}
public final ParsedResult getResult() {
return result;
}
final boolean hasCustomProductSearch() {
return customProductSearch != null;
}
final Activity getActivity() {
return activity;
}
/**
* Indicates how many buttons the derived class wants shown.
*
* @return The integer button count.
*/
public abstract int getButtonCount();
/**
* The text of the nth action button.
*
* @param index From 0 to getButtonCount() - 1
* @return The button text as a resource ID
*/
public abstract int getButtonText(int index);
/**
* Execute the action which corresponds to the nth button.
*
* @param index The button that was clicked.
*/
public abstract void handleButtonPress(int index);
/**
* Some barcode contents are considered secure, and should not be saved to history, copied to
* the clipboard, or otherwise persisted.
*
* @return If true, do not create any permanent record of these contents.
*/
public boolean areContentsSecure() {
return false;
}
/**
* Create a possibly styled string for the contents of the current barcode.
*
* @return The text to be displayed.
*/
public CharSequence getDisplayContents() {
String contents = result.getDisplayResult();
return contents.replace("\r", "");
}
/**
* A string describing the kind of barcode that was found, e.g. "Found contact info".
*
* @return The resource ID of the string.
*/
public abstract int getDisplayTitle();
/**
* A convenience method to get the parsed type. Should not be overridden.
*
* @return The parsed type, e.g. URI or ISBN
*/
public final ParsedResultType getType() {
return result.getType();
}
final void addPhoneOnlyContact(String[] phoneNumbers,String[] phoneTypes) {
addContact(null, null, null, phoneNumbers, phoneTypes, null, null, null, null, null, null, null, null, null, null, null);
}
final void addEmailOnlyContact(String[] emails, String[] emailTypes) {
addContact(null, null, null, null, null, emails, emailTypes, null, null, null, null, null, null, null, null, null);
}
final void addContact(String[] names,
String[] nicknames,
String pronunciation,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String note,
String instantMessenger,
String address,
String addressType,
String org,
String title,
String[] urls,
String birthday,
String[] geo) {
// Only use the first name in the array, if present.
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
putExtra(intent, ContactsContract.Intents.Insert.NAME, names != null ? names[0] : null);
putExtra(intent, ContactsContract.Intents.Insert.PHONETIC_NAME, pronunciation);
int phoneCount = Math.min(phoneNumbers != null ? phoneNumbers.length : 0, Contents.PHONE_KEYS.length);
for (int x = 0; x < phoneCount; x++) {
putExtra(intent, Contents.PHONE_KEYS[x], phoneNumbers[x]);
if (phoneTypes != null && x < phoneTypes.length) {
int type = toPhoneContractType(phoneTypes[x]);
if (type >= 0) {
intent.putExtra(Contents.PHONE_TYPE_KEYS[x], type);
}
}
}
int emailCount = Math.min(emails != null ? emails.length : 0, Contents.EMAIL_KEYS.length);
for (int x = 0; x < emailCount; x++) {
putExtra(intent, Contents.EMAIL_KEYS[x], emails[x]);
if (emailTypes != null && x < emailTypes.length) {
int type = toEmailContractType(emailTypes[x]);
if (type >= 0) {
intent.putExtra(Contents.EMAIL_TYPE_KEYS[x], type);
}
}
}
// No field for URL, birthday; use notes
StringBuilder aggregatedNotes = new StringBuilder();
if (urls != null) {
for (String url : urls) {
if (url != null && !url.isEmpty()) {
aggregatedNotes.append('\n').append(url);
}
}
}
for (String aNote : new String[] { birthday, note }) {
if (aNote != null) {
aggregatedNotes.append('\n').append(aNote);
}
}
if (nicknames != null) {
for (String nickname : nicknames) {
if (nickname != null && !nickname.isEmpty()) {
aggregatedNotes.append('\n').append(nickname);
}
}
}
if (geo != null) {
aggregatedNotes.append('\n').append(geo[0]).append(',').append(geo[1]);
}
if (aggregatedNotes.length() > 0) {
// Remove extra leading '\n'
putExtra(intent, ContactsContract.Intents.Insert.NOTES, aggregatedNotes.substring(1));
}
putExtra(intent, ContactsContract.Intents.Insert.IM_HANDLE, instantMessenger);
putExtra(intent, ContactsContract.Intents.Insert.POSTAL, address);
if (addressType != null) {
int type = toAddressContractType(addressType);
if (type >= 0) {
intent.putExtra(ContactsContract.Intents.Insert.POSTAL_TYPE, type);
}
}
putExtra(intent, ContactsContract.Intents.Insert.COMPANY, org);
putExtra(intent, ContactsContract.Intents.Insert.JOB_TITLE, title);
launchIntent(intent);
}
private static int toEmailContractType(String typeString) {
return doToContractType(typeString, EMAIL_TYPE_STRINGS, EMAIL_TYPE_VALUES);
}
private static int toPhoneContractType(String typeString) {
return doToContractType(typeString, PHONE_TYPE_STRINGS, PHONE_TYPE_VALUES);
}
private static int toAddressContractType(String typeString) {
return doToContractType(typeString, ADDRESS_TYPE_STRINGS, ADDRESS_TYPE_VALUES);
}
private static int doToContractType(String typeString, String[] types, int[] values) {
if (typeString == null) {
return NO_TYPE;
}
for (int i = 0; i < types.length; i++) {
String type = types[i];
if (typeString.startsWith(type) || typeString.startsWith(type.toUpperCase(Locale.ENGLISH))) {
return values[i];
}
}
return NO_TYPE;
}
final void shareByEmail(String contents) {
sendEmailFromUri("mailto:", null, null, contents);
}
final void sendEmail(String address, String subject, String body) {
sendEmailFromUri("mailto:" + address, address, subject, body);
}
// Use public Intent fields rather than private GMail app fields to specify subject and body.
final void sendEmailFromUri(String uri, String email, String subject, String body) {
Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse(uri));
if (email != null) {
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {email});
}
putExtra(intent, Intent.EXTRA_SUBJECT, subject);
putExtra(intent, Intent.EXTRA_TEXT, body);
intent.setType("text/plain");
launchIntent(intent);
}
final void shareBySMS(String contents) {
sendSMSFromUri("smsto:", contents);
}
final void sendSMS(String phoneNumber, String body) {
sendSMSFromUri("smsto:" + phoneNumber, body);
}
final void sendSMSFromUri(String uri, String body) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
putExtra(intent, "sms_body", body);
// Exit the app once the SMS is sent
intent.putExtra("compose_mode", true);
launchIntent(intent);
}
final void sendMMS(String phoneNumber, String subject, String body) {
sendMMSFromUri("mmsto:" + phoneNumber, subject, body);
}
final void sendMMSFromUri(String uri, String subject, String body) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
// The Messaging app needs to see a valid subject or else it will treat this an an SMS.
if (subject == null || subject.isEmpty()) {
putExtra(intent, "subject", activity.getString(R.string.msg_default_mms_subject));
} else {
putExtra(intent, "subject", subject);
}
putExtra(intent, "sms_body", body);
intent.putExtra("compose_mode", true);
launchIntent(intent);
}
final void dialPhone(String phoneNumber) {
launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
}
final void dialPhoneFromUri(String uri) {
launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse(uri)));
}
final void openMap(String geoURI) {
launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI)));
}
/**
* Do a geo search using the address as the query.
*
* @param address The address to find
*/
final void searchMap(String address) {
launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(address))));
}
final void getDirections(double latitude, double longitude) {
launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google." +
LocaleManager.getCountryTLD(activity) + "/maps?f=d&daddr=" + latitude + ',' + longitude)));
}
// Uses the mobile-specific version of Product Search, which is formatted for small screens.
final void openProductSearch(String upc) {
Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD(activity) +
"/m/products?q=" + upc + "&source=zxing");
launchIntent(new Intent(Intent.ACTION_VIEW, uri));
}
final void openBookSearch(String isbn) {
Uri uri = Uri.parse("http://books.google." + LocaleManager.getBookSearchCountryTLD(activity) +
"/books?vid=isbn" + isbn);
launchIntent(new Intent(Intent.ACTION_VIEW, uri));
}
final void searchBookContents(String isbnOrUrl) {
Intent intent = new Intent(Intents.SearchBookContents.ACTION);
intent.setClassName(activity, SearchBookContentsActivity.class.getName());
putExtra(intent, Intents.SearchBookContents.ISBN, isbnOrUrl);
launchIntent(intent);
}
final void openURL(String url) {
// Strangely, some Android browsers don't seem to register to handle HTTP:// or HTTPS://.
// Lower-case these as it should always be OK to lower-case these schemes.
if (url.startsWith("HTTP://")) {
url = "http" + url.substring(4);
} else if (url.startsWith("HTTPS://")) {
url = "https" + url.substring(5);
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
try {
launchIntent(intent);
} catch (ActivityNotFoundException ignored) {
Log.w(TAG, "Nothing available to handle " + intent);
}
}
final void webSearch(String query) {
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra("query", query);
launchIntent(intent);
}
/**
* Like {@link #launchIntent(Intent)} but will tell you if it is not handle-able
* via {@link ActivityNotFoundException}.
*
* @throws ActivityNotFoundException
*/
final void rawLaunchIntent(Intent intent) {
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Log.d(TAG, "Launching intent: " + intent + " with extras: " + intent.getExtras());
activity.startActivity(intent);
}
}
/**
* Like {@link #rawLaunchIntent(Intent)} but will show a user dialog if nothing is available to handle.
*/
final void launchIntent(Intent intent) {
try {
rawLaunchIntent(intent);
} catch (ActivityNotFoundException ignored) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.app_name);
builder.setMessage(R.string.msg_intent_failed);
builder.setPositiveButton(R.string.button_ok, null);
builder.show();
}
}
private static void putExtra(Intent intent, String key, String value) {
if (value != null && !value.isEmpty()) {
intent.putExtra(key, value);
}
}
private String parseCustomSearchURL() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
String customProductSearch = prefs.getString(PreferencesActivity.KEY_CUSTOM_PRODUCT_SEARCH,
null);
if (customProductSearch != null && customProductSearch.trim().isEmpty()) {
return null;
}
return customProductSearch;
}
final String fillInCustomSearchURL(String text) {
if (customProductSearch == null) {
return text; // ?
}
try {
text = URLEncoder.encode(text, "UTF-8");
} catch (UnsupportedEncodingException e) {
// can't happen; UTF-8 is always supported. Continue, I guess, without encoding
}
- String url = customProductSearch.replace("%s", text);
+ String url = text;
if (rawResult != null) {
- url = url.replace("%f", rawResult.getBarcodeFormat().toString());
+ // Replace %f but only if it doesn't seem to be a hex escape sequence. This remains
+ // problematic but avoids the more surprising problem of breaking escapes
+ url = url.replace("%f(?![0-9a-f])", rawResult.getBarcodeFormat().toString());
if (url.contains("%t")) {
ParsedResult parsedResultAgain = ResultParser.parseResult(rawResult);
url = url.replace("%t", parsedResultAgain.getType().toString());
}
}
+ // Replace %s last as it might contain itself %f or %t
+ url = customProductSearch.replace("%s", url);
return url;
}
}
| false | false | null | null |
diff --git a/src/main/java/servlet/TestLampServlet.java b/src/main/java/servlet/TestLampServlet.java
index e001986..ded6297 100644
--- a/src/main/java/servlet/TestLampServlet.java
+++ b/src/main/java/servlet/TestLampServlet.java
@@ -1,104 +1,104 @@
package main.java.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
public class TestLampServlet extends HttpServlet {
// Database Connection
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
// Hardcoded dbUrl:
// String dbUrl = "jdbc:postgres://ixhixpfgeanclh:p1uyfk5c9yLh1VEWoCOGb4FIEX@ec2-54-225-112-205.compute-1.amazonaws.com:5432/d3lbshfcpi0soa";
// Heroku dbUrl:
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
private static String convertIntToStatus(int data_value_int) {
// Convert int to string
String status_str = "on";
if (data_value_int == 0) {
status_str = "off";
}
return status_str;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Connection connection = getConnection();
// Return the latest status of the test lamp
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1");
rs.next();
request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1)));
request.setAttribute("lampStatusTime", rs.getString(2));
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-get.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = request.getParameter("data_value");
// data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
- if (data_value_str == "off") {
+ if (data_value_str.contains("off")) {
data_value_int = 0;
}
- else if (data_value_str == "on") {
+ else if (data_value_str.contains("on")) {
data_value_int = 1;
}
else {
data_value_int = 2;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())");
stmt.executeUpdate("INSERT INTO testing VALUES ('" + data_value_str + "')");
// Return the latest status of the test lamp
ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1");
rs.next();
request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1)));
request.setAttribute("lampStatusTime", rs.getString(2));
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
};
| false | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = request.getParameter("data_value");
// data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str == "off") {
data_value_int = 0;
}
else if (data_value_str == "on") {
data_value_int = 1;
}
else {
data_value_int = 2;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())");
stmt.executeUpdate("INSERT INTO testing VALUES ('" + data_value_str + "')");
// Return the latest status of the test lamp
ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1");
rs.next();
request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1)));
request.setAttribute("lampStatusTime", rs.getString(2));
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = request.getParameter("data_value");
// data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str.contains("off")) {
data_value_int = 0;
}
else if (data_value_str.contains("on")) {
data_value_int = 1;
}
else {
data_value_int = 2;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())");
stmt.executeUpdate("INSERT INTO testing VALUES ('" + data_value_str + "')");
// Return the latest status of the test lamp
ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1");
rs.next();
request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1)));
request.setAttribute("lampStatusTime", rs.getString(2));
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
|
diff --git a/src/java/org/apache/commons/jxpath/ri/model/beans/BeanPropertyPointer.java b/src/java/org/apache/commons/jxpath/ri/model/beans/BeanPropertyPointer.java
index e0ff819..7986459 100644
--- a/src/java/org/apache/commons/jxpath/ri/model/beans/BeanPropertyPointer.java
+++ b/src/java/org/apache/commons/jxpath/ri/model/beans/BeanPropertyPointer.java
@@ -1,290 +1,292 @@
/*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jxpath.ri.model.beans;
import java.beans.IndexedPropertyDescriptor;
import java.beans.PropertyDescriptor;
import org.apache.commons.jxpath.JXPathBeanInfo;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathInvalidAccessException;
import org.apache.commons.jxpath.ri.model.NodePointer;
import org.apache.commons.jxpath.util.ValueUtils;
/**
* Pointer pointing to a property of a JavaBean.
*
* @author Dmitri Plotnikov
* @version $Revision$ $Date$
*/
public class BeanPropertyPointer extends PropertyPointer {
private String propertyName;
private JXPathBeanInfo beanInfo;
private PropertyDescriptor propertyDescriptors[];
private PropertyDescriptor propertyDescriptor;
private String[] names;
private static final Object UNINITIALIZED = new Object();
private Object baseValue = UNINITIALIZED;
private Object value = UNINITIALIZED;
- private static final int UNKNOWN_LENGTH_MAX_COUNT = 10000;
public BeanPropertyPointer(NodePointer parent, JXPathBeanInfo beanInfo) {
super(parent);
this.beanInfo = beanInfo;
}
/**
* This type of node is auxiliary.
*/
public boolean isContainer() {
return true;
}
/**
* Number of the bean's properties.
*/
public int getPropertyCount() {
+ if (beanInfo.isAtomic()) {
+ return 0;
+ }
return getPropertyDescriptors().length;
}
/**
* Names of all properties, sorted alphabetically
*/
public String[] getPropertyNames() {
if (names == null) {
PropertyDescriptor pds[] = getPropertyDescriptors();
names = new String[pds.length];
for (int i = 0; i < names.length; i++) {
names[i] = pds[i].getName();
}
}
return names;
}
/**
* Select a property by name
*/
public void setPropertyName(String propertyName) {
setPropertyIndex(UNSPECIFIED_PROPERTY);
this.propertyName = propertyName;
}
/**
* Selects a property by its offset in the alphabetically sorted list.
*/
public void setPropertyIndex(int index) {
if (propertyIndex != index) {
super.setPropertyIndex(index);
propertyName = null;
propertyDescriptor = null;
baseValue = UNINITIALIZED;
value = UNINITIALIZED;
}
}
/**
* The value of the currently selected property.
*/
public Object getBaseValue() {
if (baseValue == UNINITIALIZED) {
PropertyDescriptor pd = getPropertyDescriptor();
if (pd == null) {
return null;
}
baseValue = ValueUtils.getValue(getBean(), pd);
}
return baseValue;
}
public void setIndex(int index) {
if (this.index != index) {
// When dealing with a scalar, index == 0 is equivalent to
// WHOLE_COLLECTION, so do not change it.
if (this.index != WHOLE_COLLECTION
|| index != 0
|| isCollection()) {
super.setIndex(index);
value = UNINITIALIZED;
}
}
}
/**
* If index == WHOLE_COLLECTION, the value of the property, otherwise
* the value of the index'th element of the collection represented by the
* property. If the property is not a collection, index should be zero
* and the value will be the property itself.
*/
public Object getImmediateNode() {
if (value == UNINITIALIZED) {
if (index == WHOLE_COLLECTION) {
value = ValueUtils.getValue(getBaseValue());
}
else {
PropertyDescriptor pd = getPropertyDescriptor();
if (pd == null) {
value = null;
}
else {
value = ValueUtils.getValue(getBean(), pd, index);
}
}
}
return value;
}
protected boolean isActualProperty() {
return getPropertyDescriptor() != null;
}
public boolean isCollection() {
PropertyDescriptor pd = getPropertyDescriptor();
if (pd == null) {
return false;
}
if (pd instanceof IndexedPropertyDescriptor) {
return true;
}
int hint = ValueUtils.getCollectionHint(pd.getPropertyType());
if (hint == -1) {
return false;
}
if (hint == 1) {
return true;
}
Object value = getBaseValue();
return value != null && ValueUtils.isCollection(value);
}
/**
* If the property contains a collection, then the length of that
* collection, otherwise - 1.
*/
public int getLength() {
PropertyDescriptor pd = getPropertyDescriptor();
if (pd == null) {
return 1;
}
if (pd instanceof IndexedPropertyDescriptor) {
return ValueUtils.getIndexedPropertyLength(
getBean(),
(IndexedPropertyDescriptor) pd);
}
int hint = ValueUtils.getCollectionHint(pd.getPropertyType());
if (hint == -1) {
return 1;
}
return ValueUtils.getLength(getBaseValue());
}
/**
* If index == WHOLE_COLLECTION, change the value of the property, otherwise
* change the value of the index'th element of the collection
* represented by the property.
*/
public void setValue(Object value) {
PropertyDescriptor pd = getPropertyDescriptor();
if (pd == null) {
throw new JXPathInvalidAccessException(
"Cannot set property: " + asPath() + " - no such property");
}
if (index == WHOLE_COLLECTION) {
ValueUtils.setValue(getBean(), pd, value);
}
else {
ValueUtils.setValue(getBean(), pd, index, value);
}
this.value = value;
}
/**
* @see PropertyPointer#createPath(JXPathContext)
*/
public NodePointer createPath(JXPathContext context) {
if (getImmediateNode() == null) {
super.createPath(context);
baseValue = UNINITIALIZED;
value = UNINITIALIZED;
}
return this;
}
public void remove() {
if (index == WHOLE_COLLECTION) {
setValue(null);
}
else if (isCollection()) {
Object collection = ValueUtils.remove(getBaseValue(), index);
ValueUtils.setValue(getBean(), getPropertyDescriptor(), collection);
}
else if (index == 0) {
index = WHOLE_COLLECTION;
setValue(null);
}
}
/**
* Name of the currently selected property.
*/
public String getPropertyName() {
if (propertyName == null) {
PropertyDescriptor pd = getPropertyDescriptor();
if (pd != null) {
propertyName = pd.getName();
}
}
return propertyName != null ? propertyName : "*";
}
/**
* Finds the property descriptor corresponding to the current property
* index.
*/
private PropertyDescriptor getPropertyDescriptor() {
if (propertyDescriptor == null) {
int inx = getPropertyIndex();
if (inx == UNSPECIFIED_PROPERTY) {
propertyDescriptor =
beanInfo.getPropertyDescriptor(propertyName);
}
else {
PropertyDescriptor propertyDescriptors[] =
getPropertyDescriptors();
if (inx >= 0 && inx < propertyDescriptors.length) {
propertyDescriptor = propertyDescriptors[inx];
}
else {
propertyDescriptor = null;
}
}
}
return propertyDescriptor;
}
protected PropertyDescriptor[] getPropertyDescriptors() {
if (propertyDescriptors == null) {
propertyDescriptors = beanInfo.getPropertyDescriptors();
}
return propertyDescriptors;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/org.caleydo.core/src/org/caleydo/core/view/opengl/layout2/LayoutRendererAdapter.java b/org.caleydo.core/src/org/caleydo/core/view/opengl/layout2/LayoutRendererAdapter.java
index 1328f371d..2b20d4dd7 100644
--- a/org.caleydo.core/src/org/caleydo/core/view/opengl/layout2/LayoutRendererAdapter.java
+++ b/org.caleydo.core/src/org/caleydo/core/view/opengl/layout2/LayoutRendererAdapter.java
@@ -1,265 +1,265 @@
package org.caleydo.core.view.opengl.layout2;
import gleem.linalg.Vec2f;
import java.util.HashMap;
import java.util.Map;
import javax.media.opengl.GL2;
-import org.caleydo.core.event.EventListenerManager;
import org.caleydo.core.event.EventListenerManagers;
import org.caleydo.core.event.EventListenerManagers.QueuedEventListenerManager;
import org.caleydo.core.util.base.ILabelProvider;
import org.caleydo.core.view.ViewManager;
import org.caleydo.core.view.contextmenu.AContextMenuItem;
import org.caleydo.core.view.opengl.canvas.AGLView;
import org.caleydo.core.view.opengl.canvas.PixelGLConverter;
import org.caleydo.core.view.opengl.layout.ALayoutRenderer;
import org.caleydo.core.view.opengl.picking.IPickingListener;
import org.caleydo.data.loader.ResourceLocators.IResourceLocator;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
/**
* adapter between {@link ALayoutRenderer} and {@link GLElement}, such that {@link GLElement} can be as an
* {@link ALayoutRenderer}
*
* @author Samuel Gratzl
*
*/
public final class LayoutRendererAdapter extends ALayoutRenderer implements IGLElementParent, IGLElementContext {
/*
* random name for base picking type names
*/
private final String pickingBaseType = "BUTTON" + System.currentTimeMillis();
private final Map<IPickingListener, PickingMetaData> pickingMetaData = new HashMap<>();
private int pickingNameCounter = 0;
private final QueuedEventListenerManager eventListeners;
private final AGLView view;
private final WindowGLElement root;
/**
* do we need to perform a layout
*/
private boolean dirty = true;
/**
* my position for {@link #getAbsoluteLocation()}
*/
private Vec2f location = new Vec2f(0, 0);
private final GLContextLocal local;
private final String eventSpace;
public LayoutRendererAdapter(AGLView view, IResourceLocator locator, GLElement root, String eventSpace) {
this.view = view;
this.root = new WindowGLElement(root);
this.eventListeners = EventListenerManagers.createQueued();
this.eventSpace = eventSpace;
this.local = new GLContextLocal(view.getTextRenderer(), view.getTextureManager(), locator);
- this.root.init(this);
+ this.root.setParent(this);
+ this.root.init(this);
}
@Override
protected boolean permitsWrappingDisplayLists() {
return false;
}
@Override
public Vec2f toAbsolute(Vec2f relative) {
relative.add(location);
return relative;
}
@Override
public Vec2f toRelative(Vec2f absolute) {
absolute.sub(location);
return absolute;
}
@Override
protected void prepare() {
eventListeners.processEvents();
super.prepare();
}
@Override
protected void renderContent(GL2 gl) {
final PixelGLConverter pixelGLConverter = view.getPixelGLConverter();
// size in pixel
float w = pixelGLConverter.getPixelWidthForGLWidth(x);
float h = pixelGLConverter.getPixelHeightForGLHeight(y);
gl.glPushMatrix();
// convert the coordinate system to
// 0,0 w,0
// 0,h w,h
gl.glTranslatef(0, y, 0);
gl.glScalef(x / w, -y / h, 1);
int hh = view.getParentGLCanvas().getHeight();
this.location = new Vec2f(pixelGLConverter.getPixelWidthForCurrentGLTransform(gl), hh
- pixelGLConverter.getPixelHeightForCurrentGLTransform(gl));
if (dirty) {
root.setBounds(0, 0, w, h);
dirty = false;
}
final boolean isPickingRun = GLGraphics.isPickingPass(gl);
int deltaTimeMs = 0;
if (!isPickingRun) {
deltaTimeMs = local.getDeltaTimeMs();
}
GLGraphics g = new GLGraphics(gl, local, true, deltaTimeMs);
g.checkError("pre render");
if (isPickingRun) {
// 1. pick passes
root.renderPick(g);
} else {
// 2. pass layouting
root.layout(deltaTimeMs);
// 3. pass render pass
root.render(g);
}
g.checkError("post render");
gl.glPopMatrix();
}
@Override
public void relayout() {
dirty = true;
}
@Override
public void destroy(GL2 gl) {
this.root.takeDown();
local.destroy(gl);
super.destroy(gl);
}
@Override
public void repaint() {
setDisplayListDirty(true);
}
@Override
public void repaintPick() {
setDisplayListDirty(true);
}
@Override
public IGLElementParent getParent() {
return null;
}
@Override
public int registerPickingListener(IPickingListener l) {
return registerPickingListener(l, 0);
}
@Override
public IPickingListener createTooltip(ILabelProvider label) {
return view.getParentGLCanvas().createTooltip(label);
}
@Override
public void showContextMenu(Iterable<? extends AContextMenuItem> items) {
ViewManager.get().getCanvasFactory().showPopupMenu(view.getParentGLCanvas(), items);
}
@Override
public int registerPickingListener(IPickingListener l, int objectId) {
String key = pickingBaseType + "_" + (pickingNameCounter++);
view.addIDPickingListener(l, key, objectId);
int id = view.getPickingManager().getPickingID(view.getID(), key, objectId);
pickingMetaData.put(l, new PickingMetaData(id, pickingBaseType, objectId));
return id;
}
private void unregisterPickingListener(IPickingListener l) {
PickingMetaData data = pickingMetaData.remove(l);
if (data == null)
return;
view.removeIDPickingListener(l, data.type, data.objectId);
}
@Override
public void unregisterPickingListener(int pickingID) {
for (Map.Entry<IPickingListener, PickingMetaData> entry : pickingMetaData.entrySet()) {
if (entry.getValue().pickingId == pickingID) {
unregisterPickingListener(entry.getKey());
return;
}
}
}
@Override
public void setCursor(final int swtCursorConst) {
final Composite c = view.getParentGLCanvas().asComposite();
final Display d = c.getDisplay();
d.asyncExec(new Runnable() {
@Override
public void run() {
c.setCursor(swtCursorConst < 0 ? null : d.getSystemCursor(swtCursorConst));
}
});
}
@Override
public void init(GLElement element) {
// scan object for event listeners but only the subclasses
eventListeners.register(element, eventSpace, AGLElementView.isNotBaseClass);
}
@Override
public void takeDown(GLElement element) {
// undo listeners
eventListeners.unregister(element);
}
@Override
public final DisplayListPool getDisplayListPool() {
return local.getPool();
}
@Override
public final IMouseLayer getMouseLayer() {
return root.getMouseLayer();
}
@Override
public final IPopupLayer getPopupLayer() {
return root.getPopupLayer();
}
private static class PickingMetaData {
private final int pickingId;
private final String type;
private final int objectId;
public PickingMetaData(int pickingId, String type, int objectId) {
this.pickingId = pickingId;
this.type = type;
this.objectId = objectId;
}
}
@Override
public boolean moved(GLElement child) {
return true;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/TemplateService.java b/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/TemplateService.java
index 6bc4e6383..08a82fdea 100644
--- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/TemplateService.java
+++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/TemplateService.java
@@ -1,391 +1,399 @@
package edu.northwestern.bioinformatics.studycalendar.service;
import static java.util.Arrays.asList;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarSystemException;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.dao.StudySiteDao;
import edu.northwestern.bioinformatics.studycalendar.dao.UserRoleDao;
import edu.northwestern.bioinformatics.studycalendar.dao.delta.DeltaDao;
import edu.northwestern.bioinformatics.studycalendar.domain.*;
import static edu.northwestern.bioinformatics.studycalendar.domain.StudySite.findStudySite;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Delta;
import edu.northwestern.bioinformatics.studycalendar.utils.DomainObjectTools;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.StudyCalendarAuthorizationManager;
import edu.nwu.bioinformatics.commons.StringUtils;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.util.ObjectSetUtil;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.util.*;
/**
* @author Padmaja Vedula
* @author Rhett Sutphin
*/
@Transactional
public class TemplateService {
public static final String SUBJECT_COORDINATOR_ACCESS_ROLE = "SUBJECT_COORDINATOR";
public static final String SUBJECT_COORDINATOR_GROUP = "SUBJECT_COORDINATOR";
private StudyCalendarAuthorizationManager authorizationManager;
private StudyDao studyDao;
private SiteDao siteDao;
private StudySiteDao studySiteDao;
private DeltaDao deltaDao;
private UserRoleDao userRoleDao;
public static final String USER_IS_NULL = "User is null";
public static final String SITE_IS_NULL = "Site is null";
public static final String SITES_LIST_IS_NULL = "Sites List is null";
public static final String STUDY_IS_NULL = "Study is null";
public static final String LIST_IS_NULL = "List parameter is null";
public static final String STUDIES_LIST_IS_NULL = "StudiesList is null";
public static final String STRING_IS_NULL = "String parameter is null";
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
public void assignTemplateToSites(Study studyTemplate, List<Site> sites) throws Exception {
if (studyTemplate == null) {
throw new IllegalArgumentException(STUDY_IS_NULL);
}
if (sites == null) {
throw new IllegalArgumentException(SITES_LIST_IS_NULL);
}
for (Site site : sites) {
StudySite ss = new StudySite();
ss.setStudy(studyTemplate);
ss.setSite(site);
studySiteDao.save(ss);
}
}
public edu.northwestern.bioinformatics.studycalendar.domain.User
assignTemplateToSubjectCoordinator( Study study,
Site site,
edu.northwestern.bioinformatics.studycalendar.domain.User user) throws Exception {
if (study == null) {
throw new IllegalArgumentException(STUDY_IS_NULL);
}
if (site == null) {
throw new IllegalArgumentException(SITE_IS_NULL);
}
if (user == null) {
throw new IllegalArgumentException(USER_IS_NULL);
}
UserRole userRole = user.getUserRole(Role.SUBJECT_COORDINATOR);
if (!userRole.getStudySites().contains(findStudySite(study, site))) {
userRole.addStudySite(findStudySite(study, site));
userRoleDao.save(userRole);
assignMultipleTemplates(asList(study), site, user.getCsmUserId().toString());
}
return user;
}
public edu.northwestern.bioinformatics.studycalendar.domain.User
removeAssignedTemplateFromSubjectCoordinator(Study study,
Site site,
edu.northwestern.bioinformatics.studycalendar.domain.User user) throws Exception {
if (study == null) {
throw new IllegalArgumentException(STUDY_IS_NULL);
}
if (site == null) {
throw new IllegalArgumentException(SITE_IS_NULL);
}
if (user == null) {
throw new IllegalArgumentException(USER_IS_NULL);
}
UserRole userRole = user.getUserRole(Role.SUBJECT_COORDINATOR);
if (userRole.getStudySites().contains(findStudySite(study, site))) {
userRole.removeStudySite(findStudySite(study, site));
userRoleDao.save(userRole);
removeMultipleTemplates(asList(study), site, user.getCsmUserId().toString());
}
return user;
}
public void removeTemplateFromSites(Study studyTemplate, List<Site> sites) {
List<StudySite> studySites = studyTemplate.getStudySites();
List<StudySite> toRemove = new LinkedList<StudySite>();
List<Site> cannotRemove = new LinkedList<Site>();
for (Site site : sites) {
for (StudySite studySite : studySites) {
if (studySite.getSite().equals(site)) {
if (studySite.isUsed()) {
cannotRemove.add(studySite.getSite());
} else {
try {
authorizationManager.removeProtectionGroup(DomainObjectTools.createExternalObjectId(studySite));
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new StudyCalendarSystemException(e);
}
toRemove.add(studySite);
}
}
}
}
for (StudySite studySite : toRemove) {
Site siteAssoc = studySite.getSite();
siteAssoc.getStudySites().remove(studySite);
siteDao.save(siteAssoc);
Study studyAssoc = studySite.getStudy();
studyAssoc.getStudySites().remove(studySite);
studyDao.save(studyAssoc);
}
if (cannotRemove.size() > 0) {
StringBuilder msg = new StringBuilder("Cannot remove ")
.append(StringUtils.pluralize(cannotRemove.size(), "site"))
.append(" (");
for (Iterator<Site> it = cannotRemove.iterator(); it.hasNext();) {
Site site = it.next();
msg.append(site.getName());
if (it.hasNext()) msg.append(", ");
}
msg.append(") from study ").append(studyTemplate.getName())
.append(" because there are subject(s) assigned");
throw new StudyCalendarValidationException(msg.toString());
}
}
public void assignMultipleTemplates(List<Study> studyTemplates, Site site, String userId) throws Exception {
if (studyTemplates == null) {
throw new IllegalArgumentException(STUDIES_LIST_IS_NULL);
}
if (site == null) {
throw new IllegalArgumentException(SITE_IS_NULL);
}
if (userId == null) {
throw new IllegalArgumentException(STRING_IS_NULL);
}
List<String> assignedUserIds = new ArrayList<String>();
assignedUserIds.add(userId);
for (Study template : studyTemplates) {
List<StudySite> studySites = template.getStudySites();
for (StudySite studySite : studySites) {
if (studySite.getSite().getId().intValue() == site.getId().intValue()) {
String studySitePGName = DomainObjectTools.createExternalObjectId(studySite);
authorizationManager.createAndAssignPGToUser(assignedUserIds, studySitePGName, SUBJECT_COORDINATOR_ACCESS_ROLE);
}
}
}
}
public Map getSiteLists(Study studyTemplate) throws Exception {
if (studyTemplate == null) {
throw new IllegalArgumentException(STUDY_IS_NULL);
}
Map<String, List> siteLists = new HashMap<String, List>();
List<Site> availableSites = new ArrayList<Site>();
List<Site> assignedSites = new ArrayList<Site>();
List<ProtectionGroup> allSitePGs = authorizationManager.getSites();
for (ProtectionGroup site : allSitePGs) {
availableSites.add(DomainObjectTools.loadFromExternalObjectId(site.getProtectionGroupName(), siteDao));
}
for (StudySite ss : studyTemplate.getStudySites()) {
assignedSites.add(ss.getSite());
}
availableSites = (List) ObjectSetUtil.minus(availableSites, assignedSites);
siteLists.put(StudyCalendarAuthorizationManager.ASSIGNED_PGS, assignedSites);
siteLists.put(StudyCalendarAuthorizationManager.AVAILABLE_PGS, availableSites);
return siteLists;
}
@SuppressWarnings({ "unchecked" })
public Map<String, List<Study>> getTemplatesLists(Site site, User subjectCdUser) throws Exception {
if (site == null) {
throw new IllegalArgumentException(SITE_IS_NULL);
}
if (subjectCdUser == null) {
throw new IllegalArgumentException(USER_IS_NULL);
}
Map<String, List<Study>> templatesMap = new HashMap<String, List<Study>>();
List<Study> assignedTemplates = new ArrayList<Study>();
List<Study> allTemplates = new ArrayList<Study>();
List<StudySite> studySites = site.getStudySites();
for (StudySite studySite : studySites) {
allTemplates.add(studySite.getStudy());
if (authorizationManager.isUserPGAssigned(DomainObjectTools.createExternalObjectId(studySite), subjectCdUser.getUserId().toString())) {
assignedTemplates.add(studySite.getStudy());
}
}
List<Study> availableTemplates = (List<Study>) ObjectSetUtil.minus(allTemplates, assignedTemplates);
templatesMap.put(StudyCalendarAuthorizationManager.ASSIGNED_PES, assignedTemplates);
templatesMap.put(StudyCalendarAuthorizationManager.AVAILABLE_PES, availableTemplates);
return templatesMap;
}
public ProtectionGroup getSiteProtectionGroup(String siteName) throws Exception {
if(siteName == null) {
throw new IllegalArgumentException(STRING_IS_NULL);
}
return authorizationManager.getPGByName(siteName);
}
/**
* Returns a copy of the given list of studies containing only those which should be
* visible to the given user role.
*
* @param studies
* @return
* @throws Exception
*/
public List<Study> filterForVisibility(List<Study> studies, UserRole role) throws Exception {
if (studies == null) {
throw new IllegalArgumentException(STUDIES_LIST_IS_NULL);
}
if (role == null) {
return Collections.emptyList();
}
List<Study> filtered = new ArrayList<Study>(studies);
for (Iterator<Study> it = filtered.iterator(); it.hasNext();) {
Study study = it.next();
if (!authorizationManager.isTemplateVisible(role, study)) it.remove();
}
return filtered;
}
public void removeMultipleTemplates(List<Study> studyTemplates, Site site, String userId) throws Exception {
if (studyTemplates == null) {
throw new IllegalArgumentException(STUDIES_LIST_IS_NULL);
}
if (site == null) {
throw new IllegalArgumentException(SITE_IS_NULL);
}
if (userId == null) {
throw new IllegalArgumentException(STRING_IS_NULL);
}
List<String> userIds = new ArrayList<String>();
userIds.add(userId);
for (Study template : studyTemplates) {
List<StudySite> studySites = template.getStudySites();
for (StudySite studySite : studySites) {
if (studySite.getSite().getId().intValue() == site.getId().intValue()) {
String studySitePGName = DomainObjectTools.createExternalObjectId(studySite);
ProtectionGroup studySitePG = authorizationManager.getPGByName(studySitePGName);
authorizationManager.removeProtectionGroupUsers(userIds, studySitePG);
}
}
}
}
@Transactional(propagation = Propagation.SUPPORTS)
public <P extends PlanTreeNode<?>> P findParent(PlanTreeNode<P> node) {
if (node.getParent() != null) {
return node.getParent();
} else {
Delta<P> delta = deltaDao.findDeltaWhereAdded(node);
if (delta != null) {
return delta.getNode();
}
delta = deltaDao.findDeltaWhereRemoved(node);
if (delta != null) {
return delta.getNode();
}
throw new StudyCalendarSystemException("Could not locate delta where %s was added or where it was removed", node);
}
}
@SuppressWarnings({ "unchecked" })
@Transactional(propagation = Propagation.SUPPORTS)
public <T extends PlanTreeNode<?>> T findAncestor(PlanTreeNode<?> node, Class<T> klass) {
boolean moreSpecific = DomainObjectTools.isMoreSpecific(node.getClass(), klass);
boolean parentable = PlanTreeNode.class.isAssignableFrom(node.parentClass());
if (moreSpecific && parentable) {
PlanTreeNode<?> parent = findParent((PlanTreeNode<? extends PlanTreeNode<?>>) node);
if (klass.isAssignableFrom(parent.getClass())) {
return (T) parent;
} else {
return findAncestor(parent, klass);
}
} else {
throw new StudyCalendarSystemException("%s is not a descendant of %s",
node.getClass().getSimpleName(), klass.getSimpleName());
}
}
// this is PlanTreeNode instead of PlanTreeNode<?> due to a javac bug
@SuppressWarnings({ "RawUseOfParameterizedType" })
+ @Transactional(propagation = Propagation.SUPPORTS)
public Study findStudy(PlanTreeNode node) {
if (node instanceof PlannedCalendar) return ((PlannedCalendar) node).getStudy();
else return findAncestor(node, PlannedCalendar.class).getStudy();
}
/**
* Finds the node in the given study which matches the type and id of parameter node.
*/
+ @Transactional(propagation = Propagation.SUPPORTS)
public PlanTreeNode<?> findEquivalentChild(Study study, PlanTreeNode<?> node) {
return findEquivalentChild(study.getPlannedCalendar(), node);
}
+ @Transactional(propagation = Propagation.SUPPORTS)
public PlanTreeNode<?> findEquivalentChild(PlanTreeNode<?> tree, PlanTreeNode<?> parameterNode) {
if (isEquivalent(tree, parameterNode)) return tree;
if (tree instanceof PlanTreeInnerNode) {
for (PlanTreeNode<?> child : ((PlanTreeInnerNode<?, PlanTreeNode<?>, ?>) tree).getChildren()) {
PlanTreeNode<?> match = findEquivalentChild(child, parameterNode);
if (match != null) return match;
}
}
return null;
}
+ @Transactional(propagation = Propagation.SUPPORTS)
public boolean isEquivalent(PlanTreeNode<?> node, PlanTreeNode<?> toMatch) {
return (toMatch == node) ||
(sameClassIgnoringProxies(toMatch, node) && toMatch.getId().equals(node.getId()));
}
// This is not a general solution, but it will work for all PlanTreeNode subclasses
private boolean sameClassIgnoringProxies(PlanTreeNode<?> toMatch, PlanTreeNode<?> node) {
return toMatch.getClass().isAssignableFrom(node.getClass())
|| node.getClass().isAssignableFrom(toMatch.getClass());
}
////// CONFIGURATION
@Required
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
@Required
public void setSiteDao(SiteDao siteDao) {
this.siteDao = siteDao;
}
@Required
public void setStudySiteDao(StudySiteDao studySiteDao) {
this.studySiteDao = studySiteDao;
}
public void setDeltaDao(DeltaDao deltaDao) {
this.deltaDao = deltaDao;
}
@Required
public void setStudyCalendarAuthorizationManager(StudyCalendarAuthorizationManager authorizationManager) {
this.authorizationManager = authorizationManager;
}
public void setUserRoleDao(UserRoleDao userRoleDao) {
this.userRoleDao = userRoleDao;
}
}
| false | false | null | null |
diff --git a/java/test/org/broadinstitute/sting/WalkerTest.java b/java/test/org/broadinstitute/sting/WalkerTest.java
index 6030ad4d3..9aab07b88 100755
--- a/java/test/org/broadinstitute/sting/WalkerTest.java
+++ b/java/test/org/broadinstitute/sting/WalkerTest.java
@@ -1,208 +1,208 @@
package org.broadinstitute.sting;
import junit.framework.Assert;
import org.broadinstitute.sting.gatk.CommandLineExecutable;
import org.broadinstitute.sting.gatk.CommandLineGATK;
import org.broadinstitute.sting.utils.Pair;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.Utils;
import org.junit.Before;
import org.junit.Test;
import org.apache.log4j.Appender;
import org.apache.log4j.WriterAppender;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*;
public class WalkerTest extends BaseTest {
// the default output path for the integration test
private File outputFileLocation = null;
public void setOutputFileLocation(File outputFileLocation) {
this.outputFileLocation = outputFileLocation;
}
public String assertMatchingMD5(final String name, final File resultsFile, final String expectedMD5) {
try {
byte[] bytesOfMessage = getBytesFromFile(resultsFile);
byte[] thedigest = MessageDigest.getInstance("MD5").digest(bytesOfMessage);
BigInteger bigInt = new BigInteger(1, thedigest);
String filemd5sum = bigInt.toString(16);
while (filemd5sum.length() < 32) filemd5sum = "0" + filemd5sum; // pad to length 32
if (parameterize() || expectedMD5.equals("")) {
System.out.println(String.format("PARAMETERIZATION[%s]: file %s has md5 = %s, stated expectation is %s, equal? = %b",
name, resultsFile, filemd5sum, expectedMD5, filemd5sum.equals(expectedMD5)));
} else {
System.out.println(String.format("Checking MD5 for %s [calculated=%s, expected=%s]", resultsFile, filemd5sum, expectedMD5));
System.out.flush();
Assert.assertEquals(name + " Mismatching MD5s", expectedMD5, filemd5sum);
System.out.println(String.format(" => %s PASSED", name));
}
return filemd5sum;
} catch (Exception e) {
- throw new RuntimeException("Failed to read bytes from calls file: " + resultsFile);
+ throw new RuntimeException("Failed to read bytes from calls file: " + resultsFile, e);
}
}
public List<String> assertMatchingMD5s(final String name, List<File> resultFiles, List<String> expectedMD5s) {
List<String> md5s = new ArrayList<String>();
for (int i = 0; i < resultFiles.size(); i++) {
String md5 = assertMatchingMD5(name, resultFiles.get(i), expectedMD5s.get(i));
md5s.add(i, md5);
}
return md5s;
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public class WalkerTestSpec {
String args = "";
int nOutputFiles = -1;
List<String> md5s = null;
List<String> exts = null;
protected Map<String, File> auxillaryFiles = new HashMap<String, File>();
public WalkerTestSpec(String args, int nOutputFiles, List<String> md5s) {
this.args = args;
this.nOutputFiles = nOutputFiles;
this.md5s = md5s;
}
public WalkerTestSpec(String args, int nOutputFiles, List<String> exts, List<String> md5s) {
this.args = args;
this.nOutputFiles = nOutputFiles;
this.md5s = md5s;
this.exts = exts;
}
public void addAuxFile(String expectededMD5sum, File outputfile) {
auxillaryFiles.put(expectededMD5sum, outputfile);
}
}
protected boolean parameterize() {
return false;
}
protected Pair<List<File>, List<String>> executeTest(final String name, WalkerTestSpec spec) {
List<File> tmpFiles = new ArrayList<File>();
for (int i = 0; i < spec.nOutputFiles; i++) {
String ext = spec.exts == null ? ".tmp" : "." + spec.exts.get(i);
File fl = createTempFile(String.format("walktest.tmp_param.%d", i), ext);
tmpFiles.add(fl);
}
final String args = String.format(spec.args, tmpFiles.toArray());
System.out.println(Utils.dupString('-', 80));
List<String> md5s = new LinkedList<String>();
md5s.addAll(spec.md5s);
// check to see if they included any auxillary files, if so add them to the list
for (String md5 : spec.auxillaryFiles.keySet()) {
md5s.add(md5);
tmpFiles.add(spec.auxillaryFiles.get(md5));
}
return executeTest(name, md5s, tmpFiles, args);
}
public File createTempFile(String name, String extension) {
try {
File fl = File.createTempFile(name, extension);
fl.deleteOnExit();
return fl;
} catch (IOException ex) {
throw new StingException("Cannot create temp file: " + ex.getMessage(), ex);
}
}
/**
* execute the test, given the following:
* @param name the name of the test
* @param md5s the list of md5s
* @param tmpFiles the temp file corresponding to the md5 list
* @param args the argument list
* @return a pair of file and string lists
*/
private Pair<List<File>, List<String>> executeTest(String name, List<String> md5s, List<File> tmpFiles, String args) {
CommandLineGATK instance = new CommandLineGATK();
String[] command;
// special case for ' and " so we can allow expressions
if (args.indexOf('\'') != -1)
command = escapeExpressions(args, "'");
else if (args.indexOf('\"') != -1)
command = escapeExpressions(args, "\"");
else
command = args.split(" ");
if (outputFileLocation != null) {
String[] cmd2 = Arrays.copyOf(command, command.length + 2);
cmd2[command.length] = "-o";
cmd2[command.length + 1] = this.outputFileLocation.getAbsolutePath();
command = cmd2;
}
System.out.println(String.format("Executing test %s with GATK arguments: %s", name, Utils.join(" ",command)));
CommandLineExecutable.start(instance, command);
if (CommandLineExecutable.result != 0) {
throw new RuntimeException("Error running the GATK with arguments: " + args);
}
return new Pair<List<File>, List<String>>(tmpFiles, assertMatchingMD5s(name, tmpFiles, md5s));
}
private static String[] escapeExpressions(String args, String delimiter) {
String[] command = {};
String[] split = args.split(delimiter);
for (int i = 0; i < split.length - 1; i += 2) {
command = Utils.concatArrays(command, split[i].trim().split(" "));
command = Utils.concatArrays(command, new String[]{split[i + 1]});
}
return Utils.concatArrays(command, split[split.length - 1].trim().split(" "));
}
@Test
public void testWalkerTest() {
//System.out.println("WalkerTest is just a framework");
}
}
\ No newline at end of file
diff --git a/java/test/org/broadinstitute/sting/oneoffprojects/walkers/coverage/CoverageStatisticsIntegrationTest.java b/java/test/org/broadinstitute/sting/oneoffprojects/walkers/coverage/CoverageStatisticsIntegrationTest.java
index 35328b50c..53666d5e0 100644
--- a/java/test/org/broadinstitute/sting/oneoffprojects/walkers/coverage/CoverageStatisticsIntegrationTest.java
+++ b/java/test/org/broadinstitute/sting/oneoffprojects/walkers/coverage/CoverageStatisticsIntegrationTest.java
@@ -1,69 +1,74 @@
package org.broadinstitute.sting.oneoffprojects.walkers.coverage;
import org.broadinstitute.sting.WalkerTest;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* IF THERE IS NO JAVADOC RIGHT HERE, YELL AT chartl
*
* @Author chartl
* @Date Feb 25, 2010
*/
public class CoverageStatisticsIntegrationTest extends WalkerTest {
- private boolean RUN_TESTS = false;
+ private boolean RUN_TESTS = true;
private String root = "-T CoverageStatistics ";
private String hg18 = "/seq/references/Homo_sapiens_assembly18/v0/Homo_sapiens_assembly18.fasta";
private String b36 = "/broad/1KG/reference/human_b36_both.fasta";
private String buildRootCmd(String ref, List<String> bams, List<String> intervals) {
StringBuilder bamBuilder = new StringBuilder();
do {
bamBuilder.append(" -I ");
bamBuilder.append(bams.remove(0));
} while ( bams.size() > 0 );
StringBuilder intervalBuilder = new StringBuilder();
do {
intervalBuilder.append(" -L ");
intervalBuilder.append(intervals.remove(0));
} while ( intervals.size() > 0 );
return root + "-R "+ref+bamBuilder.toString()+intervalBuilder.toString();
}
private void execute(String name, WalkerTestSpec spec) {
if ( RUN_TESTS ) {
executeTest(name,spec);
}
}
@Test
public void testBaseOutputNoFiltering() {
// our base file
File baseOutputFile = this.createTempFile("depthofcoveragenofiltering",".tmp");
this.setOutputFileLocation(baseOutputFile);
String[] intervals = {"1:10,000,000-10,000,800","1:10,250,001-10,250,500","1:10,500,001-10,500,300","1:10,750,001-10,750,400"};
String[] bams = {"/humgen/gsa-hpprojects/GATK/data/Validation_Data/NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam","/broad/1KG/DCC_merged/freeze5/NA19240.pilot2.454.bam"};
String cmd = buildRootCmd(b36,new ArrayList<String>(Arrays.asList(bams)),new ArrayList<String>(Arrays.asList(intervals))) + " -mmq 0 -mbq 0 -dels -baseCounts";
- String expected = "cb87d6069ac60c73f047efc6d9386619";
- WalkerTestSpec spec = new WalkerTestSpec(cmd,1, Arrays.asList(expected));
+ WalkerTestSpec spec = new WalkerTestSpec(cmd,0, new ArrayList<String>());
// now add the expected files that get generated
- spec.addAuxFile("aff2349d6dc221c08f6c469379aeaedf", new File(baseOutputFile.getAbsolutePath() + ".interval_statistics"));
- spec.addAuxFile("6476ed0c54a4307a618aa6d3268b050f", new File(baseOutputFile.getAbsolutePath()+".interval_summary"));
- spec.addAuxFile("c744a298b7541f3f823e6937e9a0bc67", new File(baseOutputFile.getAbsolutePath()+".locus_statistics"));
- spec.addAuxFile("65318c1e73d98a59cc6f817cde12d3d4", new File(baseOutputFile.getAbsolutePath()+".summary_statistics"));
- spec.addAuxFile("9fc19f773a7ddfbb473d124e675a3d94", new File(baseOutputFile.getAbsolutePath()+".sample_statistics"));
- if ( RUN_TESTS )
- execute("testBaseOutputNoFiltering",spec);
+ spec.addAuxFile("cb87d6069ac60c73f047efc6d9386619", baseOutputFile);
+ spec.addAuxFile("aff2349d6dc221c08f6c469379aeaedf", createTempFileFromBase(baseOutputFile.getAbsolutePath()+".interval_statistics"));
+ spec.addAuxFile("6476ed0c54a4307a618aa6d3268b050f", createTempFileFromBase(baseOutputFile.getAbsolutePath()+".interval_summary"));
+ spec.addAuxFile("c744a298b7541f3f823e6937e9a0bc67", createTempFileFromBase(baseOutputFile.getAbsolutePath()+".locus_statistics"));
+ spec.addAuxFile("65318c1e73d98a59cc6f817cde12d3d4", createTempFileFromBase(baseOutputFile.getAbsolutePath()+".summary_statistics"));
+ spec.addAuxFile("9fc19f773a7ddfbb473d124e675a3d94", createTempFileFromBase(baseOutputFile.getAbsolutePath()+".sample_statistics"));
+ execute("testBaseOutputNoFiltering",spec);
+ }
+
+ public File createTempFileFromBase(String name) {
+ File fl = new File(name);
+ fl.deleteOnExit();
+ return fl;
}
}
| false | false | null | null |
diff --git a/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/program/mchms/MchmsEnrollmentSummaryFragmentController.java b/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/program/mchms/MchmsEnrollmentSummaryFragmentController.java
index dffb250a..51dd488b 100644
--- a/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/program/mchms/MchmsEnrollmentSummaryFragmentController.java
+++ b/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/program/mchms/MchmsEnrollmentSummaryFragmentController.java
@@ -1,67 +1,67 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.kenyaemr.fragment.controller.program.mchms;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.PatientProgram;
import org.openmrs.module.kenyaemr.Dictionary;
import org.openmrs.module.kenyaemr.calculation.EmrCalculationUtils;
import org.openmrs.module.kenyaemr.util.EmrUtils;
import org.openmrs.ui.framework.annotation.FragmentParam;
import org.openmrs.ui.framework.fragment.FragmentModel;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* MCH program enrollment fragment
*/
public class MchmsEnrollmentSummaryFragmentController {
public String controller(@FragmentParam("patientProgram") PatientProgram enrollment,
@FragmentParam(value = "encounter", required = false) Encounter encounter,
@FragmentParam("showClinicalData") boolean showClinicalData,
FragmentModel model) {
Map<String, Object> dataPoints = new LinkedHashMap<String, Object>();
dataPoints.put("Enrolled", enrollment.getDateEnrolled());
Obs ancNoObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.ANTENATAL_CASE_NUMBER));
if (ancNoObs != null) {
- dataPoints.put("ANC No", ancNoObs.getValueNumeric());
+ dataPoints.put("ANC No", ancNoObs.getValueNumeric().intValue());
}
Obs lmpObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.LAST_MONTHLY_PERIOD));
if (lmpObs != null) {
dataPoints.put("LMP", lmpObs.getValueDate());
dataPoints.put("EDD (LMP)", EmrCalculationUtils.dateAddDays(lmpObs.getValueDate(), 280));
}
Obs eddUsoundObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.EXPECTED_DATE_OF_DELIVERY));
if (eddUsoundObs != null) {
dataPoints.put("EDD (Ultrasound)", eddUsoundObs.getValueDate());
}
Obs gravidaObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.GRAVIDA));
if (gravidaObs != null) {
dataPoints.put("Gravida", gravidaObs.getValueNumeric().intValue());
}
Obs parityTermObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.PARITY_TERM));
Obs parityAbortionObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.PARITY_ABORTION));
if (parityTermObs != null && parityAbortionObs != null) {
dataPoints.put("Parity", parityTermObs.getValueNumeric().intValue() + " + " + parityAbortionObs.getValueNumeric().intValue());
}
model.put("dataPoints", dataPoints);
return "view/dataPoints";
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/nodebox/client/ParameterRow.java b/src/nodebox/client/ParameterRow.java
index 38601d00..ec830b8a 100644
--- a/src/nodebox/client/ParameterRow.java
+++ b/src/nodebox/client/ParameterRow.java
@@ -1,229 +1,229 @@
package nodebox.client;
import nodebox.node.ConnectionError;
import nodebox.node.NodeEvent;
import nodebox.node.NodeEventListener;
import nodebox.node.Parameter;
import nodebox.node.event.NodeAttributeChangedEvent;
import nodebox.node.event.ValueChangedEvent;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
public class ParameterRow extends JComponent implements MouseListener, ActionListener, NodeEventListener {
private static Image popupButtonImage;
static {
try {
popupButtonImage = ImageIO.read(new File("res/options-button.png"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Parameter parameter;
private JLabel label;
private JComponent control;
private JPanel expressionPanel;
private JTextField expressionField;
private JPopupMenu popupMenu;
private JCheckBoxMenuItem expressionMenuItem;
private static final int TOP_PADDING = 2;
private static final int BOTTOM_PADDING = 2;
public ParameterRow(Parameter parameter, JComponent control) {
addMouseListener(this);
this.parameter = parameter;
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
label = new ShadowLabel(parameter.getLabel());
label.setToolTipText(parameter.getName());
label.setBorder(null);
label.setPreferredSize(new Dimension(ParameterView.LABEL_WIDTH, 16));
this.control = control;
control.setBorder(BorderFactory.createEmptyBorder(TOP_PADDING, 0, BOTTOM_PADDING, 0));
popupMenu = new JPopupMenu();
expressionMenuItem = new JCheckBoxMenuItem(new ToggleExpressionAction());
popupMenu.add(expressionMenuItem);
popupMenu.add(new RevertToDefaultAction());
expressionPanel = new JPanel(new BorderLayout());
expressionPanel.setOpaque(false);
expressionPanel.setVisible(false);
expressionField = new JTextField();
expressionField.setAction(new ExpressionFieldChangedAction());
expressionField.setBackground(Theme.PARAMETER_EXPRESSION_BACKGROUND_COLOR);
expressionField.putClientProperty("JComponent.sizeVariant", "small");
expressionField.setFont(Theme.SMALL_BOLD_FONT);
JButton expressionButton = new JButton("...");
expressionButton.setBackground(Theme.PARAMETER_VALUE_BACKGROUND);
expressionButton.putClientProperty("JComponent.sizeVariant", "small");
expressionButton.putClientProperty("JButton.buttonType", "gradient");
expressionButton.setFont(Theme.SMALL_BOLD_FONT);
expressionButton.addActionListener(this);
expressionPanel.add(expressionField, BorderLayout.CENTER);
expressionPanel.add(expressionButton, BorderLayout.EAST);
add(this.label);
add(Box.createHorizontalStrut(10));
add(this.control);
add(this.expressionPanel);
add(Box.createHorizontalGlue());
// Compensate for the popup button.
add(Box.createHorizontalStrut(30));
setExpressionStatus();
setBorder(Theme.PARAMETER_ROW_BORDER);
}
@Override
public void addNotify() {
super.addNotify();
parameter.getLibrary().addListener(this);
}
@Override
public void removeNotify() {
super.removeNotify();
parameter.getLibrary().removeListener(this);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, control.getPreferredSize().height + TOP_PADDING + BOTTOM_PADDING);
}
//// Mouse listeners ////
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (e.getX() < this.getWidth() - 20) return;
popupMenu.show(this, this.getWidth() - 20, 20);
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
@Override
protected void paintComponent(Graphics g) {
// Height aligns to 30px high control, such as float, string, color, etc.
g.drawImage(popupButtonImage, getWidth() - 20, 4, null);
}
//// Parameter context menu ////
private void setExpressionStatus() {
// Check if the current state is already correct.
if (parameter.hasExpression() && !control.isVisible()
&& expressionField.getText().equals(parameter.getExpression())) return;
if (parameter.hasExpression()) {
control.setVisible(false);
expressionPanel.setVisible(true);
expressionField.setText(parameter.getExpression());
} else {
control.setVisible(true);
expressionPanel.setVisible(false);
}
expressionMenuItem.setState(parameter.hasExpression());
}
public void receive(NodeEvent event) {
if (event.getSource() != parameter.getNode()) return;
if (event instanceof ValueChangedEvent) {
// Check if the value change triggered a change in expression status.
// This can happen if revert to default switches from value to expression
// or vice versa.
+ setEnabled(parameter.isEnabled());
ValueChangedEvent e = (ValueChangedEvent) event;
if (e.getParameter() != parameter) return;
- setEnabled(parameter.isEnabled());
setExpressionStatus();
} else if (event instanceof NodeAttributeChangedEvent) {
setEnabled(parameter.isEnabled());
}
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
control.setEnabled(enabled);
label.setEnabled(enabled);
}
/**
* A user clicked the expression editor button. Show the expression window.
*
* @param e the event
*/
public void actionPerformed(ActionEvent e) {
NodeBoxDocument doc = NodeBoxDocument.getCurrentDocument();
if (doc == null) throw new RuntimeException("No current active document.");
ExpressionWindow window = new ExpressionWindow(parameter);
window.setLocationRelativeTo(this);
window.setVisible(true);
doc.addParameterEditor(window);
}
//// Action classes ////
private class ToggleExpressionAction extends AbstractAction {
private ToggleExpressionAction() {
putValue(Action.NAME, "Toggle Expression");
}
public void actionPerformed(ActionEvent e) {
if (parameter.hasExpression()) {
parameter.clearExpression();
} else {
parameter.setExpression(parameter.asExpression());
}
// We don't have to change the expression status here.
// Instead, we respond to the valueChanged event to update our status.
// This makes the handling consistent even with multiple parameter views.
}
}
private class RevertToDefaultAction extends AbstractAction {
private RevertToDefaultAction() {
putValue(Action.NAME, "Revert to Default");
}
public void actionPerformed(ActionEvent e) {
parameter.revertToDefault();
// Reverting to default could cause an expression to be set/cleared.
// This triggers an valueChanged event, where we check if our expression field is
// still up-to-date.
}
}
private class ExpressionFieldChangedAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
try {
parameter.setExpression(expressionField.getText());
} catch (ConnectionError ce) {
JOptionPane.showMessageDialog(ParameterRow.this, ce.getMessage(), "Connection error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
| false | false | null | null |
diff --git a/test/harness/src/classes/org/jdesktop/wonderland/testharness/slave/client3D/Client3DSim.java b/test/harness/src/classes/org/jdesktop/wonderland/testharness/slave/client3D/Client3DSim.java
index dae0f958d..f18ed0f8f 100644
--- a/test/harness/src/classes/org/jdesktop/wonderland/testharness/slave/client3D/Client3DSim.java
+++ b/test/harness/src/classes/org/jdesktop/wonderland/testharness/slave/client3D/Client3DSim.java
@@ -1,518 +1,527 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2008, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* $Revision$
* $Date$
* $State$
*/
package org.jdesktop.wonderland.testharness.slave.client3D;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import java.awt.BorderLayout;
import java.awt.Canvas;
+import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.Properties;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import org.jdesktop.wonderland.client.ClientContext;
import org.jdesktop.wonderland.client.ClientPlugin;
import org.jdesktop.wonderland.client.cell.Cell;
import org.jdesktop.wonderland.client.cell.CellCache;
import org.jdesktop.wonderland.client.cell.CellCacheBasicImpl;
import org.jdesktop.wonderland.client.cell.CellRenderer;
import org.jdesktop.wonderland.client.cell.MovableComponent;
import org.jdesktop.wonderland.client.cell.MovableComponent.CellMoveListener;
import org.jdesktop.wonderland.client.cell.MovableComponent.CellMoveSource;
import org.jdesktop.wonderland.client.cell.view.LocalAvatar;
import org.jdesktop.wonderland.client.cell.view.LocalAvatar.ViewCellConfiguredListener;
import org.jdesktop.wonderland.client.comms.SessionStatusListener;
import org.jdesktop.wonderland.client.comms.WonderlandServerInfo;
import org.jdesktop.wonderland.client.comms.WonderlandSession;
import org.jdesktop.wonderland.client.comms.WonderlandSession.Status;
import org.jdesktop.wonderland.client.comms.CellClientSession;
import org.jdesktop.wonderland.client.comms.LoginFailureException;
import org.jdesktop.wonderland.client.jme.JmeClientMain;
import org.jdesktop.wonderland.client.jme.MainFrame;
import org.jdesktop.wonderland.client.jme.WonderlandURLStreamHandlerFactory;
import org.jdesktop.wonderland.client.login.LoginManager;
import org.jdesktop.wonderland.client.login.LoginUI;
import org.jdesktop.wonderland.client.login.PluginFilter;
import org.jdesktop.wonderland.client.login.ServerSessionManager;
import org.jdesktop.wonderland.client.login.ServerSessionManager.NoAuthLoginControl;
import org.jdesktop.wonderland.client.login.ServerSessionManager.UserPasswordLoginControl;
import org.jdesktop.wonderland.client.login.ServerSessionManager.WebURLLoginControl;
import org.jdesktop.wonderland.client.login.SessionCreator;
import org.jdesktop.wonderland.common.cell.CellTransform;
import org.jdesktop.wonderland.testharness.common.Client3DRequest;
import org.jdesktop.wonderland.testharness.common.TestRequest;
import org.jdesktop.wonderland.testharness.slave.ProcessingException;
import org.jdesktop.wonderland.testharness.slave.RequestProcessor;
/**
* A test client that simulates a 3D client
*/
public class Client3DSim
implements RequestProcessor, SessionStatusListener
{
/** a logger */
private static final Logger logger =
Logger.getLogger(Client3DSim.class.getName());
private static final Logger messageTimerLogger =
Logger.getLogger(MessageTimer.class.getName());
/** the name of this client */
private String username;
/** the session we are attached to */
private CellClientSession session;
/** the mover thread */
private UserSimulator userSim;
private MessageTimer messageTimer = new MessageTimer();
public Client3DSim() {
}
public String getName() {
return "Client3DSim";
}
public void initialize(String username, Properties props)
throws ProcessingException
{
this.username = username;
// set the user directory to one specific to this client
File userDir = new File(ClientContext.getUserDirectory("test"),
username);
ClientContext.setUserDirectory(userDir);
// set up the login system to
// read the server URL from a property
String serverURL = props.getProperty("serverURL");
if (serverURL == null) {
throw new ProcessingException("No serverURL found");
}
// set the login callback to give the right user name
LoginManager.setLoginUI(new ClientSimLoginUI(username, props));
// for now, load all plugins. We should modify this to only load
// some plugins, depending on the test
LoginManager.setPluginFilter(new BlacklistPluginFilter());
// create a fake mainframe
JmeClientMain.setFrame(new FakeMainFrame());
try {
ServerSessionManager mgr = LoginManager.getInstance(serverURL);
session = mgr.createSession(new SessionCreator<CellClientSession>() {
public CellClientSession createSession(WonderlandServerInfo serverInfo,
ClassLoader loader)
{
CellClientSession ccs = new CellClientSession(serverInfo, loader) {
@Override
protected CellCache createCellCache() {
CellCacheBasicImpl impl = new CellCacheBasicImpl(this,
getClassLoader(), getCellCacheConnection(),
getCellChannelConnection())
{
@Override
protected CellRenderer createCellRenderer(Cell cell) {
return null;
}
};
getCellCacheConnection().addListener(impl);
return impl;
}
};
ccs.addSessionStatusListener(Client3DSim.this);
final LocalAvatar avatar = ccs.getLocalAvatar();
avatar.addViewCellConfiguredListener(new ViewCellConfiguredListener() {
public void viewConfigured(LocalAvatar localAvatar) {
MovableComponent mc =
avatar.getViewCell().getComponent(MovableComponent.class);
mc.addServerCellMoveListener(messageTimer);
// start the simulator
userSim.start();
}
});
userSim = new UserSimulator(avatar);
return ccs;
}
});
} catch (IOException ioe) {
throw new ProcessingException(ioe);
} catch (LoginFailureException lfe) {
throw new ProcessingException(lfe);
}
}
public void destroy() {
if (session != null) {
session.logout();
}
}
public void processRequest(TestRequest request) {
if (request instanceof Client3DRequest) {
processClient3DRequest((Client3DRequest)request);
} else {
Logger.getAnonymousLogger().severe("Unsupported request "+request.getClass().getName());
}
}
private void processClient3DRequest(Client3DRequest request) {
switch(request.getAction()) {
case WALK :
userSim.walkLoop(request.getDesiredLocations(), new Vector3f(1f,0f,0f), request.getSpeed(), request.getLoopCount());
break;
default :
Logger.getAnonymousLogger().severe("Unsupported Client3DRequest "+request.getAction());
}
}
public String getUsername() {
return username;
}
public void sessionStatusChanged(WonderlandSession session,
Status status)
{
logger.info(getName() + " change session status: " + status);
if (status == Status.DISCONNECTED && userSim != null) {
userSim.quit();
}
}
public void waitForFinish() throws InterruptedException {
if (userSim == null) {
return;
}
// wait for the thread to end
userSim.join();
}
/**
* A very basic UserSimulator, this really needs a lot of attention.....
*/
class UserSimulator extends Thread {
private Vector3f currentLocation = new Vector3f();
private Vector3f[] desiredLocations;
private int locationIndex;
private Vector3f step = null;
private float speed;
private Quaternion orientation = null;
private LocalAvatar avatar;
private boolean quit = false;
private boolean walking = false;
private long sleepTime = 200; // Time between steps (in ms)
private int currentLoopCount = 0;
private int desiredLoopCount;
private Semaphore semaphore;
public UserSimulator(LocalAvatar avatar) {
super("UserSimulator");
this.avatar = avatar;
semaphore = new Semaphore(0);
}
public synchronized boolean isQuit() {
return quit;
}
public synchronized void quit() {
this.quit = true;
}
@Override
public void run() {
// Set initial position
avatar.localMoveRequest(currentLocation, orientation);
while(!quit) {
try {
semaphore.acquire();
} catch (InterruptedException ex) {
Logger.getLogger(Client3DSim.class.getName()).log(Level.SEVERE, null, ex);
}
while(!quit && walking) {
if (currentLocation.subtract(desiredLocations[locationIndex]).lengthSquared()<0.1) { // Need epsilonEquals
if (locationIndex<desiredLocations.length-1) {
locationIndex++;
step = desiredLocations[locationIndex].subtract(currentLocation);
step.multLocal(speed/(1000f/sleepTime));
} else if (locationIndex==desiredLocations.length-1 && desiredLoopCount!=currentLoopCount) {
currentLoopCount++;
locationIndex = 0;
step = desiredLocations[locationIndex].subtract(currentLocation);
step.multLocal(speed/(1000f/sleepTime));
} else
walking = false;
}
if (walking) {
currentLocation.addLocal(step);
avatar.localMoveRequest(currentLocation, orientation);
messageTimer.messageSent(new CellTransform(orientation, currentLocation));
}
try {
sleep(sleepTime);
} catch (InterruptedException ex) {
Logger.getLogger(Client3DSim.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Walk from the current location to the new location specified, and
* orient to the give look direction
* @param location
* @param lookDirection
* @param speed in meters/second
*/
void walkLoop(Vector3f[] locations, Vector3f lookDirection, float speed, int loopCount) {
this.speed = speed;
locationIndex = 0;
desiredLocations = locations;
desiredLoopCount = loopCount;
currentLoopCount = 0;
step = new Vector3f(desiredLocations[0]);
step.subtractLocal(currentLocation);
step.multLocal(speed/(1000f/sleepTime));
walking = true;
semaphore.release();
}
/**
* Send audio data to the server
*
* TODO implement
*/
public void talk() {
}
}
/**
* Measure the time between us sending a move request to the server and the server
* sending the message back to us.
*/
class MessageTimer implements CellMoveListener {
private long timeSum=0;
private long lastReport;
private int count = 0;
private long min = Long.MAX_VALUE;
private long max = 0;
private static final long REPORT_INTERVAL = 5000; // Report time in ms
private LinkedList<TimeRecord> messageTimes = new LinkedList();
public MessageTimer() {
lastReport = System.nanoTime();
}
/**
* Callback for messages from server
* @param arg0
* @param arg1
*/
public void cellMoved(CellTransform transform, CellMoveSource moveSource) {
if (messageTimes.size()!=0 && messageTimes.getFirst().transform.equals(transform)) {
TimeRecord rec = messageTimes.removeFirst();
long time = ((System.nanoTime())-rec.sendTime)/1000000;
min = Math.min(min, time);
max = Math.max(max, time);
timeSum += time;
count++;
if (System.nanoTime()-lastReport > REPORT_INTERVAL*1000000) {
long avg = timeSum/count;
messageTimerLogger.info("Roundtrip time avg "+avg + "ms "+username+" min "+min+" max "+max);
timeSum=0;
lastReport = System.nanoTime();
count = 0;
min = Long.MAX_VALUE;
max = 0;
}
} else {
logger.warning("No Time record for "+transform.getTranslation(null)+" queue size "+messageTimes.size());
// if (messageTimes.size()!=0)
// logger.warning("HEAD "+messageTimes.getFirst().transform.getTranslation(null));
}
}
public void messageSent(CellTransform transform) {
messageTimes.add(new TimeRecord(transform, System.nanoTime()));
}
}
class TimeRecord {
private CellTransform transform;
private long sendTime;
public TimeRecord(CellTransform transform, long sendTime) {
this.transform = transform;
this.sendTime = sendTime;
}
}
class ClientSimLoginUI implements LoginUI {
private String username;
private Properties props;
public ClientSimLoginUI(String username, Properties props) {
this.username = username;
this.props = props;
}
public void requestLogin(NoAuthLoginControl control) {
String fullname = props.getProperty("fullname");
if (fullname == null) {
fullname = username;
}
try {
control.authenticate(username, fullname);
} catch (LoginFailureException lfe) {
logger.log(Level.WARNING, "Login failed", lfe);
control.cancel();
}
}
public void requestLogin(UserPasswordLoginControl control) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void requestLogin(WebURLLoginControl control) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
class FakeMainFrame implements MainFrame {
private JFrame frame;
private JPanel canvasPanel;
private Canvas canvas;
public FakeMainFrame() {
- frame = new JFrame();
+ try {
+ frame = new JFrame();
+ } catch (HeadlessException he) {
+ // ignore
+ logger.log(Level.INFO, "Running in headless mode");
+ }
canvasPanel = new JPanel(new BorderLayout());
canvas = new Canvas();
canvasPanel.add(canvas, BorderLayout.CENTER);
- frame.setContentPane(canvasPanel);
+
+ if (frame != null) {
+ frame.setContentPane(canvasPanel);
+ }
}
public JFrame getFrame() {
return frame;
}
public Canvas getCanvas() {
return canvas;
}
public JPanel getCanvas3DPanel() {
return canvasPanel;
}
public void addToToolMenu(JMenuItem menuItem) {
// ignore
}
public void addToEditMenu(JMenuItem menuItem) {
// ignore
}
public void setServerURL(String serverURL) {
// ignore
}
public void addServerURLListener(ServerURLListener listener) {
// ignore
}
}
class BlacklistPluginFilter implements PluginFilter {
private final String[] JAR_BLACKLIST = {
"ant",
"ant-launcher",
"artimport-client",
"audiomanager-client",
"avatarbase-client",
"defaultenvironment-client",
"kmzloader-client"
};
private final String[] CLASS_BLACKLIST = {
};
public boolean shouldDownload(ServerSessionManager sessionManager, URL jarURL) {
String urlPath = jarURL.getPath();
int idx = urlPath.lastIndexOf("/");
if (idx != -1) {
urlPath = urlPath.substring(idx);
}
for (String check : JAR_BLACKLIST) {
if (urlPath.contains(check)) {
return false;
}
}
return true;
}
public boolean shouldInitialize(ServerSessionManager sessionManager,
ClientPlugin plugin)
{
for (String check : CLASS_BLACKLIST) {
if (plugin.getClass().getName().equals(check)) {
return false;
}
}
return true;
}
}
}
| false | false | null | null |
diff --git a/src/main/java/org/spout/engine/world/SpoutRegion.java b/src/main/java/org/spout/engine/world/SpoutRegion.java
index fd24ace6d..cd145f37c 100644
--- a/src/main/java/org/spout/engine/world/SpoutRegion.java
+++ b/src/main/java/org/spout/engine/world/SpoutRegion.java
@@ -1,912 +1,918 @@
/*
* This file is part of Spout (http://www.spout.org/).
*
* Spout is licensed under the SpoutDev License Version 1.
*
* Spout is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Spout is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.engine.world;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import org.spout.api.Source;
import org.spout.api.Spout;
import org.spout.api.entity.BlockController;
import org.spout.api.entity.Controller;
import org.spout.api.entity.Entity;
import org.spout.api.entity.PlayerController;
import org.spout.api.event.entity.EntitySpawnEvent;
import org.spout.api.generator.WorldGenerator;
import org.spout.api.geo.World;
import org.spout.api.geo.cuboid.Block;
import org.spout.api.geo.cuboid.Chunk;
import org.spout.api.geo.cuboid.Region;
import org.spout.api.geo.discrete.Point;
import org.spout.api.io.bytearrayarray.BAAWrapper;
import org.spout.api.material.BlockMaterial;
import org.spout.api.material.block.BlockFullState;
import org.spout.api.math.Vector3;
import org.spout.api.player.Player;
import org.spout.api.protocol.NetworkSynchronizer;
import org.spout.api.util.cuboid.CuboidShortBuffer;
import org.spout.api.util.map.TByteTripleObjectHashMap;
import org.spout.api.util.thread.DelayedWrite;
import org.spout.api.util.thread.LiveRead;
import org.spout.engine.entity.EntityManager;
import org.spout.engine.entity.SpoutEntity;
import org.spout.engine.filesystem.WorldFiles;
import org.spout.engine.player.SpoutPlayer;
import org.spout.engine.util.TripleInt;
import org.spout.engine.util.thread.ThreadAsyncExecutor;
import org.spout.engine.util.thread.snapshotable.SnapshotManager;
public class SpoutRegion extends Region {
private AtomicInteger numberActiveChunks = new AtomicInteger();
// Can't extend AsyncManager and Region
private final SpoutRegionManager manager;
private ConcurrentLinkedQueue<TripleInt> saveMarked = new ConcurrentLinkedQueue<TripleInt>();
@SuppressWarnings("unchecked")
public AtomicReference<SpoutChunk>[][][] chunks = new AtomicReference[Region.REGION_SIZE][Region.REGION_SIZE][Region.REGION_SIZE];
/**
* The maximum number of chunks that will be processed for population each
* tick.
*/
private static final int POPULATE_PER_TICK = 20;
/**
* The maximum number of chunks that will be reaped by the chunk reaper each
* tick.
*/
private static final int REAP_PER_TICK = 1;
/**
* The maximum number of chunks that will be processed for lighting updates
* each tick.
*/
private static final int LIGHT_PER_TICK = 20;
/**
* The segment size to use for chunk storage. The actual size is
* 2^(SEGMENT_SIZE)
*/
private final int SEGMENT_SIZE = 8;
/**
* The number of chunks in a region
*/
private final int REGION_SIZE_CUBED = REGION_SIZE * REGION_SIZE * REGION_SIZE;
/**
* The timeout for the chunk storage in ms. If the store isn't accessed
* within that time, it can be automatically shutdown
*/
public static final int TIMEOUT = 30000;
/**
* The source of this region
*/
private final RegionSource source;
/**
* Snapshot manager for this region
*/
protected SnapshotManager snapshotManager = new SnapshotManager();
/**
* Holds all of the entities to be simulated
*/
protected final EntityManager entityManager = new EntityManager();
/**
* Reference to the persistent ByteArrayArray that stores chunk data
*/
private final BAAWrapper chunkStore;
/**
* Holds all not populated chunks
*/
protected Set<Chunk> nonPopulatedChunks = Collections.newSetFromMap(new ConcurrentHashMap<Chunk, Boolean>());
private boolean isPopulatingChunks = false;
protected Queue<Chunk> unloadQueue = new ConcurrentLinkedQueue<Chunk>();
public static final byte POPULATE_CHUNK_MARGIN = 1;
/**
* A set of all blocks in this region that need a physics update in the next
* tick. The coordinates in this set are relative to this region, so (0, 0,
* 0) translates to (0 + x * 256, 0 + y * 256, 0 + z * 256)), where (x, y,
* z) are the region coordinates.
*/
//TODO thresholds?
private final TByteTripleObjectHashMap<Source> queuedPhysicsUpdates = new TByteTripleObjectHashMap<Source>();
private final int blockCoordMask;
private final int blockShifts;
/**
* A queue of chunks that have columns of light that need to be recalculated
*/
private final Queue<SpoutChunk> lightingQueue = new ConcurrentLinkedQueue<SpoutChunk>();
/**
* A queue of chunks that need to be populated
*/
private final Queue<Chunk> populationQueue = new ConcurrentLinkedQueue<Chunk>();
private final Queue<Entity> spawnQueue = new ConcurrentLinkedQueue<Entity>();
private final Queue<Entity> removeQueue = new ConcurrentLinkedQueue<Entity>();
private final Map<Vector3, BlockController> blockControllers = new HashMap<Vector3, BlockController>();
public SpoutRegion(SpoutWorld world, float x, float y, float z, RegionSource source) {
this(world, x, y, z, source, false);
}
public SpoutRegion(SpoutWorld world, float x, float y, float z, RegionSource source, boolean load) {
super(world, x * Region.EDGE, y * Region.EDGE, z * Region.EDGE);
this.source = source;
blockCoordMask = Region.REGION_SIZE * Chunk.CHUNK_SIZE - 1;
blockShifts = Region.REGION_SIZE_BITS + Chunk.CHUNK_SIZE_BITS;
manager = new SpoutRegionManager(this, 2, new ThreadAsyncExecutor(this.toString() + " Thread"), world.getServer());
for (int dx = 0; dx < Region.REGION_SIZE; dx++) {
for (int dy = 0; dy < Region.REGION_SIZE; dy++) {
for (int dz = 0; dz < Region.REGION_SIZE; dz++) {
chunks[dx][dy][dz] = new AtomicReference<SpoutChunk>(load ? getChunk(dx, dy, dz, true) : null);
}
}
}
File worldDirectory = world.getDirectory();
File regionDirectory = new File(worldDirectory, "region");
regionDirectory.mkdirs();
File regionFile = new File(regionDirectory, "reg" + getX() + "_" + getY() + "_" + getZ() + ".spr");
this.chunkStore = new BAAWrapper(regionFile, SEGMENT_SIZE, REGION_SIZE_CUBED, TIMEOUT);
}
@Override
public SpoutWorld getWorld() {
return (SpoutWorld) super.getWorld();
}
@Override
@LiveRead
public SpoutChunk getChunk(int x, int y, int z) {
return getChunk(x, y, z, true);
}
@Override
@LiveRead
public SpoutChunk getChunk(int x, int y, int z, boolean load) {
if (x < Region.REGION_SIZE && x >= 0 && y < Region.REGION_SIZE && y >= 0 && z < Region.REGION_SIZE && z >= 0) {
SpoutChunk chunk = chunks[x][y][z].get();
if (chunk != null || !load) {
return chunk;
}
AtomicReference<SpoutChunk> ref = chunks[x][y][z];
boolean success = false;
SpoutChunk newChunk = WorldFiles.loadChunk(this, x, y, z, this.getChunkInputStream(x, y, z));
if (newChunk == null) {
newChunk = generateChunk(x, y, z);
}
while (!success) {
success = ref.compareAndSet(null, newChunk);
if (success) {
newChunk.notifyColumn();
numberActiveChunks.incrementAndGet();
if (!newChunk.isPopulated()) {
nonPopulatedChunks.add(newChunk);
}
return newChunk;
} else {
newChunk.deregisterFromColumn(false);
SpoutChunk oldChunk = ref.get();
if (oldChunk != null) {
return oldChunk;
}
}
}
}
throw new IndexOutOfBoundsException("Invalid coordinates (" + x + ", " + y + ", " + z + ")");
}
private SpoutChunk generateChunk(int x, int y, int z) {
int cx = (getX() << Region.REGION_SIZE_BITS) + x;
int cy = (getY() << Region.REGION_SIZE_BITS) + y;
int cz = (getZ() << Region.REGION_SIZE_BITS) + z;
CuboidShortBuffer buffer = new CuboidShortBuffer(getWorld(), cx << Chunk.CHUNK_SIZE_BITS, cy << Chunk.CHUNK_SIZE_BITS, cz << Chunk.CHUNK_SIZE_BITS, Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE);
WorldGenerator generator = getWorld().getGenerator();
generator.generate(buffer, cx, cy, cz);
return new SpoutChunk(getWorld(), this, cx, cy, cz, buffer.getRawArray());
}
/**
* Removes a chunk from the region and indicates if the region is empty
* @param c the chunk to remove
* @return true if the region is now empty
*/
public boolean removeChunk(Chunk c) {
if (c.getRegion() != this) {
return false;
}
int cx = c.getX() & Region.REGION_SIZE - 1;
int cy = c.getY() & Region.REGION_SIZE - 1;
int cz = c.getZ() & Region.REGION_SIZE - 1;
AtomicReference<SpoutChunk> current = chunks[cx][cy][cz];
SpoutChunk currentChunk = current.get();
if (currentChunk != c) {
return false;
}
boolean success = current.compareAndSet(currentChunk, null);
if (success) {
int num = numberActiveChunks.decrementAndGet();
((SpoutChunk) currentChunk).setUnloaded();
if (num == 0) {
return true;
} else if (num < 0) {
throw new IllegalStateException("Region has less than 0 active chunks");
}
}
return false;
}
@Override
public boolean hasChunk(int x, int y, int z) {
if (x < Region.REGION_SIZE && x >= 0 && y < Region.REGION_SIZE && y >= 0 && z < Region.REGION_SIZE && z >= 0) {
return chunks[x][y][z].get() != null;
}
return false;
}
SpoutRegionManager getManager() {
return manager;
}
/**
* Queues a Chunk for saving
*/
@Override
@DelayedWrite
public void saveChunk(int x, int y, int z) {
SpoutChunk c = getChunk(x, y, z, false);
if (c != null) {
c.save();
}
}
/**
* Queues all chunks for saving
*/
@Override
@DelayedWrite
public void save() {
for (int dx = 0; dx < Region.REGION_SIZE; dx++) {
for (int dy = 0; dy < Region.REGION_SIZE; dy++) {
for (int dz = 0; dz < Region.REGION_SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
chunk.saveNoMark();
}
}
}
}
markForSaveUnload();
}
@Override
public void unload(boolean save) {
for (int dx = 0; dx < Region.REGION_SIZE; dx++) {
for (int dy = 0; dy < Region.REGION_SIZE; dy++) {
for (int dz = 0; dz < Region.REGION_SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
chunk.unloadNoMark(save);
}
}
}
}
markForSaveUnload();
}
@Override
public void unloadChunk(int x, int y, int z, boolean save) {
SpoutChunk c = getChunk(x, y, z, false);
if (c != null) {
c.unload(save);
}
}
public void markForSaveUnload(Chunk c) {
if (c.getRegion() != this) {
return;
}
int cx = c.getX() & Region.REGION_SIZE - 1;
int cy = c.getY() & Region.REGION_SIZE - 1;
int cz = c.getZ() & Region.REGION_SIZE - 1;
markForSaveUnload(cx, cy, cz);
}
public void markForSaveUnload(int x, int y, int z) {
saveMarked.add(new TripleInt(x, y, z));
}
public void markForSaveUnload() {
saveMarked.add(TripleInt.NULL);
}
public void copySnapshotRun() throws InterruptedException {
entityManager.copyAllSnapshots();
for (int dx = 0; dx < Region.REGION_SIZE; dx++) {
for (int dy = 0; dy < Region.REGION_SIZE; dy++) {
for (int dz = 0; dz < Region.REGION_SIZE; dz++) {
Chunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
((SpoutChunk) chunk).copySnapshotRun();
}
}
}
}
snapshotManager.copyAllSnapshots();
boolean empty = false;
TripleInt chunkCoords;
while ((chunkCoords = saveMarked.poll()) != null) {
if (chunkCoords == TripleInt.NULL) {
for (int dx = 0; dx < Region.REGION_SIZE; dx++) {
for (int dy = 0; dy < Region.REGION_SIZE; dy++) {
for (int dz = 0; dz < Region.REGION_SIZE; dz++) {
if (processChunkSaveUnload(dx, dy, dz)) {
empty = true;
}
}
}
}
// No point in checking any others, since all processed
saveMarked.clear();
break;
} else {
processChunkSaveUnload(chunkCoords.x, chunkCoords.y, chunkCoords.z);
}
}
// Updates on nulled chunks
snapshotManager.copyAllSnapshots();
if (empty) {
source.removeRegion(this);
}
}
public boolean processChunkSaveUnload(int x, int y, int z) {
boolean empty = false;
SpoutChunk c = (SpoutChunk) getChunk(x, y, z, false);
if (c != null) {
SpoutChunk.SaveState oldState = c.getAndResetSaveState();
if (oldState.isSave()) {
c.syncSave();
}
if (oldState.isUnload()) {
if (removeChunk(c)) {
empty = true;
}
}
}
return empty;
}
protected void queueChunkForPopulation(Chunk c) {
if (!populationQueue.contains(c)) {
populationQueue.add(c);
}
}
protected void queueLighting(SpoutChunk c) {
if (!lightingQueue.contains(c)) {
lightingQueue.add(c);
}
}
public void addEntity(Entity e) {
Controller controller = e.getController();
if (controller instanceof BlockController) {
Point pos = e.getPosition();
setBlockController(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(), (BlockController) controller);
}
if (spawnQueue.contains(e)) {
return;
}
if (removeQueue.contains(e)) {
throw new IllegalArgumentException("Cannot add an entity marked for removal");
}
spawnQueue.add(e);
}
public void removeEntity(Entity e) {
Vector3 pos = e.getPosition().floor();
if (blockControllers.containsKey(pos)) {
blockControllers.remove(pos);
}
if (removeQueue.contains(e)) {
return;
}
if (spawnQueue.contains(e)) {
spawnQueue.remove(e);
return;
}
removeQueue.add(e);
}
public void startTickRun(int stage, long delta) throws InterruptedException {
switch (stage) {
case 0: {
//Add or remove entities
if (!spawnQueue.isEmpty()) {
SpoutEntity e;
while ((e = (SpoutEntity) spawnQueue.poll()) != null) {
this.allocate(e);
EntitySpawnEvent event = new EntitySpawnEvent(e, e.getPosition());
Spout.getEngine().getEventManager().callEvent(event);
if (event.isCancelled()) {
this.deallocate((SpoutEntity) e);
}
}
}
if (!removeQueue.isEmpty()) {
SpoutEntity e;
while ((e = (SpoutEntity) removeQueue.poll()) != null) {
this.deallocate(e);
}
}
float dt = delta / 1000.f;
//Update all entities
for (SpoutEntity ent : entityManager) {
try {
ent.onTick(dt);
} catch (Exception e) {
Spout.getEngine().getLogger().severe("Unhandled exception during tick for " + ent.toString());
e.printStackTrace();
}
}
World world = getWorld();
int[] updates;
Object[] sources;
synchronized (queuedPhysicsUpdates) {
updates = queuedPhysicsUpdates.keys();
sources = queuedPhysicsUpdates.values();
queuedPhysicsUpdates.clear();
}
for (int i = 0; i < updates.length; i++) {
int key = updates[i];
Source source = (Source) sources[i];
int x = TByteTripleObjectHashMap.key1(key);
int y = TByteTripleObjectHashMap.key2(key);
int z = TByteTripleObjectHashMap.key3(key);
//switch region block coords (0-255) to a chunk index
Chunk chunk = chunks[x >> Chunk.CHUNK_SIZE_BITS][y >> Chunk.CHUNK_SIZE_BITS][z >> Chunk.CHUNK_SIZE_BITS].get();
if (chunk != null) {
BlockMaterial material = chunk.getBlockMaterial(x, y, z);
if (material.hasPhysics()) {
//switch region block coords (0-255) to world block coords
Block block = world.getBlock(x + (getX() << blockShifts), y + (getY() << blockShifts), z + (getZ() << blockShifts), source);
material.onUpdate(block);
}
}
}
for (int i = 0; i < LIGHT_PER_TICK; i++) {
SpoutChunk toLight = lightingQueue.poll();
if (toLight == null) {
break;
}
if (toLight.isLoaded()) {
toLight.processQueuedLighting();
}
}
for (int i = 0; i < POPULATE_PER_TICK; i++) {
Chunk toPopulate = populationQueue.poll();
if (toPopulate == null) {
break;
}
if (toPopulate.isLoaded()) {
toPopulate.populate();
}
}
Chunk toUnload = unloadQueue.poll();
if (toUnload != null) {
toUnload.unload(true);
}
break;
}
case 1: {
//Resolve collisions and prepare for a snapshot.
Set<SpoutEntity> resolvers = new HashSet<SpoutEntity>();
boolean shouldResolve;
for (SpoutEntity ent : entityManager) {
shouldResolve = ent.preResolve();
if (shouldResolve) {
resolvers.add(ent);
}
}
for (SpoutEntity ent : resolvers) {
try {
ent.resolve();
} catch (Exception e) {
Spout.getEngine().getLogger().severe("Unhandled exception during tick resolution for " + ent.toString());
e.printStackTrace();
}
}
break;
}
default: {
throw new IllegalStateException("Number of states exceeded limit for SpoutRegion");
}
}
}
public void haltRun() throws InterruptedException {
}
public void finalizeRun() throws InterruptedException {
entityManager.finalizeRun();
// Compress at most 1 chunk per tick per region
boolean chunkCompressed = false;
int reaped = 0;
long worldAge = getWorld().getAge();
for (int dx = 0; dx < Region.REGION_SIZE && !chunkCompressed; dx++) {
for (int dy = 0; dy < Region.REGION_SIZE && !chunkCompressed; dy++) {
for (int dz = 0; dz < Region.REGION_SIZE && !chunkCompressed; dz++) {
Chunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
chunkCompressed |= ((SpoutChunk) chunk).compressIfRequired();
if (reaped < REAP_PER_TICK && ((SpoutChunk) chunk).isReapable(worldAge)) {
((SpoutChunk) chunk).unload(true);
reaped++;
}
}
}
}
}
}
private void syncChunkToPlayers(SpoutChunk chunk, Entity entity) {
SpoutPlayer player = (SpoutPlayer) ((PlayerController) entity.getController()).getPlayer();
NetworkSynchronizer synchronizer = player.getNetworkSynchronizer();
if (synchronizer != null) {
if (!chunk.isDirtyOverflow() && !chunk.isLightDirty()) {
for (int i = 0; true; i++) {
Block block = chunk.getDirtyBlock(i);
if (block == null) {
break;
} else {
try {
synchronizer.updateBlock(chunk, block.getX(), block.getY(), block.getZ());
} catch (Exception e) {
Spout.getEngine().getLogger().log(Level.SEVERE, "Exception thrown by plugin when attempting to send a block update to " + player.getName());
}
}
}
} else {
synchronizer.sendChunk(chunk);
}
}
}
public void preSnapshotRun() throws InterruptedException {
entityManager.preSnapshotRun();
for (int dx = 0; dx < Region.REGION_SIZE; dx++) {
for (int dy = 0; dy < Region.REGION_SIZE; dy++) {
for (int dz = 0; dz < Region.REGION_SIZE; dz++) {
Chunk chunk = chunks[dx][dy][dz].get();
if (chunk == null) {
continue;
}
SpoutChunk spoutChunk = (SpoutChunk) chunk;
if (spoutChunk.isDirty()) {
for (Entity entity : spoutChunk.getObserversLive()) {
//chunk.refreshObserver(entity);
if (!(entity.getController() instanceof PlayerController)) {
continue;
}
syncChunkToPlayers(spoutChunk, entity);
}
spoutChunk.resetDirtyArrays();
}
spoutChunk.preSnapshot();
}
}
}
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Set<Entity> getAll(Class<? extends Controller> type) {
return (Set) entityManager.getAll(type);
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Set<Entity> getAll() {
return (Set) entityManager.getAll();
}
@Override
public SpoutEntity getEntity(int id) {
return entityManager.getEntity(id);
}
/**
* Allocates the id for an entity.
* @param entity The entity.
* @return The id.
*/
public int allocate(SpoutEntity entity) {
return entityManager.allocate(entity);
}
/**
* Deallocates the id for an entity.
* @param entity The entity.
*/
public void deallocate(SpoutEntity entity) {
entityManager.deallocate(entity);
}
public Iterator<SpoutEntity> iterator() {
return entityManager.iterator();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void onChunkPopulated(SpoutChunk chunk) {
if (!isPopulatingChunks) {
nonPopulatedChunks.remove(chunk);
}
}
/**
* Queues a block for a physic update at the next available tick.
* @param x, the block x coordinate
* @param y, the block y coordinate
* @param z, the block z coordinate
*/
public void queuePhysicsUpdate(int x, int y, int z, Source source) {
synchronized (queuedPhysicsUpdates) {
queuedPhysicsUpdates.put((byte) (x & blockCoordMask), (byte) (y & blockCoordMask), (byte) (z & blockCoordMask), source);
}
}
@Override
public int getNumLoadedChunks() {
return numberActiveChunks.get();
}
@Override
public String toString() {
return "SpoutRegion{ ( " + getX() + ", " + getY() + ", " + getZ() + "), World: " + this.getWorld() + "}";
}
public Thread getExceutionThread() {
return ((ThreadAsyncExecutor) manager.getExecutor());
}
/**
* This method should be called periodically in order to see if the Chunk
* Store ByteArrayArray has timed out.<br>
* <br>
* It will only close the array if no block OutputStreams are open and the
* last access occurred more than the timeout previously
*/
public void chunkStoreTimeoutCheck() {
chunkStore.timeoutCheck();
}
/**
* Gets the DataOutputStream corresponding to a given Chunk.<br>
* <br>
* WARNING: This block will be locked until the stream is closed
* @param c the chunk
* @return the DataOutputStream
*/
public OutputStream getChunkOutputStream(Chunk c) {
int key = getChunkKey(c.getX(), c.getY(), c.getZ());
return chunkStore.getBlockOutputStream(key);
}
/**
* Gets the DataInputStream corresponding to a given Chunk.<br>
* <br>
* The stream is based on a snapshot of the array.
* @param x the chunk
* @return the DataInputStream
*/
public InputStream getChunkInputStream(int x, int y, int z) {
int key = getChunkKey(x, y, z);
return chunkStore.getBlockInputStream(key);
}
private int getChunkKey(int chunkX, int chunkY, int chunkZ) {
int x = chunkX & (Region.REGION_SIZE - 1);
int y = chunkY & (Region.REGION_SIZE - 1);
int z = chunkZ & (Region.REGION_SIZE - 1);
int key = 0;
key |= x;
key |= y << (Region.REGION_SIZE_BITS);
key |= z << (Region.REGION_SIZE_BITS << 1);
return key;
}
@Override
public Chunk getChunkFromBlock(int x, int y, int z) {
return this.getWorld().getChunkFromBlock(x, y, z);
}
@Override
public Chunk getChunkFromBlock(int x, int y, int z, boolean load) {
return this.getWorld().getChunkFromBlock(x, y, z, load);
}
@Override
public Chunk getChunkFromBlock(Vector3 position) {
return this.getWorld().getChunkFromBlock(position);
}
@Override
public Chunk getChunkFromBlock(Vector3 position, boolean load) {
return this.getWorld().getChunkFromBlock(position, load);
}
@Override
public boolean hasChunkAtBlock(int x, int y, int z) {
return this.getWorld().hasChunkAtBlock(x, y, z);
}
@Override
public boolean setBlockData(int x, int y, int z, short data, Source source) {
return this.getChunkFromBlock(x, y, z).setBlockData(x, y, z, data, source);
}
@Override
public boolean setBlockMaterial(int x, int y, int z, BlockMaterial material, short data, Source source) {
return this.getChunkFromBlock(x, y, z).setBlockMaterial(x, y, z, material, data, source);
}
@Override
public boolean setBlockLight(int x, int y, int z, byte light, Source source) {
return this.getChunkFromBlock(x, y, z).setBlockLight(x, y, z, light, source);
}
@Override
public boolean setBlockSkyLight(int x, int y, int z, byte light, Source source) {
return this.getChunkFromBlock(x, y, z).setBlockSkyLight(x, y, z, light, source);
}
@Override
public void setBlockController(int x, int y, int z, BlockController controller) {
- if (controller.getParent() == null) {
+ BlockController previous = blockControllers.remove(new Vector3(x, y, z));
+ if (previous != null && previous.getParent() != null) {
+ previous.getParent().kill();
+ }
+ if (controller == null) {
+ return;
+ } else if (controller.getParent() == null) {
this.getWorld().createAndSpawnEntity(new Point(this.getWorld(), x, y, z), controller);
} else {
blockControllers.put(new Vector3(x, y, z), controller);
}
}
@Override
public BlockController getBlockController(int x, int y, int z) {
return blockControllers.get(new Vector3(x, y, z));
}
@Override
public void updateBlockPhysics(int x, int y, int z, Source source) {
this.getChunkFromBlock(x, y, z).updateBlockPhysics(x, y, z, source);
}
@Override
public Block getBlock(int x, int y, int z) {
return this.getWorld().getBlock(x, y, z);
}
@Override
public Block getBlock(int x, int y, int z, Source source) {
return this.getWorld().getBlock(x, y, z, source);
}
@Override
public Block getBlock(float x, float y, float z) {
return this.getWorld().getBlock(x, y, z);
}
@Override
public Block getBlock(float x, float y, float z, Source source) {
return this.getWorld().getBlock(x, y, z, source);
}
@Override
public Block getBlock(Vector3 position) {
return this.getWorld().getBlock(position);
}
@Override
public Block getBlock(Vector3 position, Source source) {
return this.getWorld().getBlock(position, source);
}
@Override
public BlockMaterial getBlockMaterial(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockMaterial(x, y, z);
}
@Override
public short getBlockData(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockData(x, y, z);
}
@Override
public byte getBlockLight(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockLight(x, y, z);
}
@Override
public byte getBlockSkyLight(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockSkyLight(x, y, z);
}
@Override
public boolean compareAndSetData(int x, int y, int z, BlockFullState expect, short data) {
return this.getChunkFromBlock(x, y, z).compareAndSetData(x, y, z, expect, data);
}
@Override
public Set<Player> getPlayers() {
// TODO Auto-generated method stub
return null;
}
}
| true | false | null | null |
diff --git a/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java b/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java
index 9cb2128d1..fdd37e291 100644
--- a/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java
+++ b/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java
@@ -1,117 +1,117 @@
/**
* Copyright 2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import org.mortbay.http.*;
import org.mortbay.http.handler.*;
import org.mortbay.jetty.servlet.*;
import java.io.*;
import java.net.*;
/*******************************************************
* JobTrackerInfoServer provides stats about the JobTracker
* via HTTP. It's useful for clients that want to track
* their jobs' progress.
*
* @author Mike Cafarella
*******************************************************/
class JobTrackerInfoServer {
public static class RedirectHandler extends AbstractHttpHandler {
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {
response.sendRedirect("/jobtracker");
request.setHandled(true);
}
}
/////////////////////////////////////
// The actual JobTrackerInfoServer
/////////////////////////////////////
static JobTracker jobTracker;
org.mortbay.jetty.Server server;
/**
* We need the jobTracker to grab stats, and the port to
* know where to listen.
*/
private static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");
public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException {
this.jobTracker = jobTracker;
this.server = new org.mortbay.jetty.Server();
URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps");
String path = url.getPath();
if (WINDOWS && path.startsWith("/")) {
path = path.substring(1);
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
- File jobtracker = new File(path, "jobtracker");
- WebApplicationContext context = server.addWebApplication(null, "/", jobtracker.getCanonicalPath());
+ WebApplicationContext context =
+ server.addWebApplication(null,"/",new File(path).getCanonicalPath());
SocketListener socketListener = new SocketListener();
socketListener.setPort(port);
this.server.addListener(socketListener);
//
// REMIND - mjc - I can't figure out how to get request redirect to work.
// I've tried adding an additional default handler to the context, but
// it doesn't seem to work. The handler has its handle() function called
// even when the JSP is processed correctly! I just want to add a redirect
// page, when the URL is incorrectly typed.
//
// context.addHandler(new LocalNotFoundHandler());
}
/**
* The thread class we need to kick off the HTTP server async-style.
*/
class HTTPStarter implements Runnable {
public void run() {
try {
server.start();
} catch (Exception me) {
me.printStackTrace();
}
}
}
/**
* Launch the HTTP server
*/
public void start() throws IOException {
new Thread(new HTTPStarter()).start();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
if (! server.isStarted()) {
throw new IOException("Could not start HTTP server");
}
}
/**
* Stop the HTTP server
*/
public void stop() {
try {
this.server.stop();
} catch (InterruptedException ie) {
}
}
}
| true | true | public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException {
this.jobTracker = jobTracker;
this.server = new org.mortbay.jetty.Server();
URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps");
String path = url.getPath();
if (WINDOWS && path.startsWith("/")) {
path = path.substring(1);
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
File jobtracker = new File(path, "jobtracker");
WebApplicationContext context = server.addWebApplication(null, "/", jobtracker.getCanonicalPath());
SocketListener socketListener = new SocketListener();
socketListener.setPort(port);
this.server.addListener(socketListener);
//
// REMIND - mjc - I can't figure out how to get request redirect to work.
// I've tried adding an additional default handler to the context, but
// it doesn't seem to work. The handler has its handle() function called
// even when the JSP is processed correctly! I just want to add a redirect
// page, when the URL is incorrectly typed.
//
// context.addHandler(new LocalNotFoundHandler());
}
| public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException {
this.jobTracker = jobTracker;
this.server = new org.mortbay.jetty.Server();
URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps");
String path = url.getPath();
if (WINDOWS && path.startsWith("/")) {
path = path.substring(1);
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
WebApplicationContext context =
server.addWebApplication(null,"/",new File(path).getCanonicalPath());
SocketListener socketListener = new SocketListener();
socketListener.setPort(port);
this.server.addListener(socketListener);
//
// REMIND - mjc - I can't figure out how to get request redirect to work.
// I've tried adding an additional default handler to the context, but
// it doesn't seem to work. The handler has its handle() function called
// even when the JSP is processed correctly! I just want to add a redirect
// page, when the URL is incorrectly typed.
//
// context.addHandler(new LocalNotFoundHandler());
}
|
diff --git a/mtScrabble/src/essentials/objects/BrickList.java b/mtScrabble/src/essentials/objects/BrickList.java
index 8f34a10..4bf3c34 100644
--- a/mtScrabble/src/essentials/objects/BrickList.java
+++ b/mtScrabble/src/essentials/objects/BrickList.java
@@ -1,655 +1,659 @@
package essentials.objects;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import essentials.core.ScrabbleLogger;
import essentials.enums.LetterEnum;
import essentials.enums.LogLevel;
import essentials.enums.OrientationEnum;
import essentials.interfaces.Cachable;
import essentials.interfaces.Cloneable;
/**
* Class for generating a list of bricks.
* Also contains parameters row, column and orientation
* to use class to set bricks on game map.
* @author hannes
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "bricklist")
public class BrickList implements Cloneable, Cachable{
@XmlElement
protected List<Brick> bricks;
@XmlElement
protected int row;
@XmlElement
protected int col;
@XmlElement
protected OrientationEnum orientation;
/**
* Cached values
*/
protected Integer cache_numOfJokers = null;
protected Integer cache_numOfBricksOnMap = null;
protected Integer cache_numOfBricksMissing = null;
protected Integer cache_size = null;
protected Integer cache_score = null;
protected String cache_word = null;
protected String cache_wordWithWeights = null;
/**
* Constructor
*/
public BrickList() {
this(0, 0, OrientationEnum.HORIZONTAL);
}
/**
* Constructor
* @param aRow
* @param aColumn
* @param aOrientation
*/
public BrickList(int aRow, int aColumn, OrientationEnum aOrientation){
row = aRow;
col = aColumn;
orientation = aOrientation;
bricks = new ArrayList<Brick>();
}
/**
* Constructor
* @param aBricks
* @param aRow
* @param aColumn
* @param aOrientation
*/
public BrickList(List<Brick> aBricks, int aRow, int aColumn, OrientationEnum aOrientation){
this(aRow, aColumn, aOrientation);
bricks = aBricks;
}
/**
* Constructor
* Clones another bricklist
* @param aBrickList
*/
public BrickList(BrickList aBrickList){
this(
aBrickList.getBricks(),
aBrickList.getRow(),
aBrickList.getColumn(),
aBrickList.getOrientation()
);
}
/**
* Get one brick a specific position
* @param i
* @return brick at position i (starting at position 0)
*/
public Brick get(int i){
return bricks.get(i);
}
/**
* @return cache_size of bricklist
*/
public int size(){
if(cache_size == null){
cache_size = bricks.size();
}
return cache_size;
}
/**
* @return row
*/
@XmlTransient
public int getRow(){
return row;
}
/**
* Set row
* @param aRow
*/
public void setRow(int aRow){
row = aRow;
}
/**
* @return column
*/
public int getColumn(){
return col;
}
/**
* Set column
* @param aColumn
*/
public void setColumn(int aColumn){
col = aColumn;
}
/**
* @return orientation
*/
@XmlTransient
public OrientationEnum getOrientation(){
return orientation;
}
/**
* Set orientation (horizontal or vertical)
* @param aOrientation
*/
public void setOrientation(OrientationEnum aOrientation){
orientation = aOrientation;
}
/**
* Set position (row and column)
* @param aRow
* @param aColumn
*/
public void setPosition(int aRow, int aColumn)
{
setRow(aRow);
setColumn(aColumn);
}
/**
* Sets position (row, column and orientation)
* @param aRow
* @param aColumn
* @param aOrientation
*/
public void setPosition(int aRow, int aColumn, OrientationEnum aOrientation)
{
setRow(aRow);
setColumn(aColumn);
setOrientation(aOrientation);
}
/**
* @return list of bricks
*/
@XmlTransient
public List<Brick> getBricks(){
return bricks;
}
/**
* Sets a list of bricks
* @param aBricks
*/
public void setBricks(List<Brick> aBricks){
bricks = aBricks;
}
/**
* Add a brick to bricklist
* @param aBrick
*/
public void add(Brick aBrick){
bricks.add(aBrick);
resetCache();
}
/**
* Adds a bricklist's bricks to this list
* @param aBrickList
*/
public void add(BrickList aBrickList){
for( Brick b : aBrickList.getBricks() ){
add(b);
}
}
/**
* Remove a brick with one specific letter
* @param aLetter
*/
public void remove(String aLetter){
for(Brick b : bricks){
if( b.getLetter().toString().equals(aLetter) ){
bricks.remove(b);
resetCache();
return;
}
}
}
/**
* Remove a brick with one specific letter
* from LetterEnum
* @param aLetter
*/
public void remove(LetterEnum aLetter){
remove(aLetter.toString());
}
/**
* Remove a brick from list
* ATTENTION: Only the letter is important,
* not the weight of the brick!
* @param aBrick
*/
public void remove(Brick aBrick){
if( aBrick.getWeight() >= 0 ){
if( aBrick.getWeight() == 0 ){
aBrick.setLetter( LetterEnum.JOKER );
}
remove( aBrick.getLetter() );
}
}
/**
* Removes a set of bricks from list
* @param aBrickList
*/
public void remove(BrickList aBrickList){
for( Brick b : aBrickList.getBricks() ){
remove(b);
}
}
/**
* Checks if a brick with a specific letter is inside list
* @param aLetter
* @return true if brick found, otherwise false
*/
public boolean contains(String aLetter){
for(Brick b : bricks){
if( b.getLetter().toString().equals(aLetter) ){
return true;
}
}
return false;
}
/**
* Checks if a brick with a specific letter from LetterEnum
* is inside list.
* ATTENTION: Compares only the letters,
* not the weight of the brick!
* @param aLetter
* @return true if brick found, otherwise false
*/
public boolean contains(LetterEnum aLetter){
return contains(aLetter.toString());
}
/**
* Checks if a brick with a specific letter and weight is inside list
* @param letter
* @param weight
* @return true if a brick with both (letter and weight) is in pool,
* otherwise false
*/
public boolean contains(String letter, int weight){
for( Brick b : bricks ){
int bWeight = b.getWeight();
LetterEnum bLetter = b.getLetter();
if( (bLetter.toString().equals(letter) && bWeight == weight)
|| (bLetter == LetterEnum.JOKER && weight == 0)
|| (weight < 0) ){
return true;
}
}
return false;
}
/**
* Checks if a brick with a specific letter from LetterEnum
* is inside list.
* @param aLetter
* @param weight
* @return true if a brick with both (letter and weight) is in pool,
* otherwise false
*/
public boolean contains(LetterEnum aLetter, int weight){
- return contains(aLetter.toString(), weight);
+ try{
+ return contains(aLetter.toString(), weight);
+ } catch( Exception e ){
+ return false;
+ }
}
/**
* Checks if a brick is inside list.
* @param aBrick
* @return true if a brick with both (letter and weight) is in pool,
* otherwise false
*/
public boolean contains(Brick aBrick) {
return contains(aBrick.getLetter(), aBrick.getWeight());
}
/**
* Checks if a set of bricks is in list
* Checks letter AND weight!
* @param aBrickList
* @return true if all bricks are in list, otherwise false
*/
public boolean contains(BrickList aBrickList){
for( Brick b : aBrickList.getBricks() ){
if( !contains(b) ){
return false;
}
}
return true;
}
/**
* Checks if there are enough bricks bricks in list to build a bricklist
* @param aBricklist
* @return True if there are enough bricks in list to build the bricklist
*/
public boolean containsN(BrickList aBricklist){
// check for suitable bricks
for( Brick b : aBricklist.getBricks() ){
if( b.getWeight() < -1
|| !containsN(b, aBricklist.count(b)) ){
return false;
}
}
// also check for needed jokers
if( getNumOfJokers() < aBricklist.getNumOfJokers() ){
return false;
}
return true;
}
/**
* Checks if list contains at least n specuific bricks
* @param aBrick Brick to search for
* @param n Number of min. needed bricks
* @return True if at least n bricks are in list, otherwise false.
*/
public boolean containsN(Brick aBrick, int n){
if( n <= count(aBrick) || aBrick.getLetter() == LetterEnum.NULL ){
return true;
}
return false;
}
public boolean containsN(LetterEnum aLetter, int n){
if( n <= count( aLetter, 0 ) ){
return true;
}
return false;
}
/**
* Checks if list contains at least n specific bricks with speicied letter an weight
* @param aLetter
* @param aWeight
* @param n Number of bricks needed
* @return True if at least n bricks with that letter and weight are in list, otherwise false.
*/
public boolean containsN(LetterEnum aLetter, int aWeight, int n){
return containsN( new Brick(aLetter, aWeight), n );
}
/**
* Counts the bricks with a specific letter and weight
* @param aBrick Brick to serach for
* @return Number of bricks with the same letter and weight
*/
public int count(Brick aBrick){
int n = 0;
for( Brick b : bricks ){
if( b.getWeight() >= 0 && b.equals(aBrick) ){
n++;
}
}
return n;
}
/**
* Counts the bricks with a specific letter
* @param aLetter
* @return
*/
public int count(LetterEnum aLetter){
int n = 0;
for( Brick b : bricks ){
if( b.getLetter() == aLetter ){
n++;
}
}
return n;
}
/**
* Counts the bricks with a specific letter and weight
* @param aLetter Letter to search for
* @return Number of bricks with that letter and weight
*/
public int count(LetterEnum aLetter, int aWeight){
return count( new Brick(aLetter, aWeight) );
}
/**
* Counts the bricks with a specific letter and weight
* @param aLetter Letter to search for
* @return Number of bricks with that letter and weight
*/
public int count(String aLetter, int aWeight){
LetterEnum letter = LetterEnum.valueOf(aLetter);
return count( new Brick(letter, aWeight) );
}
/**
* Counts all bricks and sets chached values
*/
private void countBricks(){
cache_numOfJokers = 0;
cache_numOfBricksOnMap = 0;
cache_numOfBricksMissing = 0;
cache_score = 0;
for( Brick b : bricks ){
if( b.getWeight() == 0 )
cache_numOfJokers++;
else if( b.getWeight() == -1 )
cache_numOfBricksOnMap++;
else if( b.getWeight() < -1 )
cache_numOfBricksMissing++;
else if( b.getWeight() > 0 ){
cache_score += b.getWeight();
}
}
}
/**
* @return cache_score of bricklist
* Fast access
*/
public int getScore(){
if( cache_score == null ){
countBricks();
}
return cache_score;
}
/**
* @return number of jokers
* Fast access
*/
public int getNumOfJokers(){
if( cache_numOfJokers == null ){
countBricks();
}
return cache_numOfJokers;
}
/**
* @return number of bricks with weight == -1
* Fast access
*/
public int getNumOfBricksOnMap(){
if( cache_numOfBricksOnMap == null ){
countBricks();
}
return cache_numOfBricksOnMap;
}
/**
* @return number of bricks withj weight < -1
* Fast access
*/
public int getNumOfBricksMissing(){
if( cache_numOfBricksMissing == null ){
countBricks();
}
return cache_numOfBricksMissing;
}
/**
* Resets all cached values
*/
public void resetCache(){
cache_numOfJokers = null;
cache_numOfBricksOnMap = null;
cache_numOfBricksMissing = null;
cache_size = null;
cache_score = null;
cache_word = null;
cache_wordWithWeights = null;
}
/**
* Converts a word into a list of bricks
* @param word
* @return List of bricks with no weight
*/
public static BrickList toBricks(String word){
BrickList bricks = new BrickList();
for( char c : word.toCharArray() ){
try{
LetterEnum letter = LetterEnum.valueOf( String.valueOf(c) );
bricks.add( new Brick(letter, 0) );
} catch(Exception e){
}
}
return bricks;
}
/**
* Calculates cache_score for a set of bricklists
* @param aBrickLists List of bricklists
* @return cache_score
*/
public static int getScore(List<BrickList> aBrickLists){
int score = 0;
for( BrickList bL : aBrickLists ){
if(bL.getScore() > 0){
score += bL.getScore();
}
}
return score;
}
/**
* Clones this object
*/
public BrickList clone(){
BrickList rBrickList = new BrickList();
rBrickList.setRow(row );
rBrickList.setColumn(col);
rBrickList.setOrientation(orientation);
for(Brick b : bricks){
rBrickList.add( new Brick(b.getLetter(), b.getWeight()) );
}
return rBrickList;
}
/**
* Converts object to string
*/
public String toString(){
StringWriter dataWriter = new StringWriter();
JAXB.marshal(this, dataWriter);
return dataWriter.toString();
}
/**
* Converts bricklist to a word
* @return
*/
public String toWord(){
if( cache_word == null ){
cache_word = "";
for(Brick b : bricks){
try{
if(b != null && b.getLetter() != LetterEnum.NULL)
cache_word += b.getLetter().toString();
} catch(Exception e){
ScrabbleLogger.log( "Error in getting string from brick letter.", LogLevel.ERROR );
}
}
}
return cache_word;
}
/**
* Converts bricklist to a string of brick letters with weights
* @return
*/
public String toStringWithWeights(){
if( cache_wordWithWeights == null ){
cache_wordWithWeights = "";
for(Brick b : bricks){
try{
if(b != null && b.getLetter() != null){
cache_wordWithWeights += b.getLetter().toString() + b.getWeight() + " ";
}
} catch(Exception e){
ScrabbleLogger.log( "Error in getting string from brick letter.", LogLevel.ERROR );
}
}
}
return cache_wordWithWeights;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/tests/frontend/org/voltdb/TestRestoreAgent.java b/tests/frontend/org/voltdb/TestRestoreAgent.java
index b00393084..c657208ce 100644
--- a/tests/frontend/org/voltdb/TestRestoreAgent.java
+++ b/tests/frontend/org/voltdb/TestRestoreAgent.java
@@ -1,779 +1,779 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.voltcore.logging.VoltLogger;
import org.voltcore.network.WriteStream;
import org.voltcore.utils.CoreUtils;
import org.voltcore.zk.ZKTestBase;
import org.voltdb.RestoreAgent.SnapshotInfo;
import org.voltdb.VoltDB.START_ACTION;
import org.voltdb.VoltTable.ColumnInfo;
import org.voltdb.VoltZK.MailboxType;
import org.voltdb.catalog.Catalog;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcCallException;
import org.voltdb.compiler.ClusterConfig;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.dtxn.TransactionInitiator;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.VoltFile;
@RunWith(Parameterized.class)
public class TestRestoreAgent extends ZKTestBase implements RestoreAgent.Callback {
private final static VoltLogger LOG = new VoltLogger("HOST");
static final int TEST_SERVER_BASE_PORT = 30210;
static final int TEST_ZK_BASE_PORT = 21820;
static int uid = 0;
@Parameters
public static Collection<Object[]> startActions() {
return Arrays.asList(new Object[][] {{START_ACTION.CREATE},
{START_ACTION.START},
{START_ACTION.RECOVER}});
}
/**
* The start action to use for some of the tests
*/
protected final START_ACTION action;
public TestRestoreAgent(START_ACTION action) {
this.action = action;
}
class MockSnapshotMonitor extends SnapshotCompletionMonitor {
@Override
public void init(final ZooKeeper zk) {
try {
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
List<String> children = zk.getChildren(VoltZK.root, this);
for (String s : children) {
if (s.equals("request_truncation_snapshot")) {
snapshotted = true;
LinkedList<SnapshotCompletionInterest> interests =
new LinkedList<SnapshotCompletionInterest>(m_interests);
for (SnapshotCompletionInterest i : interests) {
i.snapshotCompleted( "", 0, new long[0], true);
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
zk.getChildren(VoltZK.root, watcher);
} catch (Exception e) {
e.printStackTrace();
}
}
}
List<File> paths = new ArrayList<File>();
private SnapshotCompletionMonitor snapshotMonitor = null;
boolean snapshotted = false;
HashMap<Integer, SiteTracker> siteTrackers = null;
CatalogContext context;
File catalogJarFile;
String deploymentPath;
private final AtomicInteger m_count = new AtomicInteger();
volatile int m_hostCount = 0;
volatile boolean m_done = false;
final Set<String> m_unexpectedSPIs = new HashSet<String>();
protected Long snapshotTxnId = null;
/**
* A mock initiator that checks if the we have all the initiations we
* expect.
*/
class MockInitiator extends TransactionInitiator {
private final Map<String, Long> procCounts = new HashMap<String, Long>();
public MockInitiator(Set<String> procNames) {
if (procNames != null) {
for (String proc : procNames) {
procCounts.put(proc, 0l);
}
}
}
public Map<String, Long> getProcCounts() {
return procCounts;
}
@Override
public boolean createTransaction(long connectionId,
String connectionHostname,
boolean adminConnection,
StoredProcedureInvocation invocation,
boolean isReadOnly,
boolean isSinglePartition,
boolean isEverySite,
int[] partitions,
int numPartitions,
Object clientData,
int messageSize,
long now,
boolean allowMismatchedResults) {
createTransaction(connectionId, connectionHostname, adminConnection,
0, 0, invocation, isReadOnly, isSinglePartition,
isEverySite, partitions, numPartitions,
clientData, messageSize, now, allowMismatchedResults);
return true;
}
@Override
public boolean createTransaction(long connectionId,
String connectionHostname,
boolean adminConnection,
long txnId,
long timestamp,
StoredProcedureInvocation invocation,
boolean isReadOnly,
boolean isSinglePartition,
boolean isEverySite,
int[] partitions,
int numPartitions,
Object clientData,
int messageSize,
long now,
boolean allowMismatchedResults) {
String procName = invocation.procName;
if (!procCounts.containsKey(procName)) {
m_unexpectedSPIs.add(procName);
} else {
procCounts.put(procName, procCounts.get(procName) + 1);
}
// Fake success
ColumnInfo[] columns = new ColumnInfo[] {new ColumnInfo("RESULT", VoltType.STRING)};
VoltTable result = new VoltTable(columns);
result.addRow("SUCCESS");
VoltTable[] results = new VoltTable[] {result};
ClientResponseImpl response = new ClientResponseImpl(ClientResponse.SUCCESS,
results, null);
ByteBuffer buf = ByteBuffer.allocate(response.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
response.flattenToBuffer(buf);
buf.flip();
((WriteStream) clientData).enqueue(buf);
return true;
}
@Override
public long tick() {
throw new UnsupportedOperationException();
}
@Override
public long getMostRecentTxnId() {
throw new UnsupportedOperationException();
}
@Override
public void notifyExecutionSiteRejoin(ArrayList<Long> executorSiteIds) {
throw new UnsupportedOperationException();
}
@Override
public Map<Long, long[]> getOutstandingTxnStats() {
throw new UnsupportedOperationException();
}
@Override
protected void increaseBackpressure(int messageSize) {
throw new UnsupportedOperationException();
}
@Override
protected void reduceBackpressure(int messageSize) {
throw new UnsupportedOperationException();
}
@Override
public void setSendHeartbeats(boolean val) {
}
@Override
public void sendHeartbeat(long txnId) {
}
@Override
public boolean isOnBackPressure() {
return false;
}
@Override
public void removeConnectionStats(long connectionId) {
}
}
void buildCatalog(int hostCount, int sitesPerHost, int kfactor, String voltroot,
boolean excludeProcs, boolean rebuildAll)
throws Exception {
/*
* This suite is intended only to test RestoreAgentWithout command logging.
* They fail with the pro build and command logging enabled because they are
* testing for community before. TestRestoreAgentWithReplay tests with CL enabled.
* We do want to check that the community edition doesn't barf if command logging is
* accidentally request, and we want to run these tests with the pro build as well
* so we switch CL enabled on whether this is a pro build.
*/
buildCatalog(hostCount, sitesPerHost, kfactor, voltroot, isEnterprise() ? false : true,
excludeProcs, rebuildAll);
}
/**
* Build a new catalog context.
*
* @param hostCount
* @param sitesPerHost
* @param kfactor
* @param voltroot
* @param excludeProcs used to create a different catalog to check CRC match
* @param rebuildAll TODO
* @throws IOException
*/
void buildCatalog(int hostCount, int sitesPerHost, int kfactor, String voltroot,
boolean commandLog, boolean excludeProcs, boolean rebuildAll)
throws Exception {
VoltProjectBuilder builder = new VoltProjectBuilder();
String schema = "create table A (i integer not null, s varchar(30), sh smallint, l bigint, primary key (i));";
builder.addLiteralSchema(schema);
builder.addPartitionInfo("A", "i");
builder.addStmtProcedure("hello", "select * from A where i = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("world", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
if (!excludeProcs)
{
builder.addStmtProcedure("bid", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("sum", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("calc", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("HowWillAppleNameItsVaccuumCleaner", "select * from A where l = ? and sh = ? and s = ?");
builder.addStmtProcedure("Dedupe", "select * from A where l = ? and sh = ?");
builder.addStmtProcedure("Cill", "select * from A where l = ? and s = ?");
}
builder.configureLogging(voltroot, voltroot, false, commandLog, 200, 20000, 300);
File cat = File.createTempFile("temp-restore", "catalog");
cat.deleteOnExit();
assertTrue(builder.compile(cat.getAbsolutePath(), sitesPerHost,
hostCount, kfactor, voltroot));
deploymentPath = builder.getPathToDeployment();
File cat_to_use = cat;
if (rebuildAll)
{
catalogJarFile = cat;
}
else
{
cat_to_use = catalogJarFile;
}
byte[] bytes = CatalogUtil.toBytes(cat_to_use);
String serializedCat = CatalogUtil.loadCatalogFromJar(bytes, null);
assertNotNull(serializedCat);
Catalog catalog = new Catalog();
catalog.execute(serializedCat);
ClusterConfig config = new ClusterConfig(hostCount, sitesPerHost, kfactor);
List<Integer> hostIds = new ArrayList<Integer>(hostCount);
for (int ii = 0; ii < hostCount; ii++) hostIds.add(ii);
JSONObject topology = config.getTopology(hostIds);
long crc = CatalogUtil.compileDeploymentAndGetCRC(catalog, deploymentPath,
true);
context = new CatalogContext(0, catalog, bytes, crc, 0, 0);
siteTrackers = new HashMap<Integer, SiteTracker>();
// create MailboxNodeContexts for all hosts (we only need getAllHosts(), I think)
for (int i = 0; i < hostCount; i++)
{
ArrayList<MailboxNodeContent> hosts = new ArrayList<MailboxNodeContent>();
for (int j = 0; j < hostCount; j++)
{
List<Integer> localPartitions = ClusterConfig.partitionsForHost(topology, j);
for (int zz = 0; zz < localPartitions.size(); zz++) {
MailboxNodeContent mnc =
new MailboxNodeContent(CoreUtils.getHSIdFromHostAndSite(j, zz), localPartitions.get(zz));
hosts.add(mnc);
}
}
HashMap<MailboxType, List<MailboxNodeContent>> blah =
new HashMap<MailboxType, List<MailboxNodeContent>>();
blah.put(MailboxType.ExecutionSite, hosts);
siteTrackers.put(i, new SiteTracker(i, blah));
}
}
/**
* Take a snapshot
* @throws IOException
*/
void snapshot() throws Exception {
String path = context.cluster.getVoltroot() + File.separator + "snapshots";
ClientConfig clientConfig = new ClientConfig();
Client client = ClientFactory.createClient(clientConfig);
ClientResponse response = null;
try {
client.createConnection("localhost");
try {
response = client.callProcedure("@SnapshotSave",
path,
"hello",
1);
} catch (ProcCallException e) {
fail(e.getMessage());
}
} finally {
client.close();
}
assertEquals(ClientResponse.SUCCESS, response.getStatus());
assertEquals(1, response.getResults().length);
assertTrue(response.getResults()[0].advanceRow());
assertEquals("SUCCESS", response.getResults()[0].getString("RESULT"));
}
/**
* Generate a new voltroot with the given suffix. Will be automatically
* cleaned after the test.
*
* @param suffix
* @return The new voltroot
* @throws IOException
*/
String newVoltRoot(String suffix) throws IOException {
if (suffix == null) {
suffix = "";
}
File path = File.createTempFile("temp", "restore-test-" + suffix);
path.delete();
path = new VoltFile(path.getAbsolutePath());
assertTrue(path.mkdir());
paths.add(path);
return path.getAbsolutePath();
}
@Before
public void setUp() throws Exception {
m_count.set(0);
m_done = false;
snapshotted = false;
m_unexpectedSPIs.clear();
setUpZK(1);
getClient(0).create("/db", null, Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
snapshotMonitor = new MockSnapshotMonitor();
snapshotMonitor.init(getClient(0));
}
@After
public void tearDown() throws Exception {
tearDownZK();
if (snapshotMonitor != null) {
snapshotMonitor.shutdown();
}
String msg = "";
for (String name : m_unexpectedSPIs) {
msg += name + ", ";
}
assertTrue(msg, m_unexpectedSPIs.isEmpty());
for (File p : paths) {
VoltFile.recursivelyDelete(p);
}
}
/**
* Check if nothing is recovered if the action is create
* @param initiator
*/
protected void createCheck(MockInitiator initiator) {
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
assertFalse(snapshotted);
if (!initiator.getProcCounts().isEmpty()) {
for (long count : initiator.getProcCounts().values()) {
assertEquals(0, count);
}
}
}
private boolean isEnterprise() {
return VoltDB.instance().getConfig().m_isEnterprise;
}
protected RestoreAgent getRestoreAgent(MockInitiator initiator, int hostId) throws Exception {
String snapshotPath = null;
if (context.cluster.getDatabases().get("database").getSnapshotschedule().get("default") != null) {
snapshotPath = context.cluster.getDatabases().get("database").getSnapshotschedule().get("default").getPath();
}
SiteTracker st = siteTrackers.get(hostId);
int[] allPartitions = st.getAllPartitions();
org.voltdb.catalog.CommandLog cl = context.cluster.getLogconfig().get("log");
Set<Integer> all_hosts = new HashSet<Integer>();
for (int host = 0; host < m_hostCount; host++)
{
all_hosts.add(host);
}
RestoreAgent restoreAgent = new RestoreAgent(getClient(0),
snapshotMonitor, this,
hostId, this.action,
cl.getEnabled(),
cl.getLogpath(),
cl.getInternalsnapshotpath(),
snapshotPath,
allPartitions,
all_hosts);
restoreAgent.setCatalogContext(context);
restoreAgent.setSiteTracker(siteTrackers.get(hostId));
assert(initiator != null);
restoreAgent.setInitiator(initiator);
return restoreAgent;
}
@Test
public void testSingleHostEmptyRestore() throws Exception {
m_hostCount = 1;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
MockInitiator initiator = new MockInitiator(null);
RestoreAgent restoreAgent = getRestoreAgent(initiator, 0);
restoreAgent.createZKDirectory(VoltZK.restore);
restoreAgent.createZKDirectory(VoltZK.restore_barrier);
restoreAgent.createZKDirectory(VoltZK.restore_barrier + "2");
restoreAgent.enterRestore();
assertNull(restoreAgent.generatePlans());
}
@Test
public void testMultipleHostEmptyRestore() throws Exception {
m_hostCount = 3;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
MockInitiator initiator = new MockInitiator(null);
List<RestoreAgent> agents = new ArrayList<RestoreAgent>();
for (int i = 0; i < m_hostCount; i++) {
agents.add(getRestoreAgent(initiator, i));
}
ExecutorService ex = Executors.newFixedThreadPool(3);
final AtomicInteger failure = new AtomicInteger();
for (final RestoreAgent agent : agents) {
ex.submit(new Runnable() {
@Override
public void run() {
agent.createZKDirectory(VoltZK.restore);
agent.createZKDirectory(VoltZK.restore_barrier);
agent.createZKDirectory(VoltZK.restore_barrier + "2");
agent.enterRestore();
try {
if (agent.generatePlans() != null) {
failure.incrementAndGet();
}
} catch (Exception e) {
failure.incrementAndGet();
}
}
});
}
ex.shutdown();
assertTrue(ex.awaitTermination(10, TimeUnit.SECONDS));
assertEquals(0, failure.get());
}
@Test
public void testMultipleHostAgreementFailure() throws Exception {
// Don't run this test if we are in recovery mode
if (action == START_ACTION.RECOVER) {
return;
}
m_hostCount = 3;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
MockInitiator initiator = new MockInitiator(null);
List<RestoreAgent> agents = new ArrayList<RestoreAgent>();
for (int i = 0; i < m_hostCount - 1; i++) {
agents.add(getRestoreAgent(initiator, i));
}
for (RestoreAgent agent : agents) {
agent.restore();
}
int count = 0;
while (!m_done && count++ < 10) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (m_done) {
fail();
}
// Start the last restore agent, should be able to reach agreement now
RestoreAgent agent = getRestoreAgent(initiator, m_hostCount - 1);
agent.restore();
count = 0;
while (!m_done && count++ < 10) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
if (!m_done) {
fail();
}
assertFalse(snapshotted);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
}
@Test
public void testSingleHostSnapshotRestore() throws Exception {
m_hostCount = 1;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
ServerThread server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT + 1,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot();
server.shutdown();
HashSet<String> procs = new HashSet<String>();
procs.add("@SnapshotRestore");
MockInitiator initiator = new MockInitiator(procs);
RestoreAgent restoreAgent = getRestoreAgent(initiator, 0);
restoreAgent.restore();
while (!m_done) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (action != START_ACTION.CREATE) {
Long count = initiator.getProcCounts().get("@SnapshotRestore");
assertEquals(new Long(1), count);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
} else {
createCheck(initiator);
}
}
@Test
public void testSingleHostSnapshotRestoreCatalogChange() throws Exception {
m_hostCount = 1;
String voltroot = newVoltRoot(null);
buildCatalog(m_hostCount, 8, 0, voltroot, false, true);
ServerThread server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot();
server.shutdown();
buildCatalog(m_hostCount, 8, 0, voltroot, true, true);
HashSet<String> procs = new HashSet<String>();
procs.add("@SnapshotRestore");
MockInitiator initiator = new MockInitiator(procs);
RestoreAgent restoreAgent = getRestoreAgent(initiator, 0);
restoreAgent.restore();
while (!m_done) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (action != START_ACTION.CREATE) {
Long count = initiator.getProcCounts().get("@SnapshotRestore");
assertEquals(new Long(1), count);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
} else {
createCheck(initiator);
}
}
@Test
public void testMultiHostSnapshotRestore() throws Exception {
m_hostCount = 1;
String voltroot = newVoltRoot(null);
buildCatalog(m_hostCount, 8, 0, voltroot, false, true);
ServerThread server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot();
server.shutdown();
m_hostCount = 3;
buildCatalog(m_hostCount, 8, 1, voltroot, false, true);
HashSet<String> procs = new HashSet<String>();
procs.add("@SnapshotRestore");
MockInitiator initiator = new MockInitiator(procs);
List<RestoreAgent> agents = new ArrayList<RestoreAgent>();
for (int i = 0; i < m_hostCount; i++) {
agents.add(getRestoreAgent(initiator, i));
}
for (RestoreAgent agent : agents) {
agent.restore();
}
while (!m_done) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (action != START_ACTION.CREATE) {
Long count = initiator.getProcCounts().get("@SnapshotRestore");
assertEquals(new Long(1), count);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
} else {
createCheck(initiator);
}
}
@Test
public void testConsistentRestorePlan() {
List<SnapshotInfo> infos = new ArrayList<SnapshotInfo>();
SnapshotInfo info1 = new SnapshotInfo(0, "blah", "nonce", 3, 0, 0);
SnapshotInfo info2 = new SnapshotInfo(0, "blah", "nonce", 3, 0, 1);
infos.add(info1);
infos.add(info2);
- SnapshotInfo pickedInfo = RestoreAgent.pickSnapshotInfo(infos);
+ SnapshotInfo pickedInfo = RestoreAgent.consolidateSnapshotInfos(infos);
assertNotNull(pickedInfo);
assertEquals(0, pickedInfo.hostId);
// Inverse the order we add infos
infos.clear();
infos.add(info2);
infos.add(info1);
- pickedInfo = RestoreAgent.pickSnapshotInfo(infos);
+ pickedInfo = RestoreAgent.consolidateSnapshotInfos(infos);
assertNotNull(pickedInfo);
assertEquals(0, pickedInfo.hostId);
}
@Override
public void onRestoreCompletion(long txnId) {
if (snapshotTxnId != null) {
assertEquals(snapshotTxnId.longValue(), txnId);
}
snapshotTxnId = txnId;
if (m_count.incrementAndGet() == m_hostCount) {
m_done = true;
}
}
void addSnapshotInfo(Map<Long, Set<SnapshotInfo>> frags,
long txnid, long crc)
{
Set<SnapshotInfo> si = null;
if (frags.containsKey(txnid))
{
si = frags.get(txnid);
}
else
{
si = new HashSet<SnapshotInfo>();
frags.put(txnid, si);
}
si.add(new SnapshotInfo(txnid, "dummy", "dummy", 1, crc, -1));
}
}
| false | false | null | null |
diff --git a/org.amanzi.awe.gpeh/src/org/amanzi/awe/gpeh/GpehCSVSaver.java b/org.amanzi.awe.gpeh/src/org/amanzi/awe/gpeh/GpehCSVSaver.java
index 3b5aedc10..84e982df9 100644
--- a/org.amanzi.awe.gpeh/src/org/amanzi/awe/gpeh/GpehCSVSaver.java
+++ b/org.amanzi.awe.gpeh/src/org/amanzi/awe/gpeh/GpehCSVSaver.java
@@ -1,241 +1,245 @@
/* AWE - Amanzi Wireless Explorer
* http://awe.amanzi.org
* (C) 2008-2009, AmanziTel AB
*
* This library is provided under the terms of the Eclipse Public License
* as described at http://www.eclipse.org/legal/epl-v10.html. Any use,
* reproduction or distribution of the library constitutes recipient's
* acceptance of this agreement.
*
* This library is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.amanzi.awe.gpeh;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.amanzi.awe.gpeh.parser.Events;
import org.amanzi.awe.gpeh.parser.Parameters;
import org.amanzi.awe.gpeh.parser.internal.GPEHEvent.Event;
import org.amanzi.neo.loader.core.saver.ISaver;
import org.amanzi.neo.loader.core.saver.MetaData;
/**
* Class to save GPEH-data in csv-format
* <p>
*
* </p>
* @author Kasnitskij_V
* @since 1.0.0
*/
public class GpehCSVSaver implements ISaver<GpehTransferData> {
// opened files
private Map<Integer,CsvFile> openedFiles = new HashMap<Integer,CsvFile>();
// output directory to saving csv-files
private String outputDirectory = null;
// global timestamp, event id and csvfile to working in future
private long globalTimestamp = 0;
private int globalEventId = 0;
private CsvFile csvFileToWork = null;
// headers to write in file
private ArrayList<String> headers = new ArrayList<String>();
// it's constant to present timestamp
private final static String TIMESTAMP = "timestamp";
// it's constant to present format of date to name of file
private final static String SIMPLE_DATE_FORMAT = "yyyyMMddHHmm";
// it's constant to present format of file
private final static String FILE_FORMAT = ".txt";
// it's constant using in building name of file
private final static SimpleDateFormat simpleDateFormat =
new SimpleDateFormat(SIMPLE_DATE_FORMAT);
private PrintStream outputStream;
// time of before loading and after loading
private long beforeLoading = 0, afterLoading = 0;
// starting timestamp
private long startTimestamp = 0;
// count of loaded files
private int countOfLoadedFiles = 0;
// count of events
private long count = 0;
+ // true if file to write is new
+ private boolean isNewFile = false;
@Override
public void init(GpehTransferData element) {
outputDirectory = element.get(GpehTransferData.OUTPUT_DIRECTORY).toString();
beforeLoading = System.currentTimeMillis();
}
@Override
public void save(GpehTransferData element) {
count++;
long timestamp = (Long)element.get(TIMESTAMP);
if (globalTimestamp != timestamp) {
if (globalTimestamp != 0)
closeOpenFiles();
if (startTimestamp == 0)
startTimestamp = timestamp;
globalTimestamp = timestamp;
+ isNewFile = true;
}
// read id of event
Event event = (Event)element.remove(GpehTransferData.EVENT);
int eventId = event.getId();
if (openedFiles.get(eventId) == null) {
Events events = Events.findById(eventId);
Date date = new Date(globalTimestamp);
String meContext = (String) element.get(GpehTransferData.ME_CONTEXT);
String wayToFile = outputDirectory + "\\" + "Event_" + eventId + "_" +
(simpleDateFormat.format(date)) + "_" + meContext + FILE_FORMAT;
// create new file
File file = new File(wayToFile);
CsvFile csvFile;
try {
csvFile = new CsvFile(file);
} catch (IOException e1) {
throw new RuntimeException("Sorry. Can not create new file. Loading stopped.");
}
// add id to file to associate his with some event
csvFile.setEventId(eventId);
openedFiles.put(eventId,csvFile);
// create headers
Parameters[] parameters = events.getAllParametersWithTimestamp();
// create array list of headers
ArrayList<String> headers = new ArrayList<String>();
for (Parameters parameter : parameters) {
headers.add(parameter.name());
}
// add headers to csvfile
csvFile.setHeaders(headers);
// write headers to csvfile
try {
csvFile.writeHeaders(headers);
headers.remove(Parameters.EVENT_PARAM_TIMESTAMP_HOUR.toString());
headers.remove(Parameters.EVENT_PARAM_TIMESTAMP_MINUTE.toString());
headers.remove(Parameters.EVENT_PARAM_TIMESTAMP_SECOND.toString());
headers.remove(Parameters.EVENT_PARAM_TIMESTAMP_MILLISEC.toString());
} catch (IOException e) {
throw new RuntimeException("Sorry. Can not write data to file. Loading stopped.");
}
}
// get headers from csvfile
- if (globalEventId != eventId) {
+ if (globalEventId != eventId || isNewFile) {
+ isNewFile = false;
globalEventId = eventId;
csvFileToWork = openedFiles.get(eventId);
headers = csvFileToWork.getHeaders();
}
String scannerId = null;
try {
scannerId = element.get(Parameters.EVENT_PARAM_SCANNER_ID.toString()).toString();
}
catch (Exception e) {
}
// delete scanner id from headers
headers.remove(Parameters.EVENT_PARAM_SCANNER_ID.toString());
// create array list of data
ArrayList<String> data = new ArrayList<String>();
data.add(scannerId);
data.add(Long.toString(event.getHour()));
data.add(Long.toString(event.getMinute()));
data.add(Long.toString(event.getSecond()));
data.add(Long.toString(event.getMillisecond()));
String currentHeaderValue = null;
for (String header : headers) {
if (element.get(header) != null) {
if (header.equals(Parameters.EVENT_PARAM_MESSAGE_CONTENTS.toString())) {
currentHeaderValue = new String((byte[])element.get(header));
}
else {
currentHeaderValue = element.get(header).toString();
}
}
data.add(currentHeaderValue);
currentHeaderValue = null;
}
// write data to needing csvfile
try {
csvFileToWork.writeData(data);
} catch (IOException e) {
throw new RuntimeException("Sorry. Can not write data to file. Loading stopped.");
}
}
@Override
public void finishUp(GpehTransferData element) {
outputStream.println("Number of events = " + count);
closeOpenFiles();
afterLoading = System.currentTimeMillis();
long timeOfLoading = afterLoading - beforeLoading;
outputStream.println(countOfLoadedFiles + " files converted");
outputStream.println("Full time of loading = " +
(timeOfLoading) + " millisecond");
outputStream.println("Speed of loading = " + (int)(count/timeOfLoading) + " events/millisecond");
String periodDateFormat = new java.text.SimpleDateFormat("hh:mm").format(startTimestamp) + " - " +
new java.text.SimpleDateFormat("hh:mm").format(globalTimestamp + 900000);
outputStream.println("Period of converted files: " + periodDateFormat + "(HOURS:MINUTES)");
}
@Override
public PrintStream getPrintStream() {
if (outputStream==null){
return System.out;
}
return outputStream;
}
@Override
public void setPrintStream(PrintStream outputStream) {
this.outputStream = outputStream;
}
@Override
public Iterable<MetaData> getMetaData() {
return null;
}
// all files is closed here
private void closeOpenFiles() {
for (CsvFile csvFile : openedFiles.values()) {
try {
csvFile.close();
} catch (IOException e) {
throw new RuntimeException("Sorry. Can not close file and can not write data to file. Loading stopped.");
}
}
countOfLoadedFiles += openedFiles.size();
openedFiles.clear();
}
}
| false | false | null | null |
diff --git a/src/main/java/org/jboss/as/weld/deployment/processors/WebIntegrationProcessor.java b/src/main/java/org/jboss/as/weld/deployment/processors/WebIntegrationProcessor.java
index 021911c..e074111 100644
--- a/src/main/java/org/jboss/as/weld/deployment/processors/WebIntegrationProcessor.java
+++ b/src/main/java/org/jboss/as/weld/deployment/processors/WebIntegrationProcessor.java
@@ -1,115 +1,118 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.web.deployment.WarDeploymentMarker;
import org.jboss.as.web.deployment.WarMetaData;
import org.jboss.as.weld.WeldDeploymentMarker;
import org.jboss.logging.Logger;
import org.jboss.metadata.web.spec.FilterMappingMetaData;
import org.jboss.metadata.web.spec.FilterMetaData;
import org.jboss.metadata.web.spec.FiltersMetaData;
import org.jboss.metadata.web.spec.ListenerMetaData;
import org.jboss.metadata.web.spec.WebMetaData;
/**
* Deployment processor that integrates weld into the web tier
*
* @author Stuart Douglas
*/
public class WebIntegrationProcessor implements DeploymentUnitProcessor {
private final ListenerMetaData WBL;
private final ListenerMetaData JIL;
private final FilterMetaData CPF;
private final FilterMappingMetaData CPFM;
private static final Logger log = Logger.getLogger("org.jboss.as.weld");
public WebIntegrationProcessor() {
// create wbl listener
WBL = new ListenerMetaData();
WBL.setListenerClass("org.jboss.weld.servlet.WeldListener");
JIL = new ListenerMetaData();
JIL.setListenerClass("org.jboss.as.weld.webtier.jsp.JspInitializationListener");
CPF = new FilterMetaData();
CPF.setFilterName("Weld Conversation Propagation Filter");
CPF.setFilterClass("org.jboss.weld.servlet.ConversationPropagationFilter");
CPFM = new FilterMappingMetaData();
CPFM.setFilterName("Weld Conversation Propagation Filter");
CPFM.setUrlPatterns(Arrays.asList("/*"));
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!WarDeploymentMarker.isWarDeployment(deploymentUnit)) {
return; // Skip non web deployments
}
if(!WeldDeploymentMarker.isWeldDeployment(deploymentUnit)) {
return; // skip non weld deployments
}
WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
if (warMetaData == null) {
log.info("Not installing Weld web tier integration as no war metadata found");
return;
}
WebMetaData webMetaData = warMetaData.getWebMetaData();
-
+ if (webMetaData == null) {
+ log.info("Not installing Weld web tier integration as no web metadata found");
+ return;
+ }
List<ListenerMetaData> listeners = webMetaData.getListeners();
if (listeners == null) {
listeners = new ArrayList<ListenerMetaData>();
webMetaData.setListeners(listeners);
}
listeners.add(0, WBL);
listeners.add(1, JIL);
FiltersMetaData filters = webMetaData.getFilters();
if (filters == null) {
filters = new FiltersMetaData();
webMetaData.setFilters(filters);
}
filters.add(CPF);
List<FilterMappingMetaData> filterMappings = webMetaData.getFilterMappings();
if (filterMappings == null) {
filterMappings = new ArrayList<FilterMappingMetaData>();
webMetaData.setFilterMappings(filterMappings);
}
filterMappings.add(CPFM);
}
@Override
public void undeploy(DeploymentUnit context) {
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/amrcci/EssentialsTPA.java b/src/amrcci/EssentialsTPA.java
index c8b42ad..803973d 100644
--- a/src/amrcci/EssentialsTPA.java
+++ b/src/amrcci/EssentialsTPA.java
@@ -1,47 +1,46 @@
package amrcci;
-import java.lang.reflect.Method;
-
import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class EssentialsTPA implements Listener {
Essentials ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials");
@EventHandler(priority=EventPriority.HIGH,ignoreCancelled=true)
public void onEssTPA(PlayerCommandPreprocessEvent event)
{
final String[] cmds = event.getMessage().split("\\s+");
if (cmds[0].equalsIgnoreCase("/tpaccept"))
{
try {
- Method getUserMethod = ess.getClass().getDeclaredMethod("getUser", Player.class);
- getUserMethod.setAccessible(true);
- User essuser = (User) getUserMethod.invoke(ess, event.getPlayer());
- User requester = (User) getUserMethod.invoke(ess, Bukkit.getPlayerExact(essuser.getTeleportRequest()));
- if (requester != null && requester.isOnline())
+ User essuser = ess.getUser(event.getPlayer());
+ String steleporter = essuser.getTeleportRequest();
+ if (steleporter != null)
{
- PlayerCommandPreprocessEvent fakeevent = new PlayerCommandPreprocessEvent(requester.getPlayer(), "/faketpaccept");
- Bukkit.getPluginManager().callEvent(fakeevent);
- if (fakeevent.isCancelled())
+ User requester = ess.getUser(Bukkit.getPlayerExact(steleporter));
+ if (requester != null && requester.isOnline())
{
- event.setCancelled(true);
+ PlayerCommandPreprocessEvent fakeevent = new PlayerCommandPreprocessEvent(requester.getPlayer(), "/faketpaccept");
+ Bukkit.getPluginManager().callEvent(fakeevent);
+ if (fakeevent.isCancelled())
+ {
+ event.setCancelled(true);
+ }
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| false | false | null | null |
diff --git a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/Computation.java b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/Computation.java
index 9a7aa8f28..dd0376807 100644
--- a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/Computation.java
+++ b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/Computation.java
@@ -1,170 +1,171 @@
/*******************************************************************************
* Copyright (c) 2009, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.e4.core.services.internal.context;
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.eclipse.e4.core.services.context.ContextChangeEvent;
import org.eclipse.e4.core.services.context.IEclipseContext;
import org.eclipse.e4.core.services.injector.IObjectProvider;
import org.eclipse.e4.core.services.internal.context.EclipseContext.Scheduled;
abstract class Computation {
Map<IEclipseContext, Set<String>> dependencies = new HashMap<IEclipseContext, Set<String>>();
void addDependency(IEclipseContext context, String name) {
Set<String> properties = dependencies.get(context);
if (properties == null) {
properties = new HashSet<String>(4);
dependencies.put(context, properties);
}
properties.add(name);
}
final void clear(IEclipseContext context, String name) {
doClear();
stopListening(context, name);
}
protected void doClear() {
// nothing to do in default computation
}
protected void doHandleInvalid(ContextChangeEvent event, List<Scheduled> scheduled) {
// nothing to do in default computation
}
/**
* Computations must define equals because they are stored in a set.
*/
public abstract boolean equals(Object arg0);
final void handleInvalid(ContextChangeEvent event, List<Scheduled> scheduled) {
IObjectProvider provider = event.getContext();
IEclipseContext context = ((ObjectProviderContext) provider).getContext();
String name = event.getName();
Set<String> names = dependencies.get(context);
if (name == null && event.getEventType() == ContextChangeEvent.DISPOSE) {
clear(context, null);
doHandleInvalid(event, scheduled);
} else if (names != null && names.contains(name)) {
clear(context, name);
doHandleInvalid(event, scheduled);
}
}
final void handleUninjected(ContextChangeEvent event, List<Scheduled> scheduled) {
doHandleInvalid(event, scheduled);
}
/**
* Computations must define hashCode because they are stored in a set.
*/
public abstract int hashCode();
private String mapToString(Map<IEclipseContext, Set<String>> map) {
StringBuffer result = new StringBuffer('{');
for (Iterator<Map.Entry<IEclipseContext, Set<String>>> it = map.entrySet().iterator(); it
.hasNext();) {
Map.Entry<IEclipseContext, Set<String>> entry = it.next();
result.append(entry.getKey());
result.append("->("); //$NON-NLS-1$
Set<String> set = entry.getValue();
for (Iterator<String> it2 = set.iterator(); it2.hasNext();) {
String name = it2.next();
result.append(name);
if (it2.hasNext()) {
result.append(',');
}
}
result.append(')');
if (it.hasNext()) {
result.append(',');
}
}
return result.toString();
}
/**
* Remove this computation from all contexts that are tracking it
*/
protected void removeAll(EclipseContext originatingContext) {
for (Iterator<IEclipseContext> it = dependencies.keySet().iterator(); it.hasNext();) {
((EclipseContext) it.next()).listeners.remove(this);
}
dependencies.clear();
// Bug 304859
originatingContext.listeners.remove(this);
}
void startListening(EclipseContext originatingContext) {
if (EclipseContext.DEBUG)
System.out.println(toString() + " now listening to: " //$NON-NLS-1$
+ mapToString(dependencies));
for (Iterator<IEclipseContext> it = dependencies.keySet().iterator(); it.hasNext();) {
EclipseContext c = (EclipseContext) it.next(); // XXX IEclipseContex
if (c.listeners.contains(this)) { // nested
for (Iterator<Computation> existing = c.listeners.iterator(); existing.hasNext();) {
Computation existingComputation = existing.next();
- if (!equals(existingComputation))
+ // if the existing computation is equal but not identical, we need to update
+ if (!equals(existingComputation) || this == existingComputation)
continue;
for (Iterator<IEclipseContext> newDependencies = dependencies.keySet()
.iterator(); newDependencies.hasNext();) {
IEclipseContext newDependencyContext = newDependencies.next();
if (existingComputation.dependencies.containsKey(newDependencyContext))
existingComputation.dependencies.get(newDependencyContext).addAll(
dependencies.get(newDependencyContext));
else
existingComputation.dependencies.put(newDependencyContext, dependencies
.get(newDependencyContext));
}
break;
}
} else
c.listeners.add(this);
}
// Bug 304859
if (!dependencies.containsKey(originatingContext))
originatingContext.listeners.remove(this);
}
protected void stopListening(IEclipseContext context, String name) {
if (name == null) {
if (EclipseContext.DEBUG)
System.out.println(toString() + " no longer listening to " + context); //$NON-NLS-1$
dependencies.remove(context);
return;
}
Set<String> properties = dependencies.get(context);
if (properties != null) {
if (EclipseContext.DEBUG)
System.out.println(toString() + " no longer listening to " + context + ',' + name); //$NON-NLS-1$
// Bug 304859 - causes reordering of listeners
// ((EclipseContext) context).listeners.remove(this); // XXX
// IEclipseContext
properties.remove(name);
// if we no longer track any values in the context, remove dependency
if (properties.isEmpty())
dependencies.remove(context);
}
}
public Set<String> dependsOnNames(IEclipseContext context) {
return dependencies.get(context);
}
}
\ No newline at end of file
diff --git a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/EclipseContext.java b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/EclipseContext.java
index 9a704d40a..cf4edc5ef 100644
--- a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/EclipseContext.java
+++ b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/EclipseContext.java
@@ -1,650 +1,653 @@
/*******************************************************************************
* Copyright (c) 2009, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.e4.core.services.internal.context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
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.eclipse.e4.core.services.IDisposable;
import org.eclipse.e4.core.services.context.ContextChangeEvent;
import org.eclipse.e4.core.services.context.EclipseContextFactory;
import org.eclipse.e4.core.services.context.IContextFunction;
import org.eclipse.e4.core.services.context.IEclipseContext;
import org.eclipse.e4.core.services.context.IRunAndTrack;
import org.eclipse.e4.core.services.context.spi.IContextConstants;
import org.eclipse.e4.core.services.context.spi.IEclipseContextStrategy;
import org.eclipse.e4.core.services.context.spi.ILookupStrategy;
import org.eclipse.e4.core.services.context.spi.ISchedulerStrategy;
/**
* This implementation assumes that all contexts are of the class EclipseContext. The external
* methods of it are exposed via IEclipseContext.
*/
public class EclipseContext implements IEclipseContext, IDisposable {
static class LookupKey {
Object[] arguments;
String name;
public LookupKey(String name, Object[] arguments) {
this.name = name;
this.arguments = arguments;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LookupKey other = (LookupKey) obj;
if (!Arrays.equals(arguments, other.arguments))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result;
if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
Object arg = arguments[i];
result = prime * result + (arg == null ? 0 : arg.hashCode());
}
}
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/**
* String representation for debugging purposes only.
*/
public String toString() {
return "Key(" + name + ',' + Arrays.asList(arguments) + ')'; //$NON-NLS-1$
}
}
static class TrackableComputationExt extends Computation implements IRunAndTrack {
private ContextChangeEvent cachedEvent;
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 31 + ((runnable == null) ? 0 : runnable.hashCode());
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TrackableComputationExt other = (TrackableComputationExt) obj;
if (runnable == null) {
if (other.runnable != null)
return false;
} else if (!runnable.equals(other.runnable))
return false;
return true;
}
private IRunAndTrack runnable;
public TrackableComputationExt(IRunAndTrack runnable) {
this.runnable = runnable;
}
public Object getObject() {
if (runnable instanceof IRunAndTrackObject)
return ((IRunAndTrackObject) runnable).getObject();
return null;
}
final protected void doHandleInvalid(ContextChangeEvent event, List<Scheduled> scheduledList) {
int eventType = event.getEventType();
if (eventType == ContextChangeEvent.INITIAL || eventType == ContextChangeEvent.DISPOSE) {
// process right away
notify(event);
} else {
// schedule processing
Scheduled toBeScheduled = new Scheduled(this, event);
for (Iterator<Scheduled> i = scheduledList.iterator(); i.hasNext();) {
Scheduled scheduled = i.next();
if (scheduled.equals(toBeScheduled)) // eliminate duplicates
return;
}
scheduledList.add(toBeScheduled);
}
}
public boolean notify(ContextChangeEvent event) {
// is this a structural event?
// structural changes: INITIAL, DISPOSE, UNINJECTED are always processed right away
int eventType = event.getEventType();
if ((runnable instanceof IRunAndTrackObject)
&& ((IRunAndTrackObject) runnable).batchProcess()) {
if ((eventType == ContextChangeEvent.ADDED)
|| (eventType == ContextChangeEvent.REMOVED)) {
cachedEvent = event;
EclipseContext eventsContext = (EclipseContext) ((ObjectProviderContext) event
.getContext()).getContext();
eventsContext.addWaiting(this);
// eventsContext.getRoot().waiting.add(this);
return true;
}
}
Computation oldComputation = currentComputation.get();
currentComputation.set(this);
boolean result = true;
try {
if (cachedEvent != null) {
result = runnable.notify(cachedEvent);
cachedEvent = null;
}
if (eventType != ContextChangeEvent.UPDATE)
result = runnable.notify(event);
} finally {
currentComputation.set(oldComputation);
}
EclipseContext eventsContext = (EclipseContext) ((ObjectProviderContext) event
.getContext()).getContext();
if (result)
startListening(eventsContext);
else
removeAll(eventsContext);
return result;
}
public String toString() {
return "TrackableComputationExt(" + runnable + ')'; //$NON-NLS-1$
}
}
static class Scheduled {
public IRunAndTrack runnable;
public ContextChangeEvent event;
public Scheduled(IRunAndTrack runnable, ContextChangeEvent event) {
this.runnable = runnable;
this.event = event;
}
public int hashCode() {
return 31 * (31 + event.hashCode()) + runnable.hashCode();
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Scheduled other = (Scheduled) obj;
if (!event.equals(other.event))
return false;
return runnable.equals(other.runnable);
}
}
static class DebugSnap {
- List<Computation> listeners = new ArrayList<Computation>();
+ Set<Computation> listeners = new HashSet<Computation>();
Map<LookupKey, ValueComputation> localValueComputations = Collections
.synchronizedMap(new HashMap<LookupKey, ValueComputation>());
Map<String, Object> localValues = Collections
.synchronizedMap(new HashMap<String, Object>());
}
static ThreadLocal<Computation> currentComputation = new ThreadLocal<Computation>();
// TODO replace with variable on bundle-specific class
public static boolean DEBUG = false;
public static boolean DEBUG_VERBOSE = false;
public static String DEBUG_VERBOSE_NAME = null;
private DebugSnap snapshot;
private static final Object[] NO_ARGUMENTS = new Object[0];
- final List<Computation> listeners = Collections.synchronizedList(new ArrayList<Computation>());
+ final Set<Computation> listeners = Collections.synchronizedSet(new HashSet<Computation>());
final Map<LookupKey, ValueComputation> localValueComputations = Collections
.synchronizedMap(new HashMap<LookupKey, ValueComputation>());
final Map<String, Object> localValues = Collections
.synchronizedMap(new HashMap<String, Object>());
private final IEclipseContextStrategy strategy;
private ArrayList<String> modifiable;
private ArrayList<Computation> waiting; // list of Computations; null for all non-root entries
public EclipseContext(IEclipseContext parent, IEclipseContextStrategy strategy) {
this.strategy = strategy;
set(IContextConstants.PARENT, parent);
if (parent == null)
waiting = new ArrayList<Computation>();
}
public boolean containsKey(String name) {
return containsKey(name, false);
}
public boolean containsKey(String name, boolean localOnly) {
if (isSetLocally(name))
return true;
if (localOnly)
return false;
IEclipseContext parent = (IEclipseContext) getLocal(IContextConstants.PARENT);
if (parent != null && parent.containsKey(name))
return true;
if (strategy instanceof ILookupStrategy) {
if (((ILookupStrategy) strategy).containsKey(name, this))
return true;
}
return false;
}
/**
* Remember a snapshot of this context state for debugging purposes.
*/
public void debugSnap() {
snapshot = new DebugSnap();
- snapshot.listeners = new ArrayList<Computation>(listeners);
+ snapshot.listeners = new HashSet<Computation>(listeners);
snapshot.localValueComputations = new HashMap<LookupKey, ValueComputation>(
localValueComputations);
snapshot.localValues = new HashMap<String, Object>(localValues);
}
/**
* Print a diff between the current context state and the last snapshot state
*/
public void debugDiff() {
if (snapshot == null)
return;
- List<Computation> listenerDiff = new ArrayList<Computation>(listeners);
+ Set<Computation> listenerDiff = new HashSet<Computation>(listeners);
listenerDiff.removeAll(snapshot.listeners);
- listenerDiff = new ArrayList<Computation>(listenerDiff);// shrink the set
+ listenerDiff = new HashSet<Computation>(listenerDiff);// shrink the set
System.out.println("Listener diff: "); //$NON-NLS-1$
for (Iterator<Computation> it = listenerDiff.iterator(); it.hasNext();) {
System.out.println("\t" + it.next()); //$NON-NLS-1$
}
Set<ValueComputation> computationDiff = new HashSet<ValueComputation>(
localValueComputations.values());
computationDiff.removeAll(snapshot.localValueComputations.values());
System.out.println("localValueComputations diff:"); //$NON-NLS-1$
for (Iterator<ValueComputation> it = computationDiff.iterator(); it.hasNext();) {
System.out.println("\t" + it.next()); //$NON-NLS-1$
}
Set<Object> valuesDiff = new HashSet<Object>(localValues.values());
valuesDiff.removeAll(snapshot.localValues.values());
System.out.println("localValues diff:"); //$NON-NLS-1$
for (Iterator<Object> it = valuesDiff.iterator(); it.hasNext();) {
System.out.println("\t" + it.next()); //$NON-NLS-1$
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.e4.core.services.context.IEclipseContext#dispose()
*/
public void dispose() {
Computation[] ls = listeners.toArray(new Computation[listeners.size()]);
ContextChangeEvent event = EclipseContextFactory.createContextEvent(this,
ContextChangeEvent.DISPOSE, null, null, null);
// reverse order of listeners
for (int i = ls.length - 1; i >= 0; i--) {
List<Scheduled> scheduled = new ArrayList<Scheduled>();
ls[i].handleInvalid(event, scheduled);
processScheduled(scheduled);
}
// TBD used by OSGI Context strategy - is this needed? Looks like @PreDestroy
if (strategy instanceof IDisposable)
((IDisposable) strategy).dispose();
}
public Object get(String name) {
return internalGet(this, name, NO_ARGUMENTS, false);
}
public Object get(String name, Object[] arguments) {
return internalGet(this, name, arguments, false);
}
public Object getLocal(String name) {
return internalGet(this, name, null, true);
}
public Object internalGet(EclipseContext originatingContext, String name, Object[] arguments,
boolean local) {
trackAccess(name);
if (DEBUG_VERBOSE) {
System.out.println("IEC.get(" + name + ", " + arguments + ", " + local + "):" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ originatingContext + " for " + toString()); //$NON-NLS-1$
}
- LookupKey lookupKey = new LookupKey(name, arguments);
+ LookupKey lookupKey = null;
if (this == originatingContext) {
+ lookupKey = new LookupKey(name, arguments);
ValueComputation valueComputation = localValueComputations.get(lookupKey);
if (valueComputation != null) {
return valueComputation.get(arguments);
}
}
// 1. try for local value
Object result = localValues.get(name);
// 2. try the local strategy
if (result == null && strategy instanceof ILookupStrategy)
result = ((ILookupStrategy) strategy).lookup(name, originatingContext);
// if we found something, compute the concrete value and return
if (result != null) {
if (result instanceof IContextFunction) {
ValueComputation valueComputation = new ValueComputation(this, originatingContext,
name, ((IContextFunction) result));
if (EclipseContext.DEBUG)
System.out.println("created " + valueComputation); //$NON-NLS-1$
+ if (lookupKey == null)
+ lookupKey = new LookupKey(name, arguments);
originatingContext.localValueComputations.put(lookupKey, valueComputation);
// value computation depends on parent if function is defined in a parent
if (this != originatingContext)
valueComputation.addDependency(originatingContext, IContextConstants.PARENT);
result = valueComputation.get(arguments);
}
if (DEBUG_VERBOSE) {
System.out.println("IEC.get(" + name + "): " + result); //$NON-NLS-1$ //$NON-NLS-2$
}
return result;
}
// 3. delegate to parent
if (!local) {
IEclipseContext parent = (IEclipseContext) getLocal(IContextConstants.PARENT);
if (parent != null) {
return ((EclipseContext) parent).internalGet(originatingContext, name, arguments,
local); // XXX
// IEclipseContext
}
}
return null;
}
protected void invalidate(String name, int eventType, Object oldValue, List<Scheduled> scheduled) {
if (EclipseContext.DEBUG)
System.out.println("invalidating " + this + ',' + name); //$NON-NLS-1$
removeLocalValueComputations(name);
Computation[] ls = listeners.toArray(new Computation[listeners.size()]);
ContextChangeEvent event = EclipseContextFactory.createContextEvent(this, eventType, null,
name, oldValue);
for (int i = 0; i < ls.length; i++) {
ls[i].handleInvalid(event, scheduled);
}
}
private boolean isSetLocally(String name) {
trackAccess(name);
return localValues.containsKey(name);
}
public void remove(String name) {
if (isSetLocally(name)) {
Object oldValue = localValues.remove(name);
List<Scheduled> scheduled = new ArrayList<Scheduled>();
invalidate(name, ContextChangeEvent.REMOVED, oldValue, scheduled);
processScheduled(scheduled);
}
}
/**
* Removes all local value computations associated with the given name.
*
* @param name
* The name to remove
*/
private void removeLocalValueComputations(String name) {
synchronized (localValueComputations) {
// remove all keys with a matching name
for (Iterator<LookupKey> it = localValueComputations.keySet().iterator(); it.hasNext();) {
LookupKey key = it.next();
if (key.name.equals(name)) {
Object removed = localValueComputations.get(key);
if (removed instanceof ValueComputation) {
((ValueComputation) removed).clear(this, name);
}
it.remove();
}
}
}
}
public void runAndTrack(final IRunAndTrack runnable, Object[] args) {
ContextChangeEvent event = EclipseContextFactory.createContextEvent(this,
ContextChangeEvent.INITIAL, args, null, null);
TrackableComputationExt computation = new TrackableComputationExt(runnable);
computation.notify(event);
}
protected void processScheduled(List<Scheduled> scheduledList) {
boolean useScheduler = (strategy != null && strategy instanceof ISchedulerStrategy);
for (Iterator<Scheduled> i = scheduledList.iterator(); i.hasNext();) {
Scheduled scheduled = i.next();
if (useScheduler)
((ISchedulerStrategy) strategy).schedule(scheduled.runnable, scheduled.event);
else
scheduled.runnable.notify(scheduled.event);
}
}
public void set(String name, Object value) {
if (IContextConstants.PARENT.equals(name)) {
// TBD make setting parent a separate operation
List<Scheduled> scheduled = new ArrayList<Scheduled>();
handleReparent((EclipseContext) value, scheduled);
localValues.put(IContextConstants.PARENT, value);
processScheduled(scheduled);
return;
}
boolean containsKey = localValues.containsKey(name);
Object oldValue = localValues.put(name, value);
if (!containsKey || value != oldValue) {
if (DEBUG_VERBOSE) {
System.out.println("IEC.set(" + name + ',' + value + "):" + oldValue + " for " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ toString());
}
List<Scheduled> scheduled = new ArrayList<Scheduled>();
invalidate(name, ContextChangeEvent.ADDED, oldValue, scheduled);
processScheduled(scheduled);
}
}
public void modify(String name, Object value) {
List<Scheduled> scheduled = new ArrayList<Scheduled>();
if (!internalModify(name, value, scheduled))
set(name, value);
processScheduled(scheduled);
}
public boolean internalModify(String name, Object value, List<Scheduled> scheduled) {
boolean containsKey = localValues.containsKey(name);
if (containsKey) {
if (!checkModifiable(name)) {
String tmp = "Variable " + name + " is not modifiable in the context " + toString(); //$NON-NLS-1$ //$NON-NLS-2$
throw new IllegalArgumentException(tmp);
}
Object oldValue = localValues.put(name, value);
if (value != oldValue) {
if (DEBUG_VERBOSE)
System.out.println("IEC.set(" + name + ',' + value + "):" + oldValue + " for " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ toString());
invalidate(name, ContextChangeEvent.ADDED, oldValue, scheduled);
}
return true;
}
EclipseContext parent = getParent();
if (parent != null)
return parent.internalModify(name, value, scheduled);
return false;
}
// TBD should this method be an API?
public EclipseContext getParent() {
return (EclipseContext) localValues.get(IContextConstants.PARENT);
}
/**
* Returns a string representation of this context for debugging purposes only.
*/
public String toString() {
Object debugString = localValues.get(IContextConstants.DEBUG_STRING);
return debugString instanceof String ? ((String) debugString) : "Anonymous Context"; //$NON-NLS-1$
}
private void trackAccess(String name) {
Computation computation = currentComputation.get();
if (computation != null) {
computation.addDependency(this, name);
}
}
public void declareModifiable(String name) {
if (name == null)
return;
if (modifiable == null)
modifiable = new ArrayList<String>(3);
modifiable.add(name);
if (localValues.containsKey(name))
return;
localValues.put(name, null);
}
private boolean checkModifiable(String name) {
if (modifiable == null)
return false;
for (Iterator<String> i = modifiable.iterator(); i.hasNext();) {
String candidate = i.next();
if (candidate.equals(name))
return true;
}
return false;
}
public void removeListenersTo(Object object) {
if (object == null)
return;
synchronized (listeners) {
ContextChangeEvent event = EclipseContextFactory.createContextEvent(this,
ContextChangeEvent.UNINJECTED, null, null, null);
for (Iterator<Computation> i = listeners.iterator(); i.hasNext();) {
Computation computation = i.next();
if (computation instanceof TrackableComputationExt) {
if (object == ((TrackableComputationExt) computation).getObject()) {
((IRunAndTrack) computation).notify(event);
i.remove();
}
}
}
}
}
private void handleReparent(EclipseContext newParent, List<Scheduled> scheduled) {
// TBD should we lock waiting list while doing reparent?
// Add "boolean inReparent" on the root context and process right away?
processWaiting();
// 1) everybody who depends on me: I need to collect combined list of names injected
Computation[] ls = listeners.toArray(new Computation[listeners.size()]);
Set<String> usedNames = new HashSet<String>();
for (int i = 0; i < ls.length; i++) {
Set<String> listenerNames = ls[i].dependsOnNames(this);
if (listenerNames == null)
continue; // should not happen?
usedNames.addAll(listenerNames); // also removes duplicates
}
// 2) for each used name:
for (Iterator<String> i = usedNames.iterator(); i.hasNext();) {
String name = i.next();
if (localValues.containsKey(name))
continue; // it is a local value
Object oldValue = get(name);
Object newValue = (newParent != null) ? newParent.get(name) : null;
if (oldValue != newValue)
invalidate(name, ContextChangeEvent.ADDED, oldValue, scheduled);
}
localValueComputations.clear();
}
public void processWaiting() {
// traverse to the root node
EclipseContext parent = getParent();
if (parent != null) {
parent.processWaiting();
return;
}
if (waiting == null)
return;
// create update notifications
Computation[] ls = waiting.toArray(new Computation[waiting.size()]);
waiting.clear();
ContextChangeEvent event = EclipseContextFactory.createContextEvent(this,
ContextChangeEvent.UPDATE, null, null, null);
for (int i = 0; i < ls.length; i++) {
if (ls[i] instanceof TrackableComputationExt)
((TrackableComputationExt) ls[i]).notify(event);
}
}
public void addWaiting(Computation cp) {
// traverse to the root node
EclipseContext parent = getParent();
if (parent != null) {
parent.addWaiting(cp);
return;
}
if (waiting == null)
waiting = new ArrayList<Computation>();
waiting.add(cp);
}
protected EclipseContext getRoot() {
EclipseContext current = this;
EclipseContext root;
do {
root = current;
current = current.getParent();
} while (current != null);
return root;
}
}
diff --git a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/TestHelper.java b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/TestHelper.java
index 4414808a5..2cbfe613c 100644
--- a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/TestHelper.java
+++ b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/TestHelper.java
@@ -1,30 +1,30 @@
/*******************************************************************************
* Copyright (c) 2009, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.e4.core.services.internal.context;
-import java.util.List;
+import java.util.Set;
import org.eclipse.e4.core.services.context.IEclipseContext;
/**
* This class exists only for the purpose of automated testing. Clients should never reference this
* class.
*
* @noreference
*/
public final class TestHelper {
private TestHelper() {
// don't allow instantiation
}
- public static List<Computation> getListeners(IEclipseContext context) {
+ public static Set<Computation> getListeners(IEclipseContext context) {
return ((EclipseContext) context).listeners;
}
}
| false | false | null | null |
diff --git a/org/mozilla/javascript/ScriptRuntime.java b/org/mozilla/javascript/ScriptRuntime.java
index 3e88cfdf..8367d4db 100644
--- a/org/mozilla/javascript/ScriptRuntime.java
+++ b/org/mozilla/javascript/ScriptRuntime.java
@@ -1,2173 +1,2173 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
* Frank Mitchell
* Andrew Wason
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.util.*;
import java.lang.reflect.*;
import org.mozilla.javascript.tools.shell.Global;
/**
* This is the class that implements the runtime.
*
* @author Norris Boyd
*/
public class ScriptRuntime {
/**
* No instances should be created.
*/
protected ScriptRuntime() {
}
/*
* There's such a huge space (and some time) waste for the Foo.class
* syntax: the compiler sticks in a test of a static field in the
* enclosing class for null and the code for creating the class value.
* It has to do this since the reference has to get pushed off til
* executiontime (i.e. can't force an early load), but for the
* 'standard' classes - especially those in java.lang, we can trust
* that they won't cause problems by being loaded early.
*/
public final static Class UndefinedClass = Undefined.class;
public final static Class ScriptableClass = Scriptable.class;
public final static Class StringClass = String.class;
public final static Class NumberClass = Number.class;
public final static Class BooleanClass = Boolean.class;
public final static Class ByteClass = Byte.class;
public final static Class ShortClass = Short.class;
public final static Class IntegerClass = Integer.class;
public final static Class LongClass = Long.class;
public final static Class FloatClass = Float.class;
public final static Class DoubleClass = Double.class;
public final static Class CharacterClass = Character.class;
public final static Class ObjectClass = Object.class;
public final static Class FunctionClass = Function.class;
public final static Class ClassClass = Class.class;
/**
* Convert the value to a boolean.
*
* See ECMA 9.2.
*/
public static boolean toBoolean(Object val) {
if (val == null)
return false;
if (val instanceof Scriptable) {
if (Context.getContext().isVersionECMA1()) {
// pure ECMA
return val != Undefined.instance;
}
// ECMA extension
val = ((Scriptable) val).getDefaultValue(BooleanClass);
if (val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
// fall through
}
if (val instanceof String)
return ((String) val).length() != 0;
if (val instanceof Number) {
double d = ((Number) val).doubleValue();
return (d == d && d != 0.0);
}
if (val instanceof Boolean)
return ((Boolean) val).booleanValue();
throw errorWithClassName("msg.invalid.type", val);
}
/**
* Convert the value to a number.
*
* See ECMA 9.3.
*/
public static double toNumber(Object val) {
if (val != null && val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(NumberClass);
if (val != null && val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
// fall through
}
if (val == null)
return +0.0;
if (val instanceof String)
return toNumber((String) val);
if (val instanceof Number)
return ((Number) val).doubleValue();
if (val instanceof Boolean)
return ((Boolean) val).booleanValue() ? 1 : +0.0;
throw errorWithClassName("msg.invalid.type", val);
}
// This definition of NaN is identical to that in java.lang.Double
// except that it is not final. This is a workaround for a bug in
// the Microsoft VM, versions 2.01 and 3.0P1, that causes some uses
// (returns at least) of Double.NaN to be converted to 1.0.
// So we use ScriptRuntime.NaN instead of Double.NaN.
public static double NaN = 0.0d / 0.0;
public static Double NaNobj = new Double(0.0d / 0.0);
// A similar problem exists for negative zero.
public static double negativeZero = -0.0;
/*
* Helper function for toNumber, parseInt, and TokenStream.getToken.
*/
static double stringToNumber(String s, int start, int radix) {
char digitMax = '9';
char lowerCaseBound = 'a';
char upperCaseBound = 'A';
int len = s.length();
if (radix < 10) {
digitMax = (char) ('0' + radix - 1);
}
if (radix > 10) {
lowerCaseBound = (char) ('a' + radix - 10);
upperCaseBound = (char) ('A' + radix - 10);
}
int end;
double sum = 0.0;
for (end=start; end < len; end++) {
char c = s.charAt(end);
int newDigit;
if ('0' <= c && c <= digitMax)
newDigit = c - '0';
else if ('a' <= c && c < lowerCaseBound)
newDigit = c - 'a' + 10;
else if ('A' <= c && c < upperCaseBound)
newDigit = c - 'A' + 10;
else
break;
sum = sum*radix + newDigit;
}
if (start == end) {
return NaN;
}
if (sum >= 9007199254740992.0) {
if (radix == 10) {
/* If we're accumulating a decimal number and the number
* is >= 2^53, then the result from the repeated multiply-add
* above may be inaccurate. Call Java to get the correct
* answer.
*/
try {
return Double.valueOf(s.substring(start, end)).doubleValue();
} catch (NumberFormatException nfe) {
return NaN;
}
} else if (radix == 2 || radix == 4 || radix == 8 ||
radix == 16 || radix == 32)
{
/* The number may also be inaccurate for one of these bases.
* This happens if the addition in value*radix + digit causes
* a round-down to an even least significant mantissa bit
* when the first dropped bit is a one. If any of the
* following digits in the number (which haven't been added
* in yet) are nonzero then the correct action would have
* been to round up instead of down. An example of this
* occurs when reading the number 0x1000000000000081, which
* rounds to 0x1000000000000000 instead of 0x1000000000000100.
*/
BinaryDigitReader bdr = new BinaryDigitReader(radix, s, start, end);
int bit;
sum = 0.0;
/* Skip leading zeros. */
do {
bit = bdr.getNextBinaryDigit();
} while (bit == 0);
if (bit == 1) {
/* Gather the 53 significant bits (including the leading 1) */
sum = 1.0;
for (int j = 52; j != 0; j--) {
bit = bdr.getNextBinaryDigit();
if (bit < 0)
return sum;
sum = sum*2 + bit;
}
/* bit54 is the 54th bit (the first dropped from the mantissa) */
int bit54 = bdr.getNextBinaryDigit();
if (bit54 >= 0) {
double factor = 2.0;
int sticky = 0; /* sticky is 1 if any bit beyond the 54th is 1 */
int bit3;
while ((bit3 = bdr.getNextBinaryDigit()) >= 0) {
sticky |= bit3;
factor *= 2;
}
sum += bit54 & (bit | sticky);
sum *= factor;
}
}
}
/* We don't worry about inaccurate numbers for any other base. */
}
return sum;
}
/**
* ToNumber applied to the String type
*
* See ECMA 9.3.1
*/
public static double toNumber(String s) {
int len = s.length();
int start = 0;
char startChar;
for (;;) {
if (start == len) {
// Empty or contains only whitespace
return +0.0;
}
startChar = s.charAt(start);
if (!Character.isWhitespace(startChar))
break;
start++;
}
if (startChar == '0' && start+2 < len &&
Character.toLowerCase(s.charAt(start+1)) == 'x')
// A hexadecimal number
return stringToNumber(s, start + 2, 16);
if ((startChar == '+' || startChar == '-') && start+3 < len &&
s.charAt(start+1) == '0' &&
Character.toLowerCase(s.charAt(start+2)) == 'x') {
// A hexadecimal number
double val = stringToNumber(s, start + 3, 16);
return startChar == '-' ? -val : val;
}
int end = len - 1;
char endChar;
while (Character.isWhitespace(endChar = s.charAt(end)))
end--;
if (endChar == 'y') {
// check for "Infinity"
if (startChar == '+' || startChar == '-')
start++;
- if (s.regionMatches(start, "Infinity", 0, 8))
+ if (start + 7 == end && s.regionMatches(start, "Infinity", 0, 8))
return startChar == '-'
? Double.NEGATIVE_INFINITY
: Double.POSITIVE_INFINITY;
return NaN;
}
// A non-hexadecimal, non-infinity number:
// just try a normal floating point conversion
String sub = s.substring(start, end+1);
if (MSJVM_BUG_WORKAROUNDS) {
// The MS JVM will accept non-conformant strings
// rather than throwing a NumberFormatException
// as it should.
for (int i=sub.length()-1; i >= 0; i--) {
char c = sub.charAt(i);
if (('0' <= c && c <= '9') || c == '.' ||
c == 'e' || c == 'E' ||
c == '+' || c == '-')
continue;
return NaN;
}
}
try {
return Double.valueOf(sub).doubleValue();
} catch (NumberFormatException ex) {
return NaN;
}
}
/**
* Helper function for builtin objects that use the varargs form.
* ECMA function formal arguments are undefined if not supplied;
* this function pads the argument array out to the expected
* length, if necessary.
*/
public static Object[] padArguments(Object[] args, int count) {
if (count < args.length)
return args;
int i;
Object[] result = new Object[count];
for (i = 0; i < args.length; i++) {
result[i] = args[i];
}
for (; i < count; i++) {
result[i] = Undefined.instance;
}
return result;
}
/* Work around Microsoft Java VM bugs. */
private final static boolean MSJVM_BUG_WORKAROUNDS = true;
/**
* For escaping strings printed by object and array literals; not quite
* the same as 'escape.'
*/
public static String escapeString(String s) {
// ack! Java lacks \v.
String escapeMap = "\bb\ff\nn\rr\tt\u000bv\"\"''";
StringBuffer result = new StringBuffer(s.length());
for(int i=0; i < s.length(); i++) {
char c = s.charAt(i);
// an ordinary print character
if (c >= ' ' && c <= '~' // string.h isprint()
&& c != '"')
{
result.append(c);
continue;
}
// an \escaped sort of character
int index;
if ((index = escapeMap.indexOf(c)) >= 0) {
result.append("\\");
result.append(escapeMap.charAt(index + 1));
continue;
}
// 2-digit hex?
if (c < 256) {
String hex = Integer.toHexString((int) c);
if (hex.length() == 1) {
result.append("\\x0");
result.append(hex);
} else {
result.append("\\x");
result.append(hex);
}
continue;
}
// nope. Unicode.
String hex = Integer.toHexString((int) c);
// cool idiom courtesy Shaver.
result.append("\\u");
for (int l = hex.length(); l < 4; l++)
result.append("0");
result.append(hex);
}
return result.toString();
}
/**
* Convert the value to a string.
*
* See ECMA 9.8.
*/
public static String toString(Object val) {
for (;;) {
if (val == null)
return "null";
if (val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(StringClass);
if (val != Undefined.instance && val instanceof Scriptable) {
throw errorWithClassName("msg.primitive.expected", val);
}
continue;
}
if (val instanceof Number) {
// XXX should we just teach NativeNumber.stringValue()
// about Numbers?
return numberToString(((Number) val).doubleValue(), 10);
}
return val.toString();
}
}
public static String numberToString(double d, int base) {
if (d != d)
return "NaN";
if (d == Double.POSITIVE_INFINITY)
return "Infinity";
if (d == Double.NEGATIVE_INFINITY)
return "-Infinity";
if (d == 0.0)
return "0";
if ((base < 2) || (base > 36)) {
Object[] args = { Integer.toString(base) };
throw Context.reportRuntimeError(getMessage
("msg.bad.radix", args));
}
if (base != 10) {
return DToA.JS_dtobasestr(base, d);
} else {
StringBuffer result = new StringBuffer();
DToA.JS_dtostr(result, DToA.DTOSTR_STANDARD, 0, d);
return result.toString();
}
}
/**
* Convert the value to an object.
*
* See ECMA 9.9.
*/
public static Scriptable toObject(Scriptable scope, Object val) {
return toObject(scope, val, null);
}
public static Scriptable toObject(Scriptable scope, Object val,
Class staticClass)
{
if (val == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
if (val instanceof Scriptable) {
if (val == Undefined.instance) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.undef.to.object", null),
scope);
}
return (Scriptable) val;
}
String className = val instanceof String ? "String" :
val instanceof Number ? "Number" :
val instanceof Boolean ? "Boolean" :
null;
if (className == null) {
// Extension: Wrap as a LiveConnect object.
Object wrapped = NativeJavaObject.wrap(scope, val, staticClass);
if (wrapped instanceof Scriptable)
return (Scriptable) wrapped;
throw errorWithClassName("msg.invalid.type", val);
}
Object[] args = { val };
scope = ScriptableObject.getTopLevelScope(scope);
Scriptable result = newObject(Context.getContext(), scope,
className, args);
return result;
}
public static Scriptable newObject(Context cx, Scriptable scope,
String constructorName, Object[] args)
{
Exception re = null;
try {
return cx.newObject(scope, constructorName, args);
}
catch (NotAFunctionException e) {
re = e;
}
catch (PropertyException e) {
re = e;
}
catch (JavaScriptException e) {
re = e;
}
throw cx.reportRuntimeError(re.getMessage());
}
/**
*
* See ECMA 9.4.
*/
public static double toInteger(Object val) {
double d = toNumber(val);
// if it's NaN
if (d != d)
return +0.0;
if (d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return d;
if (d > 0.0)
return Math.floor(d);
else
return Math.ceil(d);
}
// convenience method
public static double toInteger(double d) {
// if it's NaN
if (d != d)
return +0.0;
if (d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return d;
if (d > 0.0)
return Math.floor(d);
else
return Math.ceil(d);
}
/**
*
* See ECMA 9.5.
*/
public static int toInt32(Object val) {
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
double two31 = 2147483648.0;
// short circuit for common small values; TokenStream
// returns them as Bytes.
if (val instanceof Byte)
return ((Number)val).intValue();
double d = toNumber(val);
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return 0;
d = Math.IEEEremainder(d, two32);
d = d >= 0
? d
: d + two32;
if (d >= two31)
return (int)(d - two32);
else
return (int)d;
}
public static int toInt32(double d) {
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
double two31 = 2147483648.0;
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return 0;
d = Math.IEEEremainder(d, two32);
d = d >= 0
? d
: d + two32;
if (d >= two31)
return (int)(d - two32);
else
return (int)d;
}
/**
*
* See ECMA 9.6.
*/
// must return long to hold an _unsigned_ int
public static long toUint32(double d) {
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return 0;
if (d > 0.0)
d = Math.floor(d);
else
d = Math.ceil(d);
d = Math.IEEEremainder(d, two32);
d = d >= 0
? d
: d + two32;
return (long) Math.floor(d);
}
public static long toUint32(Object val) {
return toUint32(toNumber(val));
}
/**
*
* See ECMA 9.7.
*/
public static char toUint16(Object val) {
long int16 = 0x10000;
double d = toNumber(val);
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = Math.IEEEremainder(d, int16);
d = d >= 0
? d
: d + int16;
return (char) Math.floor(d);
}
/**
* Unwrap a JavaScriptException. Sleight of hand so that we don't
* javadoc JavaScriptException.getRuntimeValue().
*/
public static Object unwrapJavaScriptException(JavaScriptException jse) {
return jse.value;
}
public static Object getProp(Object obj, String id, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null || start == Undefined.instance) {
String msg = start == null ? "msg.null.to.object"
: "msg.undefined";
throw NativeGlobal.constructError(
Context.getContext(), "ConversionError",
ScriptRuntime.getMessage(msg, null),
scope);
}
Scriptable m = start;
do {
Object result = m.get(id, start);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
} while (m != null);
return Undefined.instance;
}
public static Object getTopLevelProp(Scriptable scope, String id) {
Scriptable s = ScriptableObject.getTopLevelScope(scope);
Object v;
do {
v = s.get(id, s);
if (v != Scriptable.NOT_FOUND)
return v;
s = s.getPrototype();
} while (s != null);
return v;
}
/***********************************************************************/
public static Scriptable getProto(Object obj, Scriptable scope) {
Scriptable s;
if (obj instanceof Scriptable) {
s = (Scriptable) obj;
} else {
s = toObject(scope, obj);
}
if (s == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
return s.getPrototype();
}
public static Scriptable getParent(Object obj) {
Scriptable s;
try {
s = (Scriptable) obj;
}
catch (ClassCastException e) {
return null;
}
if (s == null) {
return null;
}
return getThis(s.getParentScope());
}
public static Scriptable getParent(Object obj, Scriptable scope) {
Scriptable s;
if (obj instanceof Scriptable) {
s = (Scriptable) obj;
} else {
s = toObject(scope, obj);
}
if (s == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
return s.getParentScope();
}
public static Object setProto(Object obj, Object value, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
Scriptable result = value == null ? null : toObject(scope, value);
Scriptable s = result;
while (s != null) {
if (s == start) {
Object[] args = { "__proto__" };
throw Context.reportRuntimeError(getMessage
("msg.cyclic.value", args));
}
s = s.getPrototype();
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
start.setPrototype(result);
return result;
}
public static Object setParent(Object obj, Object value, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
Scriptable result = value == null ? null : toObject(scope, value);
Scriptable s = result;
while (s != null) {
if (s == start) {
Object[] args = { "__parent__" };
throw Context.reportRuntimeError(getMessage
("msg.cyclic.value", args));
}
s = s.getParentScope();
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
start.setParentScope(result);
return result;
}
public static Object setProp(Object obj, String id, Object value,
Scriptable scope)
{
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
Scriptable m = start;
do {
if (m.has(id, start)) {
m.put(id, start, value);
return value;
}
m = m.getPrototype();
} while (m != null);
start.put(id, start, value);
return value;
}
// Return -1L if str is not an index or the index value as lower 32
// bits of the result
private static long indexFromString(String str) {
// It must be a string.
// The length of the decimal string representation of
// Integer.MAX_VALUE, 2147483647
final int MAX_VALUE_LENGTH = 10;
int len = str.length();
if (len > 0) {
int i = 0;
boolean negate = false;
int c = str.charAt(0);
if (c == '-') {
if (len > 1) {
c = str.charAt(1);
i = 1;
negate = true;
}
}
c -= '0';
if (0 <= c && c <= 9
&& len <= (negate ? MAX_VALUE_LENGTH + 1 : MAX_VALUE_LENGTH))
{
// Use negative numbers to accumulate index to handle
// Integer.MIN_VALUE that is greater by 1 in absolute value
// then Integer.MAX_VALUE
int index = -c;
int oldIndex = 0;
i++;
if (index != 0) {
// Note that 00, 01, 000 etc. are not indexes
while (i != len && 0 <= (c = str.charAt(i) - '0') && c <= 9)
{
oldIndex = index;
index = 10 * index - c;
i++;
}
}
// Make sure all characters were consumed and that it couldn't
// have overflowed.
if (i == len &&
(oldIndex > (Integer.MIN_VALUE / 10) ||
(oldIndex == (Integer.MIN_VALUE / 10) &&
c <= (negate ? -(Integer.MIN_VALUE % 10)
: (Integer.MAX_VALUE % 10)))))
{
return 0xFFFFFFFFL & (negate ? index : -index);
}
}
}
return -1L;
}
static String getStringId(Object id) {
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
int index = (int) d;
if (((double) index) == d)
return null;
return toString(id);
}
String s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0)
return null;
return s;
}
static int getIntId(Object id) {
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
int index = (int) d;
if (((double) index) == d)
return index;
return 0;
}
String s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0)
return (int)indexTest;
return 0;
}
public static Object getElem(Object obj, Object id, Scriptable scope) {
int index;
String s;
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
index = (int) d;
s = ((double) index) == d ? null : toString(id);
} else {
s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0) {
index = (int)indexTest;
s = null;
} else {
index = 0;
}
}
Scriptable start = obj instanceof Scriptable
? (Scriptable) obj
: toObject(scope, obj);
Scriptable m = start;
if (s != null) {
if (s.equals("__proto__"))
return start.getPrototype();
if (s.equals("__parent__"))
return start.getParentScope();
while (m != null) {
Object result = m.get(s, start);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
}
return Undefined.instance;
}
while (m != null) {
Object result = m.get(index, start);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
}
return Undefined.instance;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object getElem(Scriptable obj, int index)
{
Scriptable m = obj;
while (m != null) {
Object result = m.get(index, obj);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
}
return Undefined.instance;
}
public static Object setElem(Object obj, Object id, Object value,
Scriptable scope)
{
int index;
String s;
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
index = (int) d;
s = ((double) index) == d ? null : toString(id);
} else {
s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0) {
index = (int)indexTest;
s = null;
} else {
index = 0;
}
}
Scriptable start = obj instanceof Scriptable
? (Scriptable) obj
: toObject(scope, obj);
Scriptable m = start;
if (s != null) {
if (s.equals("__proto__"))
return setProto(obj, value, scope);
if (s.equals("__parent__"))
return setParent(obj, value, scope);
do {
if (m.has(s, start)) {
m.put(s, start, value);
return value;
}
m = m.getPrototype();
} while (m != null);
start.put(s, start, value);
return value;
}
do {
if (m.has(index, start)) {
m.put(index, start, value);
return value;
}
m = m.getPrototype();
} while (m != null);
start.put(index, start, value);
return value;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object setElem(Scriptable obj, int index, Object value)
{
Scriptable m = obj;
do {
if (m.has(index, obj)) {
m.put(index, obj, value);
return value;
}
m = m.getPrototype();
} while (m != null);
obj.put(index, obj, value);
return value;
}
/**
* The delete operator
*
* See ECMA 11.4.1
*
* In ECMA 0.19, the description of the delete operator (11.4.1)
* assumes that the [[Delete]] method returns a value. However,
* the definition of the [[Delete]] operator (8.6.2.5) does not
* define a return value. Here we assume that the [[Delete]]
* method doesn't return a value.
*/
public static Object delete(Object obj, Object id) {
String s = getStringId(id);
boolean result = s != null
? ScriptableObject.deleteProperty((Scriptable) obj, s)
: ScriptableObject.deleteProperty((Scriptable) obj, getIntId(id));
return result ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Looks up a name in the scope chain and returns its value.
*/
public static Object name(Scriptable scopeChain, String id) {
Scriptable obj = scopeChain;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
Object result = m.get(id, obj);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object[] args = { id.toString() };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scopeChain);
}
/**
* Returns the object in the scope chain that has a given property.
*
* The order of evaluation of an assignment expression involves
* evaluating the lhs to a reference, evaluating the rhs, and then
* modifying the reference with the rhs value. This method is used
* to 'bind' the given name to an object containing that property
* so that the side effects of evaluating the rhs do not affect
* which property is modified.
* Typically used in conjunction with setName.
*
* See ECMA 10.1.4
*/
public static Scriptable bind(Scriptable scope, String id) {
Scriptable obj = scope;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
if (m.has(id, obj))
return obj;
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
return null;
}
public static Scriptable getBase(Scriptable scope, String id) {
Scriptable obj = scope;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
if (m.get(id, obj) != Scriptable.NOT_FOUND)
return obj;
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object[] args = { id };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scope);
}
public static Scriptable getThis(Scriptable base) {
while (base instanceof NativeWith)
base = base.getPrototype();
if (base instanceof NativeCall)
base = ScriptableObject.getTopLevelScope(base);
return base;
}
public static Object setName(Scriptable bound, Object value,
Scriptable scope, String id)
{
if (bound == null) {
// "newname = 7;", where 'newname' has not yet
// been defined, creates a new property in the
// global object. Find the global object by
// walking up the scope chain.
Scriptable next = scope;
do {
bound = next;
next = bound.getParentScope();
} while (next != null);
bound.put(id, bound, value);
/*
This code is causing immense performance problems in
scripts that assign to the variables as a way of creating them.
XXX need strict mode
String[] args = { id };
String message = getMessage("msg.assn.create", args);
Context.reportWarning(message);
*/
return value;
}
return setProp(bound, id, value, scope);
}
public static Enumeration initEnum(Object value, Scriptable scope) {
Scriptable m = toObject(scope, value);
return new IdEnumeration(m);
}
public static Object nextEnum(Enumeration enum) {
// OPT this could be more efficient; should junk the Enumeration
// interface
if (!enum.hasMoreElements())
return null;
return enum.nextElement();
}
// Form used by class files generated by 1.4R3 and earlier.
public static Object call(Context cx, Object fun, Object thisArg,
Object[] args)
throws JavaScriptException
{
Scriptable scope = null;
if (fun instanceof Scriptable)
scope = ((Scriptable) fun).getParentScope();
return call(cx, fun, thisArg, args, scope);
}
public static Object call(Context cx, Object fun, Object thisArg,
Object[] args, Scriptable scope)
throws JavaScriptException
{
Function function;
try {
function = (Function) fun;
}
catch (ClassCastException e) {
Object[] errorArgs = { toString(fun) };
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.isnt.function",
errorArgs),
scope);
}
Scriptable thisObj;
if (thisArg instanceof Scriptable || thisArg == null) {
thisObj = (Scriptable) thisArg;
} else {
thisObj = ScriptRuntime.toObject(scope, thisArg);
}
return function.call(cx, scope, thisObj, args);
}
private static Object callOrNewSpecial(Context cx, Scriptable scope,
Object fun, Object jsThis, Object thisArg,
Object[] args, boolean isCall,
String filename, int lineNumber)
throws JavaScriptException
{
if (fun instanceof FunctionObject) {
FunctionObject fo = (FunctionObject) fun;
Member m = fo.method;
Class cl = m.getDeclaringClass();
String name = m.getName();
if (name.equals("eval") && cl == NativeGlobal.class)
return NativeGlobal.evalSpecial(cx, scope, thisArg, args,
filename, lineNumber);
if (name.equals("With") && cl == NativeWith.class)
return NativeWith.newWithSpecial(cx, args, fo, !isCall);
if (name.equals("jsFunction_exec") && cl == NativeScript.class)
return ((NativeScript)jsThis).exec(cx, ScriptableObject.getTopLevelScope(scope));
if (name.equals("exec")
&& (cx.getRegExpProxy() != null)
&& (cx.getRegExpProxy().isRegExp(jsThis)))
return call(cx, fun, jsThis, args, scope);
}
else // could've been <java>.XXX.exec() that was re-directed here
if (fun instanceof NativeJavaMethod)
return call(cx, fun, jsThis, args, scope);
if (isCall)
return call(cx, fun, thisArg, args, scope);
return newObject(cx, fun, args, scope);
}
public static Object callSpecial(Context cx, Object fun,
Object thisArg, Object[] args,
Scriptable enclosingThisArg,
Scriptable scope, String filename,
int lineNumber)
throws JavaScriptException
{
return callOrNewSpecial(cx, scope, fun, thisArg,
enclosingThisArg, args, true,
filename, lineNumber);
}
/**
* Operator new.
*
* See ECMA 11.2.2
*/
public static Scriptable newObject(Context cx, Object fun,
Object[] args, Scriptable scope)
throws JavaScriptException
{
Function f;
try {
f = (Function) fun;
if (f != null) {
return f.construct(cx, scope, args);
}
// else fall through to error
} catch (ClassCastException e) {
// fall through to error
}
Object[] errorArgs = { toString(fun) };
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.isnt.function", errorArgs),
scope);
}
public static Scriptable newObjectSpecial(Context cx, Object fun,
Object[] args, Scriptable scope)
throws JavaScriptException
{
return (Scriptable) callOrNewSpecial(cx, scope, fun, null, null, args,
false, null, -1);
}
/**
* The typeof operator
*/
public static String typeof(Object value) {
if (value == Undefined.instance)
return "undefined";
if (value == null)
return "object";
if (value instanceof Scriptable)
return (value instanceof Function) ? "function" : "object";
if (value instanceof String)
return "string";
if (value instanceof Number)
return "number";
if (value instanceof Boolean)
return "boolean";
throw errorWithClassName("msg.invalid.type", value);
}
/**
* The typeof operator that correctly handles the undefined case
*/
public static String typeofName(Scriptable scope, String id) {
Object val = bind(scope, id);
if (val == null)
return "undefined";
return typeof(getProp(val, id, scope));
}
// neg:
// implement the '-' operator inline in the caller
// as "-toNumber(val)"
// not:
// implement the '!' operator inline in the caller
// as "!toBoolean(val)"
// bitnot:
// implement the '~' operator inline in the caller
// as "~toInt32(val)"
public static Object add(Object val1, Object val2) {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(null);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(null);
if (!(val1 instanceof String) && !(val2 instanceof String))
if ((val1 instanceof Number) && (val2 instanceof Number))
return new Double(((Number)val1).doubleValue() +
((Number)val2).doubleValue());
else
return new Double(toNumber(val1) + toNumber(val2));
return toString(val1) + toString(val2);
}
public static Object postIncrement(Object value) {
if (value instanceof Number)
value = new Double(((Number)value).doubleValue() + 1.0);
else
value = new Double(toNumber(value) + 1.0);
return value;
}
public static Object postIncrement(Scriptable scopeChain, String id) {
Scriptable obj = scopeChain;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
Object result = m.get(id, obj);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() + 1.0);
m.put(id, obj, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) + 1.0);
m.put(id, obj, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object args[] = { id };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scopeChain);
}
public static Object postIncrement(Object obj, String id, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
Scriptable m = start;
do {
Object result = m.get(id, start);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() + 1.0);
m.put(id, start, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) + 1.0);
m.put(id, start, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
return Undefined.instance;
}
public static Object postIncrementElem(Object obj,
Object index, Scriptable scope) {
Object oldValue = getElem(obj, index, scope);
if (oldValue == Undefined.instance)
return Undefined.instance;
double resultValue = toNumber(oldValue);
Double newValue = new Double(resultValue + 1.0);
setElem(obj, index, newValue, scope);
return new Double(resultValue);
}
public static Object postDecrementElem(Object obj,
Object index, Scriptable scope) {
Object oldValue = getElem(obj, index, scope);
if (oldValue == Undefined.instance)
return Undefined.instance;
double resultValue = toNumber(oldValue);
Double newValue = new Double(resultValue - 1.0);
setElem(obj, index, newValue, scope);
return new Double(resultValue);
}
public static Object postDecrement(Object value) {
if (value instanceof Number)
value = new Double(((Number)value).doubleValue() - 1.0);
else
value = new Double(toNumber(value) - 1.0);
return value;
}
public static Object postDecrement(Scriptable scopeChain, String id) {
Scriptable obj = scopeChain;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
Object result = m.get(id, obj);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() - 1.0);
m.put(id, obj, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) - 1.0);
m.put(id, obj, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object args[] = { id };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scopeChain);
}
public static Object postDecrement(Object obj, String id, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
Scriptable m = start;
do {
Object result = m.get(id, start);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() - 1.0);
m.put(id, start, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) - 1.0);
m.put(id, start, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
return Undefined.instance;
}
public static Object toPrimitive(Object val) {
if (val == null || !(val instanceof Scriptable)) {
return val;
}
Object result = ((Scriptable) val).getDefaultValue(null);
if (result != null && result instanceof Scriptable)
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.bad.default.value", null),
val);
return result;
}
private static Class getTypeOfValue(Object obj) {
if (obj == null)
return ScriptableClass;
if (obj == Undefined.instance)
return UndefinedClass;
if (obj instanceof Scriptable)
return ScriptableClass;
if (obj instanceof Number)
return NumberClass;
return obj.getClass();
}
/**
* Equality
*
* See ECMA 11.9
*/
public static boolean eq(Object x, Object y) {
Object xCopy = x; // !!! JIT bug in Cafe 2.1
Object yCopy = y; // need local copies, otherwise their values get blown below
for (;;) {
Class typeX = getTypeOfValue(x);
Class typeY = getTypeOfValue(y);
if (typeX == typeY) {
if (typeX == UndefinedClass)
return true;
if (typeX == NumberClass)
return ((Number) x).doubleValue() ==
((Number) y).doubleValue();
if (typeX == StringClass || typeX == BooleanClass)
return xCopy.equals(yCopy); // !!! JIT bug in Cafe 2.1
if (typeX == ScriptableClass) {
if (x == y)
return true;
if (x instanceof Wrapper &&
y instanceof Wrapper)
{
return ((Wrapper) x).unwrap() ==
((Wrapper) y).unwrap();
}
return false;
}
throw new RuntimeException(); // shouldn't get here
}
if (x == null && y == Undefined.instance)
return true;
if (x == Undefined.instance && y == null)
return true;
if (typeX == NumberClass &&
typeY == StringClass)
{
return ((Number) x).doubleValue() == toNumber(y);
}
if (typeX == StringClass &&
typeY == NumberClass)
{
return toNumber(x) == ((Number) y).doubleValue();
}
if (typeX == BooleanClass) {
x = new Double(toNumber(x));
xCopy = x; // !!! JIT bug in Cafe 2.1
continue;
}
if (typeY == BooleanClass) {
y = new Double(toNumber(y));
yCopy = y; // !!! JIT bug in Cafe 2.1
continue;
}
if ((typeX == StringClass ||
typeX == NumberClass) &&
typeY == ScriptableClass && y != null)
{
y = toPrimitive(y);
yCopy = y; // !!! JIT bug in Cafe 2.1
continue;
}
if (typeX == ScriptableClass && x != null &&
(typeY == StringClass ||
typeY == NumberClass))
{
x = toPrimitive(x);
xCopy = x; // !!! JIT bug in Cafe 2.1
continue;
}
return false;
}
}
public static Boolean eqB(Object x, Object y) {
if (eq(x,y))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static Boolean neB(Object x, Object y) {
if (eq(x,y))
return Boolean.FALSE;
else
return Boolean.TRUE;
}
public static boolean shallowEq(Object x, Object y) {
Class type = getTypeOfValue(x);
if (type != getTypeOfValue(y))
return false;
if (type == StringClass || type == BooleanClass)
return x.equals(y);
if (type == NumberClass)
return ((Number) x).doubleValue() ==
((Number) y).doubleValue();
if (type == ScriptableClass) {
if (x == y)
return true;
if (x instanceof Wrapper && y instanceof Wrapper)
return ((Wrapper) x).unwrap() ==
((Wrapper) y).unwrap();
return false;
}
if (type == UndefinedClass)
return true;
return false;
}
public static Boolean seqB(Object x, Object y) {
if (shallowEq(x,y))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static Boolean sneB(Object x, Object y) {
if (shallowEq(x,y))
return Boolean.FALSE;
else
return Boolean.TRUE;
}
/**
* The instanceof operator.
*
* @return a instanceof b
*/
public static boolean instanceOf(Scriptable scope, Object a, Object b) {
// Check RHS is an object
if (! (b instanceof Scriptable)) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.instanceof.not.object", null),
scope);
}
// for primitive values on LHS, return false
// XXX we may want to change this so that
// 5 instanceof Number == true
if (! (a instanceof Scriptable))
return false;
return ((Scriptable)b).hasInstance((Scriptable)a);
}
/**
* Delegates to
*
* @return true iff rhs appears in lhs' proto chain
*/
protected static boolean jsDelegatesTo(Scriptable lhs, Scriptable rhs) {
Scriptable proto = lhs.getPrototype();
while (proto != null) {
if (proto.equals(rhs)) return true;
proto = proto.getPrototype();
}
return false;
}
/**
* The in operator.
*
* This is a new JS 1.3 language feature. The in operator mirrors
* the operation of the for .. in construct, and tests whether the
* rhs has the property given by the lhs. It is different from the
* for .. in construct in that:
* <BR> - it doesn't perform ToObject on the right hand side
* <BR> - it returns true for DontEnum properties.
* @param a the left hand operand
* @param b the right hand operand
*
* @return true if property name or element number a is a property of b
*/
public static boolean in(Object a, Object b, Scriptable scope) {
if (!(b instanceof Scriptable)) {
throw NativeGlobal.constructError(
Context.getContext(),
"TypeError",
ScriptRuntime.getMessage("msg.instanceof.not.object", null),
scope);
}
String s = getStringId(a);
return s != null
? ScriptableObject.hasProperty((Scriptable) b, s)
: ScriptableObject.hasProperty((Scriptable) b, getIntId(a));
}
public static Boolean cmp_LTB(Object val1, Object val2) {
if (cmp_LT(val1, val2) == 1)
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static int cmp_LT(Object val1, Object val2) {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (!(val1 instanceof String) || !(val2 instanceof String)) {
double d1 = toNumber(val1);
if (d1 != d1)
return 0;
double d2 = toNumber(val2);
if (d2 != d2)
return 0;
return d1 < d2 ? 1 : 0;
}
return toString(val1).compareTo(toString(val2)) < 0 ? 1 : 0;
}
public static Boolean cmp_LEB(Object val1, Object val2) {
if (cmp_LE(val1, val2) == 1)
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static int cmp_LE(Object val1, Object val2) {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (!(val1 instanceof String) || !(val2 instanceof String)) {
double d1 = toNumber(val1);
if (d1 != d1)
return 0;
double d2 = toNumber(val2);
if (d2 != d2)
return 0;
return d1 <= d2 ? 1 : 0;
}
return toString(val1).compareTo(toString(val2)) <= 0 ? 1 : 0;
}
// lt:
// implement the '<' operator inline in the caller
// as "compare(val1, val2) == 1"
// le:
// implement the '<=' operator inline in the caller
// as "compare(val2, val1) == 0"
// gt:
// implement the '>' operator inline in the caller
// as "compare(val2, val1) == 1"
// ge:
// implement the '>=' operator inline in the caller
// as "compare(val1, val2) == 0"
// ------------------
// Statements
// ------------------
public static void main(String scriptClassName, String[] args)
throws JavaScriptException
{
Context cx = Context.enter();
ScriptableObject global = new ImporterTopLevel();
cx.initStandardObjects(global);
Global.initTopLevelScope(cx, global);
// get the command line arguments and define "arguments"
// array in the top-level object
Scriptable argsObj = cx.newArray(global, args);
global.defineProperty("arguments", argsObj,
ScriptableObject.DONTENUM);
try {
Class cl = loadClassName(scriptClassName);
Script script = (Script) cl.newInstance();
script.exec(cx, global);
return;
}
catch (ClassNotFoundException e) {
}
catch (InstantiationException e) {
}
catch (IllegalAccessException e) {
}
finally {
Context.exit();
}
throw new RuntimeException("Error creating script object");
}
public static Scriptable initScript(Context cx, Scriptable scope,
NativeFunction funObj,
Scriptable thisObj,
boolean fromEvalCode)
{
String[] names = funObj.names;
if (names != null) {
ScriptableObject so;
try {
/* Global var definitions are supposed to be DONTDELETE
* so we try to create them that way by hoping that the
* scope is a ScriptableObject which provides access to
* setting the attributes.
*/
so = (ScriptableObject) scope;
} catch (ClassCastException x) {
// oh well, we tried.
so = null;
}
Scriptable varScope = scope;
if (fromEvalCode) {
// When executing an eval() inside a with statement,
// define any variables resulting from var statements
// in the first non-with scope. See bug 38590.
varScope = scope;
while (varScope instanceof NativeWith)
varScope = varScope.getParentScope();
}
for (int i=funObj.names.length-1; i > 0; i--) {
String name = funObj.names[i];
// Don't overwrite existing def if already defined in object
// or prototypes of object.
if (!hasProp(scope, name)) {
if (so != null && !fromEvalCode)
so.defineProperty(name, Undefined.instance,
ScriptableObject.PERMANENT);
else
varScope.put(name, varScope, Undefined.instance);
}
}
}
return scope;
}
public static Scriptable runScript(Script script) {
Context cx = Context.enter();
ScriptableObject global = new ImporterTopLevel();
cx.initStandardObjects(global);
Global.initTopLevelScope(cx, global);
try {
script.exec(cx, global);
} catch (JavaScriptException e) {
throw new Error(e.toString());
}
Context.exit();
return global;
}
public static Scriptable initVarObj(Context cx, Scriptable scope,
NativeFunction funObj,
Scriptable thisObj, Object[] args)
{
NativeCall result = new NativeCall(cx, scope, funObj, thisObj, args);
String[] names = funObj.names;
if (names != null) {
for (int i=funObj.argCount+1; i < funObj.names.length; i++) {
String name = funObj.names[i];
result.put(name, result, Undefined.instance);
}
}
return result;
}
public static void popActivation(Context cx) {
NativeCall current = cx.currentActivation;
if (current != null) {
cx.currentActivation = current.caller;
current.caller = null;
}
}
public static Scriptable newScope() {
return new NativeObject();
}
public static Scriptable enterWith(Object value, Scriptable scope) {
return new NativeWith(scope, toObject(scope, value));
}
public static Scriptable leaveWith(Scriptable scope) {
return scope.getParentScope();
}
public static NativeFunction initFunction(NativeFunction fn,
Scriptable scope,
String fnName,
Context cx,
boolean doSetName)
{
fn.setPrototype(ScriptableObject.getClassPrototype(scope, "Function"));
fn.setParentScope(scope);
if (doSetName)
setName(scope, fn, scope, fnName);
return fn;
}
public static NativeFunction createFunctionObject(Scriptable scope,
Class functionClass,
Context cx,
boolean setName)
{
Constructor[] ctors = functionClass.getConstructors();
NativeFunction result = null;
Object[] initArgs = { scope, cx };
try {
result = (NativeFunction) ctors[0].newInstance(initArgs);
}
catch (InstantiationException e) {
throw WrappedException.wrapException(e);
}
catch (IllegalAccessException e) {
throw WrappedException.wrapException(e);
}
catch (IllegalArgumentException e) {
throw WrappedException.wrapException(e);
}
catch (InvocationTargetException e) {
throw WrappedException.wrapException(e);
}
result.setPrototype(ScriptableObject.getClassPrototype(scope, "Function"));
result.setParentScope(scope);
String fnName = result.jsGet_name();
if (setName && fnName != null && fnName.length() != 0 &&
!fnName.equals("anonymous"))
{
setProp(scope, fnName, result, scope);
}
return result;
}
static void checkDeprecated(Context cx, String name) {
int version = cx.getLanguageVersion();
if (version >= Context.VERSION_1_4 || version == Context.VERSION_DEFAULT) {
Object[] errArgs = { name };
String msg = getMessage("msg.deprec.ctor",
errArgs);
if (version == Context.VERSION_DEFAULT)
Context.reportWarning(msg);
else
throw Context.reportRuntimeError(msg);
}
}
public static String getMessage(String messageId, Object[] arguments) {
return Context.getMessage(messageId, arguments);
}
public static RegExpProxy getRegExpProxy(Context cx) {
return cx.getRegExpProxy();
}
public static NativeCall getCurrentActivation(Context cx) {
return cx.currentActivation;
}
public static void setCurrentActivation(Context cx,
NativeCall activation)
{
cx.currentActivation = activation;
}
private static Method getContextClassLoaderMethod;
static {
try {
// We'd like to use "getContextClassLoader", but
// that's only available on Java2.
getContextClassLoaderMethod =
Thread.class.getDeclaredMethod("getContextClassLoader",
new Class[0]);
} catch (NoSuchMethodException e) {
// ignore exceptions; we'll use Class.forName instead.
} catch (SecurityException e) {
// ignore exceptions; we'll use Class.forName instead.
}
}
public static Class loadClassName(String className)
throws ClassNotFoundException
{
try {
if (getContextClassLoaderMethod != null) {
ClassLoader cl = (ClassLoader)
getContextClassLoaderMethod.invoke(
Thread.currentThread(),
new Object[0]);
if (cl != null)
return cl.loadClass(className);
}
} catch (SecurityException e) {
// fall through...
} catch (IllegalAccessException e) {
// fall through...
} catch (InvocationTargetException e) {
// fall through...
} catch (ClassNotFoundException e) {
// Rather than just letting the exception propagate
// we'll try Class.forName as well. The results could be
// different if this class was loaded on a different
// thread than the current thread.
// So fall through...
}
return Class.forName(className);
}
static boolean hasProp(Scriptable start, String name) {
Scriptable m = start;
do {
if (m.has(name, start))
return true;
m = m.getPrototype();
} while (m != null);
return false;
}
private static RuntimeException errorWithClassName(String msg, Object val)
{
Object[] args = { val.getClass().getName() };
return Context.reportRuntimeError(getMessage(msg, args));
}
static public Object[] emptyArgs = new Object[0];
}
/**
* This is the enumeration needed by the for..in statement.
*
* See ECMA 12.6.3.
*
* IdEnumeration maintains a Hashtable to make sure a given
* id is enumerated only once across multiple objects in a
* prototype chain.
*
* XXX - ECMA delete doesn't hide properties in the prototype,
* but js/ref does. This means that the js/ref for..in can
* avoid maintaining a hash table and instead perform lookups
* to see if a given property has already been enumerated.
*
*/
class IdEnumeration implements Enumeration {
IdEnumeration(Scriptable m) {
used = new Hashtable(27);
changeObject(m);
next = getNext();
}
public boolean hasMoreElements() {
return next != null;
}
public Object nextElement() {
Object result = next;
// only key used; 'next' as value for convenience
used.put(next, next);
next = getNext();
return result;
}
private void changeObject(Scriptable m) {
obj = m;
if (obj != null) {
array = m.getIds();
if (array.length == 0)
changeObject(obj.getPrototype());
}
index = 0;
}
private Object getNext() {
if (obj == null)
return null;
Object result;
for (;;) {
if (index == array.length) {
changeObject(obj.getPrototype());
if (obj == null)
return null;
}
result = array[index++];
if (result instanceof String) {
if (!obj.has((String) result, obj))
continue; // must have been deleted
} else {
if (!obj.has(((Number) result).intValue(), obj))
continue; // must have been deleted
}
if (!used.containsKey(result)) {
break;
}
}
return ScriptRuntime.toString(result);
}
private Object next;
private Scriptable obj;
private int index;
private Object[] array;
private Hashtable used;
}
diff --git a/src/org/mozilla/javascript/ScriptRuntime.java b/src/org/mozilla/javascript/ScriptRuntime.java
index 3e88cfdf..8367d4db 100644
--- a/src/org/mozilla/javascript/ScriptRuntime.java
+++ b/src/org/mozilla/javascript/ScriptRuntime.java
@@ -1,2173 +1,2173 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
* Frank Mitchell
* Andrew Wason
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.util.*;
import java.lang.reflect.*;
import org.mozilla.javascript.tools.shell.Global;
/**
* This is the class that implements the runtime.
*
* @author Norris Boyd
*/
public class ScriptRuntime {
/**
* No instances should be created.
*/
protected ScriptRuntime() {
}
/*
* There's such a huge space (and some time) waste for the Foo.class
* syntax: the compiler sticks in a test of a static field in the
* enclosing class for null and the code for creating the class value.
* It has to do this since the reference has to get pushed off til
* executiontime (i.e. can't force an early load), but for the
* 'standard' classes - especially those in java.lang, we can trust
* that they won't cause problems by being loaded early.
*/
public final static Class UndefinedClass = Undefined.class;
public final static Class ScriptableClass = Scriptable.class;
public final static Class StringClass = String.class;
public final static Class NumberClass = Number.class;
public final static Class BooleanClass = Boolean.class;
public final static Class ByteClass = Byte.class;
public final static Class ShortClass = Short.class;
public final static Class IntegerClass = Integer.class;
public final static Class LongClass = Long.class;
public final static Class FloatClass = Float.class;
public final static Class DoubleClass = Double.class;
public final static Class CharacterClass = Character.class;
public final static Class ObjectClass = Object.class;
public final static Class FunctionClass = Function.class;
public final static Class ClassClass = Class.class;
/**
* Convert the value to a boolean.
*
* See ECMA 9.2.
*/
public static boolean toBoolean(Object val) {
if (val == null)
return false;
if (val instanceof Scriptable) {
if (Context.getContext().isVersionECMA1()) {
// pure ECMA
return val != Undefined.instance;
}
// ECMA extension
val = ((Scriptable) val).getDefaultValue(BooleanClass);
if (val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
// fall through
}
if (val instanceof String)
return ((String) val).length() != 0;
if (val instanceof Number) {
double d = ((Number) val).doubleValue();
return (d == d && d != 0.0);
}
if (val instanceof Boolean)
return ((Boolean) val).booleanValue();
throw errorWithClassName("msg.invalid.type", val);
}
/**
* Convert the value to a number.
*
* See ECMA 9.3.
*/
public static double toNumber(Object val) {
if (val != null && val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(NumberClass);
if (val != null && val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
// fall through
}
if (val == null)
return +0.0;
if (val instanceof String)
return toNumber((String) val);
if (val instanceof Number)
return ((Number) val).doubleValue();
if (val instanceof Boolean)
return ((Boolean) val).booleanValue() ? 1 : +0.0;
throw errorWithClassName("msg.invalid.type", val);
}
// This definition of NaN is identical to that in java.lang.Double
// except that it is not final. This is a workaround for a bug in
// the Microsoft VM, versions 2.01 and 3.0P1, that causes some uses
// (returns at least) of Double.NaN to be converted to 1.0.
// So we use ScriptRuntime.NaN instead of Double.NaN.
public static double NaN = 0.0d / 0.0;
public static Double NaNobj = new Double(0.0d / 0.0);
// A similar problem exists for negative zero.
public static double negativeZero = -0.0;
/*
* Helper function for toNumber, parseInt, and TokenStream.getToken.
*/
static double stringToNumber(String s, int start, int radix) {
char digitMax = '9';
char lowerCaseBound = 'a';
char upperCaseBound = 'A';
int len = s.length();
if (radix < 10) {
digitMax = (char) ('0' + radix - 1);
}
if (radix > 10) {
lowerCaseBound = (char) ('a' + radix - 10);
upperCaseBound = (char) ('A' + radix - 10);
}
int end;
double sum = 0.0;
for (end=start; end < len; end++) {
char c = s.charAt(end);
int newDigit;
if ('0' <= c && c <= digitMax)
newDigit = c - '0';
else if ('a' <= c && c < lowerCaseBound)
newDigit = c - 'a' + 10;
else if ('A' <= c && c < upperCaseBound)
newDigit = c - 'A' + 10;
else
break;
sum = sum*radix + newDigit;
}
if (start == end) {
return NaN;
}
if (sum >= 9007199254740992.0) {
if (radix == 10) {
/* If we're accumulating a decimal number and the number
* is >= 2^53, then the result from the repeated multiply-add
* above may be inaccurate. Call Java to get the correct
* answer.
*/
try {
return Double.valueOf(s.substring(start, end)).doubleValue();
} catch (NumberFormatException nfe) {
return NaN;
}
} else if (radix == 2 || radix == 4 || radix == 8 ||
radix == 16 || radix == 32)
{
/* The number may also be inaccurate for one of these bases.
* This happens if the addition in value*radix + digit causes
* a round-down to an even least significant mantissa bit
* when the first dropped bit is a one. If any of the
* following digits in the number (which haven't been added
* in yet) are nonzero then the correct action would have
* been to round up instead of down. An example of this
* occurs when reading the number 0x1000000000000081, which
* rounds to 0x1000000000000000 instead of 0x1000000000000100.
*/
BinaryDigitReader bdr = new BinaryDigitReader(radix, s, start, end);
int bit;
sum = 0.0;
/* Skip leading zeros. */
do {
bit = bdr.getNextBinaryDigit();
} while (bit == 0);
if (bit == 1) {
/* Gather the 53 significant bits (including the leading 1) */
sum = 1.0;
for (int j = 52; j != 0; j--) {
bit = bdr.getNextBinaryDigit();
if (bit < 0)
return sum;
sum = sum*2 + bit;
}
/* bit54 is the 54th bit (the first dropped from the mantissa) */
int bit54 = bdr.getNextBinaryDigit();
if (bit54 >= 0) {
double factor = 2.0;
int sticky = 0; /* sticky is 1 if any bit beyond the 54th is 1 */
int bit3;
while ((bit3 = bdr.getNextBinaryDigit()) >= 0) {
sticky |= bit3;
factor *= 2;
}
sum += bit54 & (bit | sticky);
sum *= factor;
}
}
}
/* We don't worry about inaccurate numbers for any other base. */
}
return sum;
}
/**
* ToNumber applied to the String type
*
* See ECMA 9.3.1
*/
public static double toNumber(String s) {
int len = s.length();
int start = 0;
char startChar;
for (;;) {
if (start == len) {
// Empty or contains only whitespace
return +0.0;
}
startChar = s.charAt(start);
if (!Character.isWhitespace(startChar))
break;
start++;
}
if (startChar == '0' && start+2 < len &&
Character.toLowerCase(s.charAt(start+1)) == 'x')
// A hexadecimal number
return stringToNumber(s, start + 2, 16);
if ((startChar == '+' || startChar == '-') && start+3 < len &&
s.charAt(start+1) == '0' &&
Character.toLowerCase(s.charAt(start+2)) == 'x') {
// A hexadecimal number
double val = stringToNumber(s, start + 3, 16);
return startChar == '-' ? -val : val;
}
int end = len - 1;
char endChar;
while (Character.isWhitespace(endChar = s.charAt(end)))
end--;
if (endChar == 'y') {
// check for "Infinity"
if (startChar == '+' || startChar == '-')
start++;
- if (s.regionMatches(start, "Infinity", 0, 8))
+ if (start + 7 == end && s.regionMatches(start, "Infinity", 0, 8))
return startChar == '-'
? Double.NEGATIVE_INFINITY
: Double.POSITIVE_INFINITY;
return NaN;
}
// A non-hexadecimal, non-infinity number:
// just try a normal floating point conversion
String sub = s.substring(start, end+1);
if (MSJVM_BUG_WORKAROUNDS) {
// The MS JVM will accept non-conformant strings
// rather than throwing a NumberFormatException
// as it should.
for (int i=sub.length()-1; i >= 0; i--) {
char c = sub.charAt(i);
if (('0' <= c && c <= '9') || c == '.' ||
c == 'e' || c == 'E' ||
c == '+' || c == '-')
continue;
return NaN;
}
}
try {
return Double.valueOf(sub).doubleValue();
} catch (NumberFormatException ex) {
return NaN;
}
}
/**
* Helper function for builtin objects that use the varargs form.
* ECMA function formal arguments are undefined if not supplied;
* this function pads the argument array out to the expected
* length, if necessary.
*/
public static Object[] padArguments(Object[] args, int count) {
if (count < args.length)
return args;
int i;
Object[] result = new Object[count];
for (i = 0; i < args.length; i++) {
result[i] = args[i];
}
for (; i < count; i++) {
result[i] = Undefined.instance;
}
return result;
}
/* Work around Microsoft Java VM bugs. */
private final static boolean MSJVM_BUG_WORKAROUNDS = true;
/**
* For escaping strings printed by object and array literals; not quite
* the same as 'escape.'
*/
public static String escapeString(String s) {
// ack! Java lacks \v.
String escapeMap = "\bb\ff\nn\rr\tt\u000bv\"\"''";
StringBuffer result = new StringBuffer(s.length());
for(int i=0; i < s.length(); i++) {
char c = s.charAt(i);
// an ordinary print character
if (c >= ' ' && c <= '~' // string.h isprint()
&& c != '"')
{
result.append(c);
continue;
}
// an \escaped sort of character
int index;
if ((index = escapeMap.indexOf(c)) >= 0) {
result.append("\\");
result.append(escapeMap.charAt(index + 1));
continue;
}
// 2-digit hex?
if (c < 256) {
String hex = Integer.toHexString((int) c);
if (hex.length() == 1) {
result.append("\\x0");
result.append(hex);
} else {
result.append("\\x");
result.append(hex);
}
continue;
}
// nope. Unicode.
String hex = Integer.toHexString((int) c);
// cool idiom courtesy Shaver.
result.append("\\u");
for (int l = hex.length(); l < 4; l++)
result.append("0");
result.append(hex);
}
return result.toString();
}
/**
* Convert the value to a string.
*
* See ECMA 9.8.
*/
public static String toString(Object val) {
for (;;) {
if (val == null)
return "null";
if (val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(StringClass);
if (val != Undefined.instance && val instanceof Scriptable) {
throw errorWithClassName("msg.primitive.expected", val);
}
continue;
}
if (val instanceof Number) {
// XXX should we just teach NativeNumber.stringValue()
// about Numbers?
return numberToString(((Number) val).doubleValue(), 10);
}
return val.toString();
}
}
public static String numberToString(double d, int base) {
if (d != d)
return "NaN";
if (d == Double.POSITIVE_INFINITY)
return "Infinity";
if (d == Double.NEGATIVE_INFINITY)
return "-Infinity";
if (d == 0.0)
return "0";
if ((base < 2) || (base > 36)) {
Object[] args = { Integer.toString(base) };
throw Context.reportRuntimeError(getMessage
("msg.bad.radix", args));
}
if (base != 10) {
return DToA.JS_dtobasestr(base, d);
} else {
StringBuffer result = new StringBuffer();
DToA.JS_dtostr(result, DToA.DTOSTR_STANDARD, 0, d);
return result.toString();
}
}
/**
* Convert the value to an object.
*
* See ECMA 9.9.
*/
public static Scriptable toObject(Scriptable scope, Object val) {
return toObject(scope, val, null);
}
public static Scriptable toObject(Scriptable scope, Object val,
Class staticClass)
{
if (val == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
if (val instanceof Scriptable) {
if (val == Undefined.instance) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.undef.to.object", null),
scope);
}
return (Scriptable) val;
}
String className = val instanceof String ? "String" :
val instanceof Number ? "Number" :
val instanceof Boolean ? "Boolean" :
null;
if (className == null) {
// Extension: Wrap as a LiveConnect object.
Object wrapped = NativeJavaObject.wrap(scope, val, staticClass);
if (wrapped instanceof Scriptable)
return (Scriptable) wrapped;
throw errorWithClassName("msg.invalid.type", val);
}
Object[] args = { val };
scope = ScriptableObject.getTopLevelScope(scope);
Scriptable result = newObject(Context.getContext(), scope,
className, args);
return result;
}
public static Scriptable newObject(Context cx, Scriptable scope,
String constructorName, Object[] args)
{
Exception re = null;
try {
return cx.newObject(scope, constructorName, args);
}
catch (NotAFunctionException e) {
re = e;
}
catch (PropertyException e) {
re = e;
}
catch (JavaScriptException e) {
re = e;
}
throw cx.reportRuntimeError(re.getMessage());
}
/**
*
* See ECMA 9.4.
*/
public static double toInteger(Object val) {
double d = toNumber(val);
// if it's NaN
if (d != d)
return +0.0;
if (d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return d;
if (d > 0.0)
return Math.floor(d);
else
return Math.ceil(d);
}
// convenience method
public static double toInteger(double d) {
// if it's NaN
if (d != d)
return +0.0;
if (d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return d;
if (d > 0.0)
return Math.floor(d);
else
return Math.ceil(d);
}
/**
*
* See ECMA 9.5.
*/
public static int toInt32(Object val) {
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
double two31 = 2147483648.0;
// short circuit for common small values; TokenStream
// returns them as Bytes.
if (val instanceof Byte)
return ((Number)val).intValue();
double d = toNumber(val);
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return 0;
d = Math.IEEEremainder(d, two32);
d = d >= 0
? d
: d + two32;
if (d >= two31)
return (int)(d - two32);
else
return (int)d;
}
public static int toInt32(double d) {
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
double two31 = 2147483648.0;
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return 0;
d = Math.IEEEremainder(d, two32);
d = d >= 0
? d
: d + two32;
if (d >= two31)
return (int)(d - two32);
else
return (int)d;
}
/**
*
* See ECMA 9.6.
*/
// must return long to hold an _unsigned_ int
public static long toUint32(double d) {
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return 0;
if (d > 0.0)
d = Math.floor(d);
else
d = Math.ceil(d);
d = Math.IEEEremainder(d, two32);
d = d >= 0
? d
: d + two32;
return (long) Math.floor(d);
}
public static long toUint32(Object val) {
return toUint32(toNumber(val));
}
/**
*
* See ECMA 9.7.
*/
public static char toUint16(Object val) {
long int16 = 0x10000;
double d = toNumber(val);
if (d != d || d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = Math.IEEEremainder(d, int16);
d = d >= 0
? d
: d + int16;
return (char) Math.floor(d);
}
/**
* Unwrap a JavaScriptException. Sleight of hand so that we don't
* javadoc JavaScriptException.getRuntimeValue().
*/
public static Object unwrapJavaScriptException(JavaScriptException jse) {
return jse.value;
}
public static Object getProp(Object obj, String id, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null || start == Undefined.instance) {
String msg = start == null ? "msg.null.to.object"
: "msg.undefined";
throw NativeGlobal.constructError(
Context.getContext(), "ConversionError",
ScriptRuntime.getMessage(msg, null),
scope);
}
Scriptable m = start;
do {
Object result = m.get(id, start);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
} while (m != null);
return Undefined.instance;
}
public static Object getTopLevelProp(Scriptable scope, String id) {
Scriptable s = ScriptableObject.getTopLevelScope(scope);
Object v;
do {
v = s.get(id, s);
if (v != Scriptable.NOT_FOUND)
return v;
s = s.getPrototype();
} while (s != null);
return v;
}
/***********************************************************************/
public static Scriptable getProto(Object obj, Scriptable scope) {
Scriptable s;
if (obj instanceof Scriptable) {
s = (Scriptable) obj;
} else {
s = toObject(scope, obj);
}
if (s == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
return s.getPrototype();
}
public static Scriptable getParent(Object obj) {
Scriptable s;
try {
s = (Scriptable) obj;
}
catch (ClassCastException e) {
return null;
}
if (s == null) {
return null;
}
return getThis(s.getParentScope());
}
public static Scriptable getParent(Object obj, Scriptable scope) {
Scriptable s;
if (obj instanceof Scriptable) {
s = (Scriptable) obj;
} else {
s = toObject(scope, obj);
}
if (s == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
return s.getParentScope();
}
public static Object setProto(Object obj, Object value, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
Scriptable result = value == null ? null : toObject(scope, value);
Scriptable s = result;
while (s != null) {
if (s == start) {
Object[] args = { "__proto__" };
throw Context.reportRuntimeError(getMessage
("msg.cyclic.value", args));
}
s = s.getPrototype();
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
start.setPrototype(result);
return result;
}
public static Object setParent(Object obj, Object value, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
Scriptable result = value == null ? null : toObject(scope, value);
Scriptable s = result;
while (s != null) {
if (s == start) {
Object[] args = { "__parent__" };
throw Context.reportRuntimeError(getMessage
("msg.cyclic.value", args));
}
s = s.getParentScope();
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
start.setParentScope(result);
return result;
}
public static Object setProp(Object obj, String id, Object value,
Scriptable scope)
{
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
Scriptable m = start;
do {
if (m.has(id, start)) {
m.put(id, start, value);
return value;
}
m = m.getPrototype();
} while (m != null);
start.put(id, start, value);
return value;
}
// Return -1L if str is not an index or the index value as lower 32
// bits of the result
private static long indexFromString(String str) {
// It must be a string.
// The length of the decimal string representation of
// Integer.MAX_VALUE, 2147483647
final int MAX_VALUE_LENGTH = 10;
int len = str.length();
if (len > 0) {
int i = 0;
boolean negate = false;
int c = str.charAt(0);
if (c == '-') {
if (len > 1) {
c = str.charAt(1);
i = 1;
negate = true;
}
}
c -= '0';
if (0 <= c && c <= 9
&& len <= (negate ? MAX_VALUE_LENGTH + 1 : MAX_VALUE_LENGTH))
{
// Use negative numbers to accumulate index to handle
// Integer.MIN_VALUE that is greater by 1 in absolute value
// then Integer.MAX_VALUE
int index = -c;
int oldIndex = 0;
i++;
if (index != 0) {
// Note that 00, 01, 000 etc. are not indexes
while (i != len && 0 <= (c = str.charAt(i) - '0') && c <= 9)
{
oldIndex = index;
index = 10 * index - c;
i++;
}
}
// Make sure all characters were consumed and that it couldn't
// have overflowed.
if (i == len &&
(oldIndex > (Integer.MIN_VALUE / 10) ||
(oldIndex == (Integer.MIN_VALUE / 10) &&
c <= (negate ? -(Integer.MIN_VALUE % 10)
: (Integer.MAX_VALUE % 10)))))
{
return 0xFFFFFFFFL & (negate ? index : -index);
}
}
}
return -1L;
}
static String getStringId(Object id) {
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
int index = (int) d;
if (((double) index) == d)
return null;
return toString(id);
}
String s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0)
return null;
return s;
}
static int getIntId(Object id) {
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
int index = (int) d;
if (((double) index) == d)
return index;
return 0;
}
String s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0)
return (int)indexTest;
return 0;
}
public static Object getElem(Object obj, Object id, Scriptable scope) {
int index;
String s;
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
index = (int) d;
s = ((double) index) == d ? null : toString(id);
} else {
s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0) {
index = (int)indexTest;
s = null;
} else {
index = 0;
}
}
Scriptable start = obj instanceof Scriptable
? (Scriptable) obj
: toObject(scope, obj);
Scriptable m = start;
if (s != null) {
if (s.equals("__proto__"))
return start.getPrototype();
if (s.equals("__parent__"))
return start.getParentScope();
while (m != null) {
Object result = m.get(s, start);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
}
return Undefined.instance;
}
while (m != null) {
Object result = m.get(index, start);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
}
return Undefined.instance;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object getElem(Scriptable obj, int index)
{
Scriptable m = obj;
while (m != null) {
Object result = m.get(index, obj);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
}
return Undefined.instance;
}
public static Object setElem(Object obj, Object id, Object value,
Scriptable scope)
{
int index;
String s;
if (id instanceof Number) {
double d = ((Number) id).doubleValue();
index = (int) d;
s = ((double) index) == d ? null : toString(id);
} else {
s = toString(id);
long indexTest = indexFromString(s);
if (indexTest >= 0) {
index = (int)indexTest;
s = null;
} else {
index = 0;
}
}
Scriptable start = obj instanceof Scriptable
? (Scriptable) obj
: toObject(scope, obj);
Scriptable m = start;
if (s != null) {
if (s.equals("__proto__"))
return setProto(obj, value, scope);
if (s.equals("__parent__"))
return setParent(obj, value, scope);
do {
if (m.has(s, start)) {
m.put(s, start, value);
return value;
}
m = m.getPrototype();
} while (m != null);
start.put(s, start, value);
return value;
}
do {
if (m.has(index, start)) {
m.put(index, start, value);
return value;
}
m = m.getPrototype();
} while (m != null);
start.put(index, start, value);
return value;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object setElem(Scriptable obj, int index, Object value)
{
Scriptable m = obj;
do {
if (m.has(index, obj)) {
m.put(index, obj, value);
return value;
}
m = m.getPrototype();
} while (m != null);
obj.put(index, obj, value);
return value;
}
/**
* The delete operator
*
* See ECMA 11.4.1
*
* In ECMA 0.19, the description of the delete operator (11.4.1)
* assumes that the [[Delete]] method returns a value. However,
* the definition of the [[Delete]] operator (8.6.2.5) does not
* define a return value. Here we assume that the [[Delete]]
* method doesn't return a value.
*/
public static Object delete(Object obj, Object id) {
String s = getStringId(id);
boolean result = s != null
? ScriptableObject.deleteProperty((Scriptable) obj, s)
: ScriptableObject.deleteProperty((Scriptable) obj, getIntId(id));
return result ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Looks up a name in the scope chain and returns its value.
*/
public static Object name(Scriptable scopeChain, String id) {
Scriptable obj = scopeChain;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
Object result = m.get(id, obj);
if (result != Scriptable.NOT_FOUND)
return result;
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object[] args = { id.toString() };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scopeChain);
}
/**
* Returns the object in the scope chain that has a given property.
*
* The order of evaluation of an assignment expression involves
* evaluating the lhs to a reference, evaluating the rhs, and then
* modifying the reference with the rhs value. This method is used
* to 'bind' the given name to an object containing that property
* so that the side effects of evaluating the rhs do not affect
* which property is modified.
* Typically used in conjunction with setName.
*
* See ECMA 10.1.4
*/
public static Scriptable bind(Scriptable scope, String id) {
Scriptable obj = scope;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
if (m.has(id, obj))
return obj;
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
return null;
}
public static Scriptable getBase(Scriptable scope, String id) {
Scriptable obj = scope;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
if (m.get(id, obj) != Scriptable.NOT_FOUND)
return obj;
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object[] args = { id };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scope);
}
public static Scriptable getThis(Scriptable base) {
while (base instanceof NativeWith)
base = base.getPrototype();
if (base instanceof NativeCall)
base = ScriptableObject.getTopLevelScope(base);
return base;
}
public static Object setName(Scriptable bound, Object value,
Scriptable scope, String id)
{
if (bound == null) {
// "newname = 7;", where 'newname' has not yet
// been defined, creates a new property in the
// global object. Find the global object by
// walking up the scope chain.
Scriptable next = scope;
do {
bound = next;
next = bound.getParentScope();
} while (next != null);
bound.put(id, bound, value);
/*
This code is causing immense performance problems in
scripts that assign to the variables as a way of creating them.
XXX need strict mode
String[] args = { id };
String message = getMessage("msg.assn.create", args);
Context.reportWarning(message);
*/
return value;
}
return setProp(bound, id, value, scope);
}
public static Enumeration initEnum(Object value, Scriptable scope) {
Scriptable m = toObject(scope, value);
return new IdEnumeration(m);
}
public static Object nextEnum(Enumeration enum) {
// OPT this could be more efficient; should junk the Enumeration
// interface
if (!enum.hasMoreElements())
return null;
return enum.nextElement();
}
// Form used by class files generated by 1.4R3 and earlier.
public static Object call(Context cx, Object fun, Object thisArg,
Object[] args)
throws JavaScriptException
{
Scriptable scope = null;
if (fun instanceof Scriptable)
scope = ((Scriptable) fun).getParentScope();
return call(cx, fun, thisArg, args, scope);
}
public static Object call(Context cx, Object fun, Object thisArg,
Object[] args, Scriptable scope)
throws JavaScriptException
{
Function function;
try {
function = (Function) fun;
}
catch (ClassCastException e) {
Object[] errorArgs = { toString(fun) };
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.isnt.function",
errorArgs),
scope);
}
Scriptable thisObj;
if (thisArg instanceof Scriptable || thisArg == null) {
thisObj = (Scriptable) thisArg;
} else {
thisObj = ScriptRuntime.toObject(scope, thisArg);
}
return function.call(cx, scope, thisObj, args);
}
private static Object callOrNewSpecial(Context cx, Scriptable scope,
Object fun, Object jsThis, Object thisArg,
Object[] args, boolean isCall,
String filename, int lineNumber)
throws JavaScriptException
{
if (fun instanceof FunctionObject) {
FunctionObject fo = (FunctionObject) fun;
Member m = fo.method;
Class cl = m.getDeclaringClass();
String name = m.getName();
if (name.equals("eval") && cl == NativeGlobal.class)
return NativeGlobal.evalSpecial(cx, scope, thisArg, args,
filename, lineNumber);
if (name.equals("With") && cl == NativeWith.class)
return NativeWith.newWithSpecial(cx, args, fo, !isCall);
if (name.equals("jsFunction_exec") && cl == NativeScript.class)
return ((NativeScript)jsThis).exec(cx, ScriptableObject.getTopLevelScope(scope));
if (name.equals("exec")
&& (cx.getRegExpProxy() != null)
&& (cx.getRegExpProxy().isRegExp(jsThis)))
return call(cx, fun, jsThis, args, scope);
}
else // could've been <java>.XXX.exec() that was re-directed here
if (fun instanceof NativeJavaMethod)
return call(cx, fun, jsThis, args, scope);
if (isCall)
return call(cx, fun, thisArg, args, scope);
return newObject(cx, fun, args, scope);
}
public static Object callSpecial(Context cx, Object fun,
Object thisArg, Object[] args,
Scriptable enclosingThisArg,
Scriptable scope, String filename,
int lineNumber)
throws JavaScriptException
{
return callOrNewSpecial(cx, scope, fun, thisArg,
enclosingThisArg, args, true,
filename, lineNumber);
}
/**
* Operator new.
*
* See ECMA 11.2.2
*/
public static Scriptable newObject(Context cx, Object fun,
Object[] args, Scriptable scope)
throws JavaScriptException
{
Function f;
try {
f = (Function) fun;
if (f != null) {
return f.construct(cx, scope, args);
}
// else fall through to error
} catch (ClassCastException e) {
// fall through to error
}
Object[] errorArgs = { toString(fun) };
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.isnt.function", errorArgs),
scope);
}
public static Scriptable newObjectSpecial(Context cx, Object fun,
Object[] args, Scriptable scope)
throws JavaScriptException
{
return (Scriptable) callOrNewSpecial(cx, scope, fun, null, null, args,
false, null, -1);
}
/**
* The typeof operator
*/
public static String typeof(Object value) {
if (value == Undefined.instance)
return "undefined";
if (value == null)
return "object";
if (value instanceof Scriptable)
return (value instanceof Function) ? "function" : "object";
if (value instanceof String)
return "string";
if (value instanceof Number)
return "number";
if (value instanceof Boolean)
return "boolean";
throw errorWithClassName("msg.invalid.type", value);
}
/**
* The typeof operator that correctly handles the undefined case
*/
public static String typeofName(Scriptable scope, String id) {
Object val = bind(scope, id);
if (val == null)
return "undefined";
return typeof(getProp(val, id, scope));
}
// neg:
// implement the '-' operator inline in the caller
// as "-toNumber(val)"
// not:
// implement the '!' operator inline in the caller
// as "!toBoolean(val)"
// bitnot:
// implement the '~' operator inline in the caller
// as "~toInt32(val)"
public static Object add(Object val1, Object val2) {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(null);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(null);
if (!(val1 instanceof String) && !(val2 instanceof String))
if ((val1 instanceof Number) && (val2 instanceof Number))
return new Double(((Number)val1).doubleValue() +
((Number)val2).doubleValue());
else
return new Double(toNumber(val1) + toNumber(val2));
return toString(val1) + toString(val2);
}
public static Object postIncrement(Object value) {
if (value instanceof Number)
value = new Double(((Number)value).doubleValue() + 1.0);
else
value = new Double(toNumber(value) + 1.0);
return value;
}
public static Object postIncrement(Scriptable scopeChain, String id) {
Scriptable obj = scopeChain;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
Object result = m.get(id, obj);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() + 1.0);
m.put(id, obj, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) + 1.0);
m.put(id, obj, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object args[] = { id };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scopeChain);
}
public static Object postIncrement(Object obj, String id, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
Scriptable m = start;
do {
Object result = m.get(id, start);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() + 1.0);
m.put(id, start, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) + 1.0);
m.put(id, start, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
return Undefined.instance;
}
public static Object postIncrementElem(Object obj,
Object index, Scriptable scope) {
Object oldValue = getElem(obj, index, scope);
if (oldValue == Undefined.instance)
return Undefined.instance;
double resultValue = toNumber(oldValue);
Double newValue = new Double(resultValue + 1.0);
setElem(obj, index, newValue, scope);
return new Double(resultValue);
}
public static Object postDecrementElem(Object obj,
Object index, Scriptable scope) {
Object oldValue = getElem(obj, index, scope);
if (oldValue == Undefined.instance)
return Undefined.instance;
double resultValue = toNumber(oldValue);
Double newValue = new Double(resultValue - 1.0);
setElem(obj, index, newValue, scope);
return new Double(resultValue);
}
public static Object postDecrement(Object value) {
if (value instanceof Number)
value = new Double(((Number)value).doubleValue() - 1.0);
else
value = new Double(toNumber(value) - 1.0);
return value;
}
public static Object postDecrement(Scriptable scopeChain, String id) {
Scriptable obj = scopeChain;
Object prop;
while (obj != null) {
Scriptable m = obj;
do {
Object result = m.get(id, obj);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() - 1.0);
m.put(id, obj, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) - 1.0);
m.put(id, obj, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
obj = obj.getParentScope();
}
Object args[] = { id };
throw NativeGlobal.constructError(
Context.getContext(), "ReferenceError",
ScriptRuntime.getMessage("msg.is.not.defined", args),
scopeChain);
}
public static Object postDecrement(Object obj, String id, Scriptable scope) {
Scriptable start;
if (obj instanceof Scriptable) {
start = (Scriptable) obj;
} else {
start = toObject(scope, obj);
}
if (start == null) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.null.to.object", null),
scope);
}
Scriptable m = start;
do {
Object result = m.get(id, start);
if (result != Scriptable.NOT_FOUND) {
Object newValue = result;
if (newValue instanceof Number) {
newValue = new Double(
((Number)newValue).doubleValue() - 1.0);
m.put(id, start, newValue);
return result;
}
else {
newValue = new Double(toNumber(newValue) - 1.0);
m.put(id, start, newValue);
return new Double(toNumber(result));
}
}
m = m.getPrototype();
} while (m != null);
return Undefined.instance;
}
public static Object toPrimitive(Object val) {
if (val == null || !(val instanceof Scriptable)) {
return val;
}
Object result = ((Scriptable) val).getDefaultValue(null);
if (result != null && result instanceof Scriptable)
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.bad.default.value", null),
val);
return result;
}
private static Class getTypeOfValue(Object obj) {
if (obj == null)
return ScriptableClass;
if (obj == Undefined.instance)
return UndefinedClass;
if (obj instanceof Scriptable)
return ScriptableClass;
if (obj instanceof Number)
return NumberClass;
return obj.getClass();
}
/**
* Equality
*
* See ECMA 11.9
*/
public static boolean eq(Object x, Object y) {
Object xCopy = x; // !!! JIT bug in Cafe 2.1
Object yCopy = y; // need local copies, otherwise their values get blown below
for (;;) {
Class typeX = getTypeOfValue(x);
Class typeY = getTypeOfValue(y);
if (typeX == typeY) {
if (typeX == UndefinedClass)
return true;
if (typeX == NumberClass)
return ((Number) x).doubleValue() ==
((Number) y).doubleValue();
if (typeX == StringClass || typeX == BooleanClass)
return xCopy.equals(yCopy); // !!! JIT bug in Cafe 2.1
if (typeX == ScriptableClass) {
if (x == y)
return true;
if (x instanceof Wrapper &&
y instanceof Wrapper)
{
return ((Wrapper) x).unwrap() ==
((Wrapper) y).unwrap();
}
return false;
}
throw new RuntimeException(); // shouldn't get here
}
if (x == null && y == Undefined.instance)
return true;
if (x == Undefined.instance && y == null)
return true;
if (typeX == NumberClass &&
typeY == StringClass)
{
return ((Number) x).doubleValue() == toNumber(y);
}
if (typeX == StringClass &&
typeY == NumberClass)
{
return toNumber(x) == ((Number) y).doubleValue();
}
if (typeX == BooleanClass) {
x = new Double(toNumber(x));
xCopy = x; // !!! JIT bug in Cafe 2.1
continue;
}
if (typeY == BooleanClass) {
y = new Double(toNumber(y));
yCopy = y; // !!! JIT bug in Cafe 2.1
continue;
}
if ((typeX == StringClass ||
typeX == NumberClass) &&
typeY == ScriptableClass && y != null)
{
y = toPrimitive(y);
yCopy = y; // !!! JIT bug in Cafe 2.1
continue;
}
if (typeX == ScriptableClass && x != null &&
(typeY == StringClass ||
typeY == NumberClass))
{
x = toPrimitive(x);
xCopy = x; // !!! JIT bug in Cafe 2.1
continue;
}
return false;
}
}
public static Boolean eqB(Object x, Object y) {
if (eq(x,y))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static Boolean neB(Object x, Object y) {
if (eq(x,y))
return Boolean.FALSE;
else
return Boolean.TRUE;
}
public static boolean shallowEq(Object x, Object y) {
Class type = getTypeOfValue(x);
if (type != getTypeOfValue(y))
return false;
if (type == StringClass || type == BooleanClass)
return x.equals(y);
if (type == NumberClass)
return ((Number) x).doubleValue() ==
((Number) y).doubleValue();
if (type == ScriptableClass) {
if (x == y)
return true;
if (x instanceof Wrapper && y instanceof Wrapper)
return ((Wrapper) x).unwrap() ==
((Wrapper) y).unwrap();
return false;
}
if (type == UndefinedClass)
return true;
return false;
}
public static Boolean seqB(Object x, Object y) {
if (shallowEq(x,y))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static Boolean sneB(Object x, Object y) {
if (shallowEq(x,y))
return Boolean.FALSE;
else
return Boolean.TRUE;
}
/**
* The instanceof operator.
*
* @return a instanceof b
*/
public static boolean instanceOf(Scriptable scope, Object a, Object b) {
// Check RHS is an object
if (! (b instanceof Scriptable)) {
throw NativeGlobal.constructError(
Context.getContext(), "TypeError",
ScriptRuntime.getMessage("msg.instanceof.not.object", null),
scope);
}
// for primitive values on LHS, return false
// XXX we may want to change this so that
// 5 instanceof Number == true
if (! (a instanceof Scriptable))
return false;
return ((Scriptable)b).hasInstance((Scriptable)a);
}
/**
* Delegates to
*
* @return true iff rhs appears in lhs' proto chain
*/
protected static boolean jsDelegatesTo(Scriptable lhs, Scriptable rhs) {
Scriptable proto = lhs.getPrototype();
while (proto != null) {
if (proto.equals(rhs)) return true;
proto = proto.getPrototype();
}
return false;
}
/**
* The in operator.
*
* This is a new JS 1.3 language feature. The in operator mirrors
* the operation of the for .. in construct, and tests whether the
* rhs has the property given by the lhs. It is different from the
* for .. in construct in that:
* <BR> - it doesn't perform ToObject on the right hand side
* <BR> - it returns true for DontEnum properties.
* @param a the left hand operand
* @param b the right hand operand
*
* @return true if property name or element number a is a property of b
*/
public static boolean in(Object a, Object b, Scriptable scope) {
if (!(b instanceof Scriptable)) {
throw NativeGlobal.constructError(
Context.getContext(),
"TypeError",
ScriptRuntime.getMessage("msg.instanceof.not.object", null),
scope);
}
String s = getStringId(a);
return s != null
? ScriptableObject.hasProperty((Scriptable) b, s)
: ScriptableObject.hasProperty((Scriptable) b, getIntId(a));
}
public static Boolean cmp_LTB(Object val1, Object val2) {
if (cmp_LT(val1, val2) == 1)
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static int cmp_LT(Object val1, Object val2) {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (!(val1 instanceof String) || !(val2 instanceof String)) {
double d1 = toNumber(val1);
if (d1 != d1)
return 0;
double d2 = toNumber(val2);
if (d2 != d2)
return 0;
return d1 < d2 ? 1 : 0;
}
return toString(val1).compareTo(toString(val2)) < 0 ? 1 : 0;
}
public static Boolean cmp_LEB(Object val1, Object val2) {
if (cmp_LE(val1, val2) == 1)
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static int cmp_LE(Object val1, Object val2) {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (!(val1 instanceof String) || !(val2 instanceof String)) {
double d1 = toNumber(val1);
if (d1 != d1)
return 0;
double d2 = toNumber(val2);
if (d2 != d2)
return 0;
return d1 <= d2 ? 1 : 0;
}
return toString(val1).compareTo(toString(val2)) <= 0 ? 1 : 0;
}
// lt:
// implement the '<' operator inline in the caller
// as "compare(val1, val2) == 1"
// le:
// implement the '<=' operator inline in the caller
// as "compare(val2, val1) == 0"
// gt:
// implement the '>' operator inline in the caller
// as "compare(val2, val1) == 1"
// ge:
// implement the '>=' operator inline in the caller
// as "compare(val1, val2) == 0"
// ------------------
// Statements
// ------------------
public static void main(String scriptClassName, String[] args)
throws JavaScriptException
{
Context cx = Context.enter();
ScriptableObject global = new ImporterTopLevel();
cx.initStandardObjects(global);
Global.initTopLevelScope(cx, global);
// get the command line arguments and define "arguments"
// array in the top-level object
Scriptable argsObj = cx.newArray(global, args);
global.defineProperty("arguments", argsObj,
ScriptableObject.DONTENUM);
try {
Class cl = loadClassName(scriptClassName);
Script script = (Script) cl.newInstance();
script.exec(cx, global);
return;
}
catch (ClassNotFoundException e) {
}
catch (InstantiationException e) {
}
catch (IllegalAccessException e) {
}
finally {
Context.exit();
}
throw new RuntimeException("Error creating script object");
}
public static Scriptable initScript(Context cx, Scriptable scope,
NativeFunction funObj,
Scriptable thisObj,
boolean fromEvalCode)
{
String[] names = funObj.names;
if (names != null) {
ScriptableObject so;
try {
/* Global var definitions are supposed to be DONTDELETE
* so we try to create them that way by hoping that the
* scope is a ScriptableObject which provides access to
* setting the attributes.
*/
so = (ScriptableObject) scope;
} catch (ClassCastException x) {
// oh well, we tried.
so = null;
}
Scriptable varScope = scope;
if (fromEvalCode) {
// When executing an eval() inside a with statement,
// define any variables resulting from var statements
// in the first non-with scope. See bug 38590.
varScope = scope;
while (varScope instanceof NativeWith)
varScope = varScope.getParentScope();
}
for (int i=funObj.names.length-1; i > 0; i--) {
String name = funObj.names[i];
// Don't overwrite existing def if already defined in object
// or prototypes of object.
if (!hasProp(scope, name)) {
if (so != null && !fromEvalCode)
so.defineProperty(name, Undefined.instance,
ScriptableObject.PERMANENT);
else
varScope.put(name, varScope, Undefined.instance);
}
}
}
return scope;
}
public static Scriptable runScript(Script script) {
Context cx = Context.enter();
ScriptableObject global = new ImporterTopLevel();
cx.initStandardObjects(global);
Global.initTopLevelScope(cx, global);
try {
script.exec(cx, global);
} catch (JavaScriptException e) {
throw new Error(e.toString());
}
Context.exit();
return global;
}
public static Scriptable initVarObj(Context cx, Scriptable scope,
NativeFunction funObj,
Scriptable thisObj, Object[] args)
{
NativeCall result = new NativeCall(cx, scope, funObj, thisObj, args);
String[] names = funObj.names;
if (names != null) {
for (int i=funObj.argCount+1; i < funObj.names.length; i++) {
String name = funObj.names[i];
result.put(name, result, Undefined.instance);
}
}
return result;
}
public static void popActivation(Context cx) {
NativeCall current = cx.currentActivation;
if (current != null) {
cx.currentActivation = current.caller;
current.caller = null;
}
}
public static Scriptable newScope() {
return new NativeObject();
}
public static Scriptable enterWith(Object value, Scriptable scope) {
return new NativeWith(scope, toObject(scope, value));
}
public static Scriptable leaveWith(Scriptable scope) {
return scope.getParentScope();
}
public static NativeFunction initFunction(NativeFunction fn,
Scriptable scope,
String fnName,
Context cx,
boolean doSetName)
{
fn.setPrototype(ScriptableObject.getClassPrototype(scope, "Function"));
fn.setParentScope(scope);
if (doSetName)
setName(scope, fn, scope, fnName);
return fn;
}
public static NativeFunction createFunctionObject(Scriptable scope,
Class functionClass,
Context cx,
boolean setName)
{
Constructor[] ctors = functionClass.getConstructors();
NativeFunction result = null;
Object[] initArgs = { scope, cx };
try {
result = (NativeFunction) ctors[0].newInstance(initArgs);
}
catch (InstantiationException e) {
throw WrappedException.wrapException(e);
}
catch (IllegalAccessException e) {
throw WrappedException.wrapException(e);
}
catch (IllegalArgumentException e) {
throw WrappedException.wrapException(e);
}
catch (InvocationTargetException e) {
throw WrappedException.wrapException(e);
}
result.setPrototype(ScriptableObject.getClassPrototype(scope, "Function"));
result.setParentScope(scope);
String fnName = result.jsGet_name();
if (setName && fnName != null && fnName.length() != 0 &&
!fnName.equals("anonymous"))
{
setProp(scope, fnName, result, scope);
}
return result;
}
static void checkDeprecated(Context cx, String name) {
int version = cx.getLanguageVersion();
if (version >= Context.VERSION_1_4 || version == Context.VERSION_DEFAULT) {
Object[] errArgs = { name };
String msg = getMessage("msg.deprec.ctor",
errArgs);
if (version == Context.VERSION_DEFAULT)
Context.reportWarning(msg);
else
throw Context.reportRuntimeError(msg);
}
}
public static String getMessage(String messageId, Object[] arguments) {
return Context.getMessage(messageId, arguments);
}
public static RegExpProxy getRegExpProxy(Context cx) {
return cx.getRegExpProxy();
}
public static NativeCall getCurrentActivation(Context cx) {
return cx.currentActivation;
}
public static void setCurrentActivation(Context cx,
NativeCall activation)
{
cx.currentActivation = activation;
}
private static Method getContextClassLoaderMethod;
static {
try {
// We'd like to use "getContextClassLoader", but
// that's only available on Java2.
getContextClassLoaderMethod =
Thread.class.getDeclaredMethod("getContextClassLoader",
new Class[0]);
} catch (NoSuchMethodException e) {
// ignore exceptions; we'll use Class.forName instead.
} catch (SecurityException e) {
// ignore exceptions; we'll use Class.forName instead.
}
}
public static Class loadClassName(String className)
throws ClassNotFoundException
{
try {
if (getContextClassLoaderMethod != null) {
ClassLoader cl = (ClassLoader)
getContextClassLoaderMethod.invoke(
Thread.currentThread(),
new Object[0]);
if (cl != null)
return cl.loadClass(className);
}
} catch (SecurityException e) {
// fall through...
} catch (IllegalAccessException e) {
// fall through...
} catch (InvocationTargetException e) {
// fall through...
} catch (ClassNotFoundException e) {
// Rather than just letting the exception propagate
// we'll try Class.forName as well. The results could be
// different if this class was loaded on a different
// thread than the current thread.
// So fall through...
}
return Class.forName(className);
}
static boolean hasProp(Scriptable start, String name) {
Scriptable m = start;
do {
if (m.has(name, start))
return true;
m = m.getPrototype();
} while (m != null);
return false;
}
private static RuntimeException errorWithClassName(String msg, Object val)
{
Object[] args = { val.getClass().getName() };
return Context.reportRuntimeError(getMessage(msg, args));
}
static public Object[] emptyArgs = new Object[0];
}
/**
* This is the enumeration needed by the for..in statement.
*
* See ECMA 12.6.3.
*
* IdEnumeration maintains a Hashtable to make sure a given
* id is enumerated only once across multiple objects in a
* prototype chain.
*
* XXX - ECMA delete doesn't hide properties in the prototype,
* but js/ref does. This means that the js/ref for..in can
* avoid maintaining a hash table and instead perform lookups
* to see if a given property has already been enumerated.
*
*/
class IdEnumeration implements Enumeration {
IdEnumeration(Scriptable m) {
used = new Hashtable(27);
changeObject(m);
next = getNext();
}
public boolean hasMoreElements() {
return next != null;
}
public Object nextElement() {
Object result = next;
// only key used; 'next' as value for convenience
used.put(next, next);
next = getNext();
return result;
}
private void changeObject(Scriptable m) {
obj = m;
if (obj != null) {
array = m.getIds();
if (array.length == 0)
changeObject(obj.getPrototype());
}
index = 0;
}
private Object getNext() {
if (obj == null)
return null;
Object result;
for (;;) {
if (index == array.length) {
changeObject(obj.getPrototype());
if (obj == null)
return null;
}
result = array[index++];
if (result instanceof String) {
if (!obj.has((String) result, obj))
continue; // must have been deleted
} else {
if (!obj.has(((Number) result).intValue(), obj))
continue; // must have been deleted
}
if (!used.containsKey(result)) {
break;
}
}
return ScriptRuntime.toString(result);
}
private Object next;
private Scriptable obj;
private int index;
private Object[] array;
private Hashtable used;
}
| false | false | null | null |
diff --git a/src/napplet/NApplet.java b/src/napplet/NApplet.java
index 4c39077..608a3a0 100644
--- a/src/napplet/NApplet.java
+++ b/src/napplet/NApplet.java
@@ -1,870 +1,869 @@
package napplet;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Constructor;
import processing.core.PApplet;
import processing.core.PImage;
/**
* Subclass of processing.core.PApplet (Processing main sketch class.)
*
* @author acsmith
*
*/
@SuppressWarnings( { "serial" })
public class NApplet extends PApplet implements Nit, MouseWheelListener,
ComponentListener {
/**
* Library version.
*/
public static final String VERSION = "0.3.1";
/**
* Returns library version.
*
* @return version
*/
public String version() {
return VERSION;
}
/**
* Time in milliseconds when the applet was started. We need to have our own
* number for this since PApplet.millisOffset is private.
*/
long millisOffset;
/**
* Overrides PApplet's millis() routine.
*/
public int millis() {
if (embeddedNApplet || windowedNApplet)
return (int) (parentPApplet.millis() - millisOffset);
else return super.millis();
}
// New members for Napplet
/**
* The PApplet (or NApplet) that this NApplet is displayed on, if any.
*/
public PApplet parentPApplet = null;
/**
* The object managing this NApplet, i.e., a NAppletManager being run by the
* parent PApplet. Remains null if this NApplet is being run on its own,
* otherwise the manager will set it.
*/
public NAppletManager parentNAppletManager = null;
/**
* Manager for this NApplet's contained Nits (e.g., NApplets).
*/
public NAppletManager nappletManager;
/**
* The x-position of this NApplet's display space in its parent's display,
* or the x-position of the NApplet's window on the screen.
*/
public int nappletX;
/**
* The y-position of this NApplet's display space in its parent's display,
* or the y-position of the NApplet's window on the screen.
*/
public int nappletY;
/**
* True if this NApplet is displaying in another PApplet's (or NApplet's)
* display space, false if it's a stand-alone applet or in its own window.
*/
public boolean embeddedNApplet = false;
/**
* True if this NApplet is in its own window as a sub-sketch of another
* sketch, but not running by itself.
*/
public boolean windowedNApplet = false;
/**
* True if this NApplet has been hidden with the hide() method. Set to false
* after un-hidden with show().
*/
public boolean nappletHidden = false;
/**
* True if the user can close the NApplet through the normal window-closing
* controls (whatever those may be).
*/
public boolean nappletCloseable = false;
/**
* Tint used for pasting this NApplet into its parent's display space.
* Mainly useful for setting the alpha channel to get translucency. Should
* be settable with Processing's "color datatype", e.g., nappletTint =
* color(255, 127) or whatever.
*/
public int nappletTint = 0xffffffff;
/**
* Current position of the mouse wheel. Starts at zero, increases by one for
* each "click" the wheel is rotated towards the user (i.e., "down"),
* decreases for each click rotated away from the user ("up").
*/
public int mouseWheel = 0;
/**
* Previous position of the mouse wheel (before the most recent movement of
* the wheel.)
*/
public int pmouseWheel = 0;
protected boolean resizeRequest = false;
protected int resizeWidth;
protected int resizeHeight;
/**
* Base constructor. Use initEmbeddedNApplet() or initWindowedNApplet() to
* initialize a NApplet. Override this to have a custom constructor for a
* subclass using parameters (e.g., to initialize fields).
*/
public NApplet() {
}
/**
* Does the main grunt-work of NApplet initialization. Mostly it's just
* transplanted stuff from PApplet.init(); the intent is to make Pinocchio
* as much like a real boy as possible.
*
* @param pap
* Parent PApplet (or NApplet)
* @param x
* x-coordinate of the NApplet
* @param y
* y-coordinate of the NApplet
* @param sketchPath
* home folder for the NApplet (potentially this will be useful
* later on for napplet-izing an existing processing sketch. I
* need to write a tool for this).
*/
protected void initNApplet(PApplet pap, int x, int y, String sketchPath) {
parentPApplet = pap;
// Have to do this because PApplet.millisOffset is private.
millisOffset = parentPApplet.millis();
online = parentPApplet.online;
// Everything else is basically just transplanted initialization stuff
// from PApplet.init().
finished = false;
looping = true;
redraw = true;
firstMouse = true;
sizeMethods = new RegisteredMethods();
preMethods = new RegisteredMethods();
drawMethods = new RegisteredMethods();
postMethods = new RegisteredMethods();
mouseEventMethods = new RegisteredMethods();
keyEventMethods = new RegisteredMethods();
disposeMethods = new RegisteredMethods();
// Transplanted from PApplet.init().
this.sketchPath = sketchPath;
nappletX = x;
nappletY = y;
{
this.defaultSize = true;
int w = getSketchWidth();
int h = getSketchHeight();
g = makeGraphics(w, h, getSketchRenderer(), null, true);
setSize(w, h);
setPreferredSize(new Dimension(w, h));
}
nappletManager = new NAppletManager(this);
}
/**
* Used to initialize an embedded NApplet. Replaces the call to init().
*
* @param pap
* Parent PApplet (or NApplet)
* @param x
* x-coordinate of top-left corner of this NApplet's area within
* the parent's graphic space.
* @param y
* y-coordinate of top-left corner of this NApplet's area within
* the parent's graphic space.
* @param sketchPath
* Path for this NApplet's home folder.
*/
public void initEmbeddedNApplet(PApplet pap, int x, int y, String sketchPath) {
initNApplet(pap, x, y, sketchPath);
// Use the parent's size as the "screen size" for this applet.
screenWidth = parentPApplet.width;
screenHeight = parentPApplet.height;
embeddedNApplet = true;
// Do setup now, and advance the frame count so that
// PApplet.handleDraw() doesn't do it again. Not strictly necessary to
// do it this way for embedded NApplets, but for the sake of consistency
// and convenience we will anyway.
setup();
frameCount++;
}
/**
* Used to initialize a windowed NApplet. Replaces the call to init().
*
* @param pap
* Parent PApplet (or NApplet)
* @param x
* x-coordinate of top-left corner of this NApplet's window.
* @param y
* y-coordinate of top-left corner of this NApplet's window.
* @param sketchPath
* Path for this NApplet's home folder.
*/
public void initWindowedNApplet(PApplet pap, int x, int y, String sketchPath) {
initNApplet(pap, x, y, sketchPath);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = screen.width;
screenHeight = screen.height;
windowedNApplet = true;
addListeners();
// Do setup now, so the Frame can get width and height. Then advance the
// frameCount once, so PApplet.handleDraw() doesn't run it again.
setup();
frameCount++;
}
/**
* Used to initialize an embedded NApplet. Replaces the call to init().
*
* @param pap
* Parent PApplet (or NApplet)
* @param x
* x-coordinate of top-left corner of this NApplet's area within
* the parent's graphic space.
* @param y
* y-coordinate of top-left corner of this NApplet's area within
* the parent's graphic space.
*/
public void initEmbeddedNApplet(PApplet pap, int x, int y) {
initEmbeddedNApplet(pap, x, y, pap.sketchPath);
}
/**
* Initializes an embedded NApplet with its top-left corner at (0,0) in the
* parent's display.
*
* @param pap
* ParentPApplet (or NApplet)
*/
public void initEmbeddedNApplet(PApplet pap) {
initEmbeddedNApplet(pap, 0, 0, pap.sketchPath);
}
/**
* Calls PApplet.addListeners(), and additionally adds a listener for the
* mousewheel.
*
* @see processing.core.PApplet#addListeners()
*/
public void addListeners() {
super.addListeners();
addMouseWheelListener(this);
}
/**
* Allow for user closing of windowed NApplets.
*/
public void setupNAppletMessages() {
if (windowedNApplet)
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
userWindowClose();
}
});
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#getPositionX()
*/
public int getPositionX() {
return nappletX;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#getPositionY()
*/
public int getPositionY() {
return nappletY;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#setPosition(int, int)
*/
public void setPosition(int x, int y) {
nappletX = x;
nappletY = y;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#getWidth()
*/
public int getWidth() {
return width;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#getHeight()
*/
public int getHeight() {
return height;
}
/**
* Returns true if the NApplet is currently hidden from view by the
* nappletHidden variable.
*
* @return true if the NApplet is hidden.
*/
public boolean isHidden() {
return nappletHidden;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#isEmbedded()
*/
public boolean isEmbedded() {
return embeddedNApplet;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#runFrame()
*/
public void runFrame() {
if (resizeRequest) {
if (!embeddedNApplet)
resizeRenderer(resizeWidth, resizeHeight);
// size(resizeWidth, resizeHeight);
resizeRequest = false;
windowResized();
}
handleDraw();
}
public void handleDraw() {
super.handleDraw();
}
/**
* Hides the NApplet.
*/
public void hide() {
if (frame != null) {
frame.setVisible(false);
}
nappletHidden = true;
}
/**
* Unhides the NApplet.
*/
public void show() {
if (frame != null) {
frame.setVisible(true);
}
nappletHidden = false;
}
/**
* Called when a window-closing event is received (presumably the user
* clicking the close widget.)
*/
public void userWindowClose() {
if (nappletCloseable)
exit();
}
/**
* Sets a windowed or stand-alone NApplet to be user-resizable. Has no
* effect on an embedded NApplet.
*
* When a NApplet is resized, it will call the windowResized() method, which
* is empty by default and can be overriden with whatever you like.
*
* @param resizable
* true if the window should be user-resizable.
*/
public void setResizable(boolean resizable) {
if (!embeddedNApplet)
frame.setResizable(resizable);
}
/**
* Override for PApplet.exit(). Handles things for a windowed or embedded
* NApplet, or falls through to PApplet.exit() for a standalone.
*/
public void exit() {
if (windowedNApplet)
frame.dispose();
if (embeddedNApplet || windowedNApplet)
parentNAppletManager.killNit(this);
else
super.exit();
}
/**
* Override for PApplet.size(). Falls through for standalone or windowed
* NApplets.
*
* @param iwidth
* Desired width
* @param iheight
* Desired height
* @param irenderer
* Desired renderer
* @param ipath
* Desired um... path? I forget what this does; it's passed
* through to the same argument for PApplet.makeGraphics().
*/
public void size(final int iwidth, final int iheight, String irenderer,
String ipath) {
if (embeddedNApplet) {
if (g == null) {
g = makeGraphics(iwidth, iheight, irenderer, ipath, false);
width = iwidth;
height = iheight;
} else {
String currentRenderer = g.getClass().getName();
if (currentRenderer.equals(irenderer))
resizeRenderer(iwidth, iheight);
else {
g = makeGraphics(iwidth, iheight, irenderer, ipath, true);
width = iwidth;
height = iheight;
}
}
} else {
// This is for standalone and windowed napplets. Basically cribbed
// all this from PApplet.size(), but replaced the
// exception-throwing.
setSize(iwidth, iheight);
setPreferredSize(new Dimension(iwidth, iheight));
if (ipath != null)
ipath = savePath(ipath);
String currentRenderer = g.getClass().getName();
if (currentRenderer.equals(irenderer)) {
resizeRenderer(iwidth, iheight);
} else {
g = makeGraphics(iwidth, iheight, irenderer, ipath, true);
width = iwidth;
height = iheight;
defaultSize = false;
// The PApplet throws a custom exception here to force a re-run
// of setup(). If we allow the NApplet to do that, it will be
// caught by the parent PApplet, causing all kinds of
// unfortunate side effects. So instead, we force a re-run of
// setup() by simply decrementing frameCount.
frameCount--;
}
}
}
@Override
public void resize(int iwidth, int iheight) {
resizeRequest = true;
resizeWidth = iwidth;
resizeHeight = iheight;
}
/**
* Overrides PApplet's colorMode(int mode) method.
*
* For some reason, a NApplet that called colorMode(HSB) in its setup()
* without specifying a max range for the color values would have those
* ranges set to zero. (The NApplet version of the FireCube demo had this
* problem.) This method intercepts a call to colorMode with no range
* specification, checks to see if g currently has any ranges specified,
* fills any missing ranges in with 255, and then calls
* PApplet.colorMode(int, float, float, float, float) to set them
* explicitly.
*
* @see processing.core.PApplet#colorMode(int)
*/
@Override
public void colorMode(int mode) {
// Need to make sure sensible values get passed for the max color ranges
// if they aren't set already. (I'm not sure why they don't get set, but
// whatever.)
float maxX = (g.colorModeX == 0.0) ? 255 : g.colorModeX;
float maxY = (g.colorModeY == 0.0) ? 255 : g.colorModeY;
float maxZ = (g.colorModeZ == 0.0) ? 255 : g.colorModeZ;
float maxA = (g.colorModeA == 0.0) ? 255 : g.colorModeA;
super.colorMode(mode, maxX, maxY, maxZ, maxA);
}
/**
* Accessor for queueing mouse and keyboard events. Used by the
* NAppletManager since PApplet.enqueueXXXXEvent() is protected.
*
* @param event
* Input event to be queued. Mouse locations need to be
* translated to the NApplet's local coordinates.
*/
public void passEvent(InputEvent event) {
if (event instanceof MouseWheelEvent) {
if (nappletManager != null)
nappletManager.handleMouseWheelEvent((MouseWheelEvent) event);
else
this.mouseWheelMoved((MouseWheelEvent) event);
} else if (event instanceof MouseEvent) {
if (nappletManager != null)
nappletManager.handleMouseEvent((MouseEvent) event);
else
this.mousePressed((MouseEvent) event);
} else if (event instanceof java.awt.event.KeyEvent) {
if (nappletManager != null)
nappletManager.handleKeyEvent((KeyEvent) event);
else
this.keyPressed((KeyEvent) event);
}
}
/**
* Overrides PApplet.paint(). If the NApplet is embedded, uses the
* PApplet.image() method to paint the NApplet's pixels into the parent's
* display. Otherwise, just falls through to PApplet.paint().
*/
protected void paint() {
if (embeddedNApplet) {
if (!nappletHidden) {
- loadPixels();
+ //loadPixels();
parentPApplet.tint(nappletTint);
parentPApplet.image(this.g, 0, 0);
}
} else
super.paint();
-
}
/**
* NApplet factory method.
*
* @param parent
* Parent PApplet or NApplet for the new NApplet.
* @param nappletClassName
* Name of the new NApplet's class.
* @return The created NApplet.
*/
public static NApplet createNApplet(PApplet parent,
String nappletClassName, NAppletManager nappletManager) {
Class<?> nappletClass = null;
Constructor<?> constructor = null;
Class<?>[] constructorParams = {};
Object[] constructorArgs = {};
NApplet napplet = null;
try {
nappletClass = Class.forName(nappletClassName);
} catch (ClassNotFoundException e) {
try {
nappletClass = Class.forName(parent.getClass().getName() + "$"
+ nappletClassName);
} catch (ClassNotFoundException e1) {
String pcName = parent.getClass().getName();
try {
nappletClass = Class.forName(pcName.substring(0, pcName
.lastIndexOf('.'))
+ "." + nappletClassName);
} catch (ClassNotFoundException e2) {
System.err
.println("NApplet.createNapplet(): Class not found.");
e2.printStackTrace();
}
}
}
if (nappletClass != null) {
if (nappletClass.getName().contains("$")) {
constructorParams = new Class[] { parent.getClass() };
constructorArgs = new Object[] { parent };
}
try {
constructor = nappletClass.getConstructor(constructorParams);
} catch (Exception e) {
System.err
.println("NApplet.createNApplet(): Constructor access error.");
e.printStackTrace();
}
}
if (constructor != null) {
try {
napplet = (NApplet) constructor.newInstance(constructorArgs);
} catch (Exception e) {
System.err
.println("NApplet.createNApplet(): Object instantiation error.");
e.printStackTrace();
}
}
napplet.setNAppletManager(nappletManager);
// napplet.parentNAppletManager = nappletManager;
return napplet;
}
/**
* Called when the mousewheel is moved. Meant to be overridden a la
* mouseMoved(), mousePressed(), etc.
*/
public void mouseWheelMoved() {
}
/**
* Called when the window is resized. Override this when you want the
* NApplet to do something after a resize.
*/
public void windowResized() {
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#getNAppletManager()
*/
@Override
public NAppletManager getNAppletManager() {
return parentNAppletManager;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#setNAppletManager(napplet.NAppletManager)
*/
@Override
public void setNAppletManager(NAppletManager nappletManager) {
this.parentNAppletManager = nappletManager;
this.parentPApplet = nappletManager.parentPApplet;
millisOffset = parentPApplet.millis();
online = parentPApplet.online;
}
/*
* (non-Javadoc)
*
* @see napplet.Nit#inputHit(int, int)
*/
@Override
public boolean inputHit(int x, int y) {
return true;
}
// Overrides for methods inherited from PApplet that are disabled for
// NApplets because they're either inappropriate or too tricky.
/**
* Overrides PApplet.delay(). For now, this just means delay() is disabled
* for embedded NApplets. For standalone NApplets, this just passes through
* to PApplet.delay().
*/
public void delay(int napTime) {
if (embeddedNApplet || windowedNApplet)
System.err.println("NApplet: delay() disabled.");
else
super.delay(napTime);
}
/**
* Override for PApplet.frameRate(). Just disables frame rate setting for
* embedded NApplets, and passes through to PApplet.frameRate() for
* standalone NApplets.
*/
public void frameRate(float newRateTarget) {
if (embeddedNApplet || windowedNApplet)
System.err
.println("NApplet: frameRate(float newRateTarget) disabled.");
else
super.frameRate(newRateTarget);
}
// Disabled cursor manipulation for embedded NApplets for now. Will probably
// bring it back at some point, but it'll be tricky to manage it properly
// for embedded NApplets.
/**
* Cursor manipulation disabled for now for embedded NApplets. Should work
* fine for windowed or standalone NApplets (though I haven't tested that.)
*/
public void cursor(int cursorType) {
if (embeddedNApplet)
System.err
.println("NApplet: Cursor manipulation disabled for now.");
else
super.cursor(cursorType);
}
/**
* Cursor manipulation disabled for now for embedded NApplets. Should work
* fine for windowed or standalone NApplets (though I haven't tested that.)
*/
public void cursor(PImage image) {
if (embeddedNApplet)
System.err
.println("NApplet: Cursor manipulation disabled for now.");
else
super.cursor(image);
}
/**
* Cursor manipulation disabled for now for embedded NApplets. Should work
* fine for windowed or standalone NApplets (though I haven't tested that.)
*/
public void cursor(PImage image, int hotspotX, int hotspotY) {
if (embeddedNApplet)
System.err
.println("NApplet: Cursor manipulation disabled for now.");
else
super.cursor(image, hotspotX, hotspotY);
}
/**
* Cursor manipulation disabled for now for embedded NApplets. Should work
* fine for windowed or standalone NApplets (though I haven't tested that.)
*/
public void cursor() {
if (embeddedNApplet)
System.err
.println("NApplet: Cursor manipulation disabled for now.");
else
super.cursor();
}
/**
* Cursor manipulation disabled for now for embedded NApplets. Should work
* fine for windowed or standalone NApplets (though I haven't tested that.)
*/
public void noCursor() {
if (embeddedNApplet)
System.err
.println("NApplet: Cursor manipulation disabled for now.");
else
super.noCursor();
}
// Listener methods (as with listener methods for PApplet, override these at
// your own risk.)
/*
* (non-Javadoc)
*
* @seejava.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.
* MouseWheelEvent)
*/
public void mouseWheelMoved(MouseWheelEvent e) {
pmouseWheel = mouseWheel;
mouseWheel += e.getWheelRotation();
mouseWheelMoved();
}
/*
* (non-Javadoc)
*
* @seejava.awt.event.ComponentListener#componentHidden(java.awt.event.
* ComponentEvent)
*/
@Override
public void componentHidden(ComponentEvent arg0) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent
* )
*/
@Override
public void componentMoved(ComponentEvent e) {
}
/*
* (non-Javadoc)
*
* @seejava.awt.event.ComponentListener#componentResized(java.awt.event.
* ComponentEvent)
*/
@Override
public void componentResized(ComponentEvent e) {
java.awt.Insets insets = frame.getInsets();
int iwidth = e.getComponent().getWidth() - (insets.left + insets.right);
int iheight = e.getComponent().getHeight()
- (insets.top + insets.bottom);
resizeRenderer(iwidth, iheight);
windowResized();
// resize(iwidth, iheight);
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent
* )
*/
@Override
public void componentShown(ComponentEvent e) {
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/java/org/jdesktop/swingx/painter/BusyPainter.java b/src/java/org/jdesktop/swingx/painter/BusyPainter.java
index eb42af81..41c1a910 100644
--- a/src/java/org/jdesktop/swingx/painter/BusyPainter.java
+++ b/src/java/org/jdesktop/swingx/painter/BusyPainter.java
@@ -1,589 +1,622 @@
/*
* $Id$
*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx.painter;
import java.awt.Color;
import java.awt.Graphics2D;
+import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.geom.Point2D.Float;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.jdesktop.swingx.JXBusyLabel.Direction;
import org.jdesktop.swingx.color.ColorUtil;
/**
* A specific painter that paints an "infinite progress" like animation. For more details see {@link org.jdesktop.swingx.JXBusyLabel}
*
*/
public class BusyPainter<T> extends AbstractPainter<T> {
private int frame = -1;
private int points = 8;
private Color baseColor = new Color(200, 200, 200);
private Color highlightColor = Color.BLACK;
private int trailLength = 4;
private Shape pointShape;
private Shape trajectory;
private Direction direction = Direction.RIGHT;
+ private boolean paintCentered;
+
/**
* Creates new busy painter initialized to the shape of circle and bounds size 26x26 points.
*/
public BusyPainter() {
this(26);
}
/**
* Creates new painter initialized to the shape of circle and bounds of square of specified height.
* @param height Painter height.
*/
public BusyPainter(int height) {
this(getScaledDefaultPoint(height),
getScaledDefaultTrajectory(height));
}
protected static Shape getScaledDefaultTrajectory(int height) {
return new Ellipse2D.Float(((height * 8) / 26) / 2, ((height * 8) / 26) / 2, height
- ((height * 8) / 26), height - ((height * 8) / 26));
}
protected static Shape getScaledDefaultPoint(int height) {
return new RoundRectangle2D.Float(0, 0, (height * 8) / 26, 4,
4, 4);
}
/**
* Initializes painter to the specified trajectory and and point shape. Bounds are dynamically calculated to so the specified trajectory fits in.
* @param point Point shape.
* @param trajectory Trajectory shape.
*/
public BusyPainter(Shape point, Shape trajectory) {
init(point, trajectory, Color.LIGHT_GRAY, Color.BLACK);
}
/**
* Initializes painter to provided shapes and default colors.
* @param point Point shape.
* @param trajectory Trajectory shape.
*/
protected void init(Shape point, Shape trajectory, Color baseColor, Color highlightColor) {
this.baseColor = baseColor;
this.highlightColor = highlightColor;
this.pointShape = point;
this.trajectory = trajectory;
}
/**
* @inheritDoc
*/
@Override
protected void doPaint(Graphics2D g, T t, int width, int height) {
+ Rectangle r = getTrajectory().getBounds();
+ int tw = width - r.width - 2*r.x;
+ int th = height - r.height - 2*r.y;
+ if (isPaintCentered()) {
+ ((Graphics2D) g).translate(tw/2, th/2);
+ }
+
PathIterator pi = trajectory.getPathIterator(null);
float[] coords = new float[6];
Float cp = new Point2D.Float();
Point2D.Float sp = new Point2D.Float();
int ret;
float totalDist = 0;
List<float[]> segStack = new ArrayList<float[]>();
do {
try {
ret = pi.currentSegment(coords);
} catch (NoSuchElementException e) {
// invalid object definition - one of the bounds is zero or less
return;
}
if (ret == PathIterator.SEG_LINETO || (ret == PathIterator.SEG_CLOSE && (sp.x != cp.x || sp.y != cp.y))) {
//close by line
float c = calcLine(coords, cp);
totalDist += c;
// move the point to the end (just so it is same for all of them
segStack.add(new float[] { c, 0, 0, 0, 0, coords[0], coords[1], ret });
cp.x = coords[0];
cp.y = coords[1];
}
if (ret == PathIterator.SEG_MOVETO) {
sp.x = cp.x = coords[0];
sp.y = cp.y = coords[1];
}
if (ret == PathIterator.SEG_CUBICTO) {
float c = calcCube(coords, cp);
totalDist += c;
segStack.add(new float[] { c, coords[0], coords[1], coords[2],
coords[3], coords[4], coords[5], ret });
cp.x = coords[4];
cp.y = coords[5];
}
if (ret == PathIterator.SEG_QUADTO) {
float c = calcLengthOfQuad(coords, cp);
totalDist += c;
//System.out.println("quad c:" + c);
segStack.add(new float[] { c, coords[0], coords[1], 0 ,0 , coords[2],
coords[3], ret });
cp.x = coords[2];
cp.y = coords[3];
}
// got a starting point, center point on it.
pi.next();
} while (!pi.isDone());
float nxtP = totalDist / getPoints();
List<Point2D.Float> pList = new ArrayList<Point2D.Float>();
pList.add(new Float(sp.x, sp.y));
int sgIdx = 0;
float[] sgmt = segStack.get(sgIdx);
float len = sgmt[0];
float travDist = nxtP;
Float center = new Float(sp.x, sp.y);
for (int i = 1; i < getPoints(); i++) {
while (len < nxtP) {
sgIdx++;
// Be carefull when messing around with points.
sp.x = sgmt[5];
sp.y = sgmt[6];
sgmt = segStack.get(sgIdx);
travDist = nxtP - len;
len += sgmt[0];
}
len -= nxtP;
Float p = calcPoint(travDist, sp, sgmt, width, height);
pList.add(p);
center.x += p.x;
center.y += p.y;
travDist += nxtP;
}
// calculate center
center.x = ((float) width) / 2;
center.y = ((float) height) / 2;
// draw the stuff
int i = 0;
g.translate(center.x, center.y);
for (Point2D.Float p : pList) {
drawAt(g, i++, p, center);
}
g.translate(-center.x, -center.y);
+ if (isPaintCentered()) {
+ ((Graphics2D) g).translate(-tw/2, -th/2);
+ }
+ }
+
+ /**
+ * Gets value of centering hint. If true, shape will be positioned in the center of painted area.
+ * @return Whether shape will be centered over painting area or not.
+ */
+ private boolean isPaintCentered() {
+ return this.paintCentered;
}
private void drawAt(Graphics2D g, int i, Point2D.Float p, Float c) {
g.setColor(calcFrameColor(i));
paintRotatedCenteredShapeAtPoint(p, c, g);
}
private void paintRotatedCenteredShapeAtPoint(Float p, Float c, Graphics2D g) {
Shape s = getPointShape();
double hh = s.getBounds().getHeight() / 2;
double wh = s.getBounds().getWidth() / 2;
double t, x, y;
double a = c.y - p.y;
double b = p.x - c.x;
double sa = Math.signum(a);
double sb = Math.signum(b);
sa = sa == 0 ? 1 : sa;
sb = sb == 0 ? 1 : sb;
a = Math.abs(a);
b = Math.abs(b);
t = Math.atan(a / b);
t = sa > 0 ? sb > 0 ? -t : -Math.PI + t : sb > 0 ? t : Math.PI - t;
x = Math.sqrt(a * a + b * b) - wh;
y = -hh;
g.rotate(t);
g.translate(x, y);
g.fill(s);
g.translate(-x, -y);
g.rotate(-t);
}
private Point2D.Float calcPoint(float dist2go, Point2D.Float startPoint,
float[] sgmt, int w, int h) {
Float f = new Point2D.Float();
if (sgmt[7] == PathIterator.SEG_LINETO) {
// linear
float a = sgmt[5] - startPoint.x;
float b = sgmt[6] - startPoint.y;
float pathLen = sgmt[0];
f.x = startPoint.x + a * dist2go / pathLen;
f.y = startPoint.y + b * dist2go / pathLen;
} else if (sgmt[7] == PathIterator.SEG_QUADTO) {
// quadratic curve
Float ctrl = new Point2D.Float(sgmt[1]/w, sgmt[2]/h);
Float end = new Point2D.Float(sgmt[5]/w, sgmt[6]/h);
Float start = new Float(startPoint.x/w, startPoint.y/h);
// trans coords from abs to rel
f = getXY(dist2go / sgmt[0], start, ctrl, end);
f.x *= w;
f.y *= h;
} else if (sgmt[7] == PathIterator.SEG_CUBICTO) {
// bezier curve
float x = Math.abs(startPoint.x - sgmt[5]);
float y = Math.abs(startPoint.y - sgmt[6]);
// trans coords from abs to rel
float c1rx = Math.abs(startPoint.x - sgmt[1]) / x;
float c1ry = Math.abs(startPoint.y - sgmt[2]) / y;
float c2rx = Math.abs(startPoint.x - sgmt[3]) / x;
float c2ry = Math.abs(startPoint.y - sgmt[4]) / y;
f = getXY(dist2go / sgmt[0], c1rx, c1ry, c2rx, c2ry);
float a = startPoint.x - sgmt[5];
float b = startPoint.y - sgmt[6];
f.x = startPoint.x - f.x * a;
f.y = startPoint.y - f.y * b;
}
return f;
}
/**
* Calculates length of the linear segment.
* @param coords Segment coordinates.
* @param cp Start point.
* @return Length of the segment.
*/
private float calcLine(float[] coords, Float cp) {
float a = cp.x - coords[0];
float b = cp.y - coords[1];
float c = (float) Math.sqrt(a * a + b * b);
return c;
}
/**
* Claclulates length of the cubic segment.
* @param coords Segment coordinates.
* @param cp Start point.
* @return Length of the segment.
*/
private float calcCube(float[] coords, Float cp) {
float x = Math.abs(cp.x - coords[4]);
float y = Math.abs(cp.y - coords[5]);
// trans coords from abs to rel
float c1rx = Math.abs(cp.x - coords[0]) / x;
float c1ry = Math.abs(cp.y - coords[1]) / y;
float c2rx = Math.abs(cp.x - coords[2]) / x;
float c2ry = Math.abs(cp.y - coords[3]) / y;
float prevLength = 0, prevX = 0, prevY = 0;
for (float t = 0.01f; t <= 1.0f; t += .01f) {
Point2D.Float xy = getXY(t, c1rx, c1ry, c2rx, c2ry);
prevLength += (float) Math.sqrt((xy.x - prevX) * (xy.x - prevX)
+ (xy.y - prevY) * (xy.y - prevY));
prevX = xy.x;
prevY = xy.y;
}
// prev len is a fraction num of the real path length
float z = ((Math.abs(x) + Math.abs(y)) / 2) * prevLength;
return z;
}
/**
* Calculates length of the quadratic segment
* @param coords Segment coordinates
* @param cp Start point.
* @return Length of the segment.
*/
private float calcLengthOfQuad(float[] coords, Point2D.Float cp) {
Float ctrl = new Point2D.Float(coords[0], coords[1]);
Float end = new Point2D.Float(coords[2], coords[3]);
// get abs values
// ctrl1
float c1ax = Math.abs(cp.x - ctrl.x) ;
float c1ay = Math.abs(cp.y - ctrl.y) ;
// end1
float e1ax = Math.abs(cp.x - end.x) ;
float e1ay = Math.abs(cp.y - end.y) ;
// get max value on each axis
float maxX = Math.max(c1ax, e1ax);
float maxY = Math.max(c1ay, e1ay);
// trans coords from abs to rel
// ctrl1
ctrl.x = c1ax / maxX;
ctrl.y = c1ay / maxY;
// end1
end.x = e1ax / maxX;
end.y = e1ay / maxY;
// claculate length
float prevLength = 0, prevX = 0, prevY = 0;
for (float t = 0.01f; t <= 1.0f; t += .01f) {
Point2D.Float xy = getXY(t, new Float(0,0), ctrl, end);
prevLength += (float) Math.sqrt((xy.x - prevX) * (xy.x - prevX)
+ (xy.y - prevY) * (xy.y - prevY));
prevX = xy.x;
prevY = xy.y;
}
// prev len is a fraction num of the real path length
float a = Math.abs(coords[2] - cp.x);
float b = Math.abs(coords[3] - cp.y);
float dist = (float) Math.sqrt(a*a+b*b);
return prevLength * dist;
}
/**
* Calculates the XY point for a given t value.
*
* The general spline equation is: x = b0*x0 + b1*x1 + b2*x2 + b3*x3 y =
* b0*y0 + b1*y1 + b2*y2 + b3*y3 where: b0 = (1-t)^3 b1 = 3 * t * (1-t)^2 b2 =
* 3 * t^2 * (1-t) b3 = t^3 We know that (x0,y0) == (0,0) and (x1,y1) ==
* (1,1) for our splines, so this simplifies to: x = b1*x1 + b2*x2 + b3 y =
* b1*x1 + b2*x2 + b3
*
* @author chet
*
* @param t parametric value for spline calculation
*/
private Point2D.Float getXY(float t, float x1, float y1, float x2, float y2) {
Point2D.Float xy;
float invT = (1 - t);
float b1 = 3 * t * (invT * invT);
float b2 = 3 * (t * t) * invT;
float b3 = t * t * t;
xy = new Point2D.Float((b1 * x1) + (b2 * x2) + b3, (b1 * y1)
+ (b2 * y2) + b3);
return xy;
}
/**
* Calculates relative position of the point on the quad curve in time t<0,1>.
* @param t distance on the curve
* @param ctrl Control point in rel coords
* @param end End point in rel coords
* @return Solution of the quad equation for time T in non complex space in rel coords.
*/
public static Point2D.Float getXY(float t, Point2D.Float begin, Point2D.Float ctrl, Point2D.Float end) {
/*
* P1 = (x1, y1) - start point of curve
* P2 = (x2, y2) - end point of curve
* Pc = (xc, yc) - control point
*
* Pq(t) = P1*(1 - t)^2 + 2*Pc*t*(1 - t) + P2*t^2 =
* = (P1 - 2*Pc + P2)*t^2 + 2*(Pc - P1)*t + P1
* t = [0:1]
* // thx Jim ...
*
* b0 = (1 -t)^2, b1 = 2*t*(1-t), b2 = t^2
*/
Point2D.Float xy;
float invT = (1 - t);
float b0 = invT * invT;
float b1 = 2 * t * invT ;
float b2 = t * t;
xy = new Point2D.Float(b0 * begin.x + (b1 * ctrl.x) + b2* end.x, b0 * begin.y + (b1 * ctrl.y) + b2* end.y);
return xy;
}
/**
* Selects appropriate color for given frame based on the frame position and gradient difference.
* @param i Frame.
* @return Frame color.
*/
private Color calcFrameColor(final int i) {
if (frame == -1) {
return getBaseColor();
}
for (int t = 0; t < getTrailLength(); t++) {
if (direction == Direction.RIGHT
&& i == (frame - t + getPoints()) % getPoints()) {
float terp = 1 - ((float) (getTrailLength() - t))
/ (float) getTrailLength();
return ColorUtil.interpolate(getBaseColor(),
getHighlightColor(), terp);
} else if (direction == Direction.LEFT
&& i == (frame + t) % getPoints()) {
float terp = ((float) (t)) / (float) getTrailLength();
return ColorUtil.interpolate(getBaseColor(),
getHighlightColor(), terp);
}
}
return getBaseColor();
}
/**
* Gets current frame.
* @return Current frame.
*/
public int getFrame() {
return frame;
}
/**Sets current frame.
* @param frame Current frame.
*/
public void setFrame(int frame) {
this.frame = frame;
}
/**
* Gets base color.
* @return Base color.
*/
public Color getBaseColor() {
return baseColor;
}
/**
* Sets new base color. Bound property.
* @param baseColor Base color.
*/
public void setBaseColor(Color baseColor) {
Color old = getBaseColor();
this.baseColor = baseColor;
firePropertyChange("baseColor", old, getBaseColor());
}
/**
* Gets highlight color.
* @return Current highlight color.
*/
public Color getHighlightColor() {
return highlightColor;
}
/**
* Sets new highlight color. Bound property.
* @param highlightColor New highlight color.
*/
public void setHighlightColor(Color highlightColor) {
Color old = getHighlightColor();
this.highlightColor = highlightColor;
firePropertyChange("highlightColor", old, getHighlightColor());
}
/**
* Gets total amount of distinct points in spinner.
* @return Total amount of points.
*/
public int getPoints() {
return points;
}
/**
* Sets total amount of points in spinner. Bound property.
* @param points Total amount of points.
*/
public void setPoints(int points) {
int old = getPoints();
this.points = points;
firePropertyChange("points", old, getPoints());
}
/**
* Gets length of trail in number of points.
* @return Trail lenght.
*/
public int getTrailLength() {
return trailLength;
}
/**
* Sets length of the trail in points. Bound property.
* @param trailLength Trail length in points.
*/
public void setTrailLength(int trailLength) {
int old = getTrailLength();
this.trailLength = trailLength;
firePropertyChange("trailLength", old, getTrailLength());
}
/**
* Gets shape of current point.
* @return Shape of the point.
*/
public final Shape getPointShape() {
return pointShape;
}
/**
* Sets new point shape. Bound property.
* @param pointShape new Shape.
*/
public final void setPointShape(Shape pointShape) {
Shape old = getPointShape();
this.pointShape = pointShape;
if (getPointShape() != old && getPointShape() != null
&& !getPointShape().equals(old)) {
firePropertyChange("pointShape", old, getPointShape());
}
}
/**
* Gets current trajectory.
* @return Current spinner trajectory .
*/
public final Shape getTrajectory() {
return trajectory;
}
/**
* Sets new trajectory. Expected trajectory have to be closed shape. Bound property.
* @param trajectory New trajectory.
*/
public final void setTrajectory(Shape trajectory) {
Shape old = getTrajectory();
this.trajectory = trajectory;
if (getTrajectory() != old && getTrajectory() != null
&& !getTrajectory().equals(old)) {
firePropertyChange("trajectory", old, getTrajectory());
}
}
/**
* Sets new spinning direction.
* @param dir Spinning direction.
*/
public void setDirection(Direction dir) {
Direction old = getDirection();
this.direction = dir;
if (getDirection() != old && getDirection() != null
&& !getDirection().equals(old)) {
firePropertyChange("direction", old, getDirection());
}
}
/**
* Gets current direction of spinning.
* @return Current spinning direction.
*/
public Direction getDirection() {
return this.direction;
}
+ protected Shape provideShape(Graphics2D g, T comp, int width, int height) {
+ return new Rectangle(0,0,width,height);
+ }
+
+ /**
+ * Centers shape in the area covered by the painter.
+ * @param paintCentered Centering hint.
+ */
+ public void setPaintCentered(boolean paintCentered) {
+ this.paintCentered = paintCentered;
+ }
+
}
\ No newline at end of file
| false | false | null | null |
diff --git a/modules/quercus/src/com/caucho/quercus/env/QuercusClass.java b/modules/quercus/src/com/caucho/quercus/env/QuercusClass.java
index 118537396..9a4b7e1b0 100644
--- a/modules/quercus/src/com/caucho/quercus/env/QuercusClass.java
+++ b/modules/quercus/src/com/caucho/quercus/env/QuercusClass.java
@@ -1,1001 +1,1001 @@
/*
* Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.env;
import com.caucho.quercus.QuercusRuntimeException;
import com.caucho.quercus.expr.*;
import com.caucho.quercus.program.AbstractFunction;
import com.caucho.quercus.program.ClassDef;
import com.caucho.quercus.program.Function;
import com.caucho.quercus.program.InstanceInitializer;
import com.caucho.util.IdentityIntMap;
import com.caucho.util.L10N;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
/**
* Represents a Quercus runtime class.
*/
public class QuercusClass {
private final L10N L = new L10N(QuercusClass.class);
private final Logger log = Logger.getLogger(QuercusClass.class.getName());
private final ClassDef _classDef;
private ClassDef []_classDefList;
private QuercusClass _parent;
private AbstractFunction _constructor;
private AbstractFunction _get;
private AbstractFunction _set;
private AbstractFunction _call;
private final ArrayList<InstanceInitializer> _initializers
= new ArrayList<InstanceInitializer>();
private final ArrayList<String> _fieldNames
= new ArrayList<String>();
private final IdentityIntMap _fieldMap
= new IdentityIntMap();
private final HashMap<StringValue,Expr> _fieldInitMap
= new HashMap<StringValue,Expr>();
/*
private final IdentityHashMap<String,AbstractFunction> _methodMap
= new IdentityHashMap<String,AbstractFunction>();
private final HashMap<String,AbstractFunction> _lowerMethodMap
= new HashMap<String,AbstractFunction>();
*/
private final MethodMap<AbstractFunction> _methodMap
= new MethodMap<AbstractFunction>();
private final IdentityHashMap<String,Expr> _constMap
= new IdentityHashMap<String,Expr>();
private final HashMap<String,ArrayList<StaticField>> _staticFieldExprMap
= new LinkedHashMap<String,ArrayList<StaticField>>();
private final HashMap<String,Var> _staticFieldMap
= new HashMap<String,Var>();
public QuercusClass(ClassDef classDef, QuercusClass parent)
{
_classDef = classDef;
_parent = parent;
ClassDef []classDefList;
if (_parent != null) {
classDefList = new ClassDef[parent._classDefList.length + 1];
System.arraycopy(parent._classDefList, 0, classDefList, 1,
parent._classDefList.length);
classDefList[0] = classDef;
}
else {
classDefList = new ClassDef[] { classDef };
}
_classDefList = classDefList;
for (int i = classDefList.length - 1; i >= 0; i--) {
classDefList[i].initClass(this);
}
}
/**
* Returns the name.
*/
public String getName()
{
return _classDef.getName();
}
/**
* Returns the parent class.
*/
public QuercusClass getParent()
{
return _parent;
}
/**
* Sets the constructor.
*/
public void setConstructor(AbstractFunction fun)
{
_constructor = fun;
}
/**
* Sets the __get
*/
public void setGet(AbstractFunction fun)
{
_get = fun;
}
/**
* Sets the __set
*/
public void setSet(AbstractFunction fun)
{
_set = fun;
}
/**
* Sets the __set
*/
public AbstractFunction getSetField()
{
return _set;
}
/**
* Sets the __call
*/
public void setCall(AbstractFunction fun)
{
_call = fun;
}
/**
* Sets the __call
*/
public AbstractFunction getCall()
{
return _call;
}
/**
* Adds an initializer
*/
public void addInitializer(InstanceInitializer init)
{
_initializers.add(init);
}
/**
* Adds a field.
*/
public void addField(String name, int index, Expr initExpr)
{
_fieldNames.add(name);
_fieldMap.put(name, index);
_fieldInitMap.put(new StringBuilderValue(name), initExpr);
}
/**
* Adds a field.
*/
public int addFieldIndex(String name)
{
int index = _fieldMap.get(name);
if (index >= 0)
return index;
else {
index = _fieldNames.size();
_fieldMap.put(name, index);
_fieldNames.add(name);
return index;
}
}
/**
* Returns a set of the fields and their initial values
*/
public HashMap<StringValue,Expr> getClassVars()
{
return _fieldInitMap;
}
/**
* Returns the declared functions.
*/
public Iterable<AbstractFunction> getClassMethods()
{
return _methodMap.values();
}
/**
* Adds a method.
*/
public void addMethod(String name, AbstractFunction fun)
{
/*
_methodMap.put(name.intern(), fun);
_lowerMethodMap.put(name.toLowerCase(), fun);
*/
_methodMap.put(name, fun);
}
/**
* Adds a static class field.
*/
public void addStaticFieldExpr(String className, String name, Expr value)
{
ArrayList<StaticField> fieldList = _staticFieldExprMap.get(className);
if (fieldList == null) {
fieldList = new ArrayList<StaticField>();
_staticFieldExprMap.put(className, fieldList);
}
fieldList.add(new StaticField(name, value));
}
/**
* Adds a constant definition
*/
public void addConstant(String name, Expr expr)
{
_constMap.put(name, expr);
}
/**
* Returns the number of fields.
*/
public int getFieldSize()
{
return _fieldNames.size();
}
/**
* Returns the field index.
*/
public int findFieldIndex(String name)
{
return _fieldMap.get(name);
}
/**
* Returns the key set.
*/
public ArrayList<String> getFieldNames()
{
return _fieldNames;
}
public void validate(Env env)
{
if (! _classDef.isAbstract() && ! _classDef.isInterface()) {
for (AbstractFunction absFun : _methodMap.values()) {
if (! (absFun instanceof Function))
continue;
Function fun = (Function) absFun;
if (fun.isAbstract()) {
throw env.errorException(L.l("Abstract function '{0}' must be implemented in concrete class {1}.",
fun.getName(), getName()));
}
}
}
}
public void init(Env env)
{
for (Map.Entry<String,ArrayList<StaticField>> map :
_staticFieldExprMap.entrySet()) {
if (env.isInitializedClass(map.getKey()))
continue;
for (StaticField field : map.getValue()) {
Value val;
Expr expr = field._expr;
//php/096f
if (expr instanceof ClassConstExpr)
- val = ((ClassConstExpr)expr).eval(env, this);
+ val = ((ClassConstExpr)expr).eval(env);
else
val = expr.eval(env);
Var var = new Var();
var.set(val);
//var.setGlobal();
_staticFieldMap.put(field._name, var);
//env.setGlobalValue(field._name, val);
}
env.addInitializedClass(map.getKey());
}
}
public Var getStaticField(String name)
{
Var var = _staticFieldMap.get(name);
if (var != null)
return var;
QuercusClass parent = getParent();
if (parent != null)
var = parent.getStaticField(name);
return var;
}
//
// Constructors
//
/**
* Creates a new instance.
*/
public Value callNew(Env env, Expr []args)
{
Value object = _classDef.callNew(env, args);
if (object != null)
return object;
object = newInstance(env);
AbstractFunction fun = findConstructor();
if (fun != null) {
fun.callMethod(env, object, args);
}
return object;
}
/**
* Creates a new instance.
*/
public Value callNew(Env env, Value []args)
{
Value object = _classDef.callNew(env, args);
if (object != null)
return object;
object = newInstance(env);
AbstractFunction fun = findConstructor();
if (fun != null)
fun.callMethod(env, object, args);
else {
// if expr
}
return object;
}
/**
* Returns the parent class.
*/
public String getParentName()
{
return _classDefList[0].getParentName();
}
/**
* Returns true for an implementation of a class
*/
public boolean isA(String name)
{
for (int i = _classDefList.length - 1; i >= 0; i--) {
if (_classDefList[i].isA(name))
return true;
}
return false;
}
/**
* Creates a new instance.
*/
public Value newInstance(Env env)
{
Value obj = _classDef.newInstance(env, this);
for (int i = 0; i < _initializers.size(); i++) {
_initializers.get(i).initInstance(env, obj);
}
return obj;
}
/**
* Finds the matching constructor.
*/
public AbstractFunction findConstructor()
{
return _constructor;
}
//
// Fields
//
/**
* Implements the __get method call.
*/
public Value getField(Env env, Value qThis, String field)
{
if (_get != null)
return _get.callMethod(env, qThis, new StringBuilderValue(field));
else
return UnsetValue.UNSET;
}
/**
* Implements the __set method call.
*/
public void setField(Env env, Value qThis, String field, Value value)
{
if (_set != null)
_set.callMethod(env, qThis, new StringBuilderValue(field), value);
}
/**
* Finds the matching function.
*/
public AbstractFunction findFunction(String name)
{
char []key = name.toCharArray();
int hash = MethodMap.hash(key, key.length);
AbstractFunction fun = _methodMap.get(hash, key, key.length);
/*
AbstractFunction fun = _methodMap.get(name);
if (fun == null)
fun = _lowerMethodMap.get(name.toLowerCase());
*/
/* XXX: this either needs to be special cased in the actual
* constructor or put into a map.
// php/0949
if (fun == null) {
if (name.equalsIgnoreCase("__construct")) {
fun = _constructor;
}
}
*/
return fun;
}
/**
* Finds the matching function.
*/
public AbstractFunction findFunctionExact(String name)
{
throw new UnsupportedOperationException();
// return _methodMap.get(name);
}
/**
* Finds the matching function.
*/
public AbstractFunction findFunctionLowerCase(String name)
{
throw new UnsupportedOperationException();
//return _lowerMethodMap.get(name.toLowerCase());
}
/**
* Finds the matching function.
*/
public AbstractFunction findStaticFunction(String name)
{
return findFunction(name);
}
/**
* Finds the matching function.
*/
public final AbstractFunction getFunction(String name)
{
char []key = name.toCharArray();
int hash = MethodMap.hash(key, key.length);
return getFunction(hash, key, key.length);
}
/**
* Finds the matching function.
*/
public final AbstractFunction getFunction(int hash, char []name, int nameLen)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun;
else {
throw new QuercusRuntimeException(L.l("{0}::{1} is an unknown method",
getName(), toMethod(name, nameLen)));
}
}
/**
* calls the function.
*/
public Value callMethod(Env env,
Value thisValue,
int hash, char []name, int nameLength,
Expr []args)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLength);
if (fun != null)
return fun.callMethod(env, thisValue, args);
else if (getCall() != null) {
Expr []newArgs = new Expr[args.length + 1];
newArgs[0] = new StringLiteralExpr(toMethod(name, nameLength));
System.arraycopy(args, 0, newArgs, 1, args.length);
return getCall().callMethod(env, thisValue, newArgs);
}
else
return env.error(L.l("Call to undefined method {0}::{1}",
getName(), toMethod(name, nameLength)));
}
/**
* calls the function.
*/
public Value callMethod(Env env,
Value thisValue,
int hash, char []name, int nameLen,
Value []args)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethod(env, thisValue, args);
else if (getCall() != null) {
return getCall().callMethod(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl(args));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethod(Env env, Value thisValue,
int hash, char []name, int nameLen)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethod(env, thisValue);
else if (getCall() != null) {
return getCall().callMethod(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl());
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethod(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethod(env, thisValue, a1);
else if (getCall() != null) {
return getCall().callMethod(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethod(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethod(env, thisValue, a1, a2);
else if (getCall() != null) {
return getCall().callMethod(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethod(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2, Value a3)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethod(env, thisValue, a1, a2, a3);
else if (getCall() != null) {
return getCall().callMethod(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2)
.append(a3));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethod(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2, Value a3, Value a4)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethod(env, thisValue, a1, a2, a3, a4);
else if (getCall() != null) {
return getCall().callMethod(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2)
.append(a3)
.append(a4));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethod(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2, Value a3, Value a4, Value a5)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethod(env, thisValue, a1, a2, a3, a4, a5);
else if (getCall() != null) {
return getCall().callMethod(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2)
.append(a3)
.append(a4)
.append(a5));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen,
Expr []args)
{
AbstractFunction fun = getFunction(hash, name, nameLen);
return fun.callMethodRef(env, thisValue, args);
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value []args)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethodRef(env, thisValue, args);
else if (getCall() != null) {
return getCall().callMethodRef(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl(args));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethodRef(env, thisValue);
else if (getCall() != null) {
return getCall().callMethodRef(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl());
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethodRef(env, thisValue, a1);
else if (getCall() != null) {
return getCall().callMethodRef(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethodRef(env, thisValue, a1, a2);
else if (getCall() != null) {
return getCall().callMethodRef(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2, Value a3)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethodRef(env, thisValue, a1, a2, a3);
else if (getCall() != null) {
return getCall().callMethodRef(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2)
.append(a3));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2, Value a3, Value a4)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethodRef(env, thisValue, a1, a2, a3, a4);
else if (getCall() != null) {
return getCall().callMethodRef(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2)
.append(a3)
.append(a4));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
/**
* calls the function.
*/
public Value callMethodRef(Env env, Value thisValue,
int hash, char []name, int nameLen,
Value a1, Value a2, Value a3, Value a4, Value a5)
{
AbstractFunction fun = _methodMap.get(hash, name, nameLen);
if (fun != null)
return fun.callMethodRef(env, thisValue, a1, a2, a3, a4, a5);
else if (getCall() != null) {
return getCall().callMethodRef(env,
thisValue,
new StringBuilderValue(name, nameLen),
new ArrayValueImpl()
.append(a1)
.append(a2)
.append(a3)
.append(a4)
.append(a5));
}
else
return env.error(L.l("Call to undefined method {0}::{1}()",
getName(), toMethod(name, nameLen)));
}
private String toMethod(char []key, int keyLength)
{
return new String(key, 0, keyLength);
}
/**
* Finds a function.
*/
public AbstractFunction findStaticFunctionLowerCase(String name)
{
return null;
}
/**
* Finds the matching function.
*/
public final AbstractFunction getStaticFunction(String name)
{
AbstractFunction fun = findStaticFunction(name);
/*
if (fun != null)
return fun;
fun = findStaticFunctionLowerCase(name.toLowerCase());
*/
if (fun != null)
return fun;
else {
throw new QuercusRuntimeException(L.l("{0}::{1} is an unknown method",
getName(), name));
}
}
/**
* Finds the matching constant
*/
public final Value getConstant(Env env, String name)
{
Expr expr = _constMap.get(name);
if (expr != null)
return expr.eval(env);
throw new QuercusRuntimeException(L.l("{0}::{1} is an unknown constant",
getName(), name));
}
public String toString()
{
return "QuercusClass[" + getName() + "]";
}
static class StaticField
{
String _name;
Expr _expr;
StaticField(String name, Expr expr)
{
_name = name;
_expr = expr;
}
}
}
diff --git a/modules/quercus/src/com/caucho/quercus/expr/ClassConstExpr.java b/modules/quercus/src/com/caucho/quercus/expr/ClassConstExpr.java
index c233c3801..e87614e32 100644
--- a/modules/quercus/src/com/caucho/quercus/expr/ClassConstExpr.java
+++ b/modules/quercus/src/com/caucho/quercus/expr/ClassConstExpr.java
@@ -1,83 +1,78 @@
/*
* Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.expr;
import com.caucho.quercus.Location;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.QuercusClass;
import com.caucho.quercus.env.Value;
import com.caucho.util.L10N;
/**
* Represents a PHP parent::FOO constant call expression.
*/
public class ClassConstExpr extends Expr {
private static final L10N L = new L10N(ClassMethodExpr.class);
protected final String _className;
protected final String _name;
public ClassConstExpr(Location location, String className, String name)
{
super(location);
_className = className.intern();
_name = name.intern();
}
public ClassConstExpr(String className, String name)
{
_className = className.intern();
_name = name.intern();
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
public Value eval(Env env)
{
- return eval(env, env.getClass(_className));
- }
-
- public Value eval(Env env, QuercusClass ownerClass)
- {
- return ownerClass.getConstant(env, _name);
+ return env.getClass(_className).getConstant(env, _name);
}
public String toString()
{
return _className + "::" + _name + "()";
}
}
| false | false | null | null |
diff --git a/src/main/java/com/sk89q/skmcl/Launcher.java b/src/main/java/com/sk89q/skmcl/Launcher.java
index 79b1814..877bfc8 100644
--- a/src/main/java/com/sk89q/skmcl/Launcher.java
+++ b/src/main/java/com/sk89q/skmcl/Launcher.java
@@ -1,83 +1,97 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010, 2011 Albert Pham <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.skmcl;
import com.sk89q.skmcl.launch.InstanceLauncher;
import com.sk89q.skmcl.profile.Profile;
import com.sk89q.skmcl.profile.ProfileManager;
import com.sk89q.skmcl.swing.CreateProfileDialog;
import com.sk89q.skmcl.swing.LauncherFrame;
import com.sk89q.skmcl.swing.SwingHelper;
import com.sk89q.skmcl.util.SharedLocale;
import com.sk89q.skmcl.worker.Worker;
import lombok.Getter;
import lombok.NonNull;
+import lombok.extern.java.Log;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.Locale;
+import java.util.logging.Level;
+
+import static com.sk89q.skmcl.util.SharedLocale._;
/**
* Main launcher class.
*/
+@Log
public class Launcher {
@Getter
private final File baseDir;
@Getter
private final ProfileManager profiles;
public Launcher(@NonNull File baseDir) {
this.baseDir = baseDir;
this.profiles = new ProfileManager(baseDir);
}
public LauncherFrame showLauncher() {
LauncherFrame frame = new LauncherFrame(this);
frame.setVisible(true);
return frame;
}
public CreateProfileDialog showCreateProfile(Window owner) {
CreateProfileDialog dialog = new CreateProfileDialog(owner, this);
dialog.setVisible(true);
return dialog;
}
public void launchApplication(Window owner, Worker worker, Profile profile) {
InstanceLauncher task = new InstanceLauncher(profile.getApplication());
worker.submit(task);
}
public static void main(String[] args) {
SharedLocale.loadBundle("lang.Launcher", Locale.getDefault());
File dir = new File("_tempdata");
final Launcher launcher = new Launcher(dir);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
- SwingHelper.setLookAndFeel();
- launcher.showLauncher();
+ try {
+ SwingHelper.setLookAndFeel();
+ launcher.showLauncher();
+ } catch (Throwable t) {
+ log.log(Level.SEVERE, "Failed to load", t);
+ SwingHelper.setSafeLookAndFeel();
+ SwingHelper.showErrorDialog(null,
+ _("errors.criticalLoadError"),
+ _("errors.errorTitle"), t);
+ System.exit(1);
+ }
}
});
}
}
| false | false | null | null |
diff --git a/src/plugins/Freetalk/WoT/WoTMessageInserter.java b/src/plugins/Freetalk/WoT/WoTMessageInserter.java
index 5808a90d..ee9d1ef8 100644
--- a/src/plugins/Freetalk/WoT/WoTMessageInserter.java
+++ b/src/plugins/Freetalk/WoT/WoTMessageInserter.java
@@ -1,213 +1,213 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.Freetalk.WoT;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Random;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import plugins.Freetalk.Freetalk;
import plugins.Freetalk.MessageInserter;
import plugins.Freetalk.OwnMessage;
import com.db4o.ObjectContainer;
import freenet.client.FetchException;
import freenet.client.FetchResult;
import freenet.client.HighLevelSimpleClient;
import freenet.client.InsertBlock;
import freenet.client.InsertContext;
import freenet.client.InsertException;
import freenet.client.async.BaseClientPutter;
import freenet.client.async.ClientGetter;
import freenet.client.async.ClientPutter;
import freenet.keys.FreenetURI;
import freenet.node.Node;
import freenet.node.RequestClient;
+import freenet.node.RequestStarter;
import freenet.support.Logger;
import freenet.support.api.Bucket;
import freenet.support.io.Closer;
import freenet.support.io.NativeThread;
/**
* Periodically wakes up and inserts messages as CHK. The CHK URIs are then stored in the messages.
* When downloading messages, their CHK URI will have to be obtained by the reader by downloading messagelists from the given identity.
* Therefore, when a message is inserted by this class, only half of the work is done. After messages were inserted as CHK, the
* <code>WoTMessageListInserter</code> will obtain the CHK URIs of the messages from the <code>MessageManager</code> and publish them in
* a <code>MessageList</code>.
*
* @author xor
*/
public final class WoTMessageInserter extends MessageInserter {
private static final int STARTUP_DELAY = Freetalk.FAST_DEBUG_MODE ? (10 * 1000) : (10 * 60 * 1000);
// TODO: The message inserter should not constantly wake up but rather receive an event notification when there are messages to be inserted.
private static final int THREAD_PERIOD = Freetalk.FAST_DEBUG_MODE ? (2 * 60 * 1000) : (5 * 60 * 1000);
private static final int ESTIMATED_PARALLEL_MESSAGE_INSERT_COUNT = 10;
private final WoTMessageManager mMessageManager;
private final Random mRandom;
private final RequestClient mRequestClient;
/**
* For each <code>BaseClientPutter</code> (= an object associated with an insert) this hashtable stores the ID of the message which is being
* inserted by the <code>BaseClientPutter</code>.
*/
private final Hashtable<BaseClientPutter, String> mMessageIDs = new Hashtable<BaseClientPutter, String>(2*ESTIMATED_PARALLEL_MESSAGE_INSERT_COUNT);
private final WoTMessageXML mXML;
public WoTMessageInserter(Node myNode, HighLevelSimpleClient myClient, String myName, WoTIdentityManager myIdentityManager,
WoTMessageManager myMessageManager, WoTMessageXML myMessageXML) {
super(myNode, myClient, myName, myIdentityManager, myMessageManager);
mMessageManager = myMessageManager;
mRandom = mNode.fastWeakRandom;
mRequestClient = mMessageManager.mRequestClient;
mXML = myMessageXML;
}
@Override
protected Collection<ClientGetter> createFetchStorage() {
return null;
}
@Override
protected Collection<BaseClientPutter> createInsertStorage() {
return new ArrayList<BaseClientPutter>(ESTIMATED_PARALLEL_MESSAGE_INSERT_COUNT);
}
@Override
public int getPriority() {
return NativeThread.NORM_PRIORITY;
}
@Override
protected long getStartupDelay() {
return STARTUP_DELAY/2 + mRandom.nextInt(STARTUP_DELAY);
}
@Override
protected long getSleepTime() {
return THREAD_PERIOD/2 + mRandom.nextInt(THREAD_PERIOD);
}
@Override
protected synchronized void iterate() {
abortAllTransfers();
synchronized(mMessageManager) {
for(WoTOwnMessage message : mMessageManager.getNotInsertedOwnMessages()) {
try {
insertMessage(message);
}
catch(Exception e) {
Logger.error(this, "Insert of message failed", e);
}
}
}
}
/**
* You have to synchronize on this <code>WoTMessageInserter</code> when using this function.
*/
protected void insertMessage(OwnMessage m) throws InsertException, IOException, TransformerException, ParserConfigurationException {
Bucket tempB = mTBF.makeBucket(2048 + m.getText().length()); /* TODO: set to a reasonable value */
OutputStream os = null;
try {
os = tempB.getOutputStream();
mXML.encode(m, os);
os.close(); os = null;
tempB.setReadOnly();
/* We do not specifiy a ClientMetaData with mimetype because that would result in the insertion of an additional CHK */
InsertBlock ib = new InsertBlock(tempB, null, m.getInsertURI());
InsertContext ictx = mClient.getInsertContext(true);
- ClientPutter pu = mClient.insert(ib, false, null, false, ictx, this);
- // pu.setPriorityClass(RequestStarter.UPDATE_PRIORITY_CLASS); /* pluginmanager defaults to interactive priority */
+ ClientPutter pu = mClient.insert(ib, false, null, false, ictx, this, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
addInsert(pu);
mMessageIDs.put(pu, m.getID());
tempB = null;
Logger.debug(this, "Started insert of message from " + m.getAuthor().getNickname());
}
finally {
if(tempB != null)
tempB.free();
Closer.close(os);
}
}
@Override
public synchronized void onSuccess(BaseClientPutter state, ObjectContainer container) {
try {
mMessageManager.onOwnMessageInserted(mMessageIDs.get(state), state.getURI());
}
catch(Exception e) {
Logger.error(this, "Message insert finished but onSuccess() failed", e);
}
finally {
removeInsert(state);
}
}
@Override
public synchronized void onFailure(InsertException e, BaseClientPutter state, ObjectContainer container) {
try {
Logger.error(this, "Message insert failed", e);
}
finally {
removeInsert(state);
}
}
/**
* This method must be synchronized because onFailure is synchronized and TransferThread calls abortAllTransfers() during shutdown without
* synchronizing on this object.
*/
protected synchronized void abortAllTransfers() {
super.abortAllTransfers();
mMessageIDs.clear();
}
/**
* You have to synchronize on this <code>WoTMessageInserter</code> when using this function.
*/
@Override
protected void removeInsert(BaseClientPutter p) {
super.removeInsert(p);
mMessageIDs.remove(p);
}
/* Not needed functions*/
@Override
public void onSuccess(FetchResult result, ClientGetter state, ObjectContainer container) { }
@Override
public void onFailure(FetchException e, ClientGetter state, ObjectContainer container) { }
@Override
public void onGeneratedURI(FreenetURI uri, BaseClientPutter state, ObjectContainer container) { }
@Override
public void onFetchable(BaseClientPutter state, ObjectContainer container) { }
@Override
public void onMajorProgress(ObjectContainer container) { }
}
diff --git a/src/plugins/Freetalk/WoT/WoTMessageListInserter.java b/src/plugins/Freetalk/WoT/WoTMessageListInserter.java
index f92f8809..920ba8ff 100644
--- a/src/plugins/Freetalk/WoT/WoTMessageListInserter.java
+++ b/src/plugins/Freetalk/WoT/WoTMessageListInserter.java
@@ -1,217 +1,217 @@
package plugins.Freetalk.WoT;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import plugins.Freetalk.Freetalk;
import plugins.Freetalk.MessageList;
import plugins.Freetalk.MessageListInserter;
import plugins.Freetalk.exceptions.NoSuchMessageException;
import plugins.Freetalk.exceptions.NoSuchMessageListException;
import com.db4o.ObjectContainer;
import freenet.client.FetchException;
import freenet.client.FetchResult;
import freenet.client.HighLevelSimpleClient;
import freenet.client.InsertBlock;
import freenet.client.InsertContext;
import freenet.client.InsertException;
import freenet.client.async.BaseClientPutter;
import freenet.client.async.ClientGetter;
import freenet.client.async.ClientPutter;
import freenet.keys.FreenetURI;
import freenet.node.Node;
+import freenet.node.RequestStarter;
import freenet.support.Logger;
import freenet.support.api.Bucket;
import freenet.support.io.Closer;
import freenet.support.io.NativeThread;
public final class WoTMessageListInserter extends MessageListInserter {
private static final int STARTUP_DELAY = Freetalk.FAST_DEBUG_MODE ? (10 * 1000) : (10 * 60 * 1000);
private static final int THREAD_PERIOD = Freetalk.FAST_DEBUG_MODE ? (2 * 60 * 1000) : (10 * 60 * 1000);
private static final int MAX_PARALLEL_MESSAGELIST_INSERT_COUNT = 8;
private final WoTMessageManager mMessageManager;
private final Random mRandom;
private final WoTMessageListXML mXML;
public WoTMessageListInserter(Node myNode, HighLevelSimpleClient myClient, String myName, WoTIdentityManager myIdentityManager,
WoTMessageManager myMessageManager, WoTMessageListXML myMessageListXML) {
super(myNode, myClient, myName, myIdentityManager, myMessageManager);
mMessageManager = myMessageManager;
mRandom = mNode.fastWeakRandom;
mXML = myMessageListXML;
}
@Override
protected void clearBeingInsertedFlags() {
WoTMessageManager messageManager = (WoTMessageManager)super.mMessageManager;
synchronized(messageManager) {
for(WoTOwnMessageList list : messageManager.getBeingInsertedOwnMessageLists()) {
try {
messageManager.onMessageListInsertFailed(list.getURI(), false);
} catch (NoSuchMessageListException e) {
Logger.error(this, "SHOULD NOT HAPPEN", e);
}
}
}
}
@Override
protected Collection<ClientGetter> createFetchStorage() {
return null;
}
@Override
protected Collection<BaseClientPutter> createInsertStorage() {
return new HashSet<BaseClientPutter>(MAX_PARALLEL_MESSAGELIST_INSERT_COUNT * 2);
}
@Override
public int getPriority() {
return NativeThread.NORM_PRIORITY;
}
@Override
protected long getStartupDelay() {
return STARTUP_DELAY/2 + mRandom.nextInt(STARTUP_DELAY);
}
@Override
protected long getSleepTime() {
return THREAD_PERIOD/2 + mRandom.nextInt(THREAD_PERIOD);
}
@Override
protected synchronized void iterate() {
abortAllTransfers();
synchronized(mMessageManager) {
for(WoTOwnMessageList list : mMessageManager.getNotInsertedOwnMessageLists()) {
try {
/* TODO: Ensure that after creation of a message list we wait for at least a few minutes so that if the author writes
* more messages they will be put in the same list */
insertMessageList(list);
}
catch(Exception e) {
Logger.error(this, "Insert of WoTOwnMessageList failed", e);
}
}
}
}
/**
* You have to synchronize on this <code>WoTMessageListInserter</code> and then on the <code>WoTMessageManager</code> when using this function.
*/
private void insertMessageList(WoTOwnMessageList list) throws TransformerException, ParserConfigurationException, NoSuchMessageException, IOException, InsertException {
Bucket tempB = mTBF.makeBucket(4096); /* TODO: set to a reasonable value */
OutputStream os = null;
try {
os = tempB.getOutputStream();
// This is what requires synchronization on the WoTMessageManager: While being marked as "being inserted", message lists cannot be modified anymore,
// so it must be guranteed that the "being inserted" mark does not change while we encode the XML etc.
mMessageManager.onMessageListInsertStarted(list);
mXML.encode(mMessageManager, list, os);
os.close(); os = null;
tempB.setReadOnly();
/* We do not specifiy a ClientMetaData with mimetype because that would result in the insertion of an additional CHK */
InsertBlock ib = new InsertBlock(tempB, null, list.getInsertURI());
InsertContext ictx = mClient.getInsertContext(true);
- ClientPutter pu = mClient.insert(ib, false, null, false, ictx, this);
- // pu.setPriorityClass(RequestStarter.UPDATE_PRIORITY_CLASS); /* pluginmanager defaults to interactive priority */
+ ClientPutter pu = mClient.insert(ib, false, null, false, ictx, this, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
addInsert(pu);
tempB = null;
Logger.debug(this, "Started insert of WoTOwnMessageList at request URI " + list.getURI());
}
finally {
if(tempB != null)
tempB.free();
Closer.close(os);
}
}
@Override
public synchronized void onSuccess(BaseClientPutter state, ObjectContainer container) {
try {
Logger.debug(this, "Successfully inserted WoTOwnMessageList at " + state.getURI());
mMessageManager.onMessageListInsertSucceeded(state.getURI());
}
catch(Exception e) {
Logger.error(this, "WoTOwnMessageList insert succeeded but onSuccess() failed", e);
}
finally {
removeInsert(state);
}
}
@Override
public synchronized void onFailure(InsertException e, BaseClientPutter state, ObjectContainer container) {
try {
if(e.getMode() == InsertException.COLLISION) {
Logger.error(this, "WoTOwnMessageList insert collided, trying to insert with higher index ...");
try {
synchronized(mMessageManager) {
// We must call getOwnMessageList() before calling onMessageListInsertFailed() because the latter will increment the message list's
// index, resulting in the ID of the message list changing - getIDFromURI would fail with the old state.getURI() if we called it after
// onMessageListInsertFailed()
WoTOwnMessageList list = (WoTOwnMessageList)mMessageManager.getOwnMessageList(MessageList.getIDFromURI(state.getURI()));
mMessageManager.onMessageListInsertFailed(state.getURI(), true);
insertMessageList(list);
}
}
catch(Exception ex) {
Logger.error(this, "Inserting WoTOwnMessageList with higher index failed", ex);
}
} else
mMessageManager.onMessageListInsertFailed(state.getURI(), false);
}
catch(Exception ex) {
Logger.error(this, "WoTOwnMessageList insert failed", ex);
}
finally {
removeInsert(state);
}
}
/**
* This method must be synchronized because onFailure is synchronized and TransferThread calls abortAllTransfers() during shutdown without
* synchronizing on this object.
*/
protected synchronized void abortAllTransfers() {
super.abortAllTransfers();
}
/* Not needed functions*/
@Override
public void onSuccess(FetchResult result, ClientGetter state, ObjectContainer container) { }
@Override
public void onFailure(FetchException e, ClientGetter state, ObjectContainer container) { }
@Override
public void onGeneratedURI(FreenetURI uri, BaseClientPutter state, ObjectContainer container) { }
@Override
public void onFetchable(BaseClientPutter state, ObjectContainer container) { }
@Override
public void onMajorProgress(ObjectContainer container) { }
}
| false | false | null | null |
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/ddi/DDIServiceBean.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/ddi/DDIServiceBean.java
index 45d5d305..7c0ed1d9 100644
--- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/ddi/DDIServiceBean.java
+++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/ddi/DDIServiceBean.java
@@ -1,3473 +1,3473 @@
/*
* DDIServiceBean.java
*
* Created on Jan 11, 2008, 3:08:24 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.iq.dvn.core.ddi;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.study.DataTable;
import edu.harvard.iq.dvn.core.study.DataVariable;
import edu.harvard.iq.dvn.core.study.FileMetadata;
import edu.harvard.iq.dvn.core.study.Metadata;
import edu.harvard.iq.dvn.core.study.OtherFile;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyAbstract;
import edu.harvard.iq.dvn.core.study.StudyAuthor;
import edu.harvard.iq.dvn.core.study.StudyDistributor;
import edu.harvard.iq.dvn.core.study.StudyField;
import edu.harvard.iq.dvn.core.study.StudyFieldValue;
import edu.harvard.iq.dvn.core.study.StudyFile;
import edu.harvard.iq.dvn.core.study.StudyGeoBounding;
import edu.harvard.iq.dvn.core.study.StudyGrant;
import edu.harvard.iq.dvn.core.study.StudyKeyword;
import edu.harvard.iq.dvn.core.study.StudyNote;
import edu.harvard.iq.dvn.core.study.StudyOtherId;
import edu.harvard.iq.dvn.core.study.StudyOtherRef;
import edu.harvard.iq.dvn.core.study.StudyProducer;
import edu.harvard.iq.dvn.core.study.StudyRelMaterial;
import edu.harvard.iq.dvn.core.study.StudyRelPublication;
import edu.harvard.iq.dvn.core.study.StudyRelStudy;
import edu.harvard.iq.dvn.core.study.StudySoftware;
import edu.harvard.iq.dvn.core.study.StudyTopicClass;
import edu.harvard.iq.dvn.core.study.StudyVersion;
import edu.harvard.iq.dvn.core.study.SummaryStatistic;
import edu.harvard.iq.dvn.core.study.SummaryStatisticType;
import edu.harvard.iq.dvn.core.study.TabularDataFile;
import edu.harvard.iq.dvn.core.study.VariableCategory;
import edu.harvard.iq.dvn.core.study.VariableFormatType;
import edu.harvard.iq.dvn.core.study.VariableIntervalType;
import edu.harvard.iq.dvn.core.study.VariableRange;
import edu.harvard.iq.dvn.core.study.VariableRangeType;
import edu.harvard.iq.dvn.core.study.VariableServiceLocal;
import edu.harvard.iq.dvn.core.study.VersionContributor;
import edu.harvard.iq.dvn.core.util.DateUtil;
import edu.harvard.iq.dvn.core.util.FileUtil;
import edu.harvard.iq.dvn.core.util.PropertyUtil;
import edu.harvard.iq.dvn.core.util.StringUtil;
import edu.harvard.iq.dvn.core.vdc.VDCNetworkServiceLocal;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
/**
*
* @author Gustavo
*/
@Stateless
public class DDIServiceBean implements DDIServiceLocal {
@EJB VariableServiceLocal varService;
@EJB VDCNetworkServiceLocal vdcNetworkService;
// ddi constants
public static final String SOURCE_DVN_3_0 = "DVN_3_0";
public static final String AGENCY_HANDLE = "handle";
public static final String REPLICATION_FOR_TYPE = "replicationFor";
public static final String VAR_WEIGHTED = "wgtd";
public static final String VAR_INTERVAL_CONTIN = "contin";
public static final String VAR_INTERVAL_DISCRETE = "discrete";
public static final String CAT_STAT_TYPE_FREQUENCY = "freq";
public static final String VAR_FORMAT_TYPE_NUMERIC = "numeric";
public static final String VAR_FORMAT_SCHEMA_ISO = "ISO";
public static final String EVENT_START = "start";
public static final String EVENT_END = "end";
public static final String EVENT_SINGLE = "single";
public static final String LEVEL_DVN = "dvn";
public static final String LEVEL_DV = "dv";
public static final String LEVEL_STUDY = "study";
public static final String LEVEL_FILE = "file";
public static final String LEVEL_VARIABLE = "variable";
public static final String LEVEL_CATEGORY = "category";
public static final String NOTE_TYPE_UNF = "VDC:UNF";
public static final String NOTE_SUBJECT_UNF = "Universal Numeric Fingerprint";
public static final String NOTE_TYPE_TERMS_OF_USE = "DVN:TOU";
public static final String NOTE_SUBJECT_TERMS_OF_USE = "Terms Of Use";
public static final String NOTE_TYPE_CITATION = "DVN:CITATION";
public static final String NOTE_SUBJECT_CITATION = "Citation";
public static final String NOTE_TYPE_VERSION_NOTE = "DVN:VERSION_NOTE";
public static final String NOTE_SUBJECT_VERSION_NOTE= "Version Note";
public static final String NOTE_TYPE_ARCHIVE_NOTE = "DVN:ARCHIVE_NOTE";
public static final String NOTE_SUBJECT_ARCHIVE_NOTE= "Archive Note";
public static final String NOTE_TYPE_ARCHIVE_DATE = "DVN:ARCHIVE_DATE";
public static final String NOTE_SUBJECT_ARCHIVE_DATE= "Archive Date";
public static final String NOTE_TYPE_EXTENDED_METADATA = "DVN:EXTENDED_METADATA";
public static final String NOTE_TYPE_LOCKSS_CRAWL = "LOCKSS:CRAWLING";
public static final String NOTE_SUBJECT_LOCKSS_PERM = "LOCKSS Permission";
public static final String NOTE_TYPE_REPLICATION_FOR = "DVN:REPLICATION_FOR";
// db constants
public static final String DB_VAR_INTERVAL_TYPE_CONTINUOUS = "continuous";
public static final String DB_VAR_RANGE_TYPE_POINT = "point";
public static final String DB_VAR_RANGE_TYPE_MIN = "min";
public static final String DB_VAR_RANGE_TYPE_MIN_EX = "min exclusive";
public static final String DB_VAR_RANGE_TYPE_MAX = "max";
public static final String DB_VAR_RANGE_TYPE_MAX_EX = "max exclusive";
public List<VariableFormatType> variableFormatTypeList = null;
public List<VariableIntervalType> variableIntervalTypeList = null;
public List<SummaryStatisticType> summaryStatisticTypeList = null;
public List<VariableRangeType> variableRangeTypeList = null;
private XMLInputFactory xmlInputFactory = null;
private XMLOutputFactory xmlOutputFactory = null;
public void ejbCreate() {
// initialize lists
variableFormatTypeList = varService.findAllVariableFormatType();
variableIntervalTypeList = varService.findAllVariableIntervalType();
summaryStatisticTypeList = varService.findAllSummaryStatisticType();
variableRangeTypeList = varService.findAllVariableRangeType();
xmlInputFactory = javax.xml.stream.XMLInputFactory.newInstance();
xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE);
xmlOutputFactory = javax.xml.stream.XMLOutputFactory.newInstance();
//xmlof.setProperty("javax.xml.stream.isPrefixDefaulting", java.lang.Boolean.TRUE);
}
public boolean isXmlFormat() {
return true;
}
//**********************
// EXPORT METHODS
//**********************
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void exportStudy(Study s, OutputStream os) {
if (s.getReleasedVersion() == null) {
throw new IllegalArgumentException("Study does not have released version, study.id = " + s.getId());
}
if (s.isIsHarvested()) {
exportOriginalDDIPlus(s.getReleasedVersion(), os);
} else {
XMLStreamWriter xmlw = null;
try {
xmlw = xmlOutputFactory.createXMLStreamWriter(os);
xmlw.writeStartDocument();
createCodeBook(xmlw, s.getReleasedVersion(), null, null);
xmlw.writeEndDocument();
} catch (XMLStreamException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in exportStudy.", ex);
} finally {
try {
if (xmlw != null) {
xmlw.close();
}
} catch (XMLStreamException ex) {
}
}
}
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void exportStudy(Study s, OutputStream os, String xpathExclude, String xpathInclude) {
if (s == null) {
throw new IllegalArgumentException("ExportStudy called with a null study.");
}
if (s.getReleasedVersion() == null) {
throw new IllegalArgumentException("Study does not have released version, study.id = " + s.getId());
}
if ((xpathExclude == null || "".equals(xpathExclude))
&&
(xpathInclude == null || "".equals(xpathInclude))) {
this.exportStudy(s, os);
} else {
// partial export
if (s.isIsHarvested()) {
throw new IllegalArgumentException("Partial export requested on a harvested study. (study id = " + s.getId() + ")");
}
XMLStreamWriter xmlw = null;
try {
xmlw = xmlOutputFactory.createXMLStreamWriter(os);
xmlw.writeStartDocument();
createCodeBook(xmlw, s.getReleasedVersion(), xpathExclude, xpathInclude);
xmlw.writeEndDocument();
} catch (XMLStreamException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred during partial export of a study.", ex);
} finally {
try {
if (xmlw != null) {
xmlw.close();
}
} catch (XMLStreamException ex) {
}
}
}
}
public void exportDataFile(TabularDataFile tdf, OutputStream os) {
if (tdf.getReleasedFileMetadata() == null) {
throw new IllegalArgumentException("StudyFile does not have a released version, study file id = " + tdf.getId() );
}
XMLStreamWriter xmlw = null;
try {
xmlw = xmlOutputFactory.createXMLStreamWriter(os);
xmlw.writeStartDocument();
xmlw.writeStartElement("codeBook");
xmlw.writeDefaultNamespace("http://www.icpsr.umich.edu/DDI");
writeAttribute( xmlw, "version", "2.0" );
createFileDscr(xmlw, tdf.getReleasedFileMetadata(), null, null, null);
createDataDscr(xmlw, tdf);
xmlw.writeEndElement(); // codeBook
xmlw.writeEndDocument();
} catch (XMLStreamException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in exportDataFile.", ex);
} finally {
try {
if (xmlw != null) { xmlw.close(); }
} catch (XMLStreamException ex) {}
}
}
private void exportOriginalDDIPlus (StudyVersion sv, OutputStream os) {
BufferedReader in = null;
OutputStreamWriter out = null;
XMLStreamWriter xmlw = null;
File studyDir = new File(FileUtil.getStudyFileDir(), sv.getStudy().getAuthority() + File.separator + sv.getStudy().getStudyId());
File originalImport = new File(studyDir, "original_imported_study.xml");
if (originalImport.exists()) {
try {
in = new BufferedReader( new FileReader(originalImport) );
out = new OutputStreamWriter(os);
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = in.readLine()) != null){
// check to see if this is the StudyDscr in order to add the extra docDscr
if (line.indexOf("<stdyDscr>") != -1) {
out.write( line.substring(0, line.indexOf("<stdyDscr>") ) );
out.write(System.getProperty("line.separator"));
out.flush();
// now create DocDscr element (using StAX)
xmlw = xmlOutputFactory.createXMLStreamWriter(os);
createDocDscr(xmlw, sv.getMetadata(), null, null, null);
xmlw.close();
out.write(System.getProperty("line.separator"));
out.write( line.substring(line.indexOf("<stdyDscr>") ) );
out.write(System.getProperty("line.separator"));
out.flush();
} else {
out.write(line);
out.write(System.getProperty("line.separator"));
out.flush();
}
}
} catch (IOException ex) {
throw new EJBException ("A problem occurred trying to export this study (original DDI Plus).");
} catch (XMLStreamException ex) {
throw new EJBException ("A problem occurred trying to create the DocDscr for this study (original DDI Plus).");
} finally {
try {
if (xmlw != null) { xmlw.close(); }
} catch (XMLStreamException ex) { ex.printStackTrace(); }
try {
if (in!=null) { in.close(); }
} catch (IOException ex) { ex.printStackTrace(); }
try {
if (out!=null) { out.close(); }
} catch (IOException ex) { ex.printStackTrace(); }
}
} else {
throw new EJBException ("There is no original import DDI for this study.");
}
}
// <editor-fold defaultstate="collapsed" desc="export methods">
private void createCodeBook(XMLStreamWriter xmlw, StudyVersion sv, String xpathExclude, String xpathInclude) throws XMLStreamException {
Metadata md = sv.getMetadata();
String xpathCurrent = "codeBook";
xmlw.writeStartElement(xpathCurrent);
xmlw.writeDefaultNamespace("http://www.icpsr.umich.edu/DDI");
writeAttribute( xmlw, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" );
writeAttribute( xmlw, "xsi:schemaLocation", "http://www.icpsr.umich.edu/DDI http://www.icpsr.umich.edu/DDI/Version2-0.xsd" );
writeAttribute( xmlw, "version", "2.0" );
createDocDscr(xmlw, md, xpathCurrent, xpathExclude, xpathInclude);
createStdyDscr(xmlw, md, xpathCurrent, xpathExclude, xpathInclude);
// iterate through files, saving other material files for the end
List<FileMetadata> otherMatFiles = new ArrayList();
for (FileMetadata fmd : sv.getFileMetadatas()) {
StudyFile sf = fmd.getStudyFile();
if ( sf instanceof TabularDataFile ) {
createFileDscr(xmlw, fmd, xpathCurrent, xpathExclude, xpathInclude);
} else {
otherMatFiles.add(fmd);
}
}
createDataDscr(xmlw, sv, xpathCurrent, xpathExclude, xpathInclude);
// now go through otherMat files
for (FileMetadata fmd : otherMatFiles) {
createOtherMat(xmlw, fmd, xpathCurrent, xpathExclude, xpathInclude);
}
xmlw.writeEndElement(); // codeBook
}
private void createDocDscr(XMLStreamWriter xmlw, Metadata metadata, String xpathParent, String xpathExclude, String xpathInclude) throws XMLStreamException {
Study study = metadata.getStudy();
String currentElement = "docDscr";
String xpathCurrent = xpathParent + "/" + currentElement;
if (xpathExclude != null && (xpathExclude.equals(xpathCurrent))) {
return;
}
if (xpathInclude == null || xpathInclude.startsWith(xpathCurrent)) {
xmlw.writeStartElement(currentElement);
// TODO: perform similar exclude/include tests on all the child
// elements of docDscr.
// (for now we only support the exclusions and inclusions of the top-
// level DDI parts)
xmlw.writeStartElement("citation");
// titlStmt
xmlw.writeStartElement("titlStmt");
xmlw.writeStartElement("titl");
xmlw.writeCharacters( metadata.getTitle() );
xmlw.writeEndElement(); // titl
xmlw.writeStartElement("IDNo");
writeAttribute( xmlw, "agency", "handle" );
xmlw.writeCharacters( study.getGlobalId() );
xmlw.writeEndElement(); // IDNo
xmlw.writeEndElement(); // titlStmt
// distStmt
xmlw.writeStartElement("distStmt");
xmlw.writeStartElement("distrbtr");
xmlw.writeCharacters( vdcNetworkService.find().getName() + " Dataverse Network" );
xmlw.writeEndElement(); // distrbtr
String lastUpdateString = new SimpleDateFormat("yyyy-MM-dd").format(study.getLastUpdateTime());
createDateElement( xmlw, "distDate", lastUpdateString );
xmlw.writeEndElement(); // distStmt
// verStmt (DVN versions)
for (StudyVersion sv : study.getStudyVersions()) {
if (sv.isWorkingCopy()) {
continue; // we do not want to incude any info about a working copy
}
xmlw.writeStartElement("verStmt");
writeAttribute( xmlw, "source", "DVN" );
xmlw.writeStartElement("version");
writeAttribute( xmlw, "date", new SimpleDateFormat("yyyy-MM-dd").format(sv.getReleaseTime()) );
writeAttribute( xmlw, "type", sv.getVersionState().toString() );
xmlw.writeCharacters( sv.getVersionNumber().toString() );
xmlw.writeEndElement(); // version
String versionContributors = "";
for (VersionContributor vc : sv.getVersionContributors()) {
if (!"".equals(versionContributors)) {
versionContributors += ", ";
}
versionContributors += vc.getContributor().getUserName();
}
xmlw.writeStartElement("verResp");
xmlw.writeCharacters( versionContributors );
xmlw.writeEndElement(); // verResp
if (!StringUtil.isEmpty( sv.getVersionNote() )) {
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", NOTE_TYPE_VERSION_NOTE );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_VERSION_NOTE );
xmlw.writeCharacters( sv.getVersionNote());
xmlw.writeEndElement(); // notes
}
if (!StringUtil.isEmpty( sv.getArchiveNote() )) {
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", NOTE_TYPE_ARCHIVE_NOTE );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_ARCHIVE_NOTE );
xmlw.writeCharacters( sv.getArchiveNote());
xmlw.writeEndElement(); // notes
}
if (sv.getArchiveTime() != null) {
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", NOTE_TYPE_ARCHIVE_DATE );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_ARCHIVE_DATE );
xmlw.writeCharacters( new SimpleDateFormat("yyyy-MM-dd").format(sv.getArchiveTime()) );
xmlw.writeEndElement(); // notes
}
xmlw.writeEndElement(); // verStmt
}
// biblCit
xmlw.writeStartElement("biblCit");
writeAttribute( xmlw, "format", "DVN" );
xmlw.writeCharacters( metadata.getTextCitation() );
xmlw.writeEndElement(); // biblCit
// holdings
xmlw.writeEmptyElement("holdings");
writeAttribute( xmlw, "URI", "http://" + PropertyUtil.getHostUrl() + "/dvn/study?globalId=" + study.getGlobalId() );
xmlw.writeEndElement(); // citation
xmlw.writeEndElement(); // docDscr
}
}
private void createStdyDscr(XMLStreamWriter xmlw, Metadata metadata, String xpathParent, String xpathExclude, String xpathInclude) throws XMLStreamException {
String currentElement = "stdyDscr";
String xpathCurrent = xpathParent + "/" + currentElement;
if (xpathExclude != null && (xpathExclude.equals(xpathCurrent))) {
return;
}
if (xpathInclude == null || xpathInclude.startsWith(xpathCurrent)) {
xmlw.writeStartElement(currentElement);
createCitation(xmlw, metadata);
createStdyInfo(xmlw, metadata);
createMethod(xmlw, metadata);
createDataAccs(xmlw, metadata);
createOthrStdyMat(xmlw,metadata);
createNotes(xmlw,metadata);
xmlw.writeEndElement(); // stdyDscr
}
}
private void createCitation(XMLStreamWriter xmlw, Metadata metadata) throws XMLStreamException {
xmlw.writeStartElement("citation");
// titlStmt
xmlw.writeStartElement("titlStmt");
xmlw.writeStartElement("titl");
xmlw.writeCharacters( metadata.getTitle() );
xmlw.writeEndElement(); // titl
if ( !StringUtil.isEmpty( metadata.getSubTitle() ) ) {
xmlw.writeStartElement("subTitl");
xmlw.writeCharacters( metadata.getSubTitle() );
xmlw.writeEndElement(); // subTitl
}
xmlw.writeStartElement("IDNo");
writeAttribute( xmlw, "agency", "handle" );
xmlw.writeCharacters( metadata.getStudy().getGlobalId() );
xmlw.writeEndElement(); // IDNo
for (StudyOtherId otherId : metadata.getStudyOtherIds()) {
xmlw.writeStartElement("IDNo");
writeAttribute( xmlw, "agency", otherId.getAgency() );
xmlw.writeCharacters( otherId.getOtherId() );
xmlw.writeEndElement(); // IDNo
}
xmlw.writeEndElement(); // titlStmt
// rspStmt
if (metadata.getStudyAuthors() != null && metadata.getStudyAuthors().size() > 0) {
xmlw.writeStartElement("rspStmt");
for (StudyAuthor author : metadata.getStudyAuthors()) {
xmlw.writeStartElement("AuthEnty");
if ( !StringUtil.isEmpty(author.getAffiliation()) ) {
writeAttribute( xmlw, "affiliation", author.getAffiliation() );
}
xmlw.writeCharacters( author.getName() );
xmlw.writeEndElement(); // AuthEnty
}
xmlw.writeEndElement(); // rspStmt
}
// prodStmt
boolean prodStmtAdded = false;
for (StudyProducer prod : metadata.getStudyProducers()) {
prodStmtAdded = checkParentElement(xmlw, "prodStmt", prodStmtAdded);
xmlw.writeStartElement("producer");
writeAttribute( xmlw, "abbr", prod.getAbbreviation() );
writeAttribute( xmlw, "affiliation", prod.getAffiliation() );
xmlw.writeCharacters( prod.getName() );
createExtLink(xmlw, prod.getUrl(), null);
createExtLink(xmlw, prod.getLogo(), "image");
xmlw.writeEndElement(); // producer
}
if (!StringUtil.isEmpty( metadata.getProductionDate() )) {
prodStmtAdded = checkParentElement(xmlw, "prodStmt", prodStmtAdded);
createDateElement( xmlw, "prodDate", metadata.getProductionDate() );
}
if (!StringUtil.isEmpty( metadata.getProductionPlace() )) {
prodStmtAdded = checkParentElement(xmlw, "prodStmt", prodStmtAdded);
xmlw.writeStartElement("prodPlac");
xmlw.writeCharacters( metadata.getProductionPlace() );
xmlw.writeEndElement(); // prodPlac
}
for (StudySoftware soft : metadata.getStudySoftware()) {
prodStmtAdded = checkParentElement(xmlw, "prodStmt", prodStmtAdded);
xmlw.writeStartElement("software");
writeAttribute( xmlw, "version", soft.getSoftwareVersion() );
xmlw.writeCharacters( soft.getName() );
xmlw.writeEndElement(); // software
}
if (!StringUtil.isEmpty( metadata.getFundingAgency() )) {
prodStmtAdded = checkParentElement(xmlw, "prodStmt", prodStmtAdded);
xmlw.writeStartElement("fundAg");
xmlw.writeCharacters( metadata.getFundingAgency() );
xmlw.writeEndElement(); // fundAg
}
for (StudyGrant grant : metadata.getStudyGrants()) {
prodStmtAdded = checkParentElement(xmlw, "prodStmt", prodStmtAdded);
xmlw.writeStartElement("grantNo");
writeAttribute( xmlw, "agency", grant.getAgency() );
xmlw.writeCharacters( grant.getNumber() );
xmlw.writeEndElement(); // grantNo
}
if (prodStmtAdded) xmlw.writeEndElement(); // prodStmt
// distStmt
boolean distStmtAdded = false;
for (StudyDistributor dist : metadata.getStudyDistributors()) {
distStmtAdded = checkParentElement(xmlw, "distStmt", distStmtAdded);
xmlw.writeStartElement("distrbtr");
writeAttribute( xmlw, "abbr", dist.getAbbreviation() );
writeAttribute( xmlw, "affiliation", dist.getAffiliation() );
xmlw.writeCharacters( dist.getName() );
createExtLink(xmlw, dist.getUrl(), null);
createExtLink(xmlw, dist.getLogo(), "image");
xmlw.writeEndElement(); // distrbtr
}
if (!StringUtil.isEmpty( metadata.getDistributorContact()) ||
!StringUtil.isEmpty( metadata.getDistributorContactEmail()) ||
!StringUtil.isEmpty( metadata.getDistributorContactAffiliation()) ) {
distStmtAdded = checkParentElement(xmlw, "distStmt", distStmtAdded);
xmlw.writeStartElement("contact");
writeAttribute( xmlw, "email", metadata.getDistributorContactEmail() );
writeAttribute( xmlw, "affiliation", metadata.getDistributorContactAffiliation() );
xmlw.writeCharacters( metadata.getDistributorContact() );
xmlw.writeEndElement(); // contact
}
if (!StringUtil.isEmpty( metadata.getDepositor() )) {
distStmtAdded = checkParentElement(xmlw, "distStmt", distStmtAdded);
xmlw.writeStartElement("depositr");
xmlw.writeCharacters( metadata.getDepositor() );
xmlw.writeEndElement(); // depositr
}
if (!StringUtil.isEmpty( metadata.getDateOfDeposit() )) {
distStmtAdded = checkParentElement(xmlw, "distStmt", distStmtAdded);
createDateElement( xmlw, "depDate", metadata.getDateOfDeposit() );
}
if (!StringUtil.isEmpty( metadata.getDistributionDate() )) {
distStmtAdded = checkParentElement(xmlw, "distStmt", distStmtAdded);
createDateElement( xmlw, "distDate", metadata.getDistributionDate() );
}
if (distStmtAdded) xmlw.writeEndElement(); // distStmt
// serStmt
boolean serStmtAdded = false;
if (!StringUtil.isEmpty( metadata.getSeriesName() )) {
serStmtAdded = checkParentElement(xmlw, "serStmt", serStmtAdded);
xmlw.writeStartElement("serName");
xmlw.writeCharacters( metadata.getSeriesName() );
xmlw.writeEndElement(); // serName
}
if (!StringUtil.isEmpty( metadata.getSeriesInformation() )) {
serStmtAdded = checkParentElement(xmlw, "serStmt", serStmtAdded);
xmlw.writeStartElement("serInfo");
xmlw.writeCharacters( metadata.getSeriesInformation() );
xmlw.writeEndElement(); // serInfo
}
if (serStmtAdded) xmlw.writeEndElement(); // serStmt
// verStmt
boolean verStmtAdded = false;
if (!StringUtil.isEmpty( metadata.getStudyVersionText()) || !StringUtil.isEmpty( metadata.getVersionDate()) ) {
verStmtAdded = checkParentElement(xmlw, "verStmt", verStmtAdded);
xmlw.writeStartElement("version");
writeAttribute( xmlw, "date", metadata.getVersionDate() );
xmlw.writeCharacters( metadata.getStudyVersionText() );
xmlw.writeEndElement(); // version
}
if (verStmtAdded) xmlw.writeEndElement(); // verStmt
// DVN Version info
StudyVersion sv = metadata.getStudyVersion();
xmlw.writeStartElement("verStmt");
writeAttribute( xmlw, "source", "DVN" );
xmlw.writeStartElement("version");
writeAttribute( xmlw, "date", new SimpleDateFormat("yyyy-MM-dd").format(sv.getReleaseTime()) );
writeAttribute( xmlw, "type", sv.getVersionState().toString() );
xmlw.writeCharacters( sv.getVersionNumber().toString() );
xmlw.writeEndElement(); // version
xmlw.writeEndElement(); // verStmt
// UNF note
if (! StringUtil.isEmpty( metadata.getUNF()) ) {
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "level", LEVEL_STUDY );
writeAttribute( xmlw, "type", NOTE_TYPE_UNF );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_UNF );
xmlw.writeCharacters( metadata.getUNF() );
xmlw.writeEndElement(); // notes
}
xmlw.writeEndElement(); // citation
}
private void createStdyInfo(XMLStreamWriter xmlw, Metadata metadata) throws XMLStreamException {
boolean stdyInfoAdded = false;
// subject
boolean subjectAdded = false;
for (StudyKeyword kw : metadata.getStudyKeywords()) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
subjectAdded = checkParentElement(xmlw, "subject", subjectAdded);
xmlw.writeStartElement("keyword");
writeAttribute( xmlw, "vocab", kw.getVocab() );
writeAttribute( xmlw, "vocabURI", kw.getVocabURI() );
xmlw.writeCharacters( kw.getValue() );
xmlw.writeEndElement(); // keyword
}
for (StudyTopicClass tc : metadata.getStudyTopicClasses()) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
subjectAdded = checkParentElement(xmlw, "subject", subjectAdded);
xmlw.writeStartElement("topcClas");
writeAttribute( xmlw, "vocab", tc.getVocab() );
writeAttribute( xmlw, "vocabURI", tc.getVocabURI() );
xmlw.writeCharacters( tc.getValue() );
xmlw.writeEndElement(); // topcClas
}
if (subjectAdded) xmlw.writeEndElement(); // subject
// abstract
for (StudyAbstract abst : metadata.getStudyAbstracts()) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
xmlw.writeStartElement("abstract");
writeAttribute( xmlw, "date", abst.getDate() );
xmlw.writeCharacters( abst.getText() );
xmlw.writeEndElement(); // abstract
}
// sumDscr
boolean sumDscrAdded = false;
if (!StringUtil.isEmpty( metadata.getTimePeriodCoveredStart() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("timePrd");
writeAttribute( xmlw, "event", EVENT_START );
writeDateAttribute( xmlw, metadata.getTimePeriodCoveredStart() );
xmlw.writeCharacters( metadata.getTimePeriodCoveredStart() );
xmlw.writeEndElement(); // timePrd
}
if (!StringUtil.isEmpty( metadata.getTimePeriodCoveredEnd() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("timePrd");
writeAttribute( xmlw, "event", EVENT_END );
writeDateAttribute( xmlw, metadata.getTimePeriodCoveredEnd() );
xmlw.writeCharacters( metadata.getTimePeriodCoveredEnd() );
xmlw.writeEndElement(); // timePrd
}
if (!StringUtil.isEmpty( metadata.getDateOfCollectionStart() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("collDate");
writeAttribute( xmlw, "event", EVENT_START );
writeDateAttribute( xmlw, metadata.getDateOfCollectionStart() );
xmlw.writeCharacters( metadata.getDateOfCollectionStart() );
xmlw.writeEndElement(); // collDate
}
if (!StringUtil.isEmpty( metadata.getDateOfCollectionEnd() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("collDate");
writeAttribute( xmlw, "event", EVENT_END );
writeDateAttribute( xmlw, metadata.getDateOfCollectionEnd() );
xmlw.writeCharacters( metadata.getDateOfCollectionEnd() );
xmlw.writeEndElement(); // collDate
}
if (!StringUtil.isEmpty( metadata.getCountry() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("nation");
xmlw.writeCharacters( metadata.getCountry() );
xmlw.writeEndElement(); // nation
}
if (!StringUtil.isEmpty( metadata.getGeographicCoverage() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("geogCover");
xmlw.writeCharacters( metadata.getGeographicCoverage() );
xmlw.writeEndElement(); // geogCover
}
if (!StringUtil.isEmpty( metadata.getGeographicUnit() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("geogUnit");
xmlw.writeCharacters( metadata.getGeographicUnit() );
xmlw.writeEndElement(); // geogUnit
}
// we store geoboundings as list but there is only one
if (metadata.getStudyGeoBoundings() != null && metadata.getStudyGeoBoundings().size() != 0) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
StudyGeoBounding gbb = metadata.getStudyGeoBoundings().get(0);
xmlw.writeStartElement("geoBndBox");
xmlw.writeStartElement("westBL");
xmlw.writeCharacters( gbb.getWestLongitude() );
xmlw.writeEndElement(); // westBL
xmlw.writeStartElement("eastBL");
xmlw.writeCharacters( gbb.getEastLongitude() );
xmlw.writeEndElement(); // eastBL
xmlw.writeStartElement("southBL");
xmlw.writeCharacters( gbb.getSouthLatitude() );
xmlw.writeEndElement(); // southBL
xmlw.writeStartElement("northBL");
xmlw.writeCharacters( gbb.getNorthLatitude() );
xmlw.writeEndElement(); // northBL
xmlw.writeEndElement(); // geoBndBox
}
if (!StringUtil.isEmpty( metadata.getUnitOfAnalysis() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("anlyUnit");
xmlw.writeCharacters( metadata.getUnitOfAnalysis() );
xmlw.writeEndElement(); // anlyUnit
}
if (!StringUtil.isEmpty( metadata.getUniverse() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("universe");
xmlw.writeCharacters( metadata.getUniverse() );
xmlw.writeEndElement(); // universe
}
if (!StringUtil.isEmpty( metadata.getKindOfData() )) {
stdyInfoAdded = checkParentElement(xmlw, "stdyInfo", stdyInfoAdded);
sumDscrAdded = checkParentElement(xmlw, "sumDscr", sumDscrAdded);
xmlw.writeStartElement("dataKind");
xmlw.writeCharacters( metadata.getKindOfData() );
xmlw.writeEndElement(); // dataKind
}
if (sumDscrAdded) xmlw.writeEndElement(); // sumDscr
if (stdyInfoAdded) xmlw.writeEndElement(); // stdyInfo
}
private void createMethod(XMLStreamWriter xmlw, Metadata metadata) throws XMLStreamException {
boolean methodAdded = false;
// dataColl
boolean dataCollAdded = false;
if (!StringUtil.isEmpty( metadata.getTimeMethod() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("timeMeth");
xmlw.writeCharacters( metadata.getTimeMethod() );
xmlw.writeEndElement(); // timeMeth
}
if (!StringUtil.isEmpty( metadata.getDataCollector() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("dataCollector");
xmlw.writeCharacters( metadata.getDataCollector() );
xmlw.writeEndElement(); // dataCollector
}
if (!StringUtil.isEmpty( metadata.getFrequencyOfDataCollection() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("frequenc");
xmlw.writeCharacters( metadata.getFrequencyOfDataCollection() );
xmlw.writeEndElement(); // frequenc
}
if (!StringUtil.isEmpty( metadata.getSamplingProcedure() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("sampProc");
xmlw.writeCharacters( metadata.getSamplingProcedure() );
xmlw.writeEndElement(); // sampProc
}
if (!StringUtil.isEmpty( metadata.getDeviationsFromSampleDesign() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("deviat");
xmlw.writeCharacters( metadata.getDeviationsFromSampleDesign() );
xmlw.writeEndElement(); // deviat
}
if (!StringUtil.isEmpty( metadata.getCollectionMode() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("collMode");
xmlw.writeCharacters( metadata.getCollectionMode() );
xmlw.writeEndElement(); // collMode
}
if (!StringUtil.isEmpty( metadata.getResearchInstrument() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("resInstru");
xmlw.writeCharacters( metadata.getResearchInstrument() );
xmlw.writeEndElement(); // resInstru
}
//source
boolean sourcesAdded = false;
if (!StringUtil.isEmpty( metadata.getDataSources() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
sourcesAdded = checkParentElement(xmlw, "sources", sourcesAdded);
xmlw.writeStartElement("dataSrc");
xmlw.writeCharacters( metadata.getDataSources() );
xmlw.writeEndElement(); // dataSrc
}
if (!StringUtil.isEmpty( metadata.getOriginOfSources() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
sourcesAdded = checkParentElement(xmlw, "sources", sourcesAdded);
xmlw.writeStartElement("srcOrig");
xmlw.writeCharacters( metadata.getOriginOfSources() );
xmlw.writeEndElement(); // srcOrig
}
if (!StringUtil.isEmpty( metadata.getCharacteristicOfSources() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
sourcesAdded = checkParentElement(xmlw, "sources", sourcesAdded);
xmlw.writeStartElement("srcChar");
xmlw.writeCharacters( metadata.getCharacteristicOfSources() );
xmlw.writeEndElement(); // srcChar
}
if (!StringUtil.isEmpty( metadata.getAccessToSources() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
sourcesAdded = checkParentElement(xmlw, "sources", sourcesAdded);
xmlw.writeStartElement("srcDocu");
xmlw.writeCharacters( metadata.getAccessToSources() );
xmlw.writeEndElement(); // srcDocu
}
if (sourcesAdded) xmlw.writeEndElement(); // sources
if (!StringUtil.isEmpty( metadata.getDataCollectionSituation() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("collSitu");
xmlw.writeCharacters( metadata.getDataCollectionSituation() );
xmlw.writeEndElement(); // collSitu
}
if (!StringUtil.isEmpty( metadata.getActionsToMinimizeLoss() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("actMin");
xmlw.writeCharacters( metadata.getActionsToMinimizeLoss() );
xmlw.writeEndElement(); // actMin
}
if (!StringUtil.isEmpty( metadata.getControlOperations() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("ConOps");
xmlw.writeCharacters( metadata.getControlOperations() );
xmlw.writeEndElement(); // ConOps
}
if (!StringUtil.isEmpty( metadata.getWeighting() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("weight");
xmlw.writeCharacters( metadata.getWeighting() );
xmlw.writeEndElement(); // weight
}
if (!StringUtil.isEmpty( metadata.getCleaningOperations() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
dataCollAdded = checkParentElement(xmlw, "dataColl", dataCollAdded);
xmlw.writeStartElement("cleanOps");
xmlw.writeCharacters( metadata.getCleaningOperations() );
xmlw.writeEndElement(); // cleanOps
}
if (dataCollAdded) xmlw.writeEndElement(); // dataColl
// notes
// We use this "notes" section (<method><dataColl.../><notes .../>)
// for different things:
// Its default use has been to store the StudyLevelErrorNotes from
// the standard DVN Metadata; we continue storing these as
// simply "<notes>" - with no attributes.
//
// We'll also be using these notes to store extended, template-based
// metadata fields. For these, the note should be storing both
// the name and the value of the field. These notes will be tagged
// with the special attributes: type="DVN:EXTENDED_METADATA" and
// subject="TEMPLATE:XXX;FIELD:YYY"
// StudyLevelErrorNotes:
// TODO: create an explicit type attribute for this.
if (!StringUtil.isEmpty( metadata.getStudyLevelErrorNotes() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
xmlw.writeStartElement("notes");
xmlw.writeCharacters( metadata.getStudyLevelErrorNotes() );
xmlw.writeEndElement(); // notes
}
// Extended metadata (will produce multiple notes for different and/or
// multiple extended fields:
String templateName = metadata.getStudy().getTemplate().getName();
for (StudyField extField : metadata.getStudyFields()) {
for (StudyFieldValue extFieldValue : extField.getStudyFieldValues()) {
try {
String extFieldName = extField.getName();
String extFieldStrValue = extFieldValue.getStrValue();
if (extFieldName != null
&& !extFieldName.equals("")
&& extFieldStrValue != null
&& !extFieldStrValue.equals("")) {
String fieldDefinition = "TEMPLATE:" + templateName + ";FIELD:" + extFieldName;
methodAdded = checkParentElement(xmlw, "method", methodAdded);
xmlw.writeStartElement("notes");
writeAttribute(xmlw, "type", NOTE_TYPE_EXTENDED_METADATA);
writeAttribute(xmlw, "subject", fieldDefinition);
xmlw.writeCharacters(extFieldStrValue);
xmlw.writeEndElement(); // notes
}
} catch (Exception ex) {
// do nothing - if we can't retrieve the field, we are
// not going to export it, that's all.
}
}
}
// anlyInfo
boolean anlyInfoAdded = false;
if (!StringUtil.isEmpty( metadata.getResponseRate() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
anlyInfoAdded = checkParentElement(xmlw, "anlyInfo", anlyInfoAdded);
xmlw.writeStartElement("respRate");
xmlw.writeCharacters( metadata.getResponseRate() );
xmlw.writeEndElement(); // getResponseRate
}
if (!StringUtil.isEmpty( metadata.getSamplingErrorEstimate() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
anlyInfoAdded = checkParentElement(xmlw, "anlyInfo", anlyInfoAdded);
xmlw.writeStartElement("EstSmpErr");
xmlw.writeCharacters( metadata.getSamplingErrorEstimate() );
xmlw.writeEndElement(); // EstSmpErr
}
if (!StringUtil.isEmpty( metadata.getOtherDataAppraisal() )) {
methodAdded = checkParentElement(xmlw, "method", methodAdded);
anlyInfoAdded = checkParentElement(xmlw, "anlyInfo", anlyInfoAdded);
xmlw.writeStartElement("dataAppr");
xmlw.writeCharacters( metadata.getOtherDataAppraisal() );
xmlw.writeEndElement(); // dataAppr
}
if (anlyInfoAdded) xmlw.writeEndElement(); // anlyInfo
if (methodAdded) xmlw.writeEndElement(); // method
}
private void createDataAccs(XMLStreamWriter xmlw, Metadata metadata) throws XMLStreamException {
boolean dataAccsAdded = false;
// setAvail
boolean setAvailAdded = false;
if (!StringUtil.isEmpty( metadata.getPlaceOfAccess() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
setAvailAdded = checkParentElement(xmlw, "setAvail", setAvailAdded);
xmlw.writeStartElement("accsPlac");
xmlw.writeCharacters( metadata.getPlaceOfAccess() );
xmlw.writeEndElement(); // getStudyCompletion
}
if (!StringUtil.isEmpty( metadata.getOriginalArchive() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
setAvailAdded = checkParentElement(xmlw, "setAvail", setAvailAdded);
xmlw.writeStartElement("origArch");
xmlw.writeCharacters( metadata.getOriginalArchive() );
xmlw.writeEndElement(); // origArch
}
if (!StringUtil.isEmpty( metadata.getAvailabilityStatus() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
setAvailAdded = checkParentElement(xmlw, "setAvail", setAvailAdded);
xmlw.writeStartElement("avlStatus");
xmlw.writeCharacters( metadata.getAvailabilityStatus() );
xmlw.writeEndElement(); // avlStatus
}
if (!StringUtil.isEmpty( metadata.getCollectionSize() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
setAvailAdded = checkParentElement(xmlw, "setAvail", setAvailAdded);
xmlw.writeStartElement("collSize");
xmlw.writeCharacters( metadata.getCollectionSize() );
xmlw.writeEndElement(); // collSize
}
if (!StringUtil.isEmpty( metadata.getStudyCompletion() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
setAvailAdded = checkParentElement(xmlw, "setAvail", setAvailAdded);
xmlw.writeStartElement("complete");
xmlw.writeCharacters( metadata.getStudyCompletion() );
xmlw.writeEndElement(); // complete
}
if (setAvailAdded) xmlw.writeEndElement(); // setAvail
// useStmt
boolean useStmtAdded = false;
if (!StringUtil.isEmpty( metadata.getConfidentialityDeclaration() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("confDec");
xmlw.writeCharacters( metadata.getConfidentialityDeclaration() );
xmlw.writeEndElement(); // confDec
}
if (!StringUtil.isEmpty( metadata.getSpecialPermissions() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("specPerm");
xmlw.writeCharacters( metadata.getSpecialPermissions() );
xmlw.writeEndElement(); // specPerm
}
if (!StringUtil.isEmpty( metadata.getRestrictions() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("restrctn");
xmlw.writeCharacters( metadata.getRestrictions() );
xmlw.writeEndElement(); // restrctn
}
if (!StringUtil.isEmpty( metadata.getContact() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("contact");
xmlw.writeCharacters( metadata.getContact() );
xmlw.writeEndElement(); // contact
}
if (!StringUtil.isEmpty( metadata.getCitationRequirements() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("citReq");
xmlw.writeCharacters( metadata.getCitationRequirements() );
xmlw.writeEndElement(); // citReq
}
if (!StringUtil.isEmpty( metadata.getDepositorRequirements() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("deposReq");
xmlw.writeCharacters( metadata.getDepositorRequirements() );
xmlw.writeEndElement(); // deposReq
}
if (!StringUtil.isEmpty( metadata.getConditions() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("conditions");
xmlw.writeCharacters( metadata.getConditions() );
xmlw.writeEndElement(); // conditions
}
if (!StringUtil.isEmpty( metadata.getDisclaimer() )) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
useStmtAdded = checkParentElement(xmlw, "useStmt", useStmtAdded);
xmlw.writeStartElement("disclaimer");
xmlw.writeCharacters( metadata.getDisclaimer() );
xmlw.writeEndElement(); // disclaimer
}
if (useStmtAdded) xmlw.writeEndElement(); // useStmt
// terms of use notes
Study study = metadata.getStudy();
String dvTermsOfUse = null;
String dvnTermsOfUse = null;
if (study.isIsHarvested() ) {
dvTermsOfUse = metadata.getHarvestDVTermsOfUse();
dvnTermsOfUse = metadata.getHarvestDVNTermsOfUse();
} else {
dvTermsOfUse = study.getOwner().isDownloadTermsOfUseEnabled() ? study.getOwner().getDownloadTermsOfUse() : null;
dvnTermsOfUse = vdcNetworkService.find().isDownloadTermsOfUseEnabled() ? vdcNetworkService.find().getDownloadTermsOfUse() : null;
}
// Are we missing the study-level terms of use here?
// that would be:
// if (metadata.isTermsOfUseEnabled()) { ... }
// -- Actually, no, it looks like isTermsOfUseEnabled does not rely on a
// boolean stored in the database, but checks if any field from a list
// of "terms of use-related" fields is present.
// Presumably, all these values, if present, are getting exported as
// the corresponding native DDI fields.
// -- L.A., Feb. 2012
if (!StringUtil.isEmpty(dvTermsOfUse)) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "level", LEVEL_DV );
writeAttribute( xmlw, "type", NOTE_TYPE_TERMS_OF_USE );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_TERMS_OF_USE );
xmlw.writeCharacters( dvTermsOfUse );
xmlw.writeEndElement(); // notes
}
if (!StringUtil.isEmpty(dvnTermsOfUse)) {
dataAccsAdded = checkParentElement(xmlw, "dataAccs", dataAccsAdded);
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "level", LEVEL_DVN );
writeAttribute( xmlw, "type", NOTE_TYPE_TERMS_OF_USE );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_TERMS_OF_USE );
xmlw.writeCharacters( dvnTermsOfUse );
xmlw.writeEndElement(); // notes
}
if (dataAccsAdded) xmlw.writeEndElement(); // dataAccs
}
private void createOthrStdyMat(XMLStreamWriter xmlw, Metadata metadata) throws XMLStreamException {
boolean othrStdyMatAdded = false;
for (StudyRelMaterial rm : metadata.getStudyRelMaterials()) {
othrStdyMatAdded = checkParentElement(xmlw, "othrStdyMat", othrStdyMatAdded);
xmlw.writeStartElement("relMat");
xmlw.writeCharacters( rm.getText() );
xmlw.writeEndElement(); // relMat
}
for (StudyRelStudy rs : metadata.getStudyRelStudies()) {
othrStdyMatAdded = checkParentElement(xmlw, "othrStdyMat", othrStdyMatAdded);
xmlw.writeStartElement("relStdy");
xmlw.writeCharacters( rs.getText() );
xmlw.writeEndElement(); // relStdy
}
for (StudyRelPublication rp : metadata.getStudyRelPublications()) {
othrStdyMatAdded = checkParentElement(xmlw, "othrStdyMat", othrStdyMatAdded);
xmlw.writeStartElement("relPubl");
createInnerCitation(xmlw,rp);
xmlw.writeEndElement(); // relPubl
}
for (StudyOtherRef or : metadata.getStudyOtherRefs()) {
othrStdyMatAdded = checkParentElement(xmlw, "othrStdyMat", othrStdyMatAdded);
xmlw.writeStartElement("otherRefs");
xmlw.writeCharacters( or.getText() );
xmlw.writeEndElement(); // otherRefs
}
if (othrStdyMatAdded) xmlw.writeEndElement(); // othrStdyMat
}
private void createInnerCitation(XMLStreamWriter xmlw, StudyRelPublication publication) throws XMLStreamException {
// currently this field only accepts related publications, but could in theory generate a citation for other elements
// if we do this, let's creater an interface, and then have StudyRelPublication and others extend that
xmlw.writeStartElement("citation");
writeAttribute( xmlw, "source", SOURCE_DVN_3_0 );
- if (StringUtil.isEmpty(publication.getIdNumber())) {
+ if (!StringUtil.isEmpty(publication.getIdNumber())) {
xmlw.writeStartElement("titlStmt");
xmlw.writeStartElement("IDNo");
writeAttribute( xmlw, "agency", publication.getIdType() );
xmlw.writeCharacters( publication.getIdNumber() );
xmlw.writeEndElement(); // IDNo
xmlw.writeEndElement(); // titlStmt
}
xmlw.writeStartElement("biblCit");
xmlw.writeCharacters( publication.getText() );
xmlw.writeEndElement(); // biblCit
- if (StringUtil.isEmpty(publication.getUrl())) {
+ if (!StringUtil.isEmpty(publication.getUrl())) {
xmlw.writeStartElement("holdings");
writeAttribute( xmlw, "URI", publication.getUrl() );
xmlw.writeCharacters( publication.getUrl() ); // for now, just put URL here, since we don't have a title for the holdings
xmlw.writeEndElement(); // holdings
}
if (publication.isReplicationData()) {
xmlw.writeEmptyElement("notes");
writeAttribute( xmlw, "type", NOTE_TYPE_REPLICATION_FOR );
}
xmlw.writeEndElement(); // citation
}
private void createNotes(XMLStreamWriter xmlw, Metadata metadata) throws XMLStreamException {
for (StudyNote note : metadata.getStudyNotes()) {
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", note.getType() );
writeAttribute( xmlw, "subject", note.getSubject() );
xmlw.writeCharacters( note.getText() );
xmlw.writeEndElement(); // notes
}
}
private void createFileDscr(XMLStreamWriter xmlw, FileMetadata fm, String xpathParent, String xpathExclude, String xpathInclude) throws XMLStreamException {
String currentElement = "fileDscr";
String xpathCurrent = xpathParent + "/" + currentElement;
if (xpathExclude != null && (xpathExclude.equals(xpathCurrent))) {
return;
}
if (xpathInclude == null || xpathInclude.startsWith(xpathCurrent)) {
TabularDataFile tdf = (TabularDataFile) fm.getStudyFile();
DataTable dt = tdf.getDataTable();
xmlw.writeStartElement(currentElement);
writeAttribute( xmlw, "ID", "f" + tdf.getId().toString() );
writeAttribute( xmlw, "URI", determineFileURI(fm) );
// fileTxt
xmlw.writeStartElement("fileTxt");
xmlw.writeStartElement("fileName");
xmlw.writeCharacters( fm.getLabel() );
xmlw.writeEndElement(); // fileName
xmlw.writeStartElement("fileCont");
xmlw.writeCharacters( fm.getDescription() );
xmlw.writeEndElement(); // fileCont
// dimensions
if (dt.getCaseQuantity() != null || dt.getVarQuantity() != null || dt.getRecordsPerCase() != null) {
xmlw.writeStartElement("dimensns");
if (dt.getCaseQuantity() != null) {
xmlw.writeStartElement("caseQnty");
xmlw.writeCharacters( dt.getCaseQuantity().toString() );
xmlw.writeEndElement(); // caseQnty
}
if (dt.getVarQuantity() != null) {
xmlw.writeStartElement("varQnty");
xmlw.writeCharacters( dt.getVarQuantity().toString() );
xmlw.writeEndElement(); // varQnty
}
if (dt.getRecordsPerCase() != null) {
xmlw.writeStartElement("recPrCas");
xmlw.writeCharacters( dt.getRecordsPerCase().toString() );
xmlw.writeEndElement(); // recPrCas
}
xmlw.writeEndElement(); // dimensns
}
xmlw.writeStartElement("fileType");
xmlw.writeCharacters( tdf.getFileType() );
xmlw.writeEndElement(); // fileType
xmlw.writeEndElement(); // fileTxt
// notes
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "level", LEVEL_FILE );
writeAttribute( xmlw, "type", NOTE_TYPE_UNF );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_UNF );
xmlw.writeCharacters( dt.getUnf() );
xmlw.writeEndElement(); // notes
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", "vdc:category" );
xmlw.writeCharacters( fm.getCategory() );
xmlw.writeEndElement(); // notes
// A special note for LOCKSS crawlers indicating the restricted
// status of the file:
if (tdf != null && isRestrictedFile(tdf)) {
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", NOTE_TYPE_LOCKSS_CRAWL );
writeAttribute( xmlw, "level", LEVEL_FILE );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_LOCKSS_PERM );
xmlw.writeCharacters( "restricted" );
xmlw.writeEndElement(); // notes
}
// THIS IS OLD CODE FROM JAXB, but a reminder that we may want to add original fileType
// we don't yet store original file type!!!'
// do we want this in the DDI export????
//NotesType _origFileType = objFactory.createNotesType();
//_origFileType.setLevel(LEVEL_FILE);
//_origFileType.setType("VDC:MIME");
//_origFileType.setSubject("original file format");
//_origFileType.getContent().add( ORIGINAL_FILE_TYPE );
xmlw.writeEndElement(); // fileDscr
}
}
private String determineFileURI(FileMetadata fm) {
String fileURI = "";
StudyFile sf = fm.getStudyFile();
Study s = sf.getStudy();
// determine whether file is local or harvested
if (sf.isRemote()) {
fileURI = sf.getFileSystemLocation();
} else {
fileURI = "http://" + PropertyUtil.getHostUrl() + "/dvn/dv/" + s.getOwner().getAlias() + "/FileDownload/";
try {
fileURI += URLEncoder.encode(fm.getLabel(), "UTF-8") + "?fileId=" + sf.getId();
} catch (IOException e) {
throw new EJBException(e);
}
}
return fileURI;
}
private void createOtherMat(XMLStreamWriter xmlw, FileMetadata fm, String xpathParent, String xpathExclude, String xpathInclude) throws XMLStreamException {
StudyFile sf = fm.getStudyFile();
String currentElement = "otherMat";
String xpathCurrent = xpathParent + "/" + currentElement;
if (xpathExclude != null && (xpathExclude.equals(xpathCurrent))) {
return;
}
if (xpathInclude == null || xpathInclude.startsWith(xpathCurrent)) {
xmlw.writeStartElement("otherMat");
writeAttribute( xmlw, "level", LEVEL_STUDY );
writeAttribute( xmlw, "URI", determineFileURI(fm) );
xmlw.writeStartElement("labl");
xmlw.writeCharacters( fm.getLabel() );
xmlw.writeEndElement(); // labl
xmlw.writeStartElement("txt");
xmlw.writeCharacters( fm.getDescription() );
xmlw.writeEndElement(); // txt
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", "vdc:category" );
xmlw.writeCharacters( fm.getCategory() );
xmlw.writeEndElement(); // notes
// A special note for LOCKSS crawlers indicating the restricted
// status of the file:
if (sf != null && isRestrictedFile(sf)) {
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "type", NOTE_TYPE_LOCKSS_CRAWL );
writeAttribute( xmlw, "level", LEVEL_FILE );
writeAttribute( xmlw, "subject", NOTE_SUBJECT_LOCKSS_PERM );
xmlw.writeCharacters( "restricted" );
xmlw.writeEndElement(); // notes
}
xmlw.writeEndElement(); // otherMat
}
}
private Boolean isRestrictedFile(StudyFile file) {
Study study = null;
VDC vdc = null;
study = file.getStudy();
if (study != null) {
vdc = study.getOwner();
}
if (vdc != null && vdc.isFilesRestricted()) {
return true;
}
if (study != null && study.isRestricted()) {
return true;
}
if (file.isRestricted()) {
return true;
}
return false;
}
private void createDataDscr(XMLStreamWriter xmlw, StudyVersion studyVersion, String xpathParent, String xpathExclude, String xpathInclude) throws XMLStreamException {
boolean dataDscrAdded = false;
String currentElement = "dataDscr";
String xpathCurrent = xpathParent + "/" + currentElement;
if (xpathExclude != null && (xpathExclude.equals(xpathCurrent))) {
return;
}
if (xpathInclude == null || xpathInclude.startsWith(xpathCurrent)) {
for (FileMetadata fmd : studyVersion.getFileMetadatas()) {
StudyFile sf = fmd.getStudyFile();
if ( sf instanceof TabularDataFile ) {
TabularDataFile tdf = (TabularDataFile) sf;
if ( tdf.getDataTable().getDataVariables().size() > 0 ) {
dataDscrAdded = checkParentElement(xmlw, "dataDscr", dataDscrAdded);
Iterator varIter = varService.getDataVariablesByFileOrder( tdf.getDataTable().getId() ).iterator();
while (varIter.hasNext()) {
DataVariable dv = (DataVariable) varIter.next();
createVar(xmlw, dv);
}
}
}
}
if (dataDscrAdded) xmlw.writeEndElement(); //dataDscr
}
}
private void createDataDscr(XMLStreamWriter xmlw, TabularDataFile tdf) throws XMLStreamException {
// this version is to produce the dataDscr for just one file
if (tdf.getDataTable().getDataVariables().size() > 0 ) {
xmlw.writeStartElement("dataDscr");
Iterator varIter = varService.getDataVariablesByFileOrder( tdf.getDataTable().getId() ).iterator();
while (varIter.hasNext()) {
DataVariable dv = (DataVariable) varIter.next();
createVar(xmlw, dv);
}
xmlw.writeEndElement(); // dataDscr
}
}
private void createVar(XMLStreamWriter xmlw, DataVariable dv) throws XMLStreamException {
xmlw.writeStartElement("var");
writeAttribute( xmlw, "ID", "v" + dv.getId().toString() );
writeAttribute( xmlw, "name", dv.getName() );
if (dv.getNumberOfDecimalPoints() != null) {
writeAttribute(xmlw, "dcml", dv.getNumberOfDecimalPoints().toString() );
}
if (dv.getVariableIntervalType() != null) {
String interval = dv.getVariableIntervalType().getName();
interval = DB_VAR_INTERVAL_TYPE_CONTINUOUS.equals(interval) ? VAR_INTERVAL_CONTIN : interval;
writeAttribute( xmlw, "intrvl", interval );
}
// location
xmlw.writeEmptyElement("location");
if (dv.getFileStartPosition() != null) writeAttribute( xmlw, "StartPos", dv.getFileStartPosition().toString() );
if (dv.getFileEndPosition() != null) writeAttribute( xmlw, "EndPos", dv.getFileEndPosition().toString() );
if (dv.getRecordSegmentNumber() != null) writeAttribute( xmlw, "width", dv.getRecordSegmentNumber().toString());
writeAttribute( xmlw, "fileid", "f" + dv.getDataTable().getStudyFile().getId().toString() );
// labl
if (!StringUtil.isEmpty( dv.getLabel() )) {
xmlw.writeStartElement("labl");
writeAttribute( xmlw, "level", "variable" );
xmlw.writeCharacters( dv.getLabel() );
xmlw.writeEndElement(); //labl
}
// invalrng
boolean invalrngAdded = false;
for (VariableRange range : dv.getInvalidRanges()) {
if (range.getBeginValueType() != null && range.getBeginValueType().getName().equals(DB_VAR_RANGE_TYPE_POINT)) {
if (range.getBeginValue() != null ) {
invalrngAdded = checkParentElement(xmlw, "invalrng", invalrngAdded);
xmlw.writeEmptyElement("item");
writeAttribute( xmlw, "VALUE", range.getBeginValue() );
}
} else {
invalrngAdded = checkParentElement(xmlw, "invalrng", invalrngAdded);
xmlw.writeEmptyElement("range");
if ( range.getBeginValueType() != null && range.getBeginValue() != null ) {
if ( range.getBeginValueType().getName().equals(DB_VAR_RANGE_TYPE_MIN) ) {
writeAttribute( xmlw, "min", range.getBeginValue() );
} else if ( range.getBeginValueType().getName().equals(DB_VAR_RANGE_TYPE_MIN_EX) ) {
writeAttribute( xmlw, "minExclusive", range.getBeginValue() );
}
}
if ( range.getEndValueType() != null && range.getEndValue() != null) {
if ( range.getEndValueType().getName().equals(DB_VAR_RANGE_TYPE_MAX) ) {
writeAttribute( xmlw, "max", range.getEndValue() );
} else if ( range.getEndValueType().getName().equals(DB_VAR_RANGE_TYPE_MAX_EX) ) {
writeAttribute( xmlw, "maxExclusive", range.getEndValue() );
}
}
}
}
if (invalrngAdded) xmlw.writeEndElement(); // invalrng
//universe
if (!StringUtil.isEmpty( dv.getUniverse() )) {
xmlw.writeStartElement("universe");
xmlw.writeCharacters( dv.getUniverse() );
xmlw.writeEndElement(); //universe
}
//sum stats
for (SummaryStatistic sumStat : dv.getSummaryStatistics()) {
xmlw.writeStartElement("sumStat");
writeAttribute( xmlw, "type", sumStat.getType().getName() );
xmlw.writeCharacters( sumStat.getValue() );
xmlw.writeEndElement(); //sumStat
}
// categories
for (VariableCategory cat : dv.getCategories()) {
xmlw.writeStartElement("catgry");
if (cat.isMissing()) {
writeAttribute(xmlw, "missing", "Y");
}
// catValu
xmlw.writeStartElement("catValu");
xmlw.writeCharacters( cat.getValue());
xmlw.writeEndElement(); //catValu
// label
if (!StringUtil.isEmpty( cat.getLabel() )) {
xmlw.writeStartElement("labl");
writeAttribute( xmlw, "level", "category" );
xmlw.writeCharacters( cat.getLabel() );
xmlw.writeEndElement(); //labl
}
// catStat
if (cat.getFrequency() != null) {
xmlw.writeStartElement("catStat");
writeAttribute( xmlw, "type", "freq" );
// if frequency is actually a long value, we want to write "100" instead of "100.0"
if ( Math.floor(cat.getFrequency()) == cat.getFrequency() ) {
xmlw.writeCharacters( new Long(cat.getFrequency().longValue()).toString() );
} else {
xmlw.writeCharacters( cat.getFrequency().toString() );
}
xmlw.writeEndElement(); //catStat
}
xmlw.writeEndElement(); //catgry
}
//concept
if (!StringUtil.isEmpty( dv.getConcept() )) {
xmlw.writeStartElement("concept");
xmlw.writeCharacters( dv.getConcept() );
xmlw.writeEndElement(); //concept
}
// varFormat
xmlw.writeEmptyElement("varFormat");
writeAttribute( xmlw, "type", dv.getVariableFormatType().getName() );
writeAttribute( xmlw, "formatname", dv.getFormatSchemaName() );
writeAttribute( xmlw, "schema", dv.getFormatSchema() );
writeAttribute( xmlw, "category", dv.getFormatCategory() );
// notes
xmlw.writeStartElement("notes");
writeAttribute( xmlw, "subject", "Universal Numeric Fingerprint" );
writeAttribute( xmlw, "level", "variable" );
writeAttribute( xmlw, "type", "VDC:UNF" );
xmlw.writeCharacters( dv.getUnf() );
xmlw.writeEndElement(); //notes
xmlw.writeEndElement(); //var
}
private void createExtLink(XMLStreamWriter xmlw, String uri, String role) throws XMLStreamException {
if ( !StringUtil.isEmpty(uri) ) {
xmlw.writeEmptyElement("ExtLink");
writeAttribute( xmlw, "URI", uri );
if (role != null) {
writeAttribute( xmlw, "role", role );
}
}
}
private void createDateElement(XMLStreamWriter xmlw, String name, String value) throws XMLStreamException {
xmlw.writeStartElement(name);
writeDateAttribute(xmlw, value);
xmlw.writeCharacters( value );
xmlw.writeEndElement();
}
private void writeAttribute(XMLStreamWriter xmlw, String name, String value) throws XMLStreamException {
if ( !StringUtil.isEmpty(value) ) {
xmlw.writeAttribute(name, value);
}
}
private void writeDateAttribute(XMLStreamWriter xmlw, String value) throws XMLStreamException {
// only write attribute if value is a valid date
if ( DateUtil.validateDate(value) ) {
xmlw.writeAttribute( "date", value);
}
}
private boolean checkParentElement(XMLStreamWriter xmlw, String elementName, boolean elementAdded) throws XMLStreamException {
if (!elementAdded) {
xmlw.writeStartElement(elementName);
}
return true;
}
// </editor-fold>
//**********************
// IMPORT METHODS
//**********************
public Map mapDDI(String xmlToParse, StudyVersion studyVersion) {
StringReader reader = null;
XMLStreamReader xmlr = null;
Map filesMap = new HashMap();
try {
reader = new StringReader(xmlToParse);
xmlr = xmlInputFactory.createXMLStreamReader(reader);
processDDI( xmlr, studyVersion, filesMap);
} catch (XMLStreamException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in mapDDI.", ex);
} finally {
try {
if (xmlr != null) { xmlr.close(); }
} catch (XMLStreamException ex) {}
if (reader != null) { reader.close();}
}
return filesMap;
}
public Map mapDDI(File ddiFile, StudyVersion studyVersion) {
FileInputStream in = null;
XMLStreamReader xmlr = null;
Map filesMap = new HashMap();
try {
in = new FileInputStream(ddiFile);
xmlr = xmlInputFactory.createXMLStreamReader(in);
processDDI( xmlr, studyVersion, filesMap );
} catch (FileNotFoundException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in mapDDI: File Not Found!");
} catch (XMLStreamException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in mapDDI.", ex);
} finally {
try {
if (xmlr != null) { xmlr.close(); }
} catch (XMLStreamException ex) {}
try {
if (in != null) { in.close();}
} catch (IOException ex) {}
}
return filesMap;
}
public Map reMapDDI(String xmlToParse, StudyVersion studyVersion, Map filesMap) {
StringReader reader = null;
XMLStreamReader xmlr = null;
Map variablesMap;
try {
reader = new StringReader(xmlToParse);
xmlr = xmlInputFactory.createXMLStreamReader(reader);
variablesMap = processDDIdataSection( xmlr, studyVersion, filesMap );
} catch (XMLStreamException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in mapDDI.", ex);
} finally {
try {
if (xmlr != null) { xmlr.close(); }
} catch (XMLStreamException ex) {}
if (reader != null) { reader.close();}
}
return variablesMap;
}
public Map reMapDDI(File ddiFile, StudyVersion studyVersion, Map filesMap) {
FileInputStream in = null;
XMLStreamReader xmlr = null;
Map variablesMap;
try {
in = new FileInputStream(ddiFile);
xmlr = xmlInputFactory.createXMLStreamReader(in);
variablesMap = processDDIdataSection( xmlr, studyVersion, filesMap );
} catch (FileNotFoundException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in mapDDI: File Not Found!");
} catch (XMLStreamException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
throw new EJBException("ERROR occurred in mapDDI.", ex);
} finally {
try {
if (xmlr != null) { xmlr.close(); }
} catch (XMLStreamException ex) {}
try {
if (in != null) { in.close();}
} catch (IOException ex) {}
}
return variablesMap;
}
// <editor-fold defaultstate="collapsed" desc="import methods">
private void processDDI( XMLStreamReader xmlr, StudyVersion studyVersion, Map filesMap) throws XMLStreamException {
initializeCollections(studyVersion); // not sure we need this call; to be investigated
// make sure we have a codeBook
//while ( xmlr.next() == XMLStreamConstants.COMMENT ); // skip pre root comments
xmlr.nextTag();
xmlr.require(XMLStreamConstants.START_ELEMENT, null, "codeBook");
// Some DDIs provide an ID in the <codeBook> section.
// We are going to treat it as just another otherId.
// (we've seen instances where this ID was the only ID found in
// in a harvested DDI).
String codeBookLevelId = xmlr.getAttributeValue(null, "ID");
// (but first we will parse and process the entire DDI - and only
// then add this codeBook-level id to the list of identifiers; i.e.,
// we don't want it to be the first on the list, if one or more
// ids are available in the studyDscr section - those should take
// precedence!)
// In fact, we should only use these IDs when no ID is available down
// in the study description section!
processCodeBook(xmlr, studyVersion, filesMap);
if (codeBookLevelId != null && !codeBookLevelId.equals("")) {
if (studyVersion.getMetadata().getStudyOtherIds().size() == 0) {
// this means no ids were found during the parsing of the
// study description section. we'll use the one we found in
// the codeBook entry:
StudyOtherId sid = new StudyOtherId();
sid.setOtherId( codeBookLevelId );
sid.setMetadata(studyVersion.getMetadata());
studyVersion.getMetadata().getStudyOtherIds().add(sid);
}
}
}
private Map processDDIdataSection( XMLStreamReader xmlr, StudyVersion studyVersion, Map filesMap) throws XMLStreamException {
Map variablesMap = null;
xmlr.nextTag();
xmlr.require(XMLStreamConstants.START_ELEMENT, null, "codeBook");
variablesMap = processCodeBookDataSection(xmlr, studyVersion, filesMap);
return variablesMap;
}
private void initializeCollections(StudyVersion studyVersion) {
// initialize the collections
Metadata metadata = studyVersion.getMetadata();
metadata.getStudyVersion().getStudy().setStudyFiles( new ArrayList() );
metadata.setStudyAbstracts( new ArrayList() );
metadata.setStudyAuthors( new ArrayList() );
metadata.setStudyDistributors( new ArrayList() );
metadata.setStudyGeoBoundings(new ArrayList());
metadata.setStudyGrants(new ArrayList());
metadata.setStudyKeywords(new ArrayList());
metadata.setStudyNotes(new ArrayList());
metadata.setStudyOtherIds(new ArrayList());
metadata.setStudyOtherRefs(new ArrayList());
metadata.setStudyProducers(new ArrayList());
metadata.setStudyRelMaterials(new ArrayList());
metadata.setStudyRelPublications(new ArrayList());
metadata.setStudyRelStudies(new ArrayList());
metadata.setStudySoftware(new ArrayList());
metadata.setStudyTopicClasses(new ArrayList());
studyVersion.setFileMetadatas( new ArrayList() );
}
private void processCodeBook( XMLStreamReader xmlr, StudyVersion studyVersion, Map filesMap) throws XMLStreamException {
Metadata metadata = studyVersion.getMetadata();
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("docDscr")) {
processDocDscr(xmlr, metadata);
}
else if (xmlr.getLocalName().equals("stdyDscr")) {
processStdyDscr(xmlr, studyVersion);
}
else if (xmlr.getLocalName().equals("fileDscr")) {
processFileDscr(xmlr, studyVersion, filesMap);
}
//else if (xmlr.getLocalName().equals("dataDscr")) processDataDscr(xmlr, filesMap);
else if (xmlr.getLocalName().equals("otherMat")) {
processOtherMat(xmlr, studyVersion);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("codeBook")) return;
}
}
}
private Map processCodeBookDataSection( XMLStreamReader xmlr, StudyVersion studyVersion, Map filesMap) throws XMLStreamException {
//Map filesMap = new HashMap();
Map variablesMap = null;
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("dataDscr")) {
variablesMap = processDataDscrForReal(xmlr, filesMap);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("codeBook")) return variablesMap;
}
}
return variablesMap;
}
private void processDocDscr(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("IDNo") && StringUtil.isEmpty(metadata.getStudy().getStudyId()) ) {
// this will set a StudyId if it has not yet been set; it will get overridden by a metadata
// id in the StudyDscr section, if one exists
if ( AGENCY_HANDLE.equals( xmlr.getAttributeValue(null, "agency") ) ) {
parseStudyId( parseText(xmlr), metadata.getStudy() );
}
} else if ( xmlr.getLocalName().equals("holdings") && StringUtil.isEmpty(metadata.getHarvestHoldings()) ) {
metadata.setHarvestHoldings( xmlr.getAttributeValue(null, "URI") );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("docDscr")) return;
}
}
}
private void processStdyDscr(XMLStreamReader xmlr, StudyVersion sv) throws XMLStreamException {
Metadata metadata = sv.getMetadata();
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("citation")) processCitation(xmlr, sv);
else if (xmlr.getLocalName().equals("stdyInfo")) processStdyInfo(xmlr, metadata);
else if (xmlr.getLocalName().equals("method")) processMethod(xmlr, metadata);
else if (xmlr.getLocalName().equals("dataAccs")) processDataAccs(xmlr, metadata);
else if (xmlr.getLocalName().equals("othrStdyMat")) processOthrStdyMat(xmlr, metadata);
else if (xmlr.getLocalName().equals("notes")) processNotes(xmlr, metadata);
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("stdyDscr")) return;
}
}
}
private void processCitation(XMLStreamReader xmlr, StudyVersion sv) throws XMLStreamException {
Metadata metadata = sv.getMetadata();
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("titlStmt")) processTitlStmt(xmlr, metadata);
else if (xmlr.getLocalName().equals("rspStmt")) processRspStmt(xmlr,metadata);
else if (xmlr.getLocalName().equals("prodStmt")) processProdStmt(xmlr,metadata);
else if (xmlr.getLocalName().equals("distStmt")) processDistStmt(xmlr,metadata);
else if (xmlr.getLocalName().equals("serStmt")) processSerStmt(xmlr,metadata);
else if (xmlr.getLocalName().equals("verStmt")) processVerStmt(xmlr,sv);
else if (xmlr.getLocalName().equals("notes")) {
String _note = parseNoteByType( xmlr, NOTE_TYPE_UNF );
if (_note != null) {
metadata.setUNF( parseUNF( _note ) );
} else {
processNotes(xmlr, metadata);
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("citation")) return;
}
}
}
private void processTitlStmt(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("titl")) {
metadata.setTitle( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("subTitl")) {
metadata.setSubTitle( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("IDNo")) {
if ( AGENCY_HANDLE.equals( xmlr.getAttributeValue(null, "agency") ) ) {
parseStudyId( parseText(xmlr), metadata.getStudyVersion().getStudy() );
} else {
StudyOtherId sid = new StudyOtherId();
sid.setAgency( xmlr.getAttributeValue(null, "agency")) ;
sid.setOtherId( parseText(xmlr) );
sid.setMetadata(metadata);
metadata.getStudyOtherIds().add(sid);
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("titlStmt")) return;
}
}
}
private void processRspStmt(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("AuthEnty")) {
StudyAuthor author = new StudyAuthor();
author.setAffiliation( xmlr.getAttributeValue(null, "affiliation") );
author.setName( parseText(xmlr) );
author.setMetadata(metadata);
metadata.getStudyAuthors().add(author);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("rspStmt")) return;
}
}
}
private void processProdStmt(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("producer")) {
StudyProducer prod = new StudyProducer();
metadata.getStudyProducers().add(prod);
prod.setMetadata(metadata);
prod.setAbbreviation(xmlr.getAttributeValue(null, "abbr") );
prod.setAffiliation( xmlr.getAttributeValue(null, "affiliation") );
Map<String,String> prodDetails = parseCompoundText(xmlr, "producer");
prod.setName( prodDetails.get("name") );
prod.setUrl( prodDetails.get("url") );
prod.setLogo( prodDetails.get("logo") );
} else if (xmlr.getLocalName().equals("prodDate")) {
metadata.setProductionDate(parseDate(xmlr,"prodDate"));
} else if (xmlr.getLocalName().equals("prodPlac")) {
metadata.setProductionPlace( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("software")) {
StudySoftware ss = new StudySoftware();
metadata.getStudySoftware().add(ss);
ss.setMetadata(metadata);
ss.setSoftwareVersion( xmlr.getAttributeValue(null, "version") );
ss.setName( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("fundAg")) {
metadata.setFundingAgency( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("grantNo")) {
StudyGrant sg = new StudyGrant();
metadata.getStudyGrants().add(sg);
sg.setMetadata(metadata);
sg.setAgency( xmlr.getAttributeValue(null, "agency") );
sg.setNumber( parseText(xmlr) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("prodStmt")) return;
}
}
}
private void processDistStmt(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("distrbtr")) {
StudyDistributor dist = new StudyDistributor();
metadata.getStudyDistributors().add(dist);
dist.setMetadata(metadata);
dist.setAbbreviation(xmlr.getAttributeValue(null, "abbr") );
dist.setAffiliation( xmlr.getAttributeValue(null, "affiliation") );
Map<String,String> distDetails = parseCompoundText(xmlr, "distrbtr");
dist.setName( distDetails.get("name") );
dist.setUrl( distDetails.get("url") );
dist.setLogo( distDetails.get("logo") );
} else if (xmlr.getLocalName().equals("contact")) {
metadata.setDistributorContactEmail( xmlr.getAttributeValue(null, "email") );
metadata.setDistributorContactAffiliation( xmlr.getAttributeValue(null, "affiliation") );
metadata.setDistributorContact( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("depositr")) {
Map<String,String> depDetails = parseCompoundText(xmlr, "depositr");
metadata.setDepositor( depDetails.get("name") );
} else if (xmlr.getLocalName().equals("depDate")) {
metadata.setDateOfDeposit( parseDate(xmlr,"depDate") );
} else if (xmlr.getLocalName().equals("distDate")) {
metadata.setDistributionDate( parseDate(xmlr,"distDate") );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("distStmt")) return;
}
}
}
private void processSerStmt(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("serName")) {
metadata.setSeriesName( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("serInfo")) {
metadata.setSeriesInformation( parseText(xmlr) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("serStmt")) return;
}
}
}
private void processVerStmt(XMLStreamReader xmlr, StudyVersion sv) throws XMLStreamException {
Metadata metadata = sv.getMetadata();
if (!"DVN".equals(xmlr.getAttributeValue(null, "source"))) {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("version")) {
metadata.setVersionDate( xmlr.getAttributeValue(null, "date") );
metadata.setStudyVersionText( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("notes")) { processNotes(xmlr, metadata); }
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("verStmt")) return;
}
}
} else {
// this is the DVN version info; get version number for StudyVersion object
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("version")) {
String elementText = getElementText(xmlr);
System.out.println("Reading DVN version: "+elementText);
sv.setVersionNumber(Long.parseLong(elementText));
}
} else if(event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("verStmt")) return;
}
}
}
}
private void processStdyInfo(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("subject")) processSubject(xmlr, metadata);
else if (xmlr.getLocalName().equals("abstract")) {
StudyAbstract abs = new StudyAbstract();
metadata.getStudyAbstracts().add(abs);
abs.setMetadata(metadata);
abs.setDate( xmlr.getAttributeValue(null, "date") );
abs.setText( parseText(xmlr, "abstract") );
} else if (xmlr.getLocalName().equals("sumDscr")) processSumDscr(xmlr, metadata);
else if (xmlr.getLocalName().equals("notes")) processNotes(xmlr, metadata);
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("stdyInfo")) return;
}
}
}
private void processSubject(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("keyword")) {
StudyKeyword kw = new StudyKeyword();
metadata.getStudyKeywords().add(kw);
kw.setMetadata(metadata);
kw.setVocab( xmlr.getAttributeValue(null, "vocab") );
kw.setVocabURI( xmlr.getAttributeValue(null, "vocabURI") );
kw.setValue( parseText(xmlr));
} else if (xmlr.getLocalName().equals("topcClas")) {
StudyTopicClass tc = new StudyTopicClass();
metadata.getStudyTopicClasses().add(tc);
tc.setMetadata(metadata);
tc.setVocab( xmlr.getAttributeValue(null, "vocab") );
tc.setVocabURI( xmlr.getAttributeValue(null, "vocabURI") );
tc.setValue( parseText(xmlr));
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("subject")) return;
}
}
}
private void processSumDscr(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("timePrd")) {
String eventAttr = xmlr.getAttributeValue(null, "event");
if ( eventAttr == null || EVENT_SINGLE.equalsIgnoreCase(eventAttr) || EVENT_START.equalsIgnoreCase(eventAttr) ) {
metadata.setTimePeriodCoveredStart( parseDate(xmlr, "timePrd") );
} else if ( EVENT_END.equals(eventAttr) ) {
metadata.setTimePeriodCoveredEnd( parseDate(xmlr, "timePrd") );
}
} else if (xmlr.getLocalName().equals("collDate")) {
String eventAttr = xmlr.getAttributeValue(null, "event");
if ( eventAttr == null || EVENT_SINGLE.equalsIgnoreCase(eventAttr) || EVENT_START.equalsIgnoreCase(eventAttr) ) {
metadata.setDateOfCollectionStart( parseDate(xmlr, "collDate") );
} else if ( EVENT_END.equals(eventAttr) ) {
metadata.setDateOfCollectionEnd( parseDate(xmlr, "collDate") );
}
} else if (xmlr.getLocalName().equals("nation")) {
if (StringUtil.isEmpty( metadata.getCountry() ) ) {
metadata.setCountry( parseText(xmlr) );
} else {
metadata.setCountry( metadata.getCountry() + "; " + parseText(xmlr) );
}
} else if (xmlr.getLocalName().equals("geogCover")) {
if (StringUtil.isEmpty( metadata.getGeographicCoverage() ) ) {
metadata.setGeographicCoverage( parseText(xmlr) );
} else {
metadata.setGeographicCoverage( metadata.getGeographicCoverage() + "; " + parseText(xmlr) );
}
} else if (xmlr.getLocalName().equals("geogUnit")) {
if (StringUtil.isEmpty( metadata.getGeographicUnit() ) ) {
metadata.setGeographicUnit( parseText(xmlr) );
} else {
metadata.setGeographicUnit( metadata.getGeographicUnit() + "; " + parseText(xmlr) );
}
} else if (xmlr.getLocalName().equals("geoBndBox")) {
processGeoBndBox(xmlr,metadata);
} else if (xmlr.getLocalName().equals("anlyUnit")) {
if (StringUtil.isEmpty( metadata.getUnitOfAnalysis() ) ) {
metadata.setUnitOfAnalysis( parseText(xmlr,"anlyUnit") );
} else {
metadata.setUnitOfAnalysis( metadata.getUnitOfAnalysis() + "; " + parseText(xmlr,"anlyUnit") );
}
} else if (xmlr.getLocalName().equals("universe")) {
if (StringUtil.isEmpty( metadata.getUniverse() ) ) {
metadata.setUniverse( parseText(xmlr,"universe") );
} else {
metadata.setUniverse( metadata.getUniverse() + "; " + parseText(xmlr,"universe") );
}
} else if (xmlr.getLocalName().equals("dataKind")) {
if (StringUtil.isEmpty( metadata.getKindOfData() ) ) {
metadata.setKindOfData( parseText(xmlr) );
} else {
metadata.setKindOfData( metadata.getKindOfData() + "; " + parseText(xmlr) );
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("sumDscr")) return;
}
}
}
private void processGeoBndBox(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
StudyGeoBounding geoBound = new StudyGeoBounding();
metadata.getStudyGeoBoundings().add(geoBound);
geoBound.setMetadata(metadata);
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("westBL")) {
geoBound.setWestLongitude( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("eastBL")) {
geoBound.setEastLongitude( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("southBL")) {
geoBound.setSouthLatitude( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("northBL")) {
geoBound.setNorthLatitude( parseText(xmlr) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("geoBndBox")) return;
}
}
}
private void processMethod(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("dataColl")) {
processDataColl(xmlr, metadata);
} else if (xmlr.getLocalName().equals("notes")) {
// As of 3.0, this note is going to be used for the extended
// metadata fields. For now, we are not going to try to
// process these in any meaningful way.
// We also don't want them to become the "Study-Level Error
// notes" -- that's what the note was being used for
// exclusively in pre-3.0 practice.
// TODO: this needs to be revisited after 3.0, when we
// figure out how DVNs will be harvesting each others'
// extended metadata.
String noteType = xmlr.getAttributeValue(null, "type");
if (!NOTE_TYPE_EXTENDED_METADATA.equalsIgnoreCase(noteType) ) {
if (StringUtil.isEmpty( metadata.getStudyLevelErrorNotes() ) ) {
metadata.setStudyLevelErrorNotes( parseText( xmlr,"notes" ) );
} else {
metadata.setStudyLevelErrorNotes( metadata.getStudyLevelErrorNotes() + "; " + parseText( xmlr, "notes" ) );
}
}
} else if (xmlr.getLocalName().equals("anlyInfo")) {
processAnlyInfo(xmlr, metadata);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("method")) return;
}
}
}
private void processDataColl(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("timeMeth")) {
metadata.setTimeMethod( parseText( xmlr, "timeMeth" ) );
} else if (xmlr.getLocalName().equals("dataCollector")) {
metadata.setDataCollector( parseText( xmlr, "dataCollector" ) );
} else if (xmlr.getLocalName().equals("frequenc")) {
metadata.setFrequencyOfDataCollection( parseText( xmlr, "frequenc" ) );
} else if (xmlr.getLocalName().equals("sampProc")) {
metadata.setSamplingProcedure( parseText( xmlr, "sampProc" ) );
} else if (xmlr.getLocalName().equals("deviat")) {
metadata.setDeviationsFromSampleDesign( parseText( xmlr, "deviat" ) );
} else if (xmlr.getLocalName().equals("collMode")) {
metadata.setCollectionMode( parseText( xmlr, "collMode" ) );
} else if (xmlr.getLocalName().equals("resInstru")) {
metadata.setResearchInstrument( parseText( xmlr, "resInstru" ) );
} else if (xmlr.getLocalName().equals("sources")) {
processSources(xmlr,metadata);
} else if (xmlr.getLocalName().equals("collSitu")) {
metadata.setDataCollectionSituation( parseText( xmlr, "collSitu" ) );
} else if (xmlr.getLocalName().equals("actMin")) {
metadata.setActionsToMinimizeLoss( parseText( xmlr, "actMin" ) );
} else if (xmlr.getLocalName().equals("ConOps")) {
metadata.setControlOperations( parseText( xmlr, "ConOps" ) );
} else if (xmlr.getLocalName().equals("weight")) {
metadata.setWeighting( parseText( xmlr, "weight" ) );
} else if (xmlr.getLocalName().equals("cleanOps")) {
metadata.setCleaningOperations( parseText( xmlr, "cleanOps" ) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("dataColl")) return;
}
}
}
private void processSources(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("dataSrc")) {
metadata.setDataSources( parseText( xmlr, "dataSrc" ) );;
} else if (xmlr.getLocalName().equals("srcOrig")) {
metadata.setOriginOfSources( parseText( xmlr, "srcOrig" ) );
} else if (xmlr.getLocalName().equals("srcChar")) {
metadata.setCharacteristicOfSources( parseText( xmlr, "srcChar" ) );
} else if (xmlr.getLocalName().equals("srcDocu")) {
metadata.setAccessToSources( parseText( xmlr, "srcDocu" ) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("sources")) return;
}
}
}
private void processAnlyInfo(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("respRate")) {
metadata.setResponseRate( parseText( xmlr, "respRate" ) );
} else if (xmlr.getLocalName().equals("EstSmpErr")) {
metadata.setSamplingErrorEstimate( parseText( xmlr, "EstSmpErr" ) );
} else if (xmlr.getLocalName().equals("dataAppr")) {
metadata.setOtherDataAppraisal( parseText( xmlr, "dataAppr" ) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("anlyInfo")) return;
}
}
}
private void processDataAccs(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("setAvail")) processSetAvail(xmlr,metadata);
else if (xmlr.getLocalName().equals("useStmt")) processUseStmt(xmlr,metadata);
else if (xmlr.getLocalName().equals("notes")) {
String noteType = xmlr.getAttributeValue(null, "type");
if (NOTE_TYPE_TERMS_OF_USE.equalsIgnoreCase(noteType) ) {
String noteLevel = xmlr.getAttributeValue(null, "level");
if (LEVEL_DV.equalsIgnoreCase(noteLevel) ) {
metadata.setHarvestDVTermsOfUse( parseText(xmlr) );
} else if (LEVEL_DVN.equalsIgnoreCase(noteLevel) ) {
metadata.setHarvestDVNTermsOfUse( parseText(xmlr) );
}
} else {
processNotes( xmlr, metadata );
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("dataAccs")) return;
}
}
}
private void processSetAvail(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("accsPlac")) {
metadata.setPlaceOfAccess( parseText( xmlr, "accsPlac" ) );
} else if (xmlr.getLocalName().equals("origArch")) {
metadata.setOriginalArchive( parseText( xmlr, "origArch" ) );
} else if (xmlr.getLocalName().equals("avlStatus")) {
metadata.setAvailabilityStatus( parseText( xmlr, "avlStatus" ) );
} else if (xmlr.getLocalName().equals("collSize")) {
metadata.setCollectionSize( parseText( xmlr, "collSize" ) );
} else if (xmlr.getLocalName().equals("complete")) {
metadata.setStudyCompletion( parseText( xmlr, "complete" ) );
} else if (xmlr.getLocalName().equals("notes")) {
processNotes( xmlr, metadata );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("setAvail")) return;
}
}
}
private void processUseStmt(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("confDec")) {
metadata.setConfidentialityDeclaration( parseText( xmlr, "confDec" ) );
} else if (xmlr.getLocalName().equals("specPerm")) {
metadata.setSpecialPermissions( parseText( xmlr, "specPerm" ) );
} else if (xmlr.getLocalName().equals("restrctn")) {
metadata.setRestrictions( parseText( xmlr, "restrctn" ) );
} else if (xmlr.getLocalName().equals("contact")) {
metadata.setContact( parseText( xmlr, "contact" ) );
} else if (xmlr.getLocalName().equals("citReq")) {
metadata.setCitationRequirements( parseText( xmlr, "citReq" ) );
} else if (xmlr.getLocalName().equals("deposReq")) {
metadata.setDepositorRequirements( parseText( xmlr, "deposReq" ) );
} else if (xmlr.getLocalName().equals("conditions")) {
metadata.setConditions( parseText( xmlr, "conditions" ) );
} else if (xmlr.getLocalName().equals("disclaimer")) {
metadata.setDisclaimer( parseText( xmlr, "disclaimer" ) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("useStmt")) return;
}
}
}
private void processOthrStdyMat(XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
boolean replicationForFound = false;
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("relMat")) {
// this code is still here to handle imports from old DVN created ddis
if (!replicationForFound && REPLICATION_FOR_TYPE.equals( xmlr.getAttributeValue(null, "type") ) ) {
StudyRelPublication rp = new StudyRelPublication();
metadata.getStudyRelPublications().add(rp);
rp.setMetadata(metadata);
rp.setText( parseText( xmlr, "relMat" ) );
rp.setReplicationData(true);
replicationForFound = true;
} else {
StudyRelMaterial rm = new StudyRelMaterial();
metadata.getStudyRelMaterials().add(rm);
rm.setMetadata(metadata);
rm.setText( parseText( xmlr, "relMat" ) );
}
} else if (xmlr.getLocalName().equals("relStdy")) {
StudyRelStudy rs = new StudyRelStudy();
metadata.getStudyRelStudies().add(rs);
rs.setMetadata(metadata);
rs.setText( parseText( xmlr, "relStdy" ) );
} else if (xmlr.getLocalName().equals("relPubl")) {
StudyRelPublication rp = new StudyRelPublication();
metadata.getStudyRelPublications().add(rp);
rp.setMetadata(metadata);
// call new parse text logic
Object rpFromDDI = parseTextNew( xmlr, "relPubl" );
if (rpFromDDI instanceof Map) {
Map rpMap = (Map) rpFromDDI;
rp.setText((String) rpMap.get("text"));
rp.setIdType((String) rpMap.get("idType"));
rp.setIdNumber((String) rpMap.get("idNumber"));
rp.setUrl((String) rpMap.get("url"));
if (!replicationForFound && rpMap.get("replicationData") != null) {
rp.setReplicationData(true);
replicationForFound = true;
}
} else {
rp.setText( (String) rpFromDDI );
}
} else if (xmlr.getLocalName().equals("otherRefs")) {
StudyOtherRef or = new StudyOtherRef();
metadata.getStudyOtherRefs().add(or);
or.setMetadata(metadata);
or.setText( parseText( xmlr, "otherRefs" ) );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("othrStdyMat")) return;
}
}
}
private void processFileDscr(XMLStreamReader xmlr, StudyVersion studyVersion, Map filesMap) throws XMLStreamException {
FileMetadata fmd = new FileMetadata();
fmd.setStudyVersion(studyVersion);
studyVersion.getFileMetadatas().add(fmd);
//StudyFile sf = new OtherFile(studyVersion.getStudy()); // until we connect the sf and dt, we have to assume it's an other file
// as an experiment, I'm going to do it the other way around:
// assume that every fileDscr is a subsettable file now, and convert them
// to otherFiles later if no variables are referemming it -- L.A.
TabularDataFile sf = new TabularDataFile(studyVersion.getStudy());
DataTable dt = new DataTable();
dt.setStudyFile(sf);
sf.setDataTable(dt);
fmd.setStudyFile(sf);
sf.setFileSystemLocation( xmlr.getAttributeValue(null, "URI"));
String ddiFileId = xmlr.getAttributeValue(null, "ID");
/// the following Strings are used to determine the category
String catName = null;
String icpsrDesc = null;
String icpsrId = null;
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("fileTxt")) {
String tempDDIFileId = processFileTxt(xmlr, fmd, dt);
ddiFileId = ddiFileId != null ? ddiFileId : tempDDIFileId;
}
else if (xmlr.getLocalName().equals("notes")) {
String noteType = xmlr.getAttributeValue(null, "type");
if (NOTE_TYPE_UNF.equalsIgnoreCase(noteType) ) {
String unf = parseUNF( parseText(xmlr) );
sf.setUnf(unf);
dt.setUnf(unf);
} else if ("vdc:category".equalsIgnoreCase(noteType) ) {
catName = parseText(xmlr);
} else if ("icpsr:category".equalsIgnoreCase(noteType) ) {
String subjectType = xmlr.getAttributeValue(null, "subject");
if ("description".equalsIgnoreCase(subjectType)) {
icpsrDesc = parseText(xmlr);
} else if ("id".equalsIgnoreCase(subjectType)) {
icpsrId = parseText(xmlr);
}
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {// </codeBook>
if (xmlr.getLocalName().equals("fileDscr")) {
// post process
if (fmd.getLabel() == null || fmd.getLabel().trim().equals("") ) {
fmd.setLabel("file");
}
fmd.setCategory(determineFileCategory(catName, icpsrDesc, icpsrId));
if (ddiFileId != null) {
List filesMapEntry = new ArrayList();
filesMapEntry.add(fmd);
filesMapEntry.add(dt);
filesMap.put( ddiFileId, filesMapEntry);
}
return;
}
}
}
}
// Not used -- L.A.
/*
private void reProcessFileDscr(XMLStreamReader xmlr, StudyVersion studyVersion, Map filesMap) throws XMLStreamException {
String ddiFileId = xmlr.getAttributeValue(null, "ID");
String fileLabel = null;
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("fileTxt")) {
fileLabel = reProcessFileTxt(xmlr);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("fileDscr")) {
if (ddiFileId != null && fileLabel != null) {
for (FileMetadata fmd : studyVersion.getFileMetadatas()) {
String studyFileLabel = fmd.getLabel();
if (fileLabel.equals(studyFileLabel)) {
if ( fmd.getStudyFile() instanceof TabularDataFile) {
TabularDataFile tbf = (TabularDataFile)fmd.getStudyFile();
if (tbf != null) {
filesMap.put(ddiFileId, tbf.getDataTable());
}
}
}
}
}
return;
}
}
}
}*/
private String processFileTxt(XMLStreamReader xmlr, FileMetadata fmd, DataTable dt) throws XMLStreamException {
String ddiFileId = null;
StudyFile sf = fmd.getStudyFile();
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("fileName")) {
ddiFileId = xmlr.getAttributeValue(null, "ID");
fmd.setLabel( parseText(xmlr) );
sf.setFileType( FileUtil.determineFileType( fmd.getLabel() ) );
} else if (xmlr.getLocalName().equals("fileCont")) {
fmd.setDescription( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("dimensns")) processDimensns(xmlr, dt);
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("fileTxt")) return ddiFileId;
}
}
return ddiFileId;
}
private String reProcessFileTxt(XMLStreamReader xmlr) throws XMLStreamException {
String fileLabel = null;
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("fileName")) {
fileLabel = parseText(xmlr);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("fileTxt")) return fileLabel;
}
}
return fileLabel;
}
private void processDimensns(XMLStreamReader xmlr, DataTable dt) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("caseQnty")) {
try {
dt.setCaseQuantity( new Long( parseText(xmlr) ) );
} catch (NumberFormatException ex) {}
} else if (xmlr.getLocalName().equals("varQnty")) {
try{
dt.setVarQuantity( new Long( parseText(xmlr) ) );
} catch (NumberFormatException ex) {}
} else if (xmlr.getLocalName().equals("recPrCas")) {
try {
dt.setRecordsPerCase( new Long( parseText(xmlr) ) );
} catch (NumberFormatException ex) {}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {// </codeBook>
if (xmlr.getLocalName().equals("dimensns")) return;
}
}
}
// Not used -- L.A.
/*
private void processDataDscr(XMLStreamReader xmlr, Map filesMap) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("var")) {
processVar(xmlr, filesMap);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("dataDscr")) return;
}
}
}
*/
private Map processDataDscrForReal(XMLStreamReader xmlr, Map filesMap) throws XMLStreamException {
Map variableMap = new HashMap();
//Map variableMapByTableId = new HashMap();
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("var")) {
processVarForReal(xmlr, filesMap, variableMap);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("dataDscr")) {
for (Object fileId : filesMap.keySet()) {
List<DataVariable> variablesMapEntry = (List<DataVariable>) variableMap.get(fileId);
if (variablesMapEntry != null) {
// OK, this looks like we have found variables for this
// data file entry.
} else {
// TODO:
// otherwise, the studyfile needs to be converted
// from TabularFile to OtherFile; i.e., it should
// be treated as non-subsettable, if there are
// no variables in the <dataDscr> section of the
// DDI referencing the file.
// This actually happens in real life. For example,
// Roper puts some of their files into the <fileDscr>
// section, even though there's no <dataDscr>
// provided for them.
// -- L.A.
//
}
}
return variableMap;
}
}
}
return null;
}
// this method is not used, as of now;
// (this is an experiment in progress)
// see processVarForReal()
// -- L.A.
/*
private void processVar(XMLStreamReader xmlr, Map filesMap) throws XMLStreamException {
DataVariable dv = new DataVariable();
dv.setInvalidRanges(new ArrayList());
dv.setSummaryStatistics( new ArrayList() );
dv.setCategories( new ArrayList() );
dv.setName( xmlr.getAttributeValue(null, "name") );
// associate dv with the correct file
// the attribute "files" in the <var> element below is legit;
// it is never used in the DVN-produced DDIs (we use the <location>
// element to link the variable to the datafile); it must have
// been added to process DDIs produced by one of our partners (who?).
// -- L.A.
String fileId = xmlr.getAttributeValue(null, "files");
if ( fileId != null ) {
linkDataVariableToDatable(filesMap, xmlr.getAttributeValue(null, "fileid"), dv );
}
// interval type (DB value may be different than DDI value)
String _interval = xmlr.getAttributeValue(null, "intrvl");
_interval = (_interval == null ? VAR_INTERVAL_DISCRETE : _interval); // default is discrete
_interval = VAR_INTERVAL_CONTIN.equals(_interval) ? DB_VAR_INTERVAL_TYPE_CONTINUOUS : _interval; // translate contin to DB value
dv.setVariableIntervalType( varService.findVariableIntervalTypeByName(variableIntervalTypeList, _interval ));
dv.setWeighted( VAR_WEIGHTED.equals( xmlr.getAttributeValue(null, "wgt") ) );
// default is not-wgtd, so null sets weighted to false
try {
dv.setNumberOfDecimalPoints( new Long( xmlr.getAttributeValue(null, "dcml") ) );
} catch (NumberFormatException nfe) {}
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("location")) {
processLocation(xmlr, dv, filesMap);
}
else if (xmlr.getLocalName().equals("labl")) {
String _labl = processLabl( xmlr, LEVEL_VARIABLE );
if (_labl != null && !_labl.equals("") ) {
dv.setLabel( _labl );
}
} else if (xmlr.getLocalName().equals("universe")) {
dv.setUniverse( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("concept")) {
dv.setConcept( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("invalrng")) processInvalrng( xmlr, dv );
else if (xmlr.getLocalName().equals("varFormat")) {
processVarFormat( xmlr, dv );
}
else if (xmlr.getLocalName().equals("sumStat")) processSumStat( xmlr, dv );
else if (xmlr.getLocalName().equals("catgry")) processCatgry( xmlr, dv );
else if (xmlr.getLocalName().equals("notes")) {
String _note = parseNoteByType( xmlr, NOTE_TYPE_UNF );
if (_note != null && !_note.equals("") ) {
dv.setUnf( parseUNF( _note ) );
}
}
// todo: qstnTxt: wait to handle until we know more of how we will use it
// todo: wgt-var : waitng to see example
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("var")) return;
}
}
}
*/
private void processVarForReal(XMLStreamReader xmlr, Map filesMap, Map variableMap) throws XMLStreamException {
DataVariable dv = new DataVariable();
dv.setInvalidRanges(new ArrayList());
dv.setSummaryStatistics( new ArrayList() );
dv.setCategories( new ArrayList() );
dv.setName( xmlr.getAttributeValue(null, "name") );
try {
dv.setNumberOfDecimalPoints( new Long( xmlr.getAttributeValue(null, "dcml") ) );
} catch (NumberFormatException nfe) {}
// interval type (DB value may be different than DDI value)
String _interval = xmlr.getAttributeValue(null, "intrvl");
_interval = (_interval == null ? VAR_INTERVAL_DISCRETE : _interval); // default is discrete
_interval = VAR_INTERVAL_CONTIN.equals(_interval) ? DB_VAR_INTERVAL_TYPE_CONTINUOUS : _interval; // translate contin to DB value
dv.setVariableIntervalType( varService.findVariableIntervalTypeByName(variableIntervalTypeList, _interval ));
dv.setWeighted( VAR_WEIGHTED.equals( xmlr.getAttributeValue(null, "wgt") ) );
// default is not-wgtd, so null sets weighted to false
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("location")) {
processLocationForReal(xmlr, dv, filesMap, variableMap);
}
else if (xmlr.getLocalName().equals("labl")) {
String _labl = processLabl( xmlr, LEVEL_VARIABLE );
if (_labl != null && !_labl.equals("") ) {
dv.setLabel( _labl );
}
} else if (xmlr.getLocalName().equals("universe")) {
dv.setUniverse( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("concept")) {
dv.setConcept( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("invalrng")) {
processInvalrng( xmlr, dv );
} else if (xmlr.getLocalName().equals("varFormat")) {
processVarFormat( xmlr, dv );
} else if (xmlr.getLocalName().equals("sumStat")) {
processSumStat( xmlr, dv );
} else if (xmlr.getLocalName().equals("catgry")) {
processCatgry( xmlr, dv );
} else if (xmlr.getLocalName().equals("notes")) {
String _note = parseNoteByType( xmlr, NOTE_TYPE_UNF );
if (_note != null && !_note.equals("") ) {
dv.setUnf( parseUNF( _note ) );
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("var")) return;
}
}
}
// not used;
// see processLocationForReal();
/*
private void processLocation(XMLStreamReader xmlr, DataVariable dv, Map filesMap) throws XMLStreamException {
// associate dv with the correct file
if ( dv.getDataTable() == null ) {
linkDataVariableToDatable(filesMap, xmlr.getAttributeValue(null, "fileid"), dv );
}
if ( dv.getDataTable() == null ) {
String fileId = xmlr.getAttributeValue(null, "fileid");
if (fileId != null && !fileId.equals("")) {
List filesMapEntry = (List) filesMap.get( fileId );
if (filesMapEntry != null) {
FileMetadata fmd = (FileMetadata) filesMapEntry.get(0);
DataTable dt = (DataTable) filesMapEntry.get(1);
// set fileOrder to size of list (pre add, since indexes start at 0)
dv.setFileOrder( dt.getDataVariables().size() );
dv.setDataTable(dt);
dt.getDataVariables().add(dv);
}
}
}
// fileStartPos, FileEndPos, and RecSegNo
// if these fields don't convert to Long, just leave blank
try {
dv.setFileStartPosition( new Long( xmlr.getAttributeValue(null, "StartPos") ) );
} catch (NumberFormatException ex) {}
try {
dv.setFileEndPosition( new Long( xmlr.getAttributeValue(null, "EndPos") ) );
} catch (NumberFormatException ex) {}
try {
dv.setRecordSegmentNumber( new Long( xmlr.getAttributeValue(null, "RecSegNo") ) );
} catch (NumberFormatException ex) {}
}
*/
private void processLocationForReal(XMLStreamReader xmlr, DataVariable dv, Map filesMap, Map variableMap) throws XMLStreamException {
// fileStartPos, FileEndPos, and RecSegNo
// if these fields don't convert to Long, just leave blank
try {
dv.setFileStartPosition( new Long( xmlr.getAttributeValue(null, "StartPos") ) );
} catch (NumberFormatException ex) {}
try {
dv.setFileEndPosition( new Long( xmlr.getAttributeValue(null, "EndPos") ) );
} catch (NumberFormatException ex) {}
try {
dv.setRecordSegmentNumber( new Long( xmlr.getAttributeValue(null, "RecSegNo") ) );
} catch (NumberFormatException ex) {}
if ( dv.getDataTable() == null ) {
String fileId = xmlr.getAttributeValue(null, "fileid");
if (fileId != null && !fileId.equals("")) {
//DataTable filesMapEntry = (DataTable) filesMap.get( fileId );
List filesMapEntry = (List) filesMap.get( fileId );
if (filesMapEntry != null) {
//FileMetadata fmd = (FileMetadata) filesMapEntry.get(0);
DataTable dt = (DataTable) filesMapEntry.get(1);
Long fileDbId = dt.getStudyFile().getId();
dv.setDataTable(dt);
if (variableMap.get(fileDbId) == null) {
variableMap.put(fileDbId, new ArrayList());
}
List<DataVariable> variablesMapEntry = (List<DataVariable>) variableMap.get(fileDbId);
// fileOrder storeds the physical position of the variable
// in the file. We are operating under the assumption that
// the order in which the <var> sections appear in the DDI
// reflects this physical order.
// Which is a little dangerous; technically, the order of
// elements is considered meaningless in XML, and
// transformations do NOT guarantee to preserve it.
// -- L.A.
dv.setFileOrder( variablesMapEntry.size() );
variablesMapEntry.add(dv);
}
}
}
}
// not used -- L.A.
/*
private void linkDataVariableToDatable(Map filesMap, String fileId, DataVariable dv) {
List filesMapEntry = (List) filesMap.get( fileId );
if (filesMapEntry != null) {
FileMetadata fmd = (FileMetadata) filesMapEntry.get(0);
DataTable dt = (DataTable) filesMapEntry.get(1);
if ( fmd.getStudyFile() instanceof OtherFile) {
// first time with this file, so attach the dt to the file and set as subsettable)
TabularDataFile tdf = converOtherFileToTabularDataFile( fmd);
// now add link to datatable
dt.setStudyFile(tdf);
tdf.setDataTable(dt);
tdf.setFileType( FileUtil.determineTabularDataFileType( tdf ) ); // redetermine file type (suing dt), now that we know it's subsettable
}
// set fileOrder to size of list (pre add, since indexes start at 0)
dv.setFileOrder( dt.getDataVariables().size() );
dv.setDataTable(dt);
dt.getDataVariables().add(dv);
}
}
*/
// not used -- L.A.
/*
private TabularDataFile converOtherFileToTabularDataFile(FileMetadata fmd) {
OtherFile of = (OtherFile) fmd.getStudyFile();
TabularDataFile tdf = new TabularDataFile();
tdf.setFileType( of.getFileType() );
tdf.setFileSystemLocation( of.getFileSystemLocation() );
tdf.setUnf( of.getUnf() );
tdf.setOriginalFileType( of.getOriginalFileType() );
tdf.setDisplayOrder( of.getDisplayOrder() );
// reset links
fmd.setStudyFile(tdf);
Study study = of.getStudy();
tdf.setStudy( study );
study.getStudyFiles().remove(of);
study.getStudyFiles().add(tdf);
StudyFileActivity sfa = of.getStudyFileActivity();
tdf.setStudyFileActivity(sfa);
sfa.setStudyFile(tdf);
return tdf;
}
*/
private void processInvalrng(XMLStreamReader xmlr, DataVariable dv) throws XMLStreamException {
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("item")) {
VariableRange range = new VariableRange();
// commented out: -- L.A.
dv.getInvalidRanges().add(range);
range.setDataVariable(dv);
range.setBeginValue( xmlr.getAttributeValue(null, "VALUE") );
range.setBeginValueType(varService.findVariableRangeTypeByName( variableRangeTypeList, DB_VAR_RANGE_TYPE_POINT ) );
} else if (xmlr.getLocalName().equals("range")) {
VariableRange range = new VariableRange();
// commented out: -- L.A.
dv.getInvalidRanges().add(range);
range.setDataVariable(dv);
String min = xmlr.getAttributeValue(null, "min");
String minExclsuive = xmlr.getAttributeValue(null, "minExclusive");
String max = xmlr.getAttributeValue(null, "max");
String maxExclusive = xmlr.getAttributeValue(null, "maxExclusive");
if ( !StringUtil.isEmpty(min) ) {
range.setBeginValue( min );
range.setBeginValueType(varService.findVariableRangeTypeByName( variableRangeTypeList,DB_VAR_RANGE_TYPE_MIN ) );
} else if ( !StringUtil.isEmpty(minExclsuive) ) {
range.setBeginValue( minExclsuive );
range.setBeginValueType(varService.findVariableRangeTypeByName( variableRangeTypeList,DB_VAR_RANGE_TYPE_MIN_EX ) );
}
if ( !StringUtil.isEmpty(max) ) {
range.setEndValue( max );
range.setEndValueType(varService.findVariableRangeTypeByName( variableRangeTypeList,DB_VAR_RANGE_TYPE_MAX ) );
} else if ( !StringUtil.isEmpty(maxExclusive) ) {
range.setEndValue( maxExclusive );
range.setEndValueType(varService.findVariableRangeTypeByName(variableRangeTypeList, DB_VAR_RANGE_TYPE_MAX_EX ) );
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("invalrng")) return;
}
}
}
private void processVarFormat(XMLStreamReader xmlr, DataVariable dv) throws XMLStreamException {
String type = xmlr.getAttributeValue(null, "type");
type = (type == null ? VAR_FORMAT_TYPE_NUMERIC : type); // default is numeric
String schema = xmlr.getAttributeValue(null, "schema");
schema = (schema == null ? VAR_FORMAT_SCHEMA_ISO : schema); // default is ISO
dv.setVariableFormatType( varService.findVariableFormatTypeByName( variableFormatTypeList, type ) );
dv.setFormatSchema(schema);
dv.setFormatSchemaName( xmlr.getAttributeValue(null, "formatname") );
dv.setFormatCategory( xmlr.getAttributeValue(null, "category") );
}
private void processSumStat(XMLStreamReader xmlr, DataVariable dv) throws XMLStreamException {
SummaryStatistic ss = new SummaryStatistic();
ss.setType( varService.findSummaryStatisticTypeByName( summaryStatisticTypeList, xmlr.getAttributeValue(null, "type") ) );
ss.setValue( parseText(xmlr)) ;
ss.setDataVariable(dv);
dv.getSummaryStatistics().add(ss);
}
private void processCatgry(XMLStreamReader xmlr, DataVariable dv) throws XMLStreamException {
VariableCategory cat = new VariableCategory();
cat.setMissing( "Y".equals( xmlr.getAttributeValue(null, "missing") ) ); // default is N, so null sets missing to false
cat.setDataVariable(dv);
// commented out: -- L.A.
dv.getCategories().add(cat);
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("labl")) {
String _labl = processLabl( xmlr, LEVEL_CATEGORY );
if (_labl != null && !_labl.equals("") ) {
cat.setLabel( _labl );
}
} else if (xmlr.getLocalName().equals("catValu")) {
cat.setValue( parseText(xmlr, false) );
}
else if (xmlr.getLocalName().equals("catStat")) {
String type = xmlr.getAttributeValue(null, "type");
if (type == null || CAT_STAT_TYPE_FREQUENCY.equalsIgnoreCase( type ) ) {
String _freq = parseText(xmlr);
if (_freq != null && !_freq.equals("") ) {
cat.setFrequency( new Double( _freq ) );
}
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("catgry")) return;
}
}
}
private String processLabl(XMLStreamReader xmlr, String level) throws XMLStreamException {
if (level.equalsIgnoreCase( xmlr.getAttributeValue(null, "level") ) ) {
return parseText(xmlr);
} else {
return null;
}
}
private void processOtherMat(XMLStreamReader xmlr, StudyVersion studyVersion) throws XMLStreamException {
FileMetadata fmd = new FileMetadata();
fmd.setStudyVersion(studyVersion);
studyVersion.getFileMetadatas().add(fmd);
StudyFile sf = new OtherFile(studyVersion.getStudy());
fmd.setStudyFile(sf);
sf.setFileSystemLocation( xmlr.getAttributeValue(null, "URI"));
/// the following Strings are used to determine the category
String catName = null;
String icpsrDesc = null;
String icpsrId = null;
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("labl")) {
fmd.setLabel( parseText(xmlr) );
sf.setFileType( FileUtil.determineFileType( fmd.getLabel() ) );
} else if (xmlr.getLocalName().equals("txt")) {
fmd.setDescription( parseText(xmlr) );
} else if (xmlr.getLocalName().equals("notes")) {
String noteType = xmlr.getAttributeValue(null, "type");
if ("vdc:category".equalsIgnoreCase(noteType) ) {
catName = parseText(xmlr);
} else if ("icpsr:category".equalsIgnoreCase(noteType) ) {
String subjectType = xmlr.getAttributeValue(null, "subject");
if ("description".equalsIgnoreCase(subjectType)) {
icpsrDesc = parseText(xmlr);
} else if ("id".equalsIgnoreCase(subjectType)) {
icpsrId = parseText(xmlr);
}
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {// </codeBook>
if (xmlr.getLocalName().equals("otherMat")) {
// post process
if (fmd.getLabel() == null || fmd.getLabel().trim().equals("") ) {
fmd.setLabel("file");
}
fmd.setCategory(determineFileCategory(catName, icpsrDesc, icpsrId));
return;
}
}
}
}
private void processNotes (XMLStreamReader xmlr, Metadata metadata) throws XMLStreamException {
StudyNote note = new StudyNote();
metadata.getStudyNotes().add(note);
note.setMetadata(metadata);
note.setSubject( xmlr.getAttributeValue(null, "subject") );
note.setType( xmlr.getAttributeValue(null, "type") );
note.setText( parseText(xmlr, "notes") );
}
private void parseStudyId(String _id, Study s) {
int index1 = _id.indexOf(':');
int index2 = _id.indexOf('/');
if (index1==-1) {
throw new EJBException("Error parsing IdNo: "+_id+". ':' not found in string");
} else {
s.setProtocol(_id.substring(0,index1));
}
if (index2 == -1) {
throw new EJBException("Error parsing IdNo: "+_id+". '/' not found in string");
} else {
s.setAuthority(_id.substring(index1+1, index2));
}
s.setStudyId(_id.substring(index2+1));
}
private String parseNoteByType (XMLStreamReader xmlr, String type) throws XMLStreamException {
if (type.equalsIgnoreCase( xmlr.getAttributeValue(null, "type") ) ) {
return parseText(xmlr);
} else {
return null;
}
}
private String parseUNF(String unfString) {
if (unfString.indexOf("UNF:") != -1) {
return unfString.substring( unfString.indexOf("UNF:") );
} else {
return null;
}
}
private String parseText(XMLStreamReader xmlr) throws XMLStreamException {
return parseText(xmlr,true);
}
private String parseText(XMLStreamReader xmlr, boolean scrubText) throws XMLStreamException {
String tempString = getElementText(xmlr);
if (scrubText) {
tempString = tempString.trim().replace('\n',' ');
}
return tempString;
}
private String parseText(XMLStreamReader xmlr, String endTag) throws XMLStreamException {
return (String) parseTextNew(xmlr,endTag);
}
private Object parseTextNew(XMLStreamReader xmlr, String endTag) throws XMLStreamException {
String returnString = "";
Map returnMap = null;
while (true) {
if (!returnString.equals("")) { returnString += "\n";}
int event = xmlr.next();
if (event == XMLStreamConstants.CHARACTERS) {
returnString += xmlr.getText().trim().replace('\n',' ');
} else if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("p")) {
returnString += "<p>" + parseText(xmlr, "p") + "</p>";
} else if (xmlr.getLocalName().equals("emph")) {
returnString += "<em>" + parseText(xmlr, "emph") + "</em>";
} else if (xmlr.getLocalName().equals("hi")) {
returnString += "<strong>" + parseText(xmlr, "hi") + "</strong>";
} else if (xmlr.getLocalName().equals("ExtLink")) {
String uri = xmlr.getAttributeValue(null, "URI");
String text = parseText(xmlr, "ExtLink").trim();
returnString += "<a href=\"" + uri + "\">" + ( StringUtil.isEmpty(text) ? uri : text) + "</a>";
} else if (xmlr.getLocalName().equals("list")) {
returnString += parseText_list(xmlr);
} else if (xmlr.getLocalName().equals("citation")) {
if (SOURCE_DVN_3_0.equals(xmlr.getAttributeValue(null, "source")) ) {
returnMap = parseDVNCitation(xmlr);
}
returnString += parseText_citation(xmlr);
} else {
throw new EJBException("ERROR occurred in mapDDI (parseText): tag not yet supported: <" + xmlr.getLocalName() + ">" );
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals(endTag)) break;
}
}
if (returnMap != null) {
// this is one of our new citation areas for DVN3.0
return returnMap;
}
// otherwise it's a standard section and just return the String like we always did
return returnString;
}
private String parseText_list (XMLStreamReader xmlr) throws XMLStreamException {
String listString = null;
String listCloseTag = null;
// check type
String listType = xmlr.getAttributeValue(null, "type");
if ("bulleted".equals(listType) ){
listString = "<ul>\n";
listCloseTag = "</ul>";
} else if ("ordered".equals(listType) ) {
listString = "<ol>\n";
listCloseTag = "</ol>";
} else {
// this includes the default list type of "simple"
throw new EJBException("ERROR occurred in mapDDI (parseText): ListType of types other than {bulleted, ordered} not currently supported.");
}
while (true) {
int event = xmlr.next();
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("itm")) {
listString += "<li>" + parseText(xmlr,"itm") + "</li>\n";
} else {
throw new EJBException("ERROR occurred in mapDDI (parseText): ListType does not currently supported contained LabelType.");
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("list")) break;
}
}
return (listString + listCloseTag);
}
private String parseText_citation (XMLStreamReader xmlr) throws XMLStreamException {
String citation = "<!-- parsed from DDI citation title and holdings -->";
boolean addHoldings = false;
String holdings = "";
while (true) {
int event = xmlr.next();
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("titlStmt")) {
while (true) {
event = xmlr.next();
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("titl")) {
citation += parseText(xmlr);
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("titlStmt")) break;
}
}
} else if (xmlr.getLocalName().equals("holdings")) {
String uri = xmlr.getAttributeValue(null, "URI");
String holdingsText = parseText(xmlr);
if ( !StringUtil.isEmpty(uri) || !StringUtil.isEmpty(holdingsText)) {
holdings += addHoldings ? ", " : "";
addHoldings = true;
if ( StringUtil.isEmpty(uri) ) {
holdings += holdingsText;
} else if ( StringUtil.isEmpty(holdingsText) ) {
holdings += "<a href=\"" + uri + "\">" + uri + "</a>";
} else {
// both uri and text have values
holdings += "<a href=\"" + uri + "\">" + holdingsText + "</a>";
}
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("citation")) break;
}
}
if (addHoldings) {
citation += " (" + holdings + ")";
}
return citation;
}
private Map parseDVNCitation(XMLStreamReader xmlr) throws XMLStreamException {
Map returnValues = new HashMap();
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("IDNo")) {
returnValues.put("idType", xmlr.getAttributeValue(null, "agency") );
returnValues.put("idNumber", parseText(xmlr) );
}
else if (xmlr.getLocalName().equals("biblCit")) {
returnValues.put("text", parseText(xmlr) );
}
else if (xmlr.getLocalName().equals("holdings")) {
returnValues.put("url", xmlr.getAttributeValue(null, "URI") );
}
else if (xmlr.getLocalName().equals("notes")) {
if (NOTE_TYPE_REPLICATION_FOR.equals(xmlr.getAttributeValue(null, "type")) ) {
returnValues.put("replicationData", new Boolean(true));
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals("citation")) break;
}
}
return returnValues;
}
private Map<String,String> parseCompoundText (XMLStreamReader xmlr, String endTag) throws XMLStreamException {
Map<String,String> returnMap = new HashMap<String,String>();
String text = "";
while (true) {
int event = xmlr.next();
if (event == XMLStreamConstants.CHARACTERS) {
if (text != "") { text += "\n";}
text += xmlr.getText().trim().replace('\n',' ');
} else if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("ExtLink")) {
String mapKey = ("image".equalsIgnoreCase( xmlr.getAttributeValue(null, "role") ) || "logo".equalsIgnoreCase(xmlr.getAttributeValue(null, "title")))? "logo" : "url";
returnMap.put( mapKey, xmlr.getAttributeValue(null, "URI") );
parseText(xmlr, "ExtLink"); // this line effectively just skips though until the end of the tag
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (xmlr.getLocalName().equals(endTag)) break;
}
}
returnMap.put( "name", text );
return returnMap;
}
private String parseDate (XMLStreamReader xmlr, String endTag) throws XMLStreamException {
String date = xmlr.getAttributeValue(null, "date");
if (date == null) {
date = parseText(xmlr);
}
return date;
}
private String determineFileCategory(String catName, String icpsrDesc, String icpsrId) {
if (catName == null) {
catName = icpsrDesc;
if (catName != null) {
if (icpsrId != null && !icpsrId.trim().equals("") ) {
catName = icpsrId + ". " + catName;
}
}
}
return (catName != null ? catName : "");
}
/* We had to add this method because the ref getElementText has a bug where it
* would append a null before the text, if there was an escaped apostrophe; it appears
* that the code finds an null ENTITY_REFERENCE in this case which seems like a bug;
* the workaround for the moment is to comment or handling ENTITY_REFERENCE in this case
*/
private String getElementText(XMLStreamReader xmlr) throws XMLStreamException {
if(xmlr.getEventType() != XMLStreamConstants.START_ELEMENT) {
throw new XMLStreamException("parser must be on START_ELEMENT to read next text", xmlr.getLocation());
}
int eventType = xmlr.next();
StringBuffer content = new StringBuffer();
while(eventType != XMLStreamConstants.END_ELEMENT ) {
if(eventType == XMLStreamConstants.CHARACTERS
|| eventType == XMLStreamConstants.CDATA
|| eventType == XMLStreamConstants.SPACE
/* || eventType == XMLStreamConstants.ENTITY_REFERENCE*/) {
content.append(xmlr.getText());
} else if(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
|| eventType == XMLStreamConstants.COMMENT
|| eventType == XMLStreamConstants.ENTITY_REFERENCE) {
// skipping
} else if(eventType == XMLStreamConstants.END_DOCUMENT) {
throw new XMLStreamException("unexpected end of document when reading element text content");
} else if(eventType == XMLStreamConstants.START_ELEMENT) {
throw new XMLStreamException("element text content may not contain START_ELEMENT", xmlr.getLocation());
} else {
throw new XMLStreamException("Unexpected event type "+eventType, xmlr.getLocation());
}
eventType = xmlr.next();
}
return content.toString();
}
// </editor-fold>
}
| false | false | null | null |
diff --git a/src/main/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java b/src/main/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java
index 413f0f829..de5cfd234 100644
--- a/src/main/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java
+++ b/src/main/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java
@@ -1,1138 +1,1140 @@
/*
* Copyright 2009 Red Hat, Inc.
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.hornetq.core.client.impl;
import java.io.Serializable;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.hornetq.core.client.ClientSession;
import org.hornetq.core.client.ClientSessionFactory;
import org.hornetq.core.client.ConnectionLoadBalancingPolicy;
import org.hornetq.core.cluster.DiscoveryEntry;
import org.hornetq.core.cluster.DiscoveryGroup;
import org.hornetq.core.cluster.DiscoveryListener;
import org.hornetq.core.cluster.impl.DiscoveryGroupImpl;
import org.hornetq.core.config.TransportConfiguration;
import org.hornetq.core.exception.HornetQException;
import org.hornetq.core.logging.Logger;
import org.hornetq.core.remoting.Interceptor;
import org.hornetq.utils.HornetQThreadFactory;
import org.hornetq.utils.Pair;
import org.hornetq.utils.UUIDGenerator;
/**
* @author <a href="mailto:[email protected]">Tim Fox</a>
* @author <a href="mailto:[email protected]">Clebert Suconic</a>
* @author <a href="mailto:[email protected]">Jeff Mesnil</a>
* @author <a href="mailto:[email protected]">Andy Taylor</a>
* @version <tt>$Revision: 3602 $</tt>
*
*/
public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, DiscoveryListener, Serializable
{
// Constants
// ------------------------------------------------------------------------------------
private static final long serialVersionUID = 2512460695662741413L;
private static final Logger log = Logger.getLogger(ClientSessionFactoryImpl.class);
public static final String DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME = "org.hornetq.core.client.impl.RoundRobinConnectionLoadBalancingPolicy";
public static final long DEFAULT_CLIENT_FAILURE_CHECK_PERIOD = 30000;
// 1 minute - this should be higher than ping period
public static final long DEFAULT_CONNECTION_TTL = 1 * 60 * 1000;
// Any message beyond this size is considered a large message (to be sent in chunks)
public static final int DEFAULT_MIN_LARGE_MESSAGE_SIZE = 100 * 1024;
public static final int DEFAULT_CONSUMER_WINDOW_SIZE = 1024 * 1024;
public static final int DEFAULT_CONSUMER_MAX_RATE = -1;
public static final int DEFAULT_CONFIRMATION_WINDOW_SIZE = -1;
public static final int DEFAULT_PRODUCER_WINDOW_SIZE = 1024 * 1024;
public static final int DEFAULT_PRODUCER_MAX_RATE = -1;
public static final boolean DEFAULT_BLOCK_ON_ACKNOWLEDGE = false;
public static final boolean DEFAULT_BLOCK_ON_PERSISTENT_SEND = true;
public static final boolean DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND = false;
public static final boolean DEFAULT_AUTO_GROUP = false;
public static final long DEFAULT_CALL_TIMEOUT = 30000;
public static final int DEFAULT_ACK_BATCH_SIZE = 1024 * 1024;
public static final boolean DEFAULT_PRE_ACKNOWLEDGE = false;
public static final long DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT = 2000;
public static final long DEFAULT_DISCOVERY_REFRESH_TIMEOUT = 10000;
public static final long DEFAULT_RETRY_INTERVAL = 2000;
public static final double DEFAULT_RETRY_INTERVAL_MULTIPLIER = 1d;
public static final long DEFAULT_MAX_RETRY_INTERVAL = 2000;
public static final int DEFAULT_RECONNECT_ATTEMPTS = 0;
public static final boolean DEFAULT_FAILOVER_ON_SERVER_SHUTDOWN = false;
public static final boolean DEFAULT_USE_GLOBAL_POOLS = true;
public static final int DEFAULT_THREAD_POOL_MAX_SIZE = -1;
public static final int DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE = 5;
public static final boolean DEFAULT_CACHE_LARGE_MESSAGE_CLIENT = false;
// Attributes
// -----------------------------------------------------------------------------------
private final Map<Pair<TransportConfiguration, TransportConfiguration>, FailoverManager> failoverManagerMap = new LinkedHashMap<Pair<TransportConfiguration, TransportConfiguration>, FailoverManager>();
private volatile boolean receivedBroadcast = false;
private ExecutorService threadPool;
private ScheduledExecutorService scheduledThreadPool;
private DiscoveryGroup discoveryGroup;
private ConnectionLoadBalancingPolicy loadBalancingPolicy;
private FailoverManager[] failoverManagerArray;
private boolean readOnly;
// Settable attributes:
private boolean cacheLargeMessagesClient = DEFAULT_CACHE_LARGE_MESSAGE_CLIENT;
private List<Pair<TransportConfiguration, TransportConfiguration>> staticConnectors;
private String discoveryAddress;
private int discoveryPort;
private long discoveryRefreshTimeout;
private long discoveryInitialWaitTimeout;
private long clientFailureCheckPeriod;
private long connectionTTL;
private long callTimeout;
private int minLargeMessageSize;
private int consumerWindowSize;
private int consumerMaxRate;
private int confirmationWindowSize;
private int producerWindowSize;
private int producerMaxRate;
private boolean blockOnAcknowledge;
private boolean blockOnPersistentSend;
private boolean blockOnNonPersistentSend;
private boolean autoGroup;
private boolean preAcknowledge;
private String connectionLoadBalancingPolicyClassName;
private int ackBatchSize;
private boolean useGlobalPools;
private int scheduledThreadPoolMaxSize;
private int threadPoolMaxSize;
private long retryInterval;
private double retryIntervalMultiplier;
private long maxRetryInterval;
private int reconnectAttempts;
private volatile boolean closed;
private boolean failoverOnServerShutdown;
private final List<Interceptor> interceptors = new CopyOnWriteArrayList<Interceptor>();
private static ExecutorService globalThreadPool;
private static ScheduledExecutorService globalScheduledThreadPool;
private static synchronized ExecutorService getGlobalThreadPool()
{
if (globalThreadPool == null)
{
ThreadFactory factory = new HornetQThreadFactory("HornetQ-client-global-threads", true);
globalThreadPool = Executors.newCachedThreadPool(factory);
}
return globalThreadPool;
}
private static synchronized ScheduledExecutorService getGlobalScheduledThreadPool()
{
if (globalScheduledThreadPool == null)
{
ThreadFactory factory = new HornetQThreadFactory("HornetQ-client-global-scheduled-threads", true);
globalScheduledThreadPool = Executors.newScheduledThreadPool(DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, factory);
}
return globalScheduledThreadPool;
}
private void setThreadPools()
{
if (useGlobalPools)
{
threadPool = getGlobalThreadPool();
scheduledThreadPool = getGlobalScheduledThreadPool();
}
else
{
ThreadFactory factory = new HornetQThreadFactory("HornetQ-client-factory-threads-" + System.identityHashCode(this),
true);
if (threadPoolMaxSize == -1)
{
threadPool = Executors.newCachedThreadPool(factory);
}
else
{
threadPool = Executors.newFixedThreadPool(threadPoolMaxSize, factory);
}
factory = new HornetQThreadFactory("HornetQ-client-factory-pinger-threads-" + System.identityHashCode(this),
true);
scheduledThreadPool = Executors.newScheduledThreadPool(scheduledThreadPoolMaxSize, factory);
}
}
private void initialise() throws Exception
{
setThreadPools();
instantiateLoadBalancingPolicy();
if (discoveryAddress != null)
{
InetAddress groupAddress = InetAddress.getByName(discoveryAddress);
discoveryGroup = new DiscoveryGroupImpl(UUIDGenerator.getInstance().generateStringUUID(),
discoveryAddress,
groupAddress,
discoveryPort,
discoveryRefreshTimeout);
discoveryGroup.registerListener(this);
discoveryGroup.start();
}
else if (staticConnectors != null)
{
for (Pair<TransportConfiguration, TransportConfiguration> pair : staticConnectors)
{
FailoverManager cm = new FailoverManagerImpl(this,
pair.a,
pair.b,
failoverOnServerShutdown,
callTimeout,
clientFailureCheckPeriod,
connectionTTL,
retryInterval,
retryIntervalMultiplier,
maxRetryInterval,
reconnectAttempts,
threadPool,
scheduledThreadPool,
interceptors);
failoverManagerMap.put(pair, cm);
}
updatefailoverManagerArray();
}
else
{
throw new IllegalStateException("Before using a session factory you must either set discovery address and port or " + "provide some static transport configuration");
}
}
// Static
// ---------------------------------------------------------------------------------------
// Constructors
// ---------------------------------------------------------------------------------
public ClientSessionFactoryImpl(final ClientSessionFactory other)
{
discoveryAddress = other.getDiscoveryAddress();
discoveryPort = other.getDiscoveryPort();
staticConnectors = other.getStaticConnectors();
discoveryRefreshTimeout = other.getDiscoveryRefreshTimeout();
clientFailureCheckPeriod = other.getClientFailureCheckPeriod();
connectionTTL = other.getConnectionTTL();
callTimeout = other.getCallTimeout();
minLargeMessageSize = other.getMinLargeMessageSize();
consumerWindowSize = other.getConsumerWindowSize();
consumerMaxRate = other.getConsumerMaxRate();
confirmationWindowSize = other.getConfirmationWindowSize();
producerWindowSize = other.getProducerWindowSize();
producerMaxRate = other.getProducerMaxRate();
blockOnAcknowledge = other.isBlockOnAcknowledge();
blockOnPersistentSend = other.isBlockOnPersistentSend();
blockOnNonPersistentSend = other.isBlockOnNonPersistentSend();
autoGroup = other.isAutoGroup();
preAcknowledge = other.isPreAcknowledge();
ackBatchSize = other.getAckBatchSize();
connectionLoadBalancingPolicyClassName = other.getConnectionLoadBalancingPolicyClassName();
discoveryInitialWaitTimeout = other.getDiscoveryInitialWaitTimeout();
useGlobalPools = other.isUseGlobalPools();
scheduledThreadPoolMaxSize = other.getScheduledThreadPoolMaxSize();
threadPoolMaxSize = other.getThreadPoolMaxSize();
retryInterval = other.getRetryInterval();
retryIntervalMultiplier = other.getRetryIntervalMultiplier();
maxRetryInterval = other.getMaxRetryInterval();
reconnectAttempts = other.getReconnectAttempts();
failoverOnServerShutdown = other.isFailoverOnServerShutdown();
+
+ cacheLargeMessagesClient = other.isCacheLargeMessagesClient();
}
public ClientSessionFactoryImpl()
{
discoveryRefreshTimeout = DEFAULT_DISCOVERY_REFRESH_TIMEOUT;
clientFailureCheckPeriod = DEFAULT_CLIENT_FAILURE_CHECK_PERIOD;
connectionTTL = DEFAULT_CONNECTION_TTL;
callTimeout = DEFAULT_CALL_TIMEOUT;
minLargeMessageSize = DEFAULT_MIN_LARGE_MESSAGE_SIZE;
consumerWindowSize = DEFAULT_CONSUMER_WINDOW_SIZE;
consumerMaxRate = DEFAULT_CONSUMER_MAX_RATE;
confirmationWindowSize = DEFAULT_CONFIRMATION_WINDOW_SIZE;
producerWindowSize = DEFAULT_PRODUCER_WINDOW_SIZE;
producerMaxRate = DEFAULT_PRODUCER_MAX_RATE;
blockOnAcknowledge = DEFAULT_BLOCK_ON_ACKNOWLEDGE;
blockOnPersistentSend = DEFAULT_BLOCK_ON_PERSISTENT_SEND;
blockOnNonPersistentSend = DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
autoGroup = DEFAULT_AUTO_GROUP;
preAcknowledge = DEFAULT_PRE_ACKNOWLEDGE;
ackBatchSize = DEFAULT_ACK_BATCH_SIZE;
connectionLoadBalancingPolicyClassName = DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
discoveryInitialWaitTimeout = DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT;
useGlobalPools = DEFAULT_USE_GLOBAL_POOLS;
scheduledThreadPoolMaxSize = DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE;
threadPoolMaxSize = DEFAULT_THREAD_POOL_MAX_SIZE;
retryInterval = DEFAULT_RETRY_INTERVAL;
retryIntervalMultiplier = DEFAULT_RETRY_INTERVAL_MULTIPLIER;
maxRetryInterval = DEFAULT_MAX_RETRY_INTERVAL;
reconnectAttempts = DEFAULT_RECONNECT_ATTEMPTS;
failoverOnServerShutdown = DEFAULT_FAILOVER_ON_SERVER_SHUTDOWN;
}
public ClientSessionFactoryImpl(final String discoveryAddress, final int discoveryPort)
{
this();
this.discoveryAddress = discoveryAddress;
this.discoveryPort = discoveryPort;
}
public ClientSessionFactoryImpl(final List<Pair<TransportConfiguration, TransportConfiguration>> staticConnectors)
{
this();
this.staticConnectors = staticConnectors;
}
public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig,
final TransportConfiguration backupConnectorConfig)
{
this();
staticConnectors = new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
staticConnectors.add(new Pair<TransportConfiguration, TransportConfiguration>(connectorConfig,
backupConnectorConfig));
}
public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig)
{
this(connectorConfig, null);
}
// ClientSessionFactory implementation------------------------------------------------------------
public synchronized boolean isCacheLargeMessagesClient()
{
return cacheLargeMessagesClient;
}
public synchronized void setCacheLargeMessagesClient(boolean cached)
{
this.cacheLargeMessagesClient = cached;
}
public synchronized List<Pair<TransportConfiguration, TransportConfiguration>> getStaticConnectors()
{
return staticConnectors;
}
public synchronized void setStaticConnectors(List<Pair<TransportConfiguration, TransportConfiguration>> staticConnectors)
{
checkWrite();
this.staticConnectors = staticConnectors;
}
public synchronized long getClientFailureCheckPeriod()
{
return clientFailureCheckPeriod;
}
public synchronized void setClientFailureCheckPeriod(long clientFailureCheckPeriod)
{
checkWrite();
this.clientFailureCheckPeriod = clientFailureCheckPeriod;
}
public synchronized long getConnectionTTL()
{
return connectionTTL;
}
public synchronized void setConnectionTTL(long connectionTTL)
{
checkWrite();
this.connectionTTL = connectionTTL;
}
public synchronized long getCallTimeout()
{
return callTimeout;
}
public synchronized void setCallTimeout(long callTimeout)
{
checkWrite();
this.callTimeout = callTimeout;
}
public synchronized int getMinLargeMessageSize()
{
return minLargeMessageSize;
}
public synchronized void setMinLargeMessageSize(int minLargeMessageSize)
{
checkWrite();
this.minLargeMessageSize = minLargeMessageSize;
}
public synchronized int getConsumerWindowSize()
{
return consumerWindowSize;
}
public synchronized void setConsumerWindowSize(int consumerWindowSize)
{
checkWrite();
this.consumerWindowSize = consumerWindowSize;
}
public synchronized int getConsumerMaxRate()
{
return consumerMaxRate;
}
public synchronized void setConsumerMaxRate(int consumerMaxRate)
{
checkWrite();
this.consumerMaxRate = consumerMaxRate;
}
public synchronized int getConfirmationWindowSize()
{
return confirmationWindowSize;
}
public synchronized void setConfirmationWindowSize(int confirmationWindowSize)
{
checkWrite();
this.confirmationWindowSize = confirmationWindowSize;
}
public synchronized int getProducerWindowSize()
{
return producerWindowSize;
}
public synchronized void setProducerWindowSize(final int producerWindowSize)
{
checkWrite();
this.producerWindowSize = producerWindowSize;
}
public synchronized int getProducerMaxRate()
{
return producerMaxRate;
}
public synchronized void setProducerMaxRate(int producerMaxRate)
{
checkWrite();
this.producerMaxRate = producerMaxRate;
}
public synchronized boolean isBlockOnAcknowledge()
{
return blockOnAcknowledge;
}
public synchronized void setBlockOnAcknowledge(boolean blockOnAcknowledge)
{
checkWrite();
this.blockOnAcknowledge = blockOnAcknowledge;
}
public synchronized boolean isBlockOnPersistentSend()
{
return blockOnPersistentSend;
}
public synchronized void setBlockOnPersistentSend(boolean blockOnPersistentSend)
{
checkWrite();
this.blockOnPersistentSend = blockOnPersistentSend;
}
public synchronized boolean isBlockOnNonPersistentSend()
{
return blockOnNonPersistentSend;
}
public synchronized void setBlockOnNonPersistentSend(boolean blockOnNonPersistentSend)
{
checkWrite();
this.blockOnNonPersistentSend = blockOnNonPersistentSend;
}
public synchronized boolean isAutoGroup()
{
return autoGroup;
}
public synchronized void setAutoGroup(boolean autoGroup)
{
checkWrite();
this.autoGroup = autoGroup;
}
public synchronized boolean isPreAcknowledge()
{
return preAcknowledge;
}
public synchronized void setPreAcknowledge(boolean preAcknowledge)
{
checkWrite();
this.preAcknowledge = preAcknowledge;
}
public synchronized int getAckBatchSize()
{
return ackBatchSize;
}
public synchronized void setAckBatchSize(int ackBatchSize)
{
checkWrite();
this.ackBatchSize = ackBatchSize;
}
public synchronized long getDiscoveryInitialWaitTimeout()
{
return discoveryInitialWaitTimeout;
}
public synchronized void setDiscoveryInitialWaitTimeout(long initialWaitTimeout)
{
checkWrite();
this.discoveryInitialWaitTimeout = initialWaitTimeout;
}
public synchronized boolean isUseGlobalPools()
{
return useGlobalPools;
}
public synchronized void setUseGlobalPools(boolean useGlobalPools)
{
checkWrite();
this.useGlobalPools = useGlobalPools;
}
public synchronized int getScheduledThreadPoolMaxSize()
{
return scheduledThreadPoolMaxSize;
}
public synchronized void setScheduledThreadPoolMaxSize(int scheduledThreadPoolMaxSize)
{
checkWrite();
this.scheduledThreadPoolMaxSize = scheduledThreadPoolMaxSize;
}
public synchronized int getThreadPoolMaxSize()
{
return threadPoolMaxSize;
}
public synchronized void setThreadPoolMaxSize(int threadPoolMaxSize)
{
checkWrite();
this.threadPoolMaxSize = threadPoolMaxSize;
}
public synchronized long getRetryInterval()
{
return retryInterval;
}
public synchronized void setRetryInterval(long retryInterval)
{
checkWrite();
this.retryInterval = retryInterval;
}
public synchronized long getMaxRetryInterval()
{
return maxRetryInterval;
}
public synchronized void setMaxRetryInterval(long retryInterval)
{
checkWrite();
this.maxRetryInterval = retryInterval;
}
public synchronized double getRetryIntervalMultiplier()
{
return retryIntervalMultiplier;
}
public synchronized void setRetryIntervalMultiplier(double retryIntervalMultiplier)
{
checkWrite();
this.retryIntervalMultiplier = retryIntervalMultiplier;
}
public synchronized int getReconnectAttempts()
{
return reconnectAttempts;
}
public synchronized void setReconnectAttempts(int reconnectAttempts)
{
checkWrite();
this.reconnectAttempts = reconnectAttempts;
}
public synchronized boolean isFailoverOnServerShutdown()
{
return failoverOnServerShutdown;
}
public synchronized void setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
{
checkWrite();
this.failoverOnServerShutdown = failoverOnServerShutdown;
}
public synchronized String getConnectionLoadBalancingPolicyClassName()
{
return connectionLoadBalancingPolicyClassName;
}
public synchronized void setConnectionLoadBalancingPolicyClassName(String loadBalancingPolicyClassName)
{
checkWrite();
this.connectionLoadBalancingPolicyClassName = loadBalancingPolicyClassName;
}
public synchronized String getDiscoveryAddress()
{
return discoveryAddress;
}
public synchronized void setDiscoveryAddress(String discoveryAddress)
{
checkWrite();
this.discoveryAddress = discoveryAddress;
}
public synchronized int getDiscoveryPort()
{
return discoveryPort;
}
public synchronized void setDiscoveryPort(int discoveryPort)
{
checkWrite();
this.discoveryPort = discoveryPort;
}
public synchronized long getDiscoveryRefreshTimeout()
{
return discoveryRefreshTimeout;
}
public void addInterceptor(final Interceptor interceptor)
{
interceptors.add(interceptor);
}
public boolean removeInterceptor(final Interceptor interceptor)
{
return interceptors.remove(interceptor);
}
public synchronized void setDiscoveryRefreshTimeout(long discoveryRefreshTimeout)
{
checkWrite();
this.discoveryRefreshTimeout = discoveryRefreshTimeout;
}
public ClientSession createSession(final String username,
final String password,
final boolean xa,
final boolean autoCommitSends,
final boolean autoCommitAcks,
final boolean preAcknowledge,
final int ackBatchSize) throws HornetQException
{
return createSessionInternal(username,
password,
xa,
autoCommitSends,
autoCommitAcks,
preAcknowledge,
ackBatchSize);
}
public ClientSession createSession(boolean autoCommitSends, boolean autoCommitAcks, int ackBatchSize) throws HornetQException
{
return createSessionInternal(null, null, false, autoCommitSends, autoCommitAcks, preAcknowledge, ackBatchSize);
}
public ClientSession createXASession() throws HornetQException
{
return createSessionInternal(null, null, true, false, false, preAcknowledge, this.ackBatchSize);
}
public ClientSession createTransactedSession() throws HornetQException
{
return createSessionInternal(null, null, false, false, false, preAcknowledge, this.ackBatchSize);
}
public ClientSession createSession() throws HornetQException
{
return createSessionInternal(null, null, false, true, true, preAcknowledge, this.ackBatchSize);
}
public ClientSession createSession(final boolean autoCommitSends, final boolean autoCommitAcks) throws HornetQException
{
return createSessionInternal(null,
null,
false,
autoCommitSends,
autoCommitAcks,
preAcknowledge,
this.ackBatchSize);
}
public ClientSession createSession(final boolean xa, final boolean autoCommitSends, final boolean autoCommitAcks) throws HornetQException
{
return createSessionInternal(null, null, xa, autoCommitSends, autoCommitAcks, preAcknowledge, this.ackBatchSize);
}
public ClientSession createSession(final boolean xa,
final boolean autoCommitSends,
final boolean autoCommitAcks,
final boolean preAcknowledge) throws HornetQException
{
return createSessionInternal(null, null, xa, autoCommitSends, autoCommitAcks, preAcknowledge, this.ackBatchSize);
}
public int numSessions()
{
int num = 0;
for (FailoverManager failoverManager : failoverManagerMap.values())
{
num += failoverManager.numSessions();
}
return num;
}
public int numConnections()
{
int num = 0;
for (FailoverManager failoverManager : failoverManagerMap.values())
{
num += failoverManager.numConnections();
}
return num;
}
public void close()
{
if (closed)
{
return;
}
if (discoveryGroup != null)
{
try
{
discoveryGroup.stop();
}
catch (Exception e)
{
log.error("Failed to stop discovery group", e);
}
}
for (FailoverManager failoverManager : failoverManagerMap.values())
{
failoverManager.causeExit();
}
failoverManagerMap.clear();
if (!useGlobalPools)
{
if (threadPool != null)
{
threadPool.shutdown();
try
{
if (!threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS))
{
log.warn("Timed out waiting for pool to terminate");
}
}
catch (InterruptedException ignore)
{
}
}
if (scheduledThreadPool != null)
{
scheduledThreadPool.shutdown();
try
{
if (!scheduledThreadPool.awaitTermination(10000, TimeUnit.MILLISECONDS))
{
log.warn("Timed out waiting for scheduled pool to terminate");
}
}
catch (InterruptedException ignore)
{
}
}
}
closed = true;
}
public ClientSessionFactory copy()
{
return new ClientSessionFactoryImpl(this);
}
// DiscoveryListener implementation --------------------------------------------------------
public synchronized void connectorsChanged()
{
receivedBroadcast = true;
Map<String, DiscoveryEntry> newConnectors = discoveryGroup.getDiscoveryEntryMap();
Set<Pair<TransportConfiguration, TransportConfiguration>> connectorSet = new HashSet<Pair<TransportConfiguration, TransportConfiguration>>();
for (DiscoveryEntry entry : newConnectors.values())
{
connectorSet.add(entry.getConnectorPair());
}
Iterator<Map.Entry<Pair<TransportConfiguration, TransportConfiguration>, FailoverManager>> iter = failoverManagerMap.entrySet()
.iterator();
while (iter.hasNext())
{
Map.Entry<Pair<TransportConfiguration, TransportConfiguration>, FailoverManager> entry = iter.next();
if (!connectorSet.contains(entry.getKey()))
{
// failoverManager no longer there - we should remove it
iter.remove();
}
}
for (Pair<TransportConfiguration, TransportConfiguration> connectorPair : connectorSet)
{
if (!failoverManagerMap.containsKey(connectorPair))
{
// Create a new failoverManager
FailoverManager failoverManager = new FailoverManagerImpl(this,
connectorPair.a,
connectorPair.b,
failoverOnServerShutdown,
callTimeout,
clientFailureCheckPeriod,
connectionTTL,
retryInterval,
retryIntervalMultiplier,
maxRetryInterval,
reconnectAttempts,
threadPool,
scheduledThreadPool,
interceptors);
failoverManagerMap.put(connectorPair, failoverManager);
}
}
updatefailoverManagerArray();
}
public FailoverManager[] getFailoverManagers()
{
return failoverManagerArray;
}
// Protected ------------------------------------------------------------------------------
@Override
protected void finalize() throws Throwable
{
close();
super.finalize();
}
// Private --------------------------------------------------------------------------------
private void checkWrite()
{
if (readOnly)
{
throw new IllegalStateException("Cannot set attribute on SessionFactory after it has been used");
}
}
private ClientSession createSessionInternal(final String username,
final String password,
final boolean xa,
final boolean autoCommitSends,
final boolean autoCommitAcks,
final boolean preAcknowledge,
final int ackBatchSize) throws HornetQException
{
if (closed)
{
throw new IllegalStateException("Cannot create session, factory is closed (maybe it has been garbage collected)");
}
if (!readOnly)
{
try
{
initialise();
}
catch (Exception e)
{
throw new HornetQException(HornetQException.INTERNAL_ERROR, "Failed to initialise session factory", e);
}
readOnly = true;
}
if (discoveryGroup != null && !receivedBroadcast)
{
boolean ok = discoveryGroup.waitForBroadcast(discoveryInitialWaitTimeout);
if (!ok)
{
throw new HornetQException(HornetQException.CONNECTION_TIMEDOUT,
"Timed out waiting to receive initial broadcast from discovery group");
}
}
synchronized (this)
{
int pos = loadBalancingPolicy.select(failoverManagerArray.length);
FailoverManager failoverManager = failoverManagerArray[pos];
ClientSession session = failoverManager.createSession(username,
password,
xa,
autoCommitSends,
autoCommitAcks,
preAcknowledge,
ackBatchSize,
cacheLargeMessagesClient,
minLargeMessageSize,
blockOnAcknowledge,
autoGroup,
confirmationWindowSize,
producerWindowSize,
consumerWindowSize,
producerMaxRate,
consumerMaxRate,
blockOnNonPersistentSend,
blockOnPersistentSend);
return session;
}
}
private void instantiateLoadBalancingPolicy()
{
if (connectionLoadBalancingPolicyClassName == null)
{
throw new IllegalStateException("Please specify a load balancing policy class name on the session factory");
}
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try
{
Class<?> clazz = loader.loadClass(connectionLoadBalancingPolicyClassName);
loadBalancingPolicy = (ConnectionLoadBalancingPolicy)clazz.newInstance();
}
catch (Exception e)
{
throw new IllegalArgumentException("Unable to instantiate load balancing policy \"" + connectionLoadBalancingPolicyClassName +
"\"",
e);
}
}
private synchronized void updatefailoverManagerArray()
{
failoverManagerArray = new FailoverManager[failoverManagerMap.size()];
failoverManagerMap.values().toArray(failoverManagerArray);
}
}
| true | false | null | null |
diff --git a/src/main/org/testng/internal/Parameters.java b/src/main/org/testng/internal/Parameters.java
index e44c071..1b76e44 100644
--- a/src/main/org/testng/internal/Parameters.java
+++ b/src/main/org/testng/internal/Parameters.java
@@ -1,356 +1,362 @@
package org.testng.internal;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.TestNGException;
import org.testng.internal.annotations.AnnotationHelper;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.annotations.IConfiguration;
import org.testng.internal.annotations.IDataProvider;
import org.testng.internal.annotations.IFactory;
import org.testng.internal.annotations.IParameterizable;
import org.testng.internal.annotations.IParameters;
import org.testng.internal.annotations.ITest;
import org.testng.xml.XmlSuite;
/**
* Methods that bind parameters declared in testng.xml to actual values
* used to invoke methods.
*
* @author <a href="mailto:[email protected]">Cedric Beust</a>
* @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
*
* @@ANNOTATIONS@@
*/
public class Parameters {
private static final String NULL_VALUE= "null";
/**
* Creates the parameters needed for constructing a test class instance.
*/
public static Object[] createInstantiationParameters(Constructor ctor,
String methodAnnotation,
String[] parameterNames,
Map<String, String> params,
XmlSuite xmlSuite)
{
return createParameters(ctor.toString(), ctor.getParameterTypes(),
methodAnnotation, parameterNames, new MethodParameters(params), xmlSuite);
}
/**
* Creates the parameters needed for the specified <tt>@Configuration</tt> <code>Method</code>.
*
* @param m the configuraton method
* @param params
* @param currentTestMethod the current @Test method or <code>null</code> if no @Test is available (this is not
* only in case the configuration method is a @Before/@AfterMethod
* @param finder the annotation finder
* @param xmlSuite
* @return
*/
public static Object[] createConfigurationParameters(Method m,
Map<String, String> params,
ITestNGMethod currentTestMethod,
IAnnotationFinder finder,
XmlSuite xmlSuite,
ITestContext ctx)
{
Method currentTestMeth= currentTestMethod != null ?
currentTestMethod.getMethod() : null;
return createParameters(m, new MethodParameters(params, currentTestMeth, ctx),
finder, xmlSuite, IConfiguration.class, "@Configuration");
}
////////////////////////////////////////////////////////
/**
* @param m
* @param instance
* @return An array of parameters suitable to invoke this method, possibly
* picked from the property file
*/
private static Object[] createParameters(String methodName,
Class[] parameterTypes,
String methodAnnotation,
String[] parameterNames,
MethodParameters params,
XmlSuite xmlSuite)
{
Object[] result = new Object[0];
if(parameterTypes.length > 0) {
List<Object> vResult = new ArrayList<Object>();
checkParameterTypes(methodName, parameterTypes, methodAnnotation, parameterNames);
for(int i =0, j = 0; i < parameterTypes.length; i++) {
if (Method.class.equals(parameterTypes[i])) {
vResult.add(params.currentTestMethod);
}
else if (ITestContext.class.equals(parameterTypes[i])) {
vResult.add(params.context);
}
else {
String p = parameterNames[j];
String value = params.xmlParameters.get(p);
if (null == value) {
throw new TestNGException("Parameter '" + p + "' is required by "
+ methodAnnotation
+ " on method "
+ methodName
+ "\nbut has not been defined in " + xmlSuite.getFileName());
}
vResult.add(convertType(parameterTypes[i], value, p));
j++;
}
}
result = (Object[]) vResult.toArray(new Object[vResult.size()]);
}
return result;
}
// FIXME
private static void checkParameterTypes(String methodName,
Class[] parameterTypes, String methodAnnotation, String[] parameterNames)
{
if(parameterNames.length == parameterTypes.length) return;
for(int i= parameterTypes.length - 1; i >= parameterNames.length; i--) {
if(!ITestContext.class.equals(parameterTypes[i])
&& !Method.class.equals(parameterTypes[i])) {
throw new TestNGException( "Method " + methodName + " requires "
+ parameterTypes.length + " parameters but "
+ parameterNames.length
+ " were supplied in the "
+ methodAnnotation
+ " annotation.");
}
}
}
//TODO: Cosmin - making this public is not the best solution
public static Object convertType(Class type, String value, String paramName) {
Object result = null;
if(NULL_VALUE.equals(value.toLowerCase())) {
if(type.isPrimitive()) {
Utils.log("Parameters", 2, "Attempt to pass null value to primitive type parameter '" + paramName + "'");
}
return null; // null value must be used
}
if(type == String.class) {
result = value;
}
else if(type == int.class || type == Integer.class) {
result = new Integer(Integer.parseInt(value));
}
else if(type == boolean.class || type == Boolean.class) {
result = Boolean.valueOf(value);
}
else if(type == byte.class || type == Byte.class) {
result = new Byte(Byte.parseByte(value));
}
else if(type == char.class || type == Character.class) {
result = new Character(value.charAt(0));
}
else if(type == double.class || type == Double.class) {
result = new Double(Double.parseDouble(value));
}
else if(type == float.class || type == Float.class) {
result = new Float(Float.parseFloat(value));
}
else if(type == long.class || type == Long.class) {
result = new Long(Long.parseLong(value));
}
else if(type == short.class || type == Short.class) {
result = new Short(Short.parseShort(value));
}
else {
assert false : "Unsupported type parameter : " + type;
}
return result;
}
private static Method findDataProvider(Class clazz, Method m, IAnnotationFinder finder) {
Method result = null;
String dataProviderName = null;
Class dataProviderClass = null;
ITest annotation = AnnotationHelper.findTest(finder, m);
if (annotation != null) {
dataProviderName = annotation.getDataProvider();
dataProviderClass = annotation.getDataProviderClass();
}
if (dataProviderName == null) {
IFactory factory = AnnotationHelper.findFactory(finder, m);
if (factory != null) {
dataProviderName = factory.getDataProvider();
dataProviderClass = null;
}
}
if (null != dataProviderName && ! "".equals(dataProviderName)) {
result = findDataProvider(clazz, finder, dataProviderName, dataProviderClass);
+
+ if(null == result) {
+ throw new TestNGException("Method " + m + " requires a @DataProvider named : "
+ + dataProviderName + (dataProviderClass != null ? " in class " + dataProviderClass.getName() : "")
+ );
+ }
}
return result;
}
/**
* Find a method that has a @DataProvider(name=name)
*/
private static Method findDataProvider(Class cls, IAnnotationFinder finder,
String name, Class dataProviderClass)
{
boolean shouldBeStatic = false;
if (dataProviderClass != null) {
cls = dataProviderClass;
shouldBeStatic = true;
}
for (Method m : ClassHelper.getAvailableMethods(cls)) {
IDataProvider dp = (IDataProvider) finder.findAnnotation(m, IDataProvider.class);
if (null != dp && (name.equals(dp.getName()) || name.equals(m.getName()))) {
if (shouldBeStatic && (m.getModifiers() & Modifier.STATIC) == 0) {
throw new TestNGException("DataProvider should be static: " + m);
}
return m;
}
}
return null;
}
@SuppressWarnings({"deprecation"})
private static Object[] createParameters(Method m, MethodParameters params,
IAnnotationFinder finder, XmlSuite xmlSuite, Class annotationClass, String atName)
{
Object[] result = new Object[0];
//
// Try to find an @Parameters annotation
//
IParameters annotation = (IParameters) finder.findAnnotation(m, IParameters.class);
if(null != annotation) {
String[] parameterNames = annotation.getValue();
result = createParameters(m.getName(), m.getParameterTypes(),
atName, parameterNames, params, xmlSuite);
}
//
// Else, use the deprecated syntax
//
else {
IParameterizable a = (IParameterizable) finder.findAnnotation(m, annotationClass);
if(null != a) {
String[] parameterNames = a.getParameters();
result = createParameters(m.getName(), m.getParameterTypes(),
atName, parameterNames, params, xmlSuite);
}
else {
result = createParameters(m.getName(), m.getParameterTypes(),
atName, new String[0], params, xmlSuite);
}
}
return result;
}
/**
* If the method has parameters, fill them in. Either by using a @DataProvider
* if any was provided, or by looking up <parameters> in testng.xml
* @return An Iterator over the values for each parameter of this
* method.
*/
public static Iterator<Object[]> handleParameters(ITestNGMethod testMethod,
Map<String, String> allParameterNames,
Object instance,
MethodParameters methodParams,
XmlSuite xmlSuite,
IAnnotationFinder annotationFinder)
{
Iterator<Object[]> result = null;
//
// Do we have a @DataProvider? If yes, then we have several
// sets of parameters for this method
//
Method dataProvider = findDataProvider(testMethod.getTestClass().getRealClass(),
testMethod.getMethod(),
annotationFinder);
if (null != dataProvider) {
int parameterCount = testMethod.getMethod().getParameterTypes().length;
for (int i = 0; i < parameterCount; i++) {
String n = "param" + i;
allParameterNames.put(n, n);
}
result = MethodHelper.invokeDataProvider(
instance, /* a test instance or null if the dataprovider is static*/
dataProvider,
testMethod,
methodParams.context);
}
else {
//
// Normal case: we have only one set of parameters coming from testng.xml
//
allParameterNames.putAll(methodParams.xmlParameters);
// Create an Object[][] containing just one row of parameters
Object[][] allParameterValuesArray = new Object[1][];
allParameterValuesArray[0] = createParameters(testMethod.getMethod(),
methodParams, annotationFinder, xmlSuite, ITest.class, "@Test");
// Mark that this method needs to have at least a certain
// number of invocations (needed later to call AfterGroups
// at the right time).
testMethod.setParameterInvocationCount(allParameterValuesArray.length);
// Turn it into an Iterable
result = MethodHelper.createArrayIterator(allParameterValuesArray);
}
return result;
}
private static void ppp(String s) {
System.out.println("[Parameters] " + s);
}
/** A parameter passing helper class. */
public static class MethodParameters {
private final Map<String, String> xmlParameters;
private final Method currentTestMethod;
private final ITestContext context;
public MethodParameters(Map<String, String> params) {
this(params, null, null);
}
public MethodParameters(Map<String, String> params, Method m) {
this(params, m, null);
}
public MethodParameters(Map<String, String> params, Method m, ITestContext ctx) {
xmlParameters= params;
currentTestMethod= m;
context= ctx;
}
}
}
| true | false | null | null |
diff --git a/test-src/com/redhat/ceylon/compiler/java/test/cmr/CMRTest.java b/test-src/com/redhat/ceylon/compiler/java/test/cmr/CMRTest.java
index 1c89e8d9c..ad5b8efd7 100755
--- a/test-src/com/redhat/ceylon/compiler/java/test/cmr/CMRTest.java
+++ b/test-src/com/redhat/ceylon/compiler/java/test/cmr/CMRTest.java
@@ -1,486 +1,504 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.cmr;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.tools.DiagnosticListener;
import javax.tools.FileObject;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl;
import com.redhat.ceylon.compiler.java.util.Util;
public class CMRTest extends CompilerTest {
//
// Modules
@Test
public void testMdlModuleDefault() throws IOException{
compile("module/def/CeylonClass.ceylon");
File carFile = getModuleArchive("default", null);
assertTrue(carFile.exists());
JarFile car = new JarFile(carFile);
ZipEntry moduleClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/def/CeylonClass.class");
assertNotNull(moduleClass);
car.close();
}
@Test
public void testMdlModuleDefaultJavaFile() throws IOException{
compile("module/def/JavaClass.java");
File carFile = getModuleArchive("default", null);
assertTrue(carFile.exists());
JarFile car = new JarFile(carFile);
ZipEntry moduleClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/def/JavaClass.class");
assertNotNull(moduleClass);
car.close();
}
@Test
public void testMdlModuleOnlyInOutputRepo(){
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
assertFalse(carFile.exists());
File carFileInHomeRepo = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6",
Util.getHomeRepository());
if(carFileInHomeRepo.exists())
carFileInHomeRepo.delete();
compile("module/single/module.ceylon");
// make sure it was created in the output repo
assertTrue(carFile.exists());
// make sure it wasn't created in the home repo
assertFalse(carFileInHomeRepo.exists());
}
@Test
public void testMdlWithCeylonImport() throws IOException{
compile("module/ceylon_import/module.ceylon", "module/ceylon_import/ImportCeylonLanguage.ceylon");
}
@Test
public void testMdlWithCommonPrefix() throws IOException{
compile("module/depend/prefix/module.ceylon");
// This is heisenbug https://github.com/ceylon/ceylon-compiler/issues/460 and for some
// reason it only happens _sometimes_, hence the repeats
compile("module/depend/prefix_suffix/module.ceylon");
compile("module/depend/prefix_suffix/module.ceylon");
compile("module/depend/prefix_suffix/module.ceylon");
compile("module/depend/prefix_suffix/module.ceylon");
compile("module/depend/prefix_suffix/module.ceylon");
}
@Test
public void testMdlModuleFromCompiledModule() throws IOException{
compile("module/single/module.ceylon");
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
assertTrue(carFile.exists());
JarFile car = new JarFile(carFile);
// just to be sure
ZipEntry bogusEntry = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/BOGUS");
assertNull(bogusEntry);
ZipEntry moduleClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/module.class");
assertNotNull(moduleClass);
car.close();
compile("module/single/subpackage/Subpackage.ceylon");
// MUST reopen it
car = new JarFile(carFile);
ZipEntry subpackageClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/subpackage/Subpackage.class");
assertNotNull(subpackageClass);
car.close();
}
@Ignore("M3")
@Test
public void testMdlCarWithInvalidSHA1() throws IOException{
compile("module/single/module.ceylon");
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
assertTrue(carFile.exists());
JarFile car = new JarFile(carFile);
// just to be sure
ZipEntry moduleClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/module.class");
assertNotNull(moduleClass);
car.close();
// now let's break the SHA1
File shaFile = getArchiveName("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6", destDir, "car.sha1");
Writer w = new FileWriter(shaFile);
w.write("fubar");
w.flush();
w.close();
// now try to compile the subpackage with a broken SHA1
//compile("module/single/subpackage/Subpackage.ceylon");
assertErrors("module/single/subpackage/Subpackage",
new CompilerError(-1, "Module car "+destDir+"/com/redhat/ceylon/compiler/java/test/cmr/module/single/6.6.6/com.redhat.ceylon.compiler.java.test.cmr.module.single-6.6.6.car has an invalid SHA1 signature: you need to remove it and rebuild the archive, since it may be corrupted."));
}
@Test
public void testMdlCompilerGeneratesModuleForValidUnits() throws IOException{
CeyloncTaskImpl compilerTask = getCompilerTask("module/single/module.ceylon", "module/single/Correct.ceylon", "module/single/Invalid.ceylon");
Boolean success = compilerTask.call();
assertFalse(success);
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
assertTrue(carFile.exists());
JarFile car = new JarFile(carFile);
ZipEntry moduleClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/module.class");
assertNotNull(moduleClass);
ZipEntry correctClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/Correct.class");
assertNotNull(correctClass);
ZipEntry invalidClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/Invalid.class");
assertNull(invalidClass);
car.close();
}
@Ignore("M3")
@Test
public void testMdlInterdepModule(){
// first compile it all from source
compile("module/interdep/a/module.ceylon", "module/interdep/a/package.ceylon", "module/interdep/a/b.ceylon", "module/interdep/a/A.ceylon",
"module/interdep/b/module.ceylon", "module/interdep/b/package.ceylon", "module/interdep/b/a.ceylon", "module/interdep/b/B.ceylon");
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.interdep.a", "6.6.6");
assertTrue(carFile.exists());
carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.interdep.b", "6.6.6");
assertTrue(carFile.exists());
// then try to compile only one module (the other being loaded from its car)
compile("module/interdep/a/module.ceylon", "module/interdep/a/b.ceylon", "module/interdep/a/A.ceylon");
}
@Test
public void testMdlDependentModule(){
// Compile only the first module
compile("module/depend/a/module.ceylon", "module/depend/a/package.ceylon", "module/depend/a/A.ceylon");
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.depend.a", "6.6.6");
assertTrue(carFile.exists());
// then try to compile only one module (the other being loaded from its car)
compile("module/depend/b/module.ceylon", "module/depend/b/a.ceylon", "module/depend/b/aWildcard.ceylon");
carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.depend.b", "6.6.6");
assertTrue(carFile.exists());
}
@Test
public void testMdlImplicitDependentModule(){
// Compile only the first module
compile("module/implicit/a/module.ceylon", "module/implicit/a/package.ceylon", "module/implicit/a/A.ceylon",
"module/implicit/b/module.ceylon", "module/implicit/b/package.ceylon", "module/implicit/b/B.ceylon", "module/implicit/b/B2.ceylon",
"module/implicit/c/module.ceylon", "module/implicit/c/package.ceylon", "module/implicit/c/c.ceylon");
// Dependencies:
//
// c.ceylon--> B2.ceylon
// |
// '-> B.ceylon --> A.ceylon
// Successfull tests :
compile("module/implicit/c/c.ceylon");
compile("module/implicit/b/B.ceylon", "module/implicit/c/c.ceylon");
compile("module/implicit/b/B2.ceylon", "module/implicit/c/c.ceylon");
// Failing tests :
Boolean success1 = getCompilerTask("module/implicit/c/c.ceylon", "module/implicit/b/B.ceylon").call();
// => B.ceylon : package not found in dependent modules: com.redhat.ceylon.compiler.java.test.cmr.module.implicit.a
Boolean success2 = getCompilerTask("module/implicit/c/c.ceylon", "module/implicit/b/B2.ceylon").call();
// => c.ceylon : TypeVisitor caused an exception visiting Import node: com.sun.tools.javac.code.Symbol$CompletionFailure: class file for com.redhat.ceylon.compiler.test.cmr.module.implicit.a.A not found at unknown
Assert.assertTrue(success1 && success2);
}
private void copy(File source, File dest) throws IOException {
InputStream inputStream = new FileInputStream(source);
OutputStream outputStream = new FileOutputStream(dest);
byte[] buffer = new byte[4096];
int read;
while((read = inputStream.read(buffer)) != -1){
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.close();
}
@Test
public void testMdlSuppressObsoleteClasses() throws IOException{
File sourceFile = new File(path, "module/single/SuppressClass.ceylon");
copy(new File(path, "module/single/SuppressClass_1.ceylon"), sourceFile);
CeyloncTaskImpl compilerTask = getCompilerTask("module/single/module.ceylon", "module/single/SuppressClass.ceylon");
Boolean success = compilerTask.call();
assertTrue(success);
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
assertTrue(carFile.exists());
ZipFile car = new ZipFile(carFile);
ZipEntry oneClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/One.class");
assertNotNull(oneClass);
ZipEntry twoClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/Two.class");
assertNotNull(twoClass);
car.close();
copy(new File(path, "module/single/SuppressClass_2.ceylon"), sourceFile);
compilerTask = getCompilerTask("module/single/module.ceylon", "module/single/SuppressClass.ceylon");
success = compilerTask.call();
assertTrue(success);
carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
assertTrue(carFile.exists());
car = new ZipFile(carFile);
oneClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/One.class");
assertNotNull(oneClass);
twoClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/Two.class");
assertNull(twoClass);
car.close();
sourceFile.delete();
}
@Test
public void testMdlMultipleRepos(){
cleanCars("build/ceylon-cars-a");
cleanCars("build/ceylon-cars-b");
cleanCars("build/ceylon-cars-c");
// Compile the first module in its own repo
File repoA = new File("build/ceylon-cars-a");
repoA.mkdirs();
Boolean result = getCompilerTask(Arrays.asList("-out", repoA.getPath()),
"module/depend/a/module.ceylon", "module/depend/a/package.ceylon", "module/depend/a/A.ceylon").call();
Assert.assertEquals(Boolean.TRUE, result);
File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.depend.a", "6.6.6", repoA.getPath());
assertTrue(carFile.exists());
// make another repo for the second module
File repoB = new File("build/ceylon-cars-b");
repoB.mkdirs();
// then try to compile only one module (the other being loaded from its car)
result = getCompilerTask(Arrays.asList("-out", repoB.getPath(), "-rep", repoA.getPath()),
"module/depend/b/module.ceylon", "module/depend/b/package.ceylon", "module/depend/b/a.ceylon", "module/depend/b/B.ceylon").call();
Assert.assertEquals(Boolean.TRUE, result);
carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.depend.b", "6.6.6", repoB.getPath());
assertTrue(carFile.exists());
// make another repo for the third module
File repoC = new File("build/ceylon-cars-c");
repoC.mkdirs();
// then try to compile only one module (the others being loaded from their car)
result = getCompilerTask(Arrays.asList("-out", repoC.getPath(),
"-rep", repoA.getPath(), "-rep", repoB.getPath()),
"module/depend/c/module.ceylon", "module/depend/c/a.ceylon", "module/depend/c/b.ceylon").call();
Assert.assertEquals(Boolean.TRUE, result);
carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.depend.c", "6.6.6", repoC.getPath());
assertTrue(carFile.exists());
}
@Test
public void testMdlJarDependency() throws IOException{
// compile our java class
File outputFolder = new File("build/java-jar");
cleanCars(outputFolder.getPath());
outputFolder.mkdirs();
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
File javaFile = new File(path+"/module/jarDependency/java/JavaDependency.java");
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFile);
CompilationTask task = javaCompiler.getTask(null, null, null, Arrays.asList("-d", "build/java-jar", "-sourcepath", "test-src"), null, compilationUnits);
assertEquals(Boolean.TRUE, task.call());
File jarFolder = new File(outputFolder, "com/redhat/ceylon/compiler/java/test/cmr/module/jarDependency/java/1.0/");
jarFolder.mkdirs();
File jarFile = new File(jarFolder, "com.redhat.ceylon.compiler.java.test.cmr.module.jarDependency.java-1.0.jar");
// now jar it up
JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile));
ZipEntry entry = new ZipEntry("com/redhat/ceylon/compiler/java/test/cmr/module/jarDependency/java/JavaDependency.class");
outputStream.putNextEntry(entry);
FileInputStream inputStream = new FileInputStream(javaFile);
Util.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
// Try to compile the ceylon module
CeyloncTaskImpl ceylonTask = getCompilerTask(Arrays.asList("-out", destDir, "-rep", outputFolder.getPath()),
(DiagnosticListener<? super FileObject>)null,
"module/jarDependency/ceylon/module.ceylon", "module/jarDependency/ceylon/Foo.ceylon");
assertEquals(Boolean.TRUE, ceylonTask.call());
}
@Test
public void testMdlMavenDependency() throws IOException{
// Try to compile the ceylon module
CeyloncTaskImpl ceylonTask = getCompilerTask(Arrays.asList("-out", destDir, "-rep", "mvn:http://repo1.maven.org/maven2"),
(DiagnosticListener<? super FileObject>)null,
"module/maven/module.ceylon", "module/maven/foo.ceylon");
assertEquals(Boolean.TRUE, ceylonTask.call());
}
@Test
public void testMdlSourceArchive() throws IOException{
File sourceArchiveFile = getSourceArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
sourceArchiveFile.delete();
assertFalse(sourceArchiveFile.exists());
// compile one file
compile("module/single/module.ceylon");
// make sure it was created
assertTrue(sourceArchiveFile.exists());
JarFile sourceArchive = new JarFile(sourceArchiveFile);
assertEquals(1, countEntries(sourceArchive));
ZipEntry moduleClass = sourceArchive.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/module.ceylon");
assertNotNull(moduleClass);
sourceArchive.close();
// now compile another file
compile("module/single/subpackage/Subpackage.ceylon");
// MUST reopen it
sourceArchive = new JarFile(sourceArchiveFile);
assertEquals(2, countEntries(sourceArchive));
ZipEntry subpackageClass = sourceArchive.getEntry("com/redhat/ceylon/compiler/java/test/cmr/module/single/subpackage/Subpackage.ceylon");
assertNotNull(subpackageClass);
sourceArchive.close();
}
+ @Test
+ public void testMdlMultipleVersions(){
+ // Compile module A/1
+ Boolean result = getCompilerTask(Arrays.asList("-src", path+"/module/multiversion/a1"),
+ "module/multiversion/a1/a/module.ceylon", "module/multiversion/a1/a/package.ceylon", "module/multiversion/a1/a/A.ceylon").call();
+ Assert.assertEquals(Boolean.TRUE, result);
+
+ ErrorCollector collector = new ErrorCollector();
+ // Compile module A/2 with B importing A/1
+ result = getCompilerTask(Arrays.asList("-src", path+"/module/multiversion/a2:"+path+"/module/multiversion/b"),
+ collector,
+ "module/multiversion/a2/a/module.ceylon", "module/multiversion/a2/a/package.ceylon", "module/multiversion/a2/a/A.ceylon",
+ "module/multiversion/b/b/module.ceylon", "module/multiversion/b/b/B.ceylon").call();
+ Assert.assertEquals(Boolean.FALSE, result);
+
+ compareErrors(collector.actualErrors, new CompilerError(-1, "Trying to import or compile two different versions of the same module: a (1 and 2)"));
+ }
+
private int countEntries(JarFile jar) {
int count = 0;
Enumeration<JarEntry> entries = jar.entries();
while(entries.hasMoreElements()){
count++;
entries.nextElement();
}
return count;
}
@Test
public void testMdlSha1Signatures() throws IOException{
File sourceArchiveFile = getSourceArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
File sourceArchiveSignatureFile = new File(sourceArchiveFile.getPath()+".sha1");
File moduleArchiveFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.module.single", "6.6.6");
File moduleArchiveSignatureFile = new File(moduleArchiveFile.getPath()+".sha1");
// cleanup
sourceArchiveFile.delete();
sourceArchiveSignatureFile.delete();
moduleArchiveFile.delete();
moduleArchiveSignatureFile.delete();
// safety check
assertFalse(sourceArchiveFile.exists());
assertFalse(sourceArchiveSignatureFile.exists());
assertFalse(moduleArchiveFile.exists());
assertFalse(moduleArchiveSignatureFile.exists());
// compile one file
compile("module/single/module.ceylon");
// make sure everything was created
assertTrue(sourceArchiveFile.exists());
assertTrue(sourceArchiveSignatureFile.exists());
assertTrue(moduleArchiveFile.exists());
assertTrue(moduleArchiveSignatureFile.exists());
// check the signatures vaguely
checkSha1(sourceArchiveSignatureFile);
checkSha1(moduleArchiveSignatureFile);
}
private void checkSha1(File signatureFile) throws IOException {
Assert.assertEquals(40, signatureFile.length());
FileInputStream reader = new FileInputStream(signatureFile);
byte[] bytes = new byte[40];
Assert.assertEquals(40, reader.read(bytes));
reader.close();
char[] sha1 = new String(bytes, "ASCII").toCharArray();
for (int i = 0; i < sha1.length; i++) {
char c = sha1[i];
Assert.assertTrue((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F'));
}
}
}
| true | false | null | null |
diff --git a/test-src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest.java b/test-src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest.java
index 22da0b6d5..deab57618 100644
--- a/test-src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest.java
+++ b/test-src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest.java
@@ -1,493 +1,493 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.issues;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
public class IssuesTest extends CompilerTest {
@Test
public void testBug41(){
compile("Bug41.ceylon");
List<String> options = new ArrayList<String>();
options.addAll(defaultOptions);
options.add("-verbose");
options.add("-cp");
options.add(dir+File.pathSeparator+getModuleArchive("ceylon.language", TypeChecker.LANGUAGE_MODULE_VERSION, Util.getHomeRepository()));
Boolean result = getCompilerTask(options, "Bug41_2.ceylon").call();
Assert.assertEquals("Compilation worked", Boolean.TRUE, result);
}
@Test
public void testBug111(){
compareWithJavaSource("Bug111");
}
@Test
public void testBug151(){
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug151", "Bug151.ceylon");
}
@Test
public void testBug192(){
compareWithJavaSource("Bug192");
}
@Test
public void testBug193(){
compareWithJavaSource("Bug193");
}
@Test
public void testBug224(){
compareWithJavaSource("Bug224");
}
@Test
public void testBug227(){
compareWithJavaSource("Bug227");
}
@Test
public void testBug233(){
compile("Bug233_Java.java", "Bug233_Type.java");
compareWithJavaSource("Bug233");
}
@Test
public void testBug241(){
compareWithJavaSource("Bug241");
}
@Test
public void testBug242(){
compareWithJavaSource("Bug242");
}
@Test
public void testBug247(){
compareWithJavaSource("Bug247");
}
@Test
public void testBug248(){
compareWithJavaSource("Bug248");
}
@Test
public void testBug249(){
compareWithJavaSource("Bug249");
}
@Test
public void testBug253(){
compareWithJavaSource("Bug253");
}
@Test
public void testBug260(){
compareWithJavaSource("Bug260");
}
@Test
public void testBug261(){
compareWithJavaSource("Bug261");
}
@Test
public void testBug269(){
compareWithJavaSource("Bug269");
}
@Test
public void testBug270(){
compareWithJavaSource("Bug270");
}
@Test
public void testBug283() {
compareWithJavaSource("Bug283");
}
@Test
public void testBug291(){
compareWithJavaSource("Bug291");
}
@Test
public void testBug298(){
compareWithJavaSource("Bug298");
}
@Test
public void testBug299(){
compareWithJavaSource("Bug299");
}
@Test
public void testBug311(){
compareWithJavaSource("assert/Bug311");
}
@Test
public void testBug313(){
compareWithJavaSource("Bug313");
}
@Test
public void testBug323(){
compareWithJavaSource("Bug323");
}
@Test
public void testBug324(){
compareWithJavaSource("Bug324");
}
@Test
public void testBug327(){
compareWithJavaSource("Bug327");
}
@Test
public void testBug329(){
compareWithJavaSource("Bug329");
}
@Test
public void testBug330(){
// compile them both at the same time
compile("Bug330_1.ceylon", "Bug330_2.ceylon");
// compile them individually, loading the other half from the .car
compile("Bug330_1.ceylon");
compile("Bug330_2.ceylon");
}
@Test
public void testBug353(){
// compile them both at the same time
compile("Bug353_1.ceylon", "Bug353_2.ceylon");
}
@Test
public void testBug366(){
compareWithJavaSource("Bug366");
}
@Test
public void testBug399(){
compile("Bug399.ceylon");
}
@Test
public void testBug404(){
compareWithJavaSource("Bug404");
}
@Test
public void testBug406(){
compareWithJavaSource("Bug406");
}
@Test
public void testBug407(){
// make sure we don't get an NPE error
assertErrors("Bug407", new CompilerError(25, "specified expression must be assignable to declared type: Set<Map<String,Integer>.Entry<String,Integer>> is not assignable to Iterable<unknown>"));
}
@Test
public void testBug410(){
compareWithJavaSource("Bug410");
}
@Test
public void testBug441(){
compareWithJavaSource("Bug441");
}
@Test
public void testBug445(){
compareWithJavaSource("Bug445");
}
@Test
public void testBug446(){
compareWithJavaSource("Bug446");
}
@Test
public void testBug457(){
compareWithJavaSource("Bug457");
}
@Test
public void testBug458(){
compile("bug458/a/module.ceylon", "bug458/a/package.ceylon", "bug458/a/a.ceylon");
compile("bug458/b/module.ceylon", "bug458/b/b.ceylon");
}
@Test
public void testBug475(){
compareWithJavaSource("Bug475");
}
@Test
public void testBug476(){
compareWithJavaSource("Bug476");
}
@Test
public void testBug477(){
compareWithJavaSource("Bug477");
}
@Test
public void testBug479(){
compareWithJavaSource("Bug479");
}
@Test
public void testBug490(){
compareWithJavaSource("Bug490");
}
@Test
public void testBug493(){
compareWithJavaSource("bug493/module");
}
@Test
public void testBug494(){
compareWithJavaSource("Bug494");
}
@Test
public void testBug504(){
compile("Bug504.ceylon");
}
@Test
public void testBug508(){
compareWithJavaSource("Bug508");
}
@Test
public void testBug509(){
compareWithJavaSource("Bug509");
}
@Test
public void testBug510(){
compareWithJavaSource("bug510/Bug510");
}
@Test
public void testBug517(){
compareWithJavaSource("Bug517");
}
@Test
public void testBug518(){
compareWithJavaSource("Bug518");
}
@Test
public void testBug526(){
compareWithJavaSource("Bug526");
}
@Test
public void testBug533(){
compareWithJavaSource("Bug533");
}
@Test
public void testBug540(){
compareWithJavaSource("Bug540");
}
@Test
public void testBug544(){
compareWithJavaSource("Bug544");
}
@Test
public void testBug548() throws IOException{
compile("bug548/Bug548_1.ceylon");
compile("bug548/Bug548_2.ceylon");
}
@Test
public void testBug552(){
compareWithJavaSource("Bug552");
}
@Test
public void testBug568(){
compareWithJavaSource("Bug568");
}
@Test
public void testBug569(){
compile("bug569/module.ceylon", "bug569/Foo.ceylon", "bug569/z/Bar.ceylon");
}
@Test
public void testBug586(){
compareWithJavaSource("Bug586");
}
@Test
public void testBug588(){
compareWithJavaSource("Bug588");
}
@Test
public void testBug589(){
compareWithJavaSource("Bug589");
}
@Test
public void testBug591(){
compile("bug591/Bug591_1.ceylon", "bug591/Bug591_2.ceylon");
compile("bug591/Bug591_2.ceylon");
}
@Test
public void testBug592(){
compilesWithoutWarnings("Bug592.ceylon");
}
@Test
public void testBug593(){
assertErrors("Bug593",
new CompilerError(27, "argument must be assignable to parameter arg1 of newFileSystem: HashMap<String,Object> is not assignable to Map<String,Object>?"));
}
@Test
public void testBug594(){
compareWithJavaSource("Bug594");
}
@Test
public void testBug597(){
compareWithJavaSource("Bug597");
}
@Test
public void testBug601(){
compareWithJavaSource("Bug601");
}
@Test
public void testBug604(){
compareWithJavaSource("Bug604");
}
@Test
public void testBug605(){
compareWithJavaSource("bug605/Bug605");
}
@Test
public void testBug606(){
compareWithJavaSource("Bug606");
}
@Test
public void testBug607(){
compareWithJavaSource("Bug607");
}
@Test
public void testBug608(){
compareWithJavaSource("Bug608");
}
@Test
public void testBug609(){
compareWithJavaSource("bug609/Bug609");
}
@Test
public void testBug615(){
compareWithJavaSource("Bug615");
}
@Test
public void testBug616(){
compareWithJavaSource("Bug616");
}
@Test
public void testBug620(){
compareWithJavaSource("Bug620");
}
@Test
public void testBug623(){
compareWithJavaSource("Bug623");
}
@Test
public void testBug626(){
compareWithJavaSource("Bug626");
}
@Test
public void testBug627(){
compareWithJavaSource("Bug627");
}
@Test
public void testBug630(){
compareWithJavaSource("Bug630a");
compareWithJavaSource("Bug630b");
}
@Test
public void testBug639(){
compareWithJavaSource("Bug639");
}
@Test
public void testBug640(){
compareWithJavaSource("bug640/Bug640");
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug640.bug640", "bug640/Bug640.ceylon");
}
@Test
- public void testBug641_fail(){
+ public void testBug641(){
compareWithJavaSource("Bug641");
}
}
| true | false | null | null |
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java
index 12cb7e23..6c96ebff 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java
@@ -1,276 +1,276 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.fediz.service.idp.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.apache.cxf.fediz.core.util.DOMUtils;
import org.apache.cxf.fediz.service.idp.model.IDPConfig;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.util.Base64;
import org.apache.ws.security.util.UUIDGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.cxf.fediz.core.FederationConstants.SAML2_METADATA_NS;
import static org.apache.cxf.fediz.core.FederationConstants.SCHEMA_INSTANCE_NS;
import static org.apache.cxf.fediz.core.FederationConstants.WS_ADDRESSING_NS;
import static org.apache.cxf.fediz.core.FederationConstants.WS_FEDERATION_NS;
public class MetadataWriter {
private static final Logger LOG = LoggerFactory.getLogger(MetadataWriter.class);
private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance();
private static final XMLSignatureFactory XML_SIGNATURE_FACTORY = XMLSignatureFactory.getInstance("DOM");
private static final DocumentBuilderFactory DOC_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
static {
DOC_BUILDER_FACTORY.setNamespaceAware(true);
}
//CHECKSTYLE:OFF
public Document getMetaData(IDPConfig config) throws RuntimeException {
//Return as text/xml
try {
Crypto crypto = CertsUtils.createCrypto(config.getCertificate());
ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
- Writer streamWriter = new OutputStreamWriter(bout);
+ Writer streamWriter = new OutputStreamWriter(bout, "UTF-8");
XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter);
- writer.writeStartDocument();
+ writer.writeStartDocument("UTF-8", "1.0");
String referenceID = "_" + UUIDGenerator.getUUID();
writer.writeStartElement("", "EntityDescriptor", SAML2_METADATA_NS);
writer.writeAttribute("ID", referenceID);
writer.writeAttribute("entityID", config.getIdpUrl());
writer.writeNamespace("fed", WS_FEDERATION_NS);
writer.writeNamespace("wsa", WS_ADDRESSING_NS);
writer.writeNamespace("auth", WS_FEDERATION_NS);
writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
writer.writeStartElement("fed", "RoleDescriptor", WS_FEDERATION_NS);
writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType");
writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) {
writer.writeAttribute("ServiceDescription", config.getServiceDescription());
}
if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) {
writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName());
}
//http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd
//missing organization, contactperson
//KeyDescriptor
writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS);
writer.writeAttribute("use", "signing");
writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
try {
X509Certificate cert = CertsUtils.getX509Certificate(crypto, null);
writer.writeCharacters(Base64.encode(cert.getEncoded()));
} catch (Exception ex) {
LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
}
writer.writeEndElement(); // X509Certificate
writer.writeEndElement(); // X509Data
writer.writeEndElement(); // KeyInfo
writer.writeEndElement(); // KeyDescriptor
// SecurityTokenServiceEndpoint
writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS);
writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
writer.writeCharacters(config.getStsUrl());
writer.writeEndElement(); // Address
writer.writeEndElement(); // EndpointReference
writer.writeEndElement(); // SecurityTokenServiceEndpoint
// PassiveRequestorEndpoint
writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
writer.writeCharacters(config.getIdpUrl());
writer.writeEndElement(); // Address
writer.writeEndElement(); // EndpointReference
writer.writeEndElement(); // PassiveRequestorEndpoint
// create ClaimsType section
if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) {
writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS);
for (String claim : config.getClaimTypesOffered()) {
writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS);
writer.writeAttribute("Uri", claim);
writer.writeAttribute("Optional", "true");
writer.writeEndElement(); // ClaimType
}
writer.writeEndElement(); // ClaimTypesOffered
}
writer.writeEndElement(); // RoleDescriptor
writer.writeEndElement(); // EntityDescriptor
writer.writeEndDocument();
streamWriter.flush();
bout.flush();
//
if (LOG.isDebugEnabled()) {
String out = new String(bout.toByteArray());
LOG.debug("***************** unsigned ****************");
LOG.debug(out);
LOG.debug("***************** unsigned ****************");
}
InputStream is = new ByteArrayInputStream(bout.toByteArray());
ByteArrayOutputStream result = signMetaInfo(crypto, config.getCertificatePassword(), is, referenceID);
if (result != null) {
is = new ByteArrayInputStream(result.toByteArray());
} else {
throw new RuntimeException("Failed to sign the metadata document: result=null");
}
return DOMUtils.readXml(is);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
LOG.error("Error creating service metadata information ", e);
throw new RuntimeException("Error creating service metadata information: " + e.getMessage());
}
}
private ByteArrayOutputStream signMetaInfo(Crypto crypto, String keyPassword, InputStream metaInfo, String referenceID) throws Exception {
String keyAlias = crypto.getDefaultX509Identifier(); //only one key supported in JKS
X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias);
// Create a Reference to the enveloped document (in this case,
// you are signing the whole document, so a URI of "" signifies
// that, and also specify the SHA1 digest algorithm and
// the ENVELOPED Transform.
Reference ref = XML_SIGNATURE_FACTORY.newReference("#" + referenceID, XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null), Collections
.singletonList(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec)null)), null, null);
String signatureMethod = null;
if ("SHA1withDSA".equals(cert.getSigAlgName())) {
signatureMethod = SignatureMethod.DSA_SHA1;
} else if ("SHA1withRSA".equals(cert.getSigAlgName())) {
signatureMethod = SignatureMethod.RSA_SHA1;
} else if ("SHA256withRSA".equals(cert.getSigAlgName())) {
signatureMethod = SignatureMethod.RSA_SHA1;
} else {
LOG.error("Unsupported signature method: " + cert.getSigAlgName());
throw new RuntimeException("Unsupported signature method: " + cert.getSigAlgName());
}
// Create the SignedInfo.
SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec)null), XML_SIGNATURE_FACTORY
.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref));
// .newSignatureMethod(cert.getSigAlgOID(), null), Collections.singletonList(ref));
PrivateKey keyEntry = crypto.getPrivateKey(keyAlias, keyPassword);
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();
List<Object> x509Content = new ArrayList<Object>();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Instantiate the document to be signed.
Document doc = DOC_BUILDER_FACTORY.newDocumentBuilder().parse(metaInfo);
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
DOMSignContext dsc = new DOMSignContext(keyEntry, doc.getDocumentElement());
dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID");
dsc.setNextSibling(doc.getDocumentElement().getFirstChild());
// Create the XMLSignature, but don't sign it yet.
XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
// Output the resulting document.
ByteArrayOutputStream os = new ByteArrayOutputStream(8192);
Transformer trans = TRANSFORMER_FACTORY.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os));
os.flush();
return os;
}
}
| false | true | public Document getMetaData(IDPConfig config) throws RuntimeException {
//Return as text/xml
try {
Crypto crypto = CertsUtils.createCrypto(config.getCertificate());
ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
Writer streamWriter = new OutputStreamWriter(bout);
XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter);
writer.writeStartDocument();
String referenceID = "_" + UUIDGenerator.getUUID();
writer.writeStartElement("", "EntityDescriptor", SAML2_METADATA_NS);
writer.writeAttribute("ID", referenceID);
writer.writeAttribute("entityID", config.getIdpUrl());
writer.writeNamespace("fed", WS_FEDERATION_NS);
writer.writeNamespace("wsa", WS_ADDRESSING_NS);
writer.writeNamespace("auth", WS_FEDERATION_NS);
writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
writer.writeStartElement("fed", "RoleDescriptor", WS_FEDERATION_NS);
writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType");
writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) {
writer.writeAttribute("ServiceDescription", config.getServiceDescription());
}
if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) {
writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName());
}
//http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd
//missing organization, contactperson
//KeyDescriptor
writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS);
writer.writeAttribute("use", "signing");
writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
try {
X509Certificate cert = CertsUtils.getX509Certificate(crypto, null);
writer.writeCharacters(Base64.encode(cert.getEncoded()));
} catch (Exception ex) {
LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
}
writer.writeEndElement(); // X509Certificate
writer.writeEndElement(); // X509Data
writer.writeEndElement(); // KeyInfo
writer.writeEndElement(); // KeyDescriptor
// SecurityTokenServiceEndpoint
writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS);
writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
writer.writeCharacters(config.getStsUrl());
writer.writeEndElement(); // Address
writer.writeEndElement(); // EndpointReference
writer.writeEndElement(); // SecurityTokenServiceEndpoint
// PassiveRequestorEndpoint
writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
writer.writeCharacters(config.getIdpUrl());
writer.writeEndElement(); // Address
writer.writeEndElement(); // EndpointReference
writer.writeEndElement(); // PassiveRequestorEndpoint
// create ClaimsType section
if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) {
writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS);
for (String claim : config.getClaimTypesOffered()) {
writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS);
writer.writeAttribute("Uri", claim);
writer.writeAttribute("Optional", "true");
writer.writeEndElement(); // ClaimType
}
writer.writeEndElement(); // ClaimTypesOffered
}
writer.writeEndElement(); // RoleDescriptor
writer.writeEndElement(); // EntityDescriptor
writer.writeEndDocument();
streamWriter.flush();
bout.flush();
//
if (LOG.isDebugEnabled()) {
String out = new String(bout.toByteArray());
LOG.debug("***************** unsigned ****************");
LOG.debug(out);
LOG.debug("***************** unsigned ****************");
}
InputStream is = new ByteArrayInputStream(bout.toByteArray());
ByteArrayOutputStream result = signMetaInfo(crypto, config.getCertificatePassword(), is, referenceID);
if (result != null) {
is = new ByteArrayInputStream(result.toByteArray());
} else {
throw new RuntimeException("Failed to sign the metadata document: result=null");
}
return DOMUtils.readXml(is);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
LOG.error("Error creating service metadata information ", e);
throw new RuntimeException("Error creating service metadata information: " + e.getMessage());
}
}
| public Document getMetaData(IDPConfig config) throws RuntimeException {
//Return as text/xml
try {
Crypto crypto = CertsUtils.createCrypto(config.getCertificate());
ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
Writer streamWriter = new OutputStreamWriter(bout, "UTF-8");
XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter);
writer.writeStartDocument("UTF-8", "1.0");
String referenceID = "_" + UUIDGenerator.getUUID();
writer.writeStartElement("", "EntityDescriptor", SAML2_METADATA_NS);
writer.writeAttribute("ID", referenceID);
writer.writeAttribute("entityID", config.getIdpUrl());
writer.writeNamespace("fed", WS_FEDERATION_NS);
writer.writeNamespace("wsa", WS_ADDRESSING_NS);
writer.writeNamespace("auth", WS_FEDERATION_NS);
writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
writer.writeStartElement("fed", "RoleDescriptor", WS_FEDERATION_NS);
writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType");
writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) {
writer.writeAttribute("ServiceDescription", config.getServiceDescription());
}
if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) {
writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName());
}
//http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd
//missing organization, contactperson
//KeyDescriptor
writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS);
writer.writeAttribute("use", "signing");
writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
try {
X509Certificate cert = CertsUtils.getX509Certificate(crypto, null);
writer.writeCharacters(Base64.encode(cert.getEncoded()));
} catch (Exception ex) {
LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
}
writer.writeEndElement(); // X509Certificate
writer.writeEndElement(); // X509Data
writer.writeEndElement(); // KeyInfo
writer.writeEndElement(); // KeyDescriptor
// SecurityTokenServiceEndpoint
writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS);
writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
writer.writeCharacters(config.getStsUrl());
writer.writeEndElement(); // Address
writer.writeEndElement(); // EndpointReference
writer.writeEndElement(); // SecurityTokenServiceEndpoint
// PassiveRequestorEndpoint
writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
writer.writeCharacters(config.getIdpUrl());
writer.writeEndElement(); // Address
writer.writeEndElement(); // EndpointReference
writer.writeEndElement(); // PassiveRequestorEndpoint
// create ClaimsType section
if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) {
writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS);
for (String claim : config.getClaimTypesOffered()) {
writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS);
writer.writeAttribute("Uri", claim);
writer.writeAttribute("Optional", "true");
writer.writeEndElement(); // ClaimType
}
writer.writeEndElement(); // ClaimTypesOffered
}
writer.writeEndElement(); // RoleDescriptor
writer.writeEndElement(); // EntityDescriptor
writer.writeEndDocument();
streamWriter.flush();
bout.flush();
//
if (LOG.isDebugEnabled()) {
String out = new String(bout.toByteArray());
LOG.debug("***************** unsigned ****************");
LOG.debug(out);
LOG.debug("***************** unsigned ****************");
}
InputStream is = new ByteArrayInputStream(bout.toByteArray());
ByteArrayOutputStream result = signMetaInfo(crypto, config.getCertificatePassword(), is, referenceID);
if (result != null) {
is = new ByteArrayInputStream(result.toByteArray());
} else {
throw new RuntimeException("Failed to sign the metadata document: result=null");
}
return DOMUtils.readXml(is);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
LOG.error("Error creating service metadata information ", e);
throw new RuntimeException("Error creating service metadata information: " + e.getMessage());
}
}
|
diff --git a/farrago/src/com/lucidera/farrago/namespace/flatfile/FlatFileDataServer.java b/farrago/src/com/lucidera/farrago/namespace/flatfile/FlatFileDataServer.java
index 0a6d8b4aa..5f209bf82 100644
--- a/farrago/src/com/lucidera/farrago/namespace/flatfile/FlatFileDataServer.java
+++ b/farrago/src/com/lucidera/farrago/namespace/flatfile/FlatFileDataServer.java
@@ -1,478 +1,483 @@
/*
// $Id$
// Farrago is an extensible data management system.
// Copyright (C) 2005-2005 LucidEra, Inc.
// Copyright (C) 2005-2005 The Eigenbase Project
// Portions Copyright (C) 2003-2005 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.lucidera.farrago.namespace.flatfile;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import javax.sql.*;
import net.sf.farrago.namespace.*;
import net.sf.farrago.namespace.impl.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.trace.*;
import net.sf.farrago.type.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.util.*;
/**
* FlatFileDataServer provides an implementation of the {@link
* FarragoMedDataServer} interface.
*
* @author John Pham
* @version $Id$
*/
class FlatFileDataServer
extends MedAbstractDataServer
{
//~ Static fields/initializers ---------------------------------------------
private static final Logger tracer =
FarragoTrace.getClassTracer(FlatFileDataServer.class);
private static int DESCRIBE_COLUMN_LENGTH = 2048;
private static String DESCRIBE_COLUMN_NAME = "FIELD_SIZES";
private static String QUALIFIED_NAME_SEPARATOR = ".";
private static String SQL_QUOTE_CHARACTER = "\"";
//~ Instance fields --------------------------------------------------------
private MedAbstractDataWrapper wrapper;
FlatFileParams params;
//~ Constructors -----------------------------------------------------------
FlatFileDataServer(
MedAbstractDataWrapper wrapper,
String serverMofId,
Properties props)
{
super(serverMofId, props);
this.wrapper = wrapper;
}
//~ Methods ----------------------------------------------------------------
void initialize()
throws SQLException
{
params = new FlatFileParams(getProperties());
params.decode();
// throw an error if directory doesn't exist
File dir = new File(params.getDirectory());
if (!dir.exists() && !params.getDirectory().equals("")) {
throw FarragoResource.instance().InvalidDirectory.ex(
params.getDirectory());
}
// throw an error when using fixed position parsing mode
// with incompatible parameters
if (params.getFieldDelimiter() == 0) {
if ((params.getQuoteChar() != 0)
|| (params.getEscapeChar() != 0)) {
throw FarragoResource.instance().FlatFileInvalidFixedPosParams
.ex();
}
}
+
+ if (params.getMapped() && params.getWithHeader() == false) {
+ throw FarragoResource.instance().FlatFileMappedRequiresWithHeader
+ .ex();
+ }
}
// implement FarragoMedDataServer
public FarragoMedNameDirectory getNameDirectory()
throws SQLException
{
// scan directory and files for metadata (Phase II)
return
new FlatFileNameDirectory(
this,
FarragoMedMetadataQuery.OTN_SCHEMA);
}
// implement FarragoMedDataServer
public FarragoMedColumnSet newColumnSet(
String [] localName,
Properties tableProps,
FarragoTypeFactory typeFactory,
RelDataType rowType,
Map<String,Properties> columnPropMap)
throws SQLException
{
String schemaName = getSchemaName(localName);
FlatFileParams.SchemaType schemaType =
FlatFileParams.getSchemaType(schemaName, true);
if (rowType == null) {
// scan control file/data file for metadata (Phase II)
String filename =
tableProps.getProperty(
FlatFileColumnSet.PROP_FILENAME);
if (filename == null) {
filename = getTableName(localName);
}
// check data file exists
String dataFilePath =
params.getDirectory() + filename
+ params.getFileExtenstion();
File dataFile = new File(dataFilePath);
if (!dataFile.exists()) {
return null;
}
String ctrlFilePath =
params.getDirectory() + filename
+ params.getControlFileExtenstion();
FlatFileBCPFile bcpFile =
new FlatFileBCPFile(ctrlFilePath, typeFactory);
rowType =
deriveRowType(
typeFactory,
schemaType,
localName,
filename,
bcpFile);
}
if (rowType == null) {
return null;
}
return
new FlatFileColumnSet(
localName,
rowType,
params,
tableProps,
schemaType);
}
// implement FarragoMedDataServer
public Object getRuntimeSupport(Object param)
throws SQLException
{
return null;
}
// implement FarragoMedDataServer
public void registerRules(RelOptPlanner planner)
{
super.registerRules(planner);
}
// implement FarragoAllocation
public void closeAllocation()
{
super.closeAllocation();
}
MedAbstractDataWrapper getWrapper()
{
return wrapper;
}
RelDataType createRowType(
FarragoTypeFactory typeFactory,
RelDataType [] types,
String [] names)
{
return typeFactory.createStructType(types, names);
}
/**
* Derives the row type of a table when other type information is not
* available. Also derives the row type of internal queries.
*
* @throws SQLException
*/
private RelDataType deriveRowType(
FarragoTypeFactory typeFactory,
FlatFileParams.SchemaType schemaType,
String [] localName,
String filename,
FlatFileBCPFile bcpFile)
throws SQLException
{
List<RelDataType> fieldTypes = new ArrayList<RelDataType>();
List<String> fieldNames = new ArrayList<String>();
String [] foreignName =
{
this.getProperties().getProperty("NAME"),
FlatFileParams.SchemaType.QUERY.getSchemaName(),
filename
};
// Cannot describe or sample a fixed position data file
if (params.getFieldDelimiter() == 0) {
switch (schemaType) {
case DESCRIBE:
case SAMPLE:
throw FarragoResource.instance().FlatFileNoFixedPosSample.ex(
filename);
}
}
switch (schemaType) {
case DESCRIBE:
fieldTypes.add(
typeFactory.createSqlType(
SqlTypeName.Varchar,
DESCRIBE_COLUMN_LENGTH));
fieldNames.add(DESCRIBE_COLUMN_NAME);
break;
case SAMPLE:
List<Integer> fieldSizes = getFieldSizes(foreignName);
int i = 1;
for (Integer size : fieldSizes) {
RelDataType type =
typeFactory.createSqlType(
SqlTypeName.Varchar,
size.intValue());
RelDataType nullableType =
typeFactory.createTypeWithNullability(type, true);
fieldTypes.add(nullableType);
fieldNames.add("COL" + i++);
}
break;
case QUERY:
synchronized (FlatFileBCPFile.class) {
if (!bcpFile.exists()) {
if (!sampleAndCreateBcp(foreignName, bcpFile)) {
return null;
}
}
if (bcpFile.parse()) {
return
createRowType(
typeFactory,
bcpFile.types,
bcpFile.colNames);
}
// couldn't parse control file
return null;
}
default:
return null;
}
return typeFactory.createStructType(fieldTypes, fieldNames);
}
/**
* Returns the sizes of a flat file's fields, based upon an internal
* describe query.
*/
private List<Integer> getFieldSizes(String [] localName)
throws SQLException
{
// Attempt to issue a loopback query into Farrago to
// get the number of rows to produce.
DataSource loopbackDataSource = getLoopbackDataSource();
Connection connection = null;
if (loopbackDataSource != null) {
try {
connection = loopbackDataSource.getConnection();
Statement stmt = connection.createStatement();
String sql = getDescribeQuery(localName);
ResultSet resultSet = stmt.executeQuery(sql);
if (resultSet.next()) {
String result = resultSet.getString(1);
StringTokenizer parser = new StringTokenizer(result);
List<Integer> sizes = new ArrayList<Integer>();
while (parser.hasMoreTokens()) {
String token = parser.nextToken();
Integer columnSize;
try {
columnSize = Integer.valueOf(token);
} catch (NumberFormatException e) {
throw Util.newInternal(
"failed to parse sample desc: '" + result
+ "'");
}
sizes.add(columnSize);
}
return sizes;
}
} finally {
// It's OK not to clean up stmt and resultSet;
// connection.close() will do that for us.
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
tracer.severe("could not close connection");
}
}
}
}
return null;
}
/**
* Creates the given control file based on an internal sample query.
*/
public boolean sampleAndCreateBcp(
String [] localName,
FlatFileBCPFile bcpFile)
throws SQLException
{
// Attempt to issue a loopback query into Farrago to
// get sample data back
DataSource loopbackDataSource = getLoopbackDataSource();
Connection connection = null;
if (loopbackDataSource != null) {
try {
connection = loopbackDataSource.getConnection();
Statement stmt = connection.createStatement();
String sql = getSampleQuery(localName);
ResultSet resultSet = stmt.executeQuery(sql);
ResultSetMetaData rsmeta = resultSet.getMetaData();
String [] cols = new String[rsmeta.getColumnCount()];
String [] numRows =
{ Integer.toString(rsmeta.getColumnCount()) };
if (!bcpFile.create()) { // write version
throw FarragoResource.instance().FileWriteFailed.ex(
bcpFile.fileName);
}
if (!bcpFile.write(numRows, null)) { // write numCols
throw FarragoResource.instance().FileWriteFailed.ex(
bcpFile.fileName);
}
boolean skipNext = params.getWithHeader();
while (resultSet.next()) {
for (int j = 0; j < cols.length; j++) {
cols[j] = resultSet.getString(j + 1);
}
if (skipNext) {
skipNext = false;
bcpFile.update(cols, true);
} else {
bcpFile.update(cols, false);
}
}
if (!bcpFile.write(cols, params)) {
throw FarragoResource.instance().FileWriteFailed.ex(
bcpFile.fileName);
}
return true;
} finally {
// It's OK not to clean up stmt and resultSet;
// connection.close() will do that for us.
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
tracer.severe("could not close connection");
}
}
}
}
return false;
}
/**
* Constructs an internal query to describe the results of sampling
*/
private String getDescribeQuery(String [] localName)
{
assert (localName.length == 3);
String [] newName =
setSchemaName(
localName,
FlatFileParams.SchemaType.DESCRIBE.getSchemaName());
return "select * from " + getQualifiedName(newName);
}
/**
* Constructs an internal query to sample
*/
private String getSampleQuery(String [] localName)
{
assert (localName.length == 3);
String [] newName =
setSchemaName(
localName,
FlatFileParams.SchemaType.SAMPLE.getSchemaName());
return "select * from " + getQualifiedName(newName);
}
/**
* Constructs a qualified (multi-part) name
*/
private String getQualifiedName(String [] localName)
{
String qual = quoteName(localName[0]);
for (int i = 1; i < localName.length; i++) {
qual += QUALIFIED_NAME_SEPARATOR + quoteName(localName[i]);
}
return qual;
}
/**
* Constructs a quoted name
*/
private String quoteName(String name)
{
return SQL_QUOTE_CHARACTER + name + SQL_QUOTE_CHARACTER;
}
/**
* Returns the last name of localName. TODO: move this into a better place
*/
private String getTableName(String [] localName)
{
assert (localName.length > 0);
return localName[localName.length - 1];
}
/**
* Returns the second to last name of localName. TODO: move this into a
* better place
*/
private String getSchemaName(String [] localName)
{
assert (localName.length > 1);
return localName[localName.length - 2];
}
/**
* Sets the second to last name of localName. TODO: move this into a better
* place
*/
private String [] setSchemaName(String [] localName, String schemaName)
{
String [] newName = localName.clone();
assert (newName.length > 1);
newName[newName.length - 2] = schemaName;
return newName;
}
}
// End FlatFileDataServer.java
| true | false | null | null |
diff --git a/src/main/java/test/cli/cloudify/CommandTestUtils.java b/src/main/java/test/cli/cloudify/CommandTestUtils.java
index 66b1595a..594afd74 100644
--- a/src/main/java/test/cli/cloudify/CommandTestUtils.java
+++ b/src/main/java/test/cli/cloudify/CommandTestUtils.java
@@ -1,204 +1,208 @@
package test.cli.cloudify;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicReference;
import framework.tools.SGTestHelper;
import framework.utils.AssertUtils;
import framework.utils.LogUtils;
import framework.utils.ScriptUtils;
public class CommandTestUtils {
/**
* Runs the specified cloudify commands and outputs the result log.
* @param command - The actual cloudify commands delimited by ';'.
* @param wait - used for determining if to wait for command
* @param failCommand - used for determining if the command is expected to fail
* @return String - log output or null if wait is false
* @throws IOException
* @throws InterruptedException
*/
public static String runCommand(final String command, boolean wait, boolean failCommand) throws IOException, InterruptedException {
return runLocalCommand( getCloudifyCommand(command), wait, failCommand);
}
/**
* Runs the specified cloudify commands and outputs the result log.
* @param command - The actual cloudify commands delimited by ';'.
* @return the cloudify output, and the exitcode
* @throws IOException
* @throws InterruptedException
*/
public static ProcessResult runCloudifyCommandAndWait(final String cloudifyCommand) throws IOException, InterruptedException {
final Process process = startProcess(getCloudifyCommand(cloudifyCommand));
- return handleCliOutput(process);
+ ProcessResult handleCliOutput = handleCliOutput(process);
+ if (handleCliOutput.getExitcode() != 0) {
+ AssertUtils.assertFail("In RunCommand: Process did not complete successfully. " + handleCliOutput);
+ }
+ return handleCliOutput;
}
private static String getCloudifyCommand(String command) {
final String commandExtention = getCommandExtention();
final String cloudifyPath = ScriptUtils.getBuildPath()+
MessageFormat.format("{0}tools{0}cli{0}cloudify.{1} ", File.separatorChar, commandExtention);
return (cloudifyPath + command).replace("\\", "/");
}
public static String runLocalCommand(final String command, boolean wait, boolean failCommand) throws IOException, InterruptedException {
final Process process = startProcess(command);
if(wait)
return handleCliOutput(process, failCommand);
else
return null;
}
private static Process startProcess(String command)
throws IOException {
String cmdLine = command;
if (isWindows()) {
// need to use the call command to intercept the cloudify batch file return code.
cmdLine = "cmd /c call " + cmdLine;
}
final String[] parts = cmdLine.split(" ");
final ProcessBuilder pb = new ProcessBuilder(parts);
pb.redirectErrorStream(true);
LogUtils.log("Executing Command line: " + cmdLine);
final Process process = pb.start();
return process;
}
public static class ProcessResult {
private final String output;
private final int exitcode;
public ProcessResult(String output, int exitcode) {
this.output = output;
this.exitcode = exitcode;
}
@Override
public String toString() {
return "ProcessResult [output=" + getOutput() + ", exitcode=" + getExitcode()
+ "]";
}
public String getOutput() {
return output;
}
public int getExitcode() {
return exitcode;
}
}
private static String handleCliOutput(Process process, boolean failCommand) throws IOException, InterruptedException{
ProcessResult result = handleCliOutput(process);
if (result.getExitcode() != 0 && !failCommand) {
AssertUtils.assertFail("In RunCommand: Process did not complete successfully. " + result);
}
return result.output;
}
private static ProcessResult handleCliOutput(Process process) throws InterruptedException {
// Print CLI output if exists.
final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
final StringBuilder consoleOutput = new StringBuilder("");
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
Thread thread = new Thread(new Runnable() {
String line = null;
@Override
public void run() {
try {
while ((line = br.readLine()) != null) {
LogUtils.log(line);
consoleOutput.append(line + "\n");
}
} catch (Throwable e) {
exception.set(e);
}
}
});
thread.setDaemon(true);
thread.start();
int exitcode = process.waitFor();
thread.join(5000);
if (exception.get() != null) {
AssertUtils.assertFail("Failed to get process output. output="+consoleOutput,exception.get());
}
String stdout = consoleOutput.toString();
return new ProcessResult(stdout, exitcode);
}
/**
* @param command
* @return
* @throws IOException
* @throws InterruptedException
*/
public static String runCommandAndWait(final String command) throws IOException, InterruptedException {
return runCommand(command, true, false);
}
/**
* @param command
* @return
* @throws IOException
* @throws InterruptedException
*/
public static String runCommandExpectedFail(final String command) throws IOException, InterruptedException {
return runCommand(command, true, true);
}
public static String runCommand(final String command) throws IOException, InterruptedException {
return runCommand(command, false, false);
}
private static String getCommandExtention() {
String osExtention;
if (isWindows()) {
osExtention = "bat";
} else {
osExtention = "sh";
}
return osExtention;
}
public static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().startsWith("win");
}
public static String getPath(String relativePath) {
return new File(SGTestHelper.getSGTestRootDir(), relativePath).getAbsolutePath().replace('\\', '/');
}
public static String getBuildServicesPath() {
return SGTestHelper.getBuildDir() + "/recipes/services";
}
public static String getBuildApplicationsPath() {
return SGTestHelper.getBuildDir() + "/recipes/apps";
}
}
| true | false | null | null |
diff --git a/src/framework/utils/ScriptUtils.java b/src/framework/utils/ScriptUtils.java
index 7fafeb25..7bf85b17 100644
--- a/src/framework/utils/ScriptUtils.java
+++ b/src/framework/utils/ScriptUtils.java
@@ -1,427 +1,427 @@
package framework.utils;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.codehaus.groovy.control.CompilationFailedException;
import com.j_spaces.kernel.PlatformVersion;
public class ScriptUtils {
/**
* this method should be used to forcefully kill windows processes by pid
* @param pid - the process id of witch to kill
* @return
* @throws IOException
* @throws InterruptedException
*/
public static int killWindowsProcess(int pid) throws IOException, InterruptedException {
String cmdLine = "cmd /c call taskkill /pid " + pid + " /F";
String[] parts = cmdLine.split(" ");
ProcessBuilder pb = new ProcessBuilder(parts);
LogUtils.log("Executing Command line: " + cmdLine);
Process process = pb.start();
int result = process.waitFor();
return result;
}
@SuppressWarnings("deprecation")
public static String runScript(String args, long timeout) throws Exception {
RunScript runScript = new RunScript(args);
Thread script = new Thread(runScript);
script.start();
Thread.sleep(timeout);
script.stop();
runScript.kill();
return runScript.getScriptOutput();
}
public static RunScript runScript(String args) throws Exception {
RunScript runScript = new RunScript(args);
Thread script = new Thread(runScript);
script.start();
return runScript;
}
public static class RunScript implements Runnable {
private String[] args;
private String scriptFilename;
private String binPath;
private StringBuilder sb = new StringBuilder();
private Process process;
public RunScript(String args) {
this.args = args.split(" ");
scriptFilename = this.args[0];
scriptFilename += getScriptSuffix();
binPath = getBuildBinPath();
this.args[0] = binPath + "/" + scriptFilename;
}
public void run() {
String line;
ProcessBuilder pb = new ProcessBuilder(args);
pb.directory(new File(binPath));
pb.redirectErrorStream(true);
try {
process = pb.start();
InputStreamReader isr = new InputStreamReader(process.getInputStream());
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getScriptOutput() {
return sb.toString();
}
public RunScript(String args, boolean relativeToGigaspacesBinDir) {
this.args = args.split(" ");
if (relativeToGigaspacesBinDir) {
scriptFilename = this.args[0];
scriptFilename += getScriptSuffix();
binPath = getBuildBinPath();
this.args[0] = binPath + "/" + scriptFilename;
}
}
public void kill() throws IOException, InterruptedException {
String scriptOutput = sb.toString();
//This regular expression captures the script's pid
String regex = "(?:Log file:.+-)([0-9]+)(?:\\.log)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(scriptOutput);
while (matcher.find()) {
int pid = Integer.parseInt(matcher.group(1));
String processIdAsString = Integer.toString(pid);
try {
if (isLinuxMachine()) {
new ProcessBuilder("kill", "-9", processIdAsString).start().waitFor();
} else {
new ProcessBuilder("taskkill", "/F", "/PID", processIdAsString).start().waitFor();
}
} catch (IOException e) { }
}
process.destroy();
}
}
public static String getScriptSuffix() {
return isLinuxMachine() ? ".sh" : ".bat";
}
public static boolean isLinuxMachine() {
return !isWindows();
}
public static String getBuildPath() {
String referencePath = getClassLocation(PlatformVersion.class);
String jarPath = referencePath.split("!")[0];
int startOfPathLocation = jarPath.indexOf("/");
if (isLinuxMachine()) {
jarPath = jarPath.substring(startOfPathLocation);
}
else {
jarPath = jarPath.substring(startOfPathLocation + 1);
}
int startOfJarFilename = jarPath.indexOf("gs-runtime.jar");
jarPath = jarPath.substring(0, startOfJarFilename);
jarPath += "../..";
return jarPath;
}
public static String getBuildBinPath() {
return getBuildPath() + File.separator + "bin";
}
public static String getBuildRecipesPath() {
return getBuildPath() + File.separator + "recipes";
}
public static String getBuildRecipesServicesPath() {
return getBuildRecipesPath() + File.separator + "services";
}
public static String getBuildRecipesApplicationsPath() {
return getBuildRecipesPath() + File.separator + "applications";
}
private static String getClassLocation(Class<?> clazz) {
String clsAsResource = clazz.getName().replace('.', '/').concat(".class");
final ClassLoader clsLoader = clazz.getClassLoader();
URL result = clsLoader != null ? clsLoader.getResource(clsAsResource) :
ClassLoader.getSystemResource(clsAsResource);
return result.getPath();
}
public static File getGigaspacesZipFile() throws IOException {
File gigaspacesDirectory = new File ( ScriptUtils.getBuildPath());
- String gigaspacesFolderName = "gigaspaces-" + PlatformVersion.getEdition() + "-"+PlatformVersion.getVersion()+"-"+PlatformVersion.getMilestone();
+ String gigaspacesFolderName = "gigaspaces-" + PlatformVersion.getEdition().toLowerCase() + "-"+PlatformVersion.getVersion()+"-"+PlatformVersion.getMilestone();
String gigaspacesZipFilename = gigaspacesFolderName + "-b" + PlatformVersion.getBuildNumber() + ".zip";
File gigaspacesZip = new File(new File(gigaspacesDirectory,".."), gigaspacesZipFilename);
if (!gigaspacesZip.exists()) {
File[] excludeDirectories = new File[]{new File(gigaspacesDirectory,"work"),
new File(gigaspacesDirectory,"logs"),
new File(gigaspacesDirectory,"deploy"),
new File(gigaspacesDirectory,"tools/cli/plugins/esc/ec2/upload")};
File[] includeDirectories = new File[]{new File(gigaspacesDirectory,"deploy/templates")};
File[] emptyDirectories = new File[]{new File(gigaspacesDirectory,"logs"),
new File(gigaspacesDirectory,"lib/platform/esm")};
ZipUtils.zipDirectory(gigaspacesZip, gigaspacesDirectory, includeDirectories, excludeDirectories,emptyDirectories,gigaspacesFolderName);
}
if (!ZipUtils.isZipIntact(gigaspacesZip)) {
throw new IOException(gigaspacesZip + " is not a valid zip file.");
}
return gigaspacesZip.getCanonicalFile();
}
//////////////////////
public static class ScriptPatternIterator implements Iterator<Object[]> {
private InputStream is;
private XMLStreamReader parser;
private int event;
public ScriptPatternIterator(String xmlPath) throws XMLStreamException, FactoryConfigurationError, IOException {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlPath);
parser = XMLInputFactory.newInstance().createXMLStreamReader(is);
nextScript();
}
public boolean hasNext() {
return (event != XMLStreamConstants.END_DOCUMENT);
}
public Object[] next() {
String currentScript = parser.getAttributeValue(null, "name");
long timeout = Long.parseLong(parser.getAttributeValue(null, "timeout"));
List<String[]> patterns = new ArrayList<String[]>();
try {
nextPattern();
} catch (XMLStreamException e1) {
e1.printStackTrace();
}
while (event != XMLStreamConstants.END_ELEMENT ||
!parser.getName().toString().equals("script")) {
String currentRegex = parser.getAttributeValue(null, "regex");
String currentExpectedAmount = parser.getAttributeValue(null, "expected-amount");
patterns.add(new String[] { currentRegex, currentExpectedAmount });
try {
nextPattern();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
String[][] patternObjects = new String[patterns.size()][];
for (int i = 0; i < patterns.size(); i++) {
patternObjects[i] = patterns.get(i);
}
try {
nextScript();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Object[] { currentScript, patternObjects , timeout };
}
public void remove() {
throw new UnsupportedOperationException();
}
private void nextScript() throws XMLStreamException, IOException {
while (true) {
event = parser.next();
if (event == XMLStreamConstants.END_DOCUMENT) {
parser.close();
is.close();
return;
}
if (event == XMLStreamConstants.START_ELEMENT
&& parser.getName().toString().equals("script")) {
return;
}
}
}
private void nextPattern() throws XMLStreamException {
while (true) {
event = parser.next();
if (event == XMLStreamConstants.END_ELEMENT
&& parser.getName().toString().equals("script")) {
return;
}
if (event == XMLStreamConstants.START_ELEMENT
&& parser.getName().toString().equals("pattern")) {
return;
}
}
}
}
public static Map<String,String> loadPropertiesFromClasspath(String resourceName) throws IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream in = classLoader.getResourceAsStream(resourceName);
Properties properties = null;
if (in != null) {
properties = new Properties();
properties.load(in);
}
return convertPropertiesToStringProperties(properties);
}
private static Map<String,String> convertPropertiesToStringProperties(Properties properties) {
Map<String,String> stringProperties = new HashMap<String,String>();
for (Object key : properties.keySet()) {
stringProperties.put(key.toString(),properties.get(key).toString());
}
return stringProperties;
}
public static Map<String, String> loadPropertiesFromFile(File file) throws FileNotFoundException, IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(file));
return convertPropertiesToStringProperties(properties);
}
public static GroovyObject getGroovyObject(String className) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException{
ClassLoader parent = ScriptUtils.class.getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class<?> groovyClass = loader.parseClass(new File(className));
return (GroovyObject) groovyClass.newInstance();
}
/**
* @param className the name of the .groovy file with path starting from sgtest base dir
* @param methodName the name of the method in className we wnt to invoke
* @throws CompilationFailedException
* @throws IOException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static void runGroovy(String className, String methodName) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException{
GroovyObject obj = getGroovyObject(className);
Object[] args = {};
obj.invokeMethod(methodName, args);
}
/**
* @param className the name of the .groovy file with path starting from sgtest base dir
* @param methodName the name of the method in className we wnt to invoke
* @param args the arguments for the method to invoke
* @throws CompilationFailedException
* @throws IOException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static void runGroovy(String className, String methodName, Object...args) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException{
GroovyObject obj = getGroovyObject(className);
obj.invokeMethod(methodName, args);
}
/**
* this method runs a .groovy file with a relative path to current working directory
* use example: <code>ScriptUtils.runGroovy("src/test/maven/copyMuleJars.groovy")</code>
*
* @param className the name of the .groovy file with path starting from current working directory
* @throws CompilationFailedException
* @throws IOException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static void runGroovy(String className) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException{
GroovyObject obj = getGroovyObject(className);
Object[] args = {};
obj.invokeMethod("run", args);
}
public static boolean isWindows() {
return (System.getenv("windir") != null);
}
@SuppressWarnings("deprecation")
public static String runScriptRelativeToGigaspacesBinDir(String args, long timeout) throws Exception {
RunScript runScript = new RunScript(args, true);
Thread script = new Thread(runScript);
script.start();
Thread.sleep(timeout);
script.stop();
runScript.kill();
return runScript.getScriptOutput();
}
public static String runScriptWithAbsolutePath(String args, long timeout) throws Exception {
RunScript runScript = new RunScript(args, false);
Thread script = new Thread(runScript);
script.start();
script.join(timeout);
runScript.kill();
return runScript.getScriptOutput();
}
public static RunScript runScriptRelativeToGigaspacesBinDir(String args) throws Exception {
RunScript runScript = new RunScript(args, true);
Thread script = new Thread(runScript);
script.start();
return runScript;
}
}
| true | false | null | null |
diff --git a/src/com/googlecode/sardine/SardineImpl.java b/src/com/googlecode/sardine/SardineImpl.java
index fc85212..7ae0a19 100644
--- a/src/com/googlecode/sardine/SardineImpl.java
+++ b/src/com/googlecode/sardine/SardineImpl.java
@@ -1,358 +1,374 @@
package com.googlecode.sardine;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
+import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import com.googlecode.sardine.model.Creationdate;
import com.googlecode.sardine.model.Getcontentlength;
import com.googlecode.sardine.model.Getcontenttype;
import com.googlecode.sardine.model.Getlastmodified;
import com.googlecode.sardine.model.Multistatus;
import com.googlecode.sardine.model.Prop;
import com.googlecode.sardine.model.Response;
import com.googlecode.sardine.util.SardineException;
import com.googlecode.sardine.util.SardineUtil;
import com.googlecode.sardine.util.SardineUtil.HttpCopy;
import com.googlecode.sardine.util.SardineUtil.HttpMkCol;
import com.googlecode.sardine.util.SardineUtil.HttpMove;
import com.googlecode.sardine.util.SardineUtil.HttpPropFind;
/**
* Implementation of the Sardine interface. This
* is where the meat of the Sardine library lives.
*
* @author jonstevens
*/
public class SardineImpl implements Sardine
{
/** */
Factory factory;
/** */
DefaultHttpClient client;
+ /** was a username/password passed in? */
+ boolean authEnabled;
+
/** */
public SardineImpl(Factory factory) throws SardineException
{
this(factory, null, null, null, null);
}
/** */
public SardineImpl(Factory factory, String username, String password) throws SardineException
{
this(factory, username, password, null, null);
}
/**
* Main constructor.
*/
public SardineImpl(Factory factory, String username, String password, SSLSocketFactory sslSocketFactory, HttpRoutePlanner routePlanner) throws SardineException
{
this.factory = factory;
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 100);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUserAgent(params, "Sardine/" + Version.getSpecification());
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
if (sslSocketFactory != null)
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
else
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
this.client = new DefaultHttpClient(cm, params);
// for proxy configurations
if (routePlanner != null)
this.client.setRoutePlanner(routePlanner);
if ((username != null) && (password != null))
+ {
this.client.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password));
+
+ this.authEnabled = true;
+ }
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#getResources(java.lang.String)
*/
public List<DavResource> getResources(String url) throws SardineException
{
HttpPropFind propFind = new HttpPropFind(url);
propFind.setEntity(SardineUtil.getResourcesEntity());
HttpResponse response = this.executeWrapper(propFind);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException("Failed to get resources. Is the url valid?", url,
statusLine.getStatusCode(), statusLine.getReasonPhrase());
// Process the response from the server.
Multistatus multistatus = SardineUtil.getMulitstatus(this.factory.getUnmarshaller(), response, url);
List<Response> responses = multistatus.getResponse();
List<DavResource> resources = new ArrayList<DavResource>(responses.size());
// Are we getting a directory listing or not?
// the path after the host stuff
int firstSlash = url.indexOf('/', 8);
String baseUrl = null;
if (url.endsWith("/"))
baseUrl = url.substring(firstSlash);
// http://server.com
String hostPart = url.substring(0, firstSlash);
for (Response resp : responses)
{
String href = resp.getHref().get(0);
// figure out the name of the file and set
// the baseUrl if it isn't already set (like when
// we are looking for just one file)
String name = null;
if (baseUrl != null)
{
name = href.substring(baseUrl.length());
}
else
{
int last = href.lastIndexOf("/") + 1;
name = href.substring(last);
baseUrl = href.substring(0, last);
}
// Ignore crap files
if (name.equals(".DS_Store"))
continue;
boolean currentDirectory = false;
if (baseUrl.equals(href))
currentDirectory = true;
// Remove the final / from the name for directories
if (name.endsWith("/"))
name = name.substring(0, name.length() - 1);
Prop prop = resp.getPropstat().get(0).getProp();
String creationdate = null;
Creationdate gcd = prop.getCreationdate();
if (gcd != null && gcd.getContent().size() == 1)
creationdate = gcd.getContent().get(0);
// modifieddate is sometimes not set
// if that's the case, use creationdate
String modifieddate = null;
Getlastmodified glm = prop.getGetlastmodified();
if (glm != null && glm.getContent().size() == 1)
modifieddate = glm.getContent().get(0);
else
modifieddate = creationdate;
String contentType = null;
Getcontenttype gtt = prop.getGetcontenttype();
if (gtt != null && gtt.getContent().size() == 1)
contentType = gtt.getContent().get(0);
String contentLength = "0";
Getcontentlength gcl = prop.getGetcontentlength();
if (gcl != null && gcl.getContent().size() == 1)
contentLength = gcl.getContent().get(0);
DavResource dr = new DavResource(hostPart + baseUrl, name, SardineUtil.parseDate(creationdate),
SardineUtil.parseDate(modifieddate), contentType, Long.valueOf(contentLength), currentDirectory);
resources.add(dr);
}
return resources;
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#getInputStream(java.lang.String)
*/
public InputStream getInputStream(String url) throws SardineException
{
HttpGet get = new HttpGet(url);
HttpResponse response = this.executeWrapper(get);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException(url, statusLine.getStatusCode(), statusLine.getReasonPhrase());
try
{
return response.getEntity().getContent();
}
catch (IOException ex)
{
throw new SardineException(ex);
}
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#put(java.lang.String, byte[])
*/
public void put(String url, byte[] data) throws SardineException
{
HttpPut put = new HttpPut(url);
ByteArrayEntity entity = new ByteArrayEntity(data);
put.setEntity(entity);
HttpResponse response = this.executeWrapper(put);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException(url, statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#put(java.lang.String, InputStream)
*/
public void put(String url, InputStream dataStream) throws SardineException
{
HttpPut put = new HttpPut(url);
// A length of -1 means "go until end of stream"
InputStreamEntity entity = new InputStreamEntity(dataStream, -1);
put.setEntity(entity);
HttpResponse response = this.executeWrapper(put);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException(url, statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#delete(java.lang.String)
*/
public void delete(String url) throws SardineException
{
HttpDelete delete = new HttpDelete(url);
HttpResponse response = this.executeWrapper(delete);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException(url, statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#move(java.lang.String, java.lang.String)
*/
public void move(String sourceUrl, String destinationUrl) throws SardineException
{
HttpMove move = new HttpMove(sourceUrl, destinationUrl);
HttpResponse response = this.executeWrapper(move);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException("sourceUrl: " + sourceUrl + ", destinationUrl: " + destinationUrl,
statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#copy(java.lang.String, java.lang.String)
*/
public void copy(String sourceUrl, String destinationUrl)
throws SardineException
{
HttpCopy copy = new HttpCopy(sourceUrl, destinationUrl);
HttpResponse response = this.executeWrapper(copy);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException("sourceUrl: " + sourceUrl + ", destinationUrl: " + destinationUrl,
statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#createDirectory(java.lang.String)
*/
public void createDirectory(String url) throws SardineException
{
HttpMkCol mkcol = new HttpMkCol(url);
mkcol.setEntity(SardineUtil.createDirectoryEntity());
HttpResponse response = this.executeWrapper(mkcol);
StatusLine statusLine = response.getStatusLine();
if (!SardineUtil.isGoodResponse(statusLine.getStatusCode()))
throw new SardineException(url, statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
/*
* (non-Javadoc)
* @see com.googlecode.sardine.Sardine#exists(java.lang.String)
*/
public boolean exists(String url) throws SardineException
{
HttpHead head = new HttpHead(url);
HttpResponse response = this.executeWrapper(head);
StatusLine statusLine = response.getStatusLine();
return (SardineUtil.isGoodResponse(statusLine.getStatusCode()));
}
/**
* Small wrapper around HttpClient.execute() in order to wrap the IOException
* into a SardineException.
*/
private HttpResponse executeWrapper(HttpRequestBase base) throws SardineException
{
try
{
+ if (this.authEnabled)
+ {
+ Credentials creds = this.client.getCredentialsProvider().getCredentials(AuthScope.ANY);
+ String value = "Basic " + new String(Base64.encodeBase64(new String(creds.getUserPrincipal().getName() + ":" + creds.getPassword()).getBytes()));
+ base.setHeader("Authorization", value);
+ }
+
return this.client.execute(base);
}
catch (IOException ex)
{
throw new SardineException(ex);
}
}
}
diff --git a/src/com/googlecode/sardine/test/SardineTest.java b/src/com/googlecode/sardine/test/SardineTest.java
index 85fe560..d06af0b 100644
--- a/src/com/googlecode/sardine/test/SardineTest.java
+++ b/src/com/googlecode/sardine/test/SardineTest.java
@@ -1,54 +1,63 @@
package com.googlecode.sardine.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import java.io.File;
+import java.io.FileInputStream;
import java.util.List;
import org.junit.Test;
import com.googlecode.sardine.DavResource;
import com.googlecode.sardine.Sardine;
import com.googlecode.sardine.SardineFactory;
/**
* Unfortunately, this test suite can only be run
* at work since that is where my dav server is. At
* some point in the future, I'll consider bundling a java based
* server with sardine and testing against that. For now,
* this is easier.
*
* @author jonstevens
*/
public class SardineTest
{
@Test
public void testGetSingleFile() throws Exception
{
Sardine sardine = SardineFactory.begin();
List<DavResource> resources = sardine.getResources("http://webdav.prod.365.kink.y/cybernetentertainment/imagedb/7761/v/h/320/7761_1.flv");
assertEquals(1, resources.size());
DavResource res = resources.get(0);
assertEquals("7761_1.flv", res.getName());
assertEquals("7761_1.flv", res.getNameDecoded());
assertEquals("http://webdav.prod.365.kink.y/cybernetentertainment/imagedb/7761/v/h/320/", res.getBaseUrl());
assertEquals("http://webdav.prod.365.kink.y/cybernetentertainment/imagedb/7761/v/h/320/7761_1.flv", res.getAbsoluteUrl());
assertFalse(res.isDirectory());
// server currently doesn't know what a .flv is. bug in apache in that a HEAD returns the default mimetype (text/plain) and PROPFIND doesn't?
// assertEquals(res.getContentType(), "video/x-flv");
}
@Test
public void testGetDirectoryListing() throws Exception
{
Sardine sardine = SardineFactory.begin();
List<DavResource> resources = sardine.getResources("http://webdav.prod.365.kink.y/cybernetentertainment/imagedb/7761/v/h/320/");
// for (DavResource res : resources)
// {
// System.out.println(res);
// }
assertEquals(31, resources.size());
}
+
+ @Test
+ public void testPutFile() throws Exception
+ {
+ Sardine sardine = SardineFactory.begin("admin", "admin");
+ sardine.put("http://localhost/uploads/file2.txt", new FileInputStream(new File("/tmp/mysql.log.jon")));
+ }
}
| false | false | null | null |
diff --git a/core/src/main/java/hudson/tasks/Fingerprinter.java b/core/src/main/java/hudson/tasks/Fingerprinter.java
index 6f110d6ce..a0e39740a 100644
--- a/core/src/main/java/hudson/tasks/Fingerprinter.java
+++ b/core/src/main/java/hudson/tasks/Fingerprinter.java
@@ -1,288 +1,295 @@
package hudson.tasks;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.model.Action;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Fingerprint;
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Project;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.remoting.VirtualChannel;
import hudson.util.IOException2;
import hudson.util.FormFieldValidator;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Records fingerprints of the specified files.
*
* @author Kohsuke Kawaguchi
*/
public class Fingerprinter extends Publisher implements Serializable {
/**
* Comma-separated list of files/directories to be fingerprinted.
*/
private final String targets;
/**
* Also record all the finger prints of the build artifacts.
*/
private final boolean recordBuildArtifacts;
public Fingerprinter(String targets, boolean recordBuildArtifacts) {
this.targets = targets;
this.recordBuildArtifacts = recordBuildArtifacts;
}
public String getTargets() {
return targets;
}
public boolean getRecordBuildArtifacts() {
return recordBuildArtifacts;
}
public boolean perform(Build<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException {
try {
listener.getLogger().println("Recording fingerprints");
Map<String,String> record = new HashMap<String,String>();
if(targets.length()!=0)
record(build, listener, record, targets);
if(recordBuildArtifacts) {
ArtifactArchiver aa = (ArtifactArchiver) build.getProject().getPublishers().get(ArtifactArchiver.DESCRIPTOR);
if(aa==null) {
// configuration error
listener.error("Build artifacts are supposed to be fingerprinted, but build artifact archiving is not configured");
build.setResult(Result.FAILURE);
return true;
}
record(build, listener, record, aa.getArtifacts() );
}
build.getActions().add(new FingerprintAction(build,record));
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to record fingerprints"));
build.setResult(Result.FAILURE);
}
// failing to record fingerprints is an error but not fatal
return true;
}
private void record(Build<?,?> build, BuildListener listener, Map<String,String> record, final String targets) throws IOException, InterruptedException {
final class Record implements Serializable {
final boolean produced;
final String relativePath;
final String fileName;
final String md5sum;
public Record(boolean produced, String relativePath, String fileName, String md5sum) {
this.produced = produced;
this.relativePath = relativePath;
this.fileName = fileName;
this.md5sum = md5sum;
}
Fingerprint addRecord(Build build) throws IOException {
FingerprintMap map = Hudson.getInstance().getFingerprintMap();
return map.getOrCreate(produced?build:null, fileName, md5sum);
}
private static final long serialVersionUID = 1L;
}
Project p = build.getProject();
final long buildTimestamp = build.getTimestamp().getTimeInMillis();
- List<Record> records = p.getWorkspace().act(new FileCallable<List<Record>>() {
+ FilePath ws = p.getWorkspace();
+ if(ws==null) {
+ listener.error("Unable to record fingerprints because there's no workspace");
+ build.setResult(Result.FAILURE);
+ return;
+ }
+
+ List<Record> records = ws.act(new FileCallable<List<Record>>() {
public List<Record> invoke(File baseDir, VirtualChannel channel) throws IOException {
List<Record> results = new ArrayList<Record>();
FileSet src = new FileSet();
src.setDir(baseDir);
src.setIncludes(targets);
DirectoryScanner ds = src.getDirectoryScanner(new org.apache.tools.ant.Project());
for( String f : ds.getIncludedFiles() ) {
File file = new File(baseDir,f);
// consider the file to be produced by this build only if the timestamp
// is newer than when the build has started.
boolean produced = buildTimestamp <= file.lastModified();
try {
results.add(new Record(produced,f,file.getName(),new FilePath(file).digest()));
} catch (IOException e) {
throw new IOException2("Failed to compute digest for "+file,e);
} catch (InterruptedException e) {
throw new IOException2("Aborted",e);
}
}
return results;
}
});
for (Record r : records) {
Fingerprint fp = r.addRecord(build);
if(fp==null) {
listener.error("failed to record fingerprint for "+r.relativePath);
continue;
}
fp.add(build);
record.put(r.relativePath,fp.getHashString());
}
}
public Descriptor<Publisher> getDescriptor() {
return DESCRIPTOR;
}
public static final Descriptor<Publisher> DESCRIPTOR = new DescriptorImpl();
public static class DescriptorImpl extends Descriptor<Publisher> {
public DescriptorImpl() {
super(Fingerprinter.class);
}
public String getDisplayName() {
return "Record fingerprints of files to track usage";
}
public String getHelpFile() {
return "/help/project-config/fingerprint.html";
}
/**
* Performs on-the-fly validation on the file mask wildcard.
*/
public void doCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator.WorkspaceFileMask(req,rsp).process();
}
public Publisher newInstance(StaplerRequest req) {
return new Fingerprinter(
req.getParameter("fingerprint_targets").trim(),
req.getParameter("fingerprint_artifacts")!=null);
}
}
/**
* Action for displaying fingerprints.
*/
public static final class FingerprintAction implements Action {
private final AbstractBuild build;
/**
* From file name to the digest.
*/
private final Map<String,String> record;
private transient WeakReference<Map<String,Fingerprint>> ref;
public FingerprintAction(AbstractBuild build, Map<String, String> record) {
this.build = build;
this.record = record;
}
public String getIconFileName() {
return "fingerprint.gif";
}
public String getDisplayName() {
return "See fingerprints";
}
public String getUrlName() {
return "fingerprints";
}
public AbstractBuild getBuild() {
return build;
}
/**
* Map from file names of the fingerprinted file to its fingerprint record.
*/
public synchronized Map<String,Fingerprint> getFingerprints() {
if(ref!=null) {
Map<String,Fingerprint> m = ref.get();
if(m!=null)
return m;
}
Hudson h = Hudson.getInstance();
Map<String,Fingerprint> m = new TreeMap<String,Fingerprint>();
for (Entry<String, String> r : record.entrySet()) {
try {
Fingerprint fp = h._getFingerprint(r.getValue());
if(fp!=null)
m.put(r.getKey(), fp);
} catch (IOException e) {
logger.log(Level.WARNING,e.getMessage(),e);
}
}
m = Collections.unmodifiableMap(m);
ref = new WeakReference<Map<String,Fingerprint>>(m);
return m;
}
/**
* Gets the dependency to other builds in a map.
* Returns build numbers instead of {@link Build}, since log records may be gone.
*/
public Map<AbstractProject,Integer> getDependencies() {
Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
for (Fingerprint fp : getFingerprints().values()) {
BuildPtr bp = fp.getOriginal();
if(bp==null) continue; // outside Hudson
if(bp.is(build)) continue; // we are the owner
Integer existing = r.get(bp.getJob());
if(existing!=null && existing>bp.getNumber())
continue; // the record in the map is already up to date
r.put(bp.getJob(),bp.getNumber());
}
return r;
}
}
private static final Logger logger = Logger.getLogger(Fingerprinter.class.getName());
private static final long serialVersionUID = 1L;
}
| true | false | null | null |
diff --git a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIUtil.java b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIUtil.java
index 89b66131b..0ec78c458 100644
--- a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIUtil.java
+++ b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIUtil.java
@@ -1,1191 +1,1195 @@
/*******************************************************************************
* Copyright (c) 2009 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.core;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.tools.ant.util.FileUtils;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotatable;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeParameter;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jst.j2ee.project.facet.IJ2EEFacetConstants;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.jboss.tools.cdi.internal.core.impl.ClassBean;
import org.jboss.tools.cdi.internal.core.validation.AnnotationValidationDelegate;
import org.jboss.tools.cdi.internal.core.validation.CDICoreValidator;
import org.jboss.tools.common.EclipseUtil;
import org.jboss.tools.common.java.IAnnotated;
import org.jboss.tools.common.java.IAnnotationDeclaration;
import org.jboss.tools.common.java.IAnnotationType;
import org.jboss.tools.common.java.IJavaMemberReference;
import org.jboss.tools.common.java.IParametedType;
import org.jboss.tools.common.model.util.EclipseJavaUtil;
import org.jboss.tools.common.model.util.EclipseResourceUtil;
import org.jboss.tools.common.text.ITextSourceReference;
import org.jboss.tools.common.zip.UnzipOperation;
import org.jboss.tools.jst.web.WebModelPlugin;
import org.jboss.tools.jst.web.kb.IKbProject;
import org.jboss.tools.jst.web.kb.internal.KbBuilder;
import org.osgi.framework.Bundle;
/**
* @author Alexey Kazakov
*/
public class CDIUtil {
private static File TEMPLATE_FOLDER;
/**
* Adds CDI and KB builders to the project.
*
* @param project
* @param genearteBeansXml
*/
public static void enableCDI(IProject project, boolean genearteBeansXml, IProgressMonitor monitor) {
try {
WebModelPlugin.addNatureToProjectWithValidationSupport(project, KbBuilder.BUILDER_ID, IKbProject.NATURE_ID);
WebModelPlugin.addNatureToProjectWithValidationSupport(project, CDICoreBuilder.BUILDER_ID, CDICoreNature.NATURE_ID);
if(genearteBeansXml) {
File beansXml = getBeansXml(project);
if(beansXml!=null && !beansXml.exists()) {
// Create an empty beans.xml
beansXml.getParentFile().mkdir();
try {
FileUtils.getFileUtils().copyFile(new File(getTemplatesFolder(), "beans.xml"), beansXml, null, false, false);
} catch (IOException e) {
CDICorePlugin.getDefault().logError(e);
}
}
project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
IProject[] ps = project.getWorkspace().getRoot().getProjects();
for (IProject p: ps) {
CDICoreNature n = CDICorePlugin.getCDI(p, false);
if(n != null && n.isStorageResolved()) {
n.getClassPath().validateProjectDependencies();
}
}
} catch (CoreException e) {
CDICorePlugin.getDefault().logError(e);
}
}
/**
* Removes CDI builder from the project.
*
* @param project
*/
public static void disableCDI(IProject project) {
try {
EclipseUtil.removeNatureFromProject(project, CDICoreNature.NATURE_ID);
CDICoreValidator.cleanProject(project);
} catch (CoreException e) {
CDICorePlugin.getDefault().logError(e);
}
}
/**
* Calculate path to templates folder
*
* @return path to templates
* @throws IOException if templates folder not found
*/
public static File getTemplatesFolder() throws IOException {
if(TEMPLATE_FOLDER==null) {
Bundle bundle = CDICorePlugin.getDefault().getBundle();
String version = bundle.getVersion().toString();
IPath stateLocation = Platform.getStateLocation(bundle);
File templatesDir = FileLocator.getBundleFile(bundle);
if(templatesDir.isFile()) {
File toCopy = new File(stateLocation.toFile(),version);
if(!toCopy.exists()) {
toCopy.mkdirs();
UnzipOperation unZip = new UnzipOperation(templatesDir.getAbsolutePath());
unZip.execute(toCopy,"templates.*");
}
templatesDir = toCopy;
}
TEMPLATE_FOLDER = new File(templatesDir,"templates");
}
return TEMPLATE_FOLDER;
}
private static final String BEANS_XML_FILE_NAME = "beans.xml"; //$NON-NLS-1$
/**
* Returns java.io.File which represents beans.xml for the project.
* If the project is a faceted Java project then <src>/META-INF/beans.xml will be return.
* If there are a few source folders then the folder which contains META-INF folder will be return.
* If there are a few source folders but no any META-INF in them then null will be return.
* If the project is a faceted WAR then /<WebContent>/WEB-INF/beans.xml will be return.
* The beans.xml may or may not exist.
* @param project the project
* @return java.io.File which represents beans.xml for the project.
* @throws CoreException
*/
public static File getBeansXml(IProject project) throws CoreException {
IFacetedProject facetedProject = ProjectFacetsManager.create(project);
if(facetedProject!=null) {
IProjectFacetVersion webVersion = facetedProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET);
if(webVersion!=null) {
// WAR
IVirtualComponent com = ComponentCore.createComponent(project);
if(com!=null && com.getRootFolder()!=null) {
IVirtualFolder webInf = com.getRootFolder().getFolder(new Path("/WEB-INF")); //$NON-NLS-1$
if(webInf!=null) {
IContainer webInfFolder = webInf.getUnderlyingFolder();
if(webInfFolder.isAccessible()) {
File file = new File(webInfFolder.getLocation().toFile(), BEANS_XML_FILE_NAME);
return file;
}
}
}
} else if(facetedProject.getProjectFacetVersion(ProjectFacetsManager.getProjectFacet(IJ2EEFacetConstants.JAVA))!=null) {
// JAR
Set<IFolder> sources = EclipseResourceUtil.getSourceFolders(project);
if(sources.size()==1) {
return new File(sources.iterator().next().getLocation().toFile(), "META-INF/beans.xml"); //$NON-NLS-1$
} else {
for (IFolder src : sources) {
IFolder metaInf = src.getFolder("META-INF");
if(metaInf!=null && metaInf.isAccessible()) {
return new File(metaInf.getLocation().toFile(), BEANS_XML_FILE_NAME);
}
}
}
}
}
return null;
}
/**
* Finds CDI injected point in beans for particular java element.
*
* @param beans
* @param element
*/
public static IInjectionPoint findInjectionPoint(Set<IBean> beans, IJavaElement element, int position) {
if (!(element instanceof IField) && !(element instanceof IMethod) && !(element instanceof ILocalVariable)) {
return null;
}
for (IBean bean : beans) {
Set<IInjectionPoint> injectionPoints = bean.getInjectionPoints();
for (IInjectionPoint iPoint : injectionPoints) {
if (element instanceof IField && iPoint instanceof IInjectionPointField) {
if (((IInjectionPointField) iPoint).getField() != null && ((IInjectionPointField) iPoint).getField().getElementName().equals(element.getElementName()))
return iPoint;
}else if(element instanceof ILocalVariable && iPoint instanceof IInjectionPointParameter){
- if (((IInjectionPointParameter) iPoint).getName().equals(element.getElementName()))
+ IInjectionPointParameter param = (IInjectionPointParameter)iPoint;
+ if (param.getBeanMethod().getMethod().equals(element.getParent())
+ && param.getName().equals(element.getElementName())) {
return iPoint;
+ }
}else if(iPoint instanceof IInjectionPointParameter && position != 0){
- if(iPoint.getStartPosition() <= position && (iPoint.getStartPosition()+iPoint.getLength()) >= position)
+ if(iPoint.getStartPosition() <= position && (iPoint.getStartPosition()+iPoint.getLength()) >= position) {
return iPoint;
+ }
}
}
}
return null;
}
/**
* Sorts CDI beans which may be injected. The following order will be used:
* 1) selected alternative beans
* 2) nonalternative beans
* 3) non-seleceted alternatives
* 4) decorators
* 5) interceptors
*
* @param beans
*/
public static List<IBean> sortBeans(Set<IBean> beans) {
Set<IBean> alternativeBeans = new HashSet<IBean>();
Set<IBean> selectedAlternativeBeans = new HashSet<IBean>();
Set<IBean> nonAlternativeBeans = new HashSet<IBean>();
Set<IBean> decorators = new HashSet<IBean>();
Set<IBean> interceptors = new HashSet<IBean>();
for (IBean bean : beans) {
if (bean.isSelectedAlternative()) {
selectedAlternativeBeans.add(bean);
} else if (bean.isAlternative()) {
alternativeBeans.add(bean);
} else if (bean instanceof IDecorator) {
decorators.add(bean);
} else if (bean instanceof IInterceptor) {
interceptors.add(bean);
} else {
nonAlternativeBeans.add(bean);
}
}
ArrayList<IBean> sortedBeans = new ArrayList<IBean>();
sortedBeans.addAll(selectedAlternativeBeans);
sortedBeans.addAll(nonAlternativeBeans);
sortedBeans.addAll(alternativeBeans);
sortedBeans.addAll(decorators);
sortedBeans.addAll(interceptors);
return sortedBeans;
}
/**
* Checks if the bean has @Depended scope. If it has different scope then @Depended
* then returns this scope declaration or a stereotype which declares the
* scope. Otherwise returns null.
*
* @param bean
* @param scopeTypeName
* @return
*/
public static IAnnotationDeclaration getDifferentScopeDeclarationThanDepentend(IScoped scoped) {
return getAnotherScopeDeclaration(scoped, CDIConstants.DEPENDENT_ANNOTATION_TYPE_NAME);
}
/**
* Checks if the bean has @ApplicationScoped scope. If it has different scope then @ApplicationScoped
* then returns this scope declaration or a stereotype which declares the
* scope. Otherwise returns null.
*
* @param bean
* @param scopeTypeName
* @return
*/
public static IAnnotationDeclaration getDifferentScopeDeclarationThanApplicationScoped(IScoped scoped) {
return getAnotherScopeDeclaration(scoped, CDIConstants.APPLICATION_SCOPED_ANNOTATION_TYPE_NAME);
}
/**
* Checks if the bean has given scope. If it has different scope then given
* then returns this scope declaration or a stereotype which declares the
* scope. Otherwise returns null.
*
* @param bean
* @param scopeTypeName
* @return
*/
public static IAnnotationDeclaration getAnotherScopeDeclaration(IScoped scoped, String scopeTypeName) {
IScope scope = scoped.getScope();
if(scope == null) {
return null;
}
if (!scopeTypeName.equals(scope.getSourceType().getFullyQualifiedName())) {
Set<IScopeDeclaration> scopeDeclarations = scoped.getScopeDeclarations();
if (!scopeDeclarations.isEmpty()) {
return scopeDeclarations.iterator().next();
}
if (scoped instanceof IStereotyped) {
Set<IStereotypeDeclaration> stereoTypeDeclarations = ((IStereotyped) scoped).getStereotypeDeclarations();
for (IStereotypeDeclaration stereotypeDeclaration : stereoTypeDeclarations) {
IStereotype stereotype = stereotypeDeclaration.getStereotype();
IScope stereotypeScope = stereotype.getScope();
if (stereotypeScope != null && !scopeTypeName.equals(stereotypeScope.getSourceType().getFullyQualifiedName())) {
return stereotypeDeclaration;
}
}
}
}
return null;
}
/**
* Returns the scope annotation declaration if it exists in the bean. If the
* scope declared in a stereotype then returns this stereotype declaration.
* Returns null if there is not this scope declaration neither corresponding
* stereotype declaration.
*
* @param bean
* @param scopeTypeName
* @return
*/
public static IAnnotationDeclaration getScopeDeclaration(IBean bean, String scopeTypeName) {
IScope scope = bean.getScope();
if (scopeTypeName.equals(scope.getSourceType().getFullyQualifiedName())) {
Set<IScopeDeclaration> scopeDeclarations = bean.getScopeDeclarations();
for (IScopeDeclaration scopeDeclaration : scopeDeclarations) {
if (scopeTypeName.equals(scopeDeclaration.getScope().getSourceType().getFullyQualifiedName())) {
return scopeDeclaration;
}
}
Set<IStereotypeDeclaration> stereoTypeDeclarations = bean.getStereotypeDeclarations();
for (IStereotypeDeclaration stereotypeDeclaration : stereoTypeDeclarations) {
IScope stereotypeScope = stereotypeDeclaration.getStereotype().getScope();
if (stereotypeScope != null && scopeTypeName.equals(stereotypeScope.getSourceType().getFullyQualifiedName())) {
return stereotypeDeclaration;
}
}
}
return null;
}
/**
* Returns the annotation declaration if it exists in the annotated element. If the
* annotation declared in a stereotype then returns this stereotype declaration.
* Returns null if there is not this annotation declaration neither corresponding
* stereotype declaration. Doesn't check if a stereotype is inherited or not.
*
* @param bean
* @param scopeTypeName
* @return
*/
public static IAnnotationDeclaration getAnnotationDeclaration(IAnnotated annotated, ICDIAnnotation annotation) {
List<IAnnotationDeclaration> annotations = annotated.getAnnotations();
for (IAnnotationDeclaration annotationDeclaration : annotations) {
IAnnotationType annotationElement = annotationDeclaration.getAnnotation();
if(annotationElement!=null && annotation.equals(annotationElement)) {
return annotationDeclaration;
}
}
if(annotated instanceof IStereotyped) {
Set<IStereotypeDeclaration> stereoTypeDeclarations = ((IStereotyped)annotated).getStereotypeDeclarations();
for (IStereotypeDeclaration stereotypeDeclaration : stereoTypeDeclarations) {
if(getAnnotationDeclaration(stereotypeDeclaration.getStereotype(), annotation) != null) {
return stereotypeDeclaration;
}
}
}
return null;
}
/**
* Returns the annotation declaration directly or indirectly declared for this element.
* For instance some annotation directly declared for the element may declare wanted annotation then the method will return this declaration.
* So the returned declaration may be from a resource other than the resource of the element.
* Returns null if no declaration found.
*
* @param injection
* @param qualifierTypeName
* @return
*/
public static IAnnotationDeclaration getAnnotationDeclaration(IAnnotated element, String annotationTypeName) {
List<IAnnotationDeclaration> declarations = element.getAnnotations();
for (IAnnotationDeclaration declaration : declarations) {
IAnnotationType type = declaration.getAnnotation();
if(type!=null) {
if(annotationTypeName.equals(type.getSourceType().getFullyQualifiedName())) {
return declaration;
}
if(type instanceof IAnnotated) {
IAnnotationDeclaration decl = getAnnotationDeclaration((IAnnotated)type, annotationTypeName);
if(decl!=null) {
return decl;
}
}
}
}
return null;
}
/**
* Returns @Named declaration or the stereotype declaration if it declares @Named.
*
* @param stereotyped
* @return
*/
public static IAnnotationDeclaration getNamedDeclaration(IBean bean) {
return getQualifierDeclaration(bean, CDIConstants.NAMED_QUALIFIER_TYPE_NAME);
}
/**
* Return the qualifier declaration or the stereotype or @Specializes declaration if it declares this qualifier.
*
* @param stereotyped
* @return
*/
public static IAnnotationDeclaration getQualifierDeclaration(IBean bean, String qualifierTypeName) {
IAnnotationDeclaration declaration = getQualifiedStereotypeDeclaration(bean, qualifierTypeName);
if(declaration == null) {
declaration = getQualifiedSpecializesDeclaration(bean, qualifierTypeName);
}
return declaration;
}
/**
* Returns the @Specializes declaration of the bean if the specialized bean declares the given qualifier.
*
* @param bean
* @param qualifierTypeName
* @return
*/
public static IAnnotationDeclaration getQualifiedSpecializesDeclaration(IBean bean, String qualifierTypeName) {
IBean specializedBean = bean.getSpecializedBean();
return specializedBean!=null?getQualifierDeclaration(specializedBean, qualifierTypeName):null;
}
/**
* Return the stereotype declaration which declares the given qualifier.
*
* @param stereotyped
* @return
*/
public static IAnnotationDeclaration getQualifiedStereotypeDeclaration(IStereotyped stereotyped, String qualifierTypeName) {
IAnnotationDeclaration qualifierDeclaration = stereotyped.getAnnotation(qualifierTypeName);
if (qualifierDeclaration != null) {
return qualifierDeclaration;
}
Set<IStereotypeDeclaration> stereotypeDeclarations = stereotyped.getStereotypeDeclarations();
for (IStereotypeDeclaration declaration : stereotypeDeclarations) {
if (getQualifiedStereotypeDeclaration(declaration.getStereotype(), qualifierTypeName) != null) {
return declaration;
}
}
return null;
}
/**
* Return the stereotype declaration which declares @Named.
*
* @param stereotyped
* @return
*/
public static IAnnotationDeclaration getNamedStereotypeDeclaration(IStereotyped stereotyped) {
return getQualifiedStereotypeDeclaration(stereotyped, CDIConstants.NAMED_QUALIFIER_TYPE_NAME);
}
/**
* Returns all found annotations for parameters of the method.
*
* @param method
* @param annotationTypeName
* @return
*/
public static Set<ITextSourceReference> getAnnotationPossitions(IBeanMethod method, String annotationTypeName) {
List<IParameter> params = method.getParameters();
Set<ITextSourceReference> declarations = new HashSet<ITextSourceReference>();
for (IParameter param : params) {
ITextSourceReference declaration = param.getAnnotationPosition(annotationTypeName);
if (declaration != null) {
declarations.add(declaration);
}
}
return declarations;
}
/**
* Returns true if the class bean is a session bean.
*
* @param bean
* @return
*/
public static IAnnotationDeclaration getSessionDeclaration(IClassBean bean) {
IAnnotationDeclaration declaration = bean.getAnnotation(CDIConstants.STATEFUL_ANNOTATION_TYPE_NAME);
if(declaration!=null) {
return declaration;
}
declaration = bean.getAnnotation(CDIConstants.STATELESS_ANNOTATION_TYPE_NAME);
if(declaration!=null) {
return declaration;
}
declaration = bean.getAnnotation(CDIConstants.SINGLETON_ANNOTATION_TYPE_NAME);
return declaration;
}
/**
* Returns true if the class bean is a session bean.
*
* @param bean
* @return
*/
public static boolean isSessionBean(IBean bean) {
return bean instanceof ISessionBean || (bean instanceof IClassBean && (bean.getAnnotation(CDIConstants.STATEFUL_ANNOTATION_TYPE_NAME)!=null || bean.getAnnotation(CDIConstants.STATELESS_ANNOTATION_TYPE_NAME)!=null || bean.getAnnotation(CDIConstants.SINGLETON_ANNOTATION_TYPE_NAME)!=null));
}
/**
* Returns true if the class bean is a decorator.
*
* @param bean
* @return
*/
public static boolean isDecorator(IBean bean) {
return bean instanceof IDecorator || (bean instanceof IClassBean && bean.getAnnotation(CDIConstants.DECORATOR_STEREOTYPE_TYPE_NAME)!=null);
}
/**
* Returns true if the class bean is an interceptor.
*
* @param bean
* @return
*/
public static boolean isInterceptor(IBean bean) {
return bean instanceof IInterceptor || (bean instanceof IClassBean && bean.getAnnotation(CDIConstants.INTERCEPTOR_ANNOTATION_TYPE_NAME)!=null);
}
/**
* Returns false if the method is a non-static method of the session bean class, and the method is not a business method of the session bean.
*
* @param bean
* @param method
* @return
*/
public static boolean isBusinessOrStaticMethod(ISessionBean bean, IBeanMethod method) {
return getBusinessMethodDeclaration(bean, method)!=null;
}
/**
* Returns the set of interfaces annotated @Local for the session bean.
* Returns an empty set if there is no such interfaces or if the bean class (or any supper class) annotated @LocalBean.
*
* @param bean
* @return
*/
public static Set<IType> getLocalInterfaces(ISessionBean bean) {
Set<IType> sourceTypes = new HashSet<IType>();
try {
Set<IParametedType> types = bean.getLegalTypes();
for (IParametedType type : types) {
IType sourceType = type.getType();
if (sourceType == null) {
continue;
}
// Check if the class annotated @LocalBean
IAnnotation[] annotations = sourceType.getAnnotations();
for (IAnnotation annotation : annotations) {
if(CDIConstants.LOCAL_BEAN_ANNOTATION_TYPE_NAME.equals(annotation.getElementName()) || "LocalBean".equals(annotation.getElementName())) {
return Collections.emptySet();
}
}
if(sourceType.isInterface()) {
IAnnotation annotation = sourceType.getAnnotation(CDIConstants.LOCAL_ANNOTATION_TYPE_NAME);
if (!annotation.exists()) {
annotation = sourceType.getAnnotation("Local"); //$NON-NLS-N1
}
if (annotation.exists() && CDIConstants.LOCAL_ANNOTATION_TYPE_NAME.equals(EclipseJavaUtil.resolveType(sourceType, "Local"))) { //$NON-NLS-N1
sourceTypes.add(sourceType);
}
}
}
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return sourceTypes;
}
/**
* Returns IMethod of @Local interface which is implemented by given business method if such an interface is defined.
* If such an interface is not define then return then check if the method is static or public, not final and doesn't start with "ejb".
* If so then return this method, otherwise return null.
*
* @param bean
* @param method
* @return
*/
public static IMethod getBusinessMethodDeclaration(ISessionBean bean, IBeanMethod method) {
try {
int flags = method.getMethod().getFlags();
if(Flags.isStatic(flags)) {
return method.getMethod();
} else if (!Flags.isFinal(flags) && Flags.isPublic(flags)) {
if(bean.getAnnotation(CDIConstants.SINGLETON_ANNOTATION_TYPE_NAME)!=null) {
return method.getMethod();
}
Set<IType> sourceTypes = getLocalInterfaces(bean);
if(sourceTypes.isEmpty()) {
return method.getMethod();
}
for (IType sourceType : sourceTypes) {
IMethod[] methods = sourceType.getMethods();
for (IMethod iMethod : methods) {
if (method.getMethod().isSimilar(iMethod)) {
return iMethod;
}
}
}
return null;
}
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return null;
}
/**
* Finds the method which is overridden by the given method. Or null if this method overrides nothing.
*
* @param method
* @return
*/
public static IMethod getOverridingMethodDeclaration(IBeanMethod method) {
IClassBean bean = method.getClassBean();
Map<IType, IMethod> foundMethods = new HashMap<IType, IMethod>();
try {
if (Flags.isStatic(method.getMethod().getFlags())) {
return null;
}
Set<IParametedType> types = bean.getLegalTypes();
for (IParametedType type : types) {
IType sourceType = type.getType();
if (sourceType == null || sourceType.isInterface()) {
continue;
}
IMethod[] methods = sourceType.getMethods();
for (IMethod iMethod : methods) {
if (method.getMethod().isSimilar(iMethod)) {
foundMethods.put(iMethod.getDeclaringType(), iMethod);
}
}
}
if(foundMethods.size()==1) {
return foundMethods.values().iterator().next();
} else if(foundMethods.size()>1) {
IType type = bean.getBeanClass();
IType superClass = getSuperClass(type);
while(superClass!=null) {
IMethod m = foundMethods.get(superClass);
if(m!=null) {
return m;
}
superClass = getSuperClass(superClass);
}
}
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return null;
}
/**
* Finds the method which is overridden by the given method. Or null if this method overrides nothing.
*
* @param method
* @return
*/
public static IMethod getDirectOverridingMethodDeclaration(IBeanMethod method) {
IClassBean bean = method.getClassBean();
try {
if (Flags.isStatic(method.getMethod().getFlags())) {
return null;
}
IType type = bean.getBeanClass();
IType superClass = getSuperClass(type);
if(superClass!=null) {
IMethod[] methods = superClass.getMethods();
for (IMethod iMethod : methods) {
if (method.getMethod().isSimilar(iMethod)) {
return iMethod;
}
}
}
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return null;
}
/**
* Returns all the injection point parameters of the bean class.
*
* @param bean
* @return
*/
public static Set<IInjectionPointParameter> getInjectionPointParameters(IClassBean bean) {
Set<IInjectionPoint> points = bean.getInjectionPoints();
Set<IInjectionPointParameter> params = new HashSet<IInjectionPointParameter>();
for (IInjectionPoint injection : points) {
if(injection instanceof IInjectionPointParameter) {
params.add((IInjectionPointParameter)injection);
}
}
return params;
}
/**
* Returns true if the method is generic
*
* @param method
* @return
*/
public static boolean isMethodGeneric(IBeanMethod method) {
try {
return method.getMethod().getTypeParameters().length>0;
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return false;
}
/**
* Returns true if the method is static
*
* @param method
* @return
*/
public static boolean isMethodStatic(IBeanMethod method) {
try {
return Flags.isStatic(method.getMethod().getFlags());
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return false;
}
/**
* Returns true if the method is abstract
*
* @param method
* @return
*/
public static boolean isMethodAbstract(IBeanMethod method) {
try {
return Flags.isAbstract(method.getMethod().getFlags());
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return false;
}
/**
* Checks if the bean member has a type variable as a type.
* If the bean member is a field then checks its type.
* If the bean member is a parameter of a method then checks its type.
* If the bean member is a method then checks its return type.
*
* @param member
* @param checkGenericMethod if true then checks if this member use a type variable which is declared in the generic method (in case of the member is a method).
* @return
*/
public static boolean isTypeVariable(IBeanMember member, boolean checkGenericMethod) {
try {
String[] typeVariableSegnatures = member.getClassBean().getBeanClass().getTypeParameterSignatures();
List<String> variables = new ArrayList<String>();
for (String variableSig : typeVariableSegnatures) {
variables.add(Signature.getTypeVariable(variableSig));
}
if(checkGenericMethod) {
ITypeParameter[] typeParams = null;
if(member instanceof IParameter) {
typeParams = ((IParameter)member).getBeanMethod().getMethod().getTypeParameters();
} if(member instanceof IBeanMethod) {
typeParams = ((IBeanMethod)member).getMethod().getTypeParameters();
}
if(typeParams!=null) {
for (ITypeParameter param : typeParams) {
variables.add(param.getElementName());
}
}
}
String signature = null;
if(member instanceof IBeanField) {
signature = ((IBeanField)member).getField().getTypeSignature();
} else if(member instanceof IParameter) {
if(((IParameter)member).getType()==null) {
return false;
}
signature = ((IParameter)member).getType().getSignature();
} else if(member instanceof IBeanMethod) {
signature = ((IBeanMethod)member).getMethod().getReturnType();
}
return isTypeVariable(variables, signature);
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return false;
}
private static boolean isTypeVariable(List<String> typeVariables, String signature) {
if(signature==null) {
return false;
}
String typeString = Signature.toString(signature);
for (String variableName : typeVariables) {
if(typeString.equals(variableName)) {
return true;
}
}
return false;
}
private static IType getSuperClass(IType type) throws JavaModelException {
String superclassName = type.getSuperclassName();
if(superclassName!=null) {
String fullySuperclassName = EclipseJavaUtil.resolveType(type, superclassName);
if(fullySuperclassName!=null&&!fullySuperclassName.equals("java.lang.Object")) { //$NON-NLS-1$
if(fullySuperclassName.equals(type.getFullyQualifiedName())) {
return null;
}
IType superType = type.getJavaProject().findType(fullySuperclassName);
return superType;
}
}
return null;
}
/**
* Returns true if the member annotated @NonBinding.
*
* @param sourceType the type where the member is declared
* @param member
* @return
*/
public static boolean hasNonBindingAnnotationDeclaration(IType sourceType, IAnnotatable member) {
return hasAnnotationDeclaration(sourceType, member, CDIConstants.NON_BINDING_ANNOTATION_TYPE_NAME);
}
/**
* Returns true if the member has the given annotation.
*
* @param sourceType the type where the member is declared
* @param member
* @param annotationTypeName
* @return
*/
public static boolean hasAnnotationDeclaration(IType sourceType, IAnnotatable member, String annotationTypeName) {
try {
IAnnotation[] annotations = member.getAnnotations();
String simpleAnnotationTypeName = annotationTypeName;
int lastDot = annotationTypeName.lastIndexOf('.');
if(lastDot>-1) {
simpleAnnotationTypeName = simpleAnnotationTypeName.substring(lastDot + 1);
}
for (IAnnotation annotation : annotations) {
if(annotationTypeName.equals(annotation.getElementName())) {
return true;
}
if(simpleAnnotationTypeName.equals(annotation.getElementName())) {
String fullAnnotationclassName = EclipseJavaUtil.resolveType(sourceType, simpleAnnotationTypeName);
if(fullAnnotationclassName!=null) {
IType annotationType = sourceType.getJavaProject().findType(fullAnnotationclassName);
if(annotationType!=null && annotationType.getFullyQualifiedName().equals(annotationTypeName)) {
return true;
}
}
}
}
} catch (JavaModelException e) {
CDICorePlugin.getDefault().logError(e);
}
return false;
}
/**
* Converts ISourceRange to ITextSourceReference
*
* @param range
* @return
*/
public static ITextSourceReference convertToSourceReference(final ISourceRange range, final IResource resource) {
return new ITextSourceReference() {
public int getStartPosition() {
return range.getOffset();
}
public int getLength() {
return range.getLength();
}
public IResource getResource() {
return resource;
}
};
}
/**
* Returns true if the injection point declares @Default qualifier or doesn't declare any qualifier at all.
*
* @param point
* @return
*/
public static boolean containsDefaultQualifier(IInjectionPoint point) {
Set<IQualifierDeclaration> declarations = point.getQualifierDeclarations();
if(declarations.isEmpty()) {
return true;
}
for (IQualifierDeclaration declaration : declarations) {
if(CDIConstants.DEFAULT_QUALIFIER_TYPE_NAME.equals(declaration.getQualifier().getSourceType().getFullyQualifiedName())) {
return true;
}
}
return false;
}
/**
* Build a CDI model for the project if it hasn't built yet and show a Progress dialog.
*
* @param project
* @return the CDI nature for the project
*/
public static CDICoreNature getCDINatureWithProgress(final IProject project){
final CDICoreNature cdiNature = CDICorePlugin.getCDI(project, false);
if(cdiNature != null && !cdiNature.isStorageResolved()){
if (Display.getCurrent() != null) {
try{
PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress(){
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
monitor.beginTask(CDICoreMessages.CDI_UTIL_BUILD_CDI_MODEL, 10);
monitor.worked(3);
cdiNature.resolve();
monitor.worked(7);
}
});
}catch(InterruptedException ie){
CDICorePlugin.getDefault().logError(ie);
}catch(InvocationTargetException ite){
CDICorePlugin.getDefault().logError(ite);
}
} else {
cdiNature.resolve();
}
}
return cdiNature;
}
public static Set<IInterceptorBinding> getAllInterceptorBindings(IInterceptorBinded binded) {
Set<IInterceptorBindingDeclaration> ds = collectAdditionalInterceptorBindingDeclaratios(binded, new HashSet<IInterceptorBindingDeclaration>());
Set<IInterceptorBinding> result = new HashSet<IInterceptorBinding>();
for (IInterceptorBindingDeclaration d: ds) {
IInterceptorBinding b = d.getInterceptorBinding();
if(b != null) result.add(b);
}
return result;
}
/**
* Collect all the interceptor binding declarations from the bean class or method including all the inherited bindings.
* @param binded bean class or method
*
* @return
*/
public static Set<IInterceptorBindingDeclaration> getAllInterceptorBindingDeclaratios(IInterceptorBinded binded) {
return collectAdditionalInterceptorBindingDeclaratios(binded, new HashSet<IInterceptorBindingDeclaration>());
}
private static Set<IInterceptorBindingDeclaration> collectAdditionalInterceptorBindingDeclaratios(IInterceptorBinded binded, Set<IInterceptorBindingDeclaration> result) {
Set<IInterceptorBindingDeclaration> declarations = binded.getInterceptorBindingDeclarations(true);
for (IInterceptorBindingDeclaration declaration : declarations) {
if(!result.contains(declaration)) {
result.add(declaration);
IInterceptorBinding binding = declaration.getInterceptorBinding();
collectAdditionalInterceptorBindingDeclaratios(binding, result);
if(binding instanceof IStereotyped) {
collectAdditionalInterceptorBindingDeclaratiosFromStereotyps((IStereotyped)binding, result);
}
}
}
if(binded instanceof IStereotyped) {
collectAdditionalInterceptorBindingDeclaratiosFromStereotyps((IStereotyped)binded, result);
}
return result;
}
private static Set<IInterceptorBindingDeclaration> collectAdditionalInterceptorBindingDeclaratiosFromStereotyps(IStereotyped stereotyped, Set<IInterceptorBindingDeclaration> result) {
Set<IStereotypeDeclaration> stereotypeDeclarations = collectInheritedStereotypDeclarations(stereotyped, new HashSet<IStereotypeDeclaration>());
if(stereotyped instanceof ClassBean) {
stereotypeDeclarations.addAll(((ClassBean)stereotyped).getInheritedStereotypDeclarations());
}
for (IStereotypeDeclaration stereotypeDeclaration : stereotypeDeclarations) {
collectAdditionalInterceptorBindingDeclaratios(stereotypeDeclaration.getStereotype(), result);
}
return result;
}
private static Set<IStereotypeDeclaration> collectInheritedStereotypDeclarations(IStereotyped stereotyped, Set<IStereotypeDeclaration> result) {
Set<IStereotypeDeclaration> declarations = stereotyped.getStereotypeDeclarations();
for (IStereotypeDeclaration declaration : declarations) {
if(!result.contains(declaration)) {
result.add(declaration);
collectInheritedStereotypDeclarations(declaration.getStereotype(), result);
}
}
return result;
}
/**
* Check all the values of @Target declaration of the annotation.
* Returns null if there is no @Target at all. Returns true if any of the variants presents.
* For example this method will return true for {{TYPE, FIELD, METHOD}, {TYPE}} for @Target(TYPE)
* @param annotationType
* @param variants
* @return
* @throws JavaModelException
*/
public static Boolean checkTargetAnnotation(IAnnotationType annotationType, String[][] variants) throws JavaModelException {
IAnnotationDeclaration target = annotationType.getAnnotationDeclaration(CDIConstants.TARGET_ANNOTATION_TYPE_NAME);
return target == null?null:checkTargetAnnotation(target, variants);
}
/**
* Check all the values of @Target declaration
* Returns true if any of the variants presents.
* For example this method will return true for {{TYPE, FIELD, METHOD}, {TYPE}} for @Target(TYPE)
* @param target
* @param variants
* @return
* @throws JavaModelException
*/
public static boolean checkTargetAnnotation(IAnnotationDeclaration target, String[][] variants) throws JavaModelException {
Set<String> vs = getTargetAnnotationValues(target);
boolean ok = false;
for (int i = 0; i < variants.length; i++) {
if(vs.size() == variants[i].length) {
boolean ok2 = true;
String[] values = variants[i];
for (String s: values) {
if(!vs.contains(s)) {
ok2 = false;
break;
}
}
if(ok2) {
ok = true;
break;
}
}
}
return ok;
}
/**
* Returns values of @Tagret declaration of the annotation type.
* @param target
* @return
* @throws JavaModelException
*/
public static Set<String> getTargetAnnotationValues(IAnnotationDeclaration target) throws JavaModelException {
Set<String> result = new HashSet<String>();
Object o = target.getMemberValue(null);
if(o instanceof Object[]) {
Object[] os = (Object[])o;
for (Object q: os) {
String s = q.toString();
int i = s.lastIndexOf('.');
if(i >= 0 && AnnotationValidationDelegate.ELEMENT_TYPE_TYPE_NAME.equals(s.substring(0, i))) {
s = s.substring(i + 1);
result.add(s);
}
}
} else if(o != null) {
String s = o.toString();
int i = s.lastIndexOf('.');
if(i >= 0 && AnnotationValidationDelegate.ELEMENT_TYPE_TYPE_NAME.equals(s.substring(0, i))) {
s = s.substring(i + 1);
result.add(s);
}
}
return result;
}
/**
* returns set of IBean elements filtered in order to have unique IJavaElement
* @param cdiProject
* @param attemptToResolveAmbiguousDependency
* @param injectionPoint
* @return
*/
public static Set<IBean> getFilteredBeans(ICDIProject cdiProject, boolean attemptToResolveAmbiguousDependency, IInjectionPoint injectionPoint){
Set<IBean> beans = cdiProject.getBeans(attemptToResolveAmbiguousDependency, injectionPoint);
HashSet<IJavaElement> elements = new HashSet<IJavaElement>();
HashSet<IBean> result = new HashSet<IBean>();
for(IBean bean : beans){
IJavaElement element = getJavaElement(bean);
if(!elements.contains(element)){
elements.add(element);
result.add(bean);
}
}
return result;
}
/**
* returns set of IBean elements filtered in order to have unique IJavaElement
* @param cdiProject
* @param path
* @return
*/
public static Set<IBean> getFilteredBeans(ICDIProject cdiProject, IPath path){
Set<IBean> beans = cdiProject.getBeans(path);
HashSet<IJavaElement> elements = new HashSet<IJavaElement>();
HashSet<IBean> result = new HashSet<IBean>();
for(IBean bean : beans){
IJavaElement element = getJavaElement(bean);
if(!elements.contains(element)){
elements.add(element);
result.add(bean);
}
}
return result;
}
public static List<IBean> getSortedBeans(ICDIProject cdiProject, boolean attemptToResolveAmbiguousDependency, IInjectionPoint injectionPoint){
Set<IBean> beans = getFilteredBeans(cdiProject, attemptToResolveAmbiguousDependency, injectionPoint);
return sortBeans(beans);
}
public static List<IBean> getSortedBeans(ICDIProject cdiProject, IPath path){
Set<IBean> beans = getFilteredBeans(cdiProject, path);
return sortBeans(beans);
}
public static IJavaElement getJavaElement(ICDIElement cdiElement){
if(cdiElement instanceof IJavaMemberReference)
return ((IJavaMemberReference)cdiElement).getSourceMember();
if(cdiElement instanceof IBean)
return ((IBean)cdiElement).getBeanClass();
else if(cdiElement instanceof IInjectionPointParameter){
IMethod method = ((IInjectionPointParameter)cdiElement).getBeanMethod().getMethod();
return getParameter(method, ((IInjectionPointParameter)cdiElement).getName());
}
return null;
}
public static ILocalVariable getParameter(IMethod method, String name){
try{
for(ILocalVariable param : method.getParameters()){
if(param.getElementName().equals(name))
return param;
}
}catch(JavaModelException ex){
CDICorePlugin.getDefault().logError(ex);
}
return null;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/model/AbstractMappingContext.java b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/model/AbstractMappingContext.java
index 9fe5a592..4c7094a6 100644
--- a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/model/AbstractMappingContext.java
+++ b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/model/AbstractMappingContext.java
@@ -1,241 +1,251 @@
/* Copyright (C) 2010 SpringSource
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.grails.datastore.mapping.model;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.grails.datastore.mapping.model.types.conversion.DefaultConversionService;
import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.core.convert.support.GenericConversionService;
import org.grails.datastore.mapping.proxy.JavassistProxyFactory;
import org.grails.datastore.mapping.proxy.ProxyFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.validation.Validator;
/**
* Abstract implementation of the MappingContext interface.
*
* @author Graeme Rocher
* @since 1.0
*/
@SuppressWarnings("rawtypes")
public abstract class AbstractMappingContext implements MappingContext {
public static final String GROOVY_PROXY_FACTORY_NAME = "org.grails.datastore.gorm.proxy.GroovyProxyFactory";
public static final String JAVASIST_PROXY_FACTORY = "javassist.util.proxy.ProxyFactory";
protected Collection<PersistentEntity> persistentEntities = new ConcurrentLinkedQueue<PersistentEntity>();
protected Map<String,PersistentEntity> persistentEntitiesByName = new ConcurrentHashMap<String,PersistentEntity>();
protected Map<PersistentEntity,Map<String,PersistentEntity>> persistentEntitiesByDiscriminator = new ConcurrentHashMap<PersistentEntity,Map<String,PersistentEntity>>();
protected Map<PersistentEntity,Validator> entityValidators = new ConcurrentHashMap<PersistentEntity, Validator>();
protected Collection<Listener> eventListeners = new ConcurrentLinkedQueue<Listener>();
protected GenericConversionService conversionService = new DefaultConversionService();
protected ProxyFactory proxyFactory;
public ConversionService getConversionService() {
return conversionService;
}
public ConverterRegistry getConverterRegistry() {
return conversionService;
}
public abstract MappingFactory getMappingFactory();
public ProxyFactory getProxyFactory() {
if (this.proxyFactory == null) {
ClassLoader classLoader = AbstractMappingContext.class.getClassLoader();
if(ClassUtils.isPresent(JAVASIST_PROXY_FACTORY, classLoader)) {
proxyFactory = DefaultProxyFactoryCreator.create();
}
else if(ClassUtils.isPresent(GROOVY_PROXY_FACTORY_NAME, classLoader)) {
try {
proxyFactory = (ProxyFactory) BeanUtils.instantiate(ClassUtils.forName(GROOVY_PROXY_FACTORY_NAME, classLoader));
} catch (ClassNotFoundException e) {
proxyFactory = DefaultProxyFactoryCreator.create();
}
}
else {
proxyFactory = DefaultProxyFactoryCreator.create();
}
}
return proxyFactory;
}
public void addMappingContextListener(Listener listener) {
if (listener != null)
eventListeners.add(listener);
}
public void setProxyFactory(ProxyFactory factory) {
if (factory != null) {
this.proxyFactory = factory;
}
}
private static class DefaultProxyFactoryCreator {
public static ProxyFactory create() {
return new JavassistProxyFactory();
}
}
public void addTypeConverter(Converter converter) {
conversionService.addConverter(converter);
}
public Validator getEntityValidator(PersistentEntity entity) {
if (entity != null) {
return entityValidators.get(entity);
}
return null;
}
public void addEntityValidator(PersistentEntity entity, Validator validator) {
if (entity != null && validator != null) {
entityValidators.put(entity, validator);
}
}
public PersistentEntity addExternalPersistentEntity(Class javaClass) {
Assert.notNull(javaClass, "PersistentEntity class cannot be null");
PersistentEntity entity = persistentEntitiesByName.get(javaClass.getName());
if (entity == null) {
entity = addPersistentEntityInternal(javaClass, true);
}
return entity;
}
/**
* Adds a PersistentEntity instance
*
* @param javaClass The Java class representing the entity
* @param override Whether to override an existing entity
* @return The PersistentEntity instance
*/
@Override
public PersistentEntity addPersistentEntity(Class javaClass, boolean override) {
Assert.notNull(javaClass, "PersistentEntity class cannot be null");
if(override)
return addPersistentEntityInternal(javaClass, false);
else {
return addPersistentEntity(javaClass);
}
}
public final PersistentEntity addPersistentEntity(Class javaClass) {
Assert.notNull(javaClass, "PersistentEntity class cannot be null");
PersistentEntity entity = persistentEntitiesByName.get(javaClass.getName());
if (entity == null) {
entity = addPersistentEntityInternal(javaClass, false);
}
return entity;
}
private PersistentEntity addPersistentEntityInternal(Class javaClass, boolean isExternal) {
PersistentEntity entity = createPersistentEntity(javaClass);
if (entity == null) {
return null;
}
entity.setExternal(isExternal);
persistentEntities.remove(entity); persistentEntities.add(entity);
persistentEntitiesByName.put(entity.getName(), entity);
- entity.initialize();
+
+ try {
+ entity.initialize();
+ }
+ catch(IllegalMappingException x) {
+ persistentEntities.remove(entity);
+ persistentEntitiesByName.remove(entity.getName());
+ throw x;
+ }
+
+
if (!entity.isRoot()) {
PersistentEntity root = entity.getRootEntity();
Map<String, PersistentEntity> children = persistentEntitiesByDiscriminator.get(root);
if (children == null) {
children = new ConcurrentHashMap<String,PersistentEntity>();
persistentEntitiesByDiscriminator.put(root, children);
}
children.put(entity.getDiscriminator(), entity);
}
for (Listener eventListener : eventListeners) {
eventListener.persistentEntityAdded(entity);
}
return entity;
}
/**
* Returns true if the given entity is in an inheritance hierarchy
*
* @param entity The entity
* @return True if it is
*/
public boolean isInInheritanceHierarchy(PersistentEntity entity) {
if(entity != null) {
if(!entity.isRoot()) return true;
else {
PersistentEntity rootEntity = entity.getRootEntity();
final Map<String, PersistentEntity> children = persistentEntitiesByDiscriminator.get(rootEntity);
if(children != null && !children.isEmpty()) {
return true;
}
}
}
return false;
}
public PersistentEntity getChildEntityByDiscriminator(PersistentEntity root, String discriminator) {
final Map<String, PersistentEntity> children = persistentEntitiesByDiscriminator.get(root);
if (children != null) {
return children.get(discriminator);
}
return null;
}
protected abstract PersistentEntity createPersistentEntity(Class javaClass);
public PersistentEntity createEmbeddedEntity(Class type) {
EmbeddedPersistentEntity embedded = new EmbeddedPersistentEntity(type, this);
embedded.initialize();
return embedded;
}
public Collection<PersistentEntity> getPersistentEntities() {
return persistentEntities;
}
public boolean isPersistentEntity(Class type) {
return type != null && getPersistentEntity(type.getName()) != null;
}
public boolean isPersistentEntity(Object value) {
return value != null && isPersistentEntity(value.getClass());
}
public PersistentEntity getPersistentEntity(String name) {
final int proxyIndicator = name.indexOf("_$$_");
if (proxyIndicator > -1) {
name = name.substring(0, proxyIndicator);
}
return persistentEntitiesByName.get(name);
}
}
| true | false | null | null |
diff --git a/srcj/com/sun/electric/tool/io/output/GDS.java b/srcj/com/sun/electric/tool/io/output/GDS.java
index 22aa3ce6a..97031c5db 100755
--- a/srcj/com/sun/electric/tool/io/output/GDS.java
+++ b/srcj/com/sun/electric/tool/io/output/GDS.java
@@ -1,910 +1,919 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: GDS.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.output;
import com.sun.electric.database.geometry.Poly;
+import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.prototype.ArcProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.FlagSet;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.Layer;
import com.sun.electric.tool.io.IOTool;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.List;
/**
* This class writes files in GDS format.
*/
public class GDS extends Geometry
{
private static final int GDSVERSION = 3;
private static final int BYTEMASK = 0xFF;
private static final int DSIZE = 512; /* data block */
private static final int MAXPOINTS = 510; /* maximum points in a polygon */
private static final int EXPORTPRESENTATION= 0; /* centered (was 8 for bottomleft) */
// GDSII bit assignments in STRANS record
private static final int STRANS_REFLX = 0x8000;
private static final int STRANS_ABSA = 0x2;
// data type codes
private static final int DTYP_NONE = 0;
// header codes
private static final short HDR_HEADER = 0x0002;
private static final short HDR_BGNLIB = 0x0102;
private static final short HDR_LIBNAME = 0x0206;
private static final short HDR_UNITS = 0x0305;
private static final short HDR_ENDLIB = 0x0400;
private static final short HDR_BGNSTR = 0x0502;
private static final short HDR_STRNAME = 0x0606;
private static final short HDR_ENDSTR = 0x0700;
private static final short HDR_BOUNDARY = 0x0800;
private static final short HDR_PATH = 0x0900;
private static final short HDR_SREF = 0x0A00;
private static final short HDR_AREF = 0x0B00;
private static final short HDR_TEXT = 0x0C00;
private static final short HDR_LAYER = 0x0D02;
private static final short HDR_DATATYPE = 0x0E02;
private static final short HDR_XY = 0x1003;
private static final short HDR_ENDEL = 0x1100;
private static final short HDR_SNAME = 0x1206;
private static final short HDR_TEXTTYPE = 0x1602;
private static final short HDR_PRESENTATION= 0x1701;
private static final short HDR_STRING = 0x1906;
private static final short HDR_STRANS = 0x1A01;
private static final short HDR_MAG = 0x1B05;
private static final short HDR_ANGLE = 0x1C05;
// Header byte counts
private static final short HDR_N_BGNLIB = 28;
private static final short HDR_N_UNITS = 20;
private static final short HDR_N_ANGLE = 12;
private static final short HDR_N_MAG = 12;
// Maximum string sizes
private static final int HDR_M_SNAME = 32;
private static final int HDR_M_STRNAME = 32;
private static final int HDR_M_ASCII = 256;
// contour gathering thresholds for polygon accumulation
private static final double BESTTHRESH = 0.001; /* 1/1000 of a millimeter */
private static final double WORSTTHRESH = 0.1; /* 1/10 of a millimeter */
public static class GDSLayers
{
public int normal;
public int pin;
public int text;
}
/** for buffering output data */ private static byte [] dataBufferGDS = new byte[DSIZE];
/** for buffering output data */ private static byte [] emptyBuffer = new byte[DSIZE];
/** Current layer for gds output */ private static GDSLayers currentLayerNumbers;
/** Position of next byte in the buffer */ private static int bufferPosition;
/** Number data buffers output so far */ private static int blockCount;
/** constant for GDS units */ private static double scaleFactor;
/** cell naming map */ private HashMap cellNames;
/** layer number map */ private HashMap layerNumbers;
/**
* Main entry point for GDS output.
* @param cell the top-level cell to write.
* @param filePath the name of the file to create.
*/
public static void writeGDSFile(Cell cell, VarContext context, String filePath)
{
GDS out = new GDS();
if (out.openBinaryOutputStream(filePath)) return;
BloatVisitor visitor = out.makeBloatVisitor(getMaxHierDepth(cell));
if (out.writeCell(cell, context, visitor)) return;
if (out.closeBinaryOutputStream()) return;
System.out.println(filePath + " written");
}
/** Creates a new instance of GDS */
GDS()
{
}
protected void start()
{
initOutput();
outputBeginLibrary(topCell);
}
protected void done()
{
outputHeader(HDR_ENDLIB, 0);
doneWritingOutput();
}
/** Method to write cellGeom */
protected void writeCellGeom(CellGeom cellGeom)
{
// write this cell
Cell cell = cellGeom.cell;
outputBeginStruct(cell);
// write all polys by Layer
Set layers = cellGeom.polyMap.keySet();
for (Iterator it = layers.iterator(); it.hasNext();)
{
Layer layer = (Layer)it.next();
selectLayer(layer);
List polyList = (List)cellGeom.polyMap.get(layer);
for (Iterator polyIt = polyList.iterator(); polyIt.hasNext(); )
{
Poly poly = (Poly)polyIt.next();
writePoly(poly, currentLayerNumbers.normal);
}
}
// write all instances
for (Iterator noIt = cellGeom.nodables.iterator(); noIt.hasNext(); )
{
Nodable no = (Nodable)noIt.next();
writeNodable(no);
}
// now write exports
if (IOTool.getGDSOutDefaultTextLayer() >= 0 && IOTool.isGDSOutWritesExportPins())
{
for(Iterator it = cell.getPorts(); it.hasNext(); )
{
Export pp = (Export)it.next();
// find the node at the bottom of this export
NodeInst bottomNi = pp.getOriginalPort().getNodeInst();
PortProto bottomPp = pp.getOriginalPort().getPortProto();
AffineTransform trans = bottomNi.rotateOut();
while (bottomNi.getProto() instanceof Cell)
{
AffineTransform tempTrans = bottomNi.translateOut();
tempTrans.preConcatenate(trans);
PortInst pi = ((Export)bottomPp).getOriginalPort();
bottomNi = pi.getNodeInst();
bottomPp = pi.getPortProto();
trans = bottomNi.rotateOut();
trans.preConcatenate(tempTrans);
}
// find the layer associated with this node
boolean wasWiped = bottomNi.isWiped();
bottomNi.clearWiped();
Technology tech = bottomNi.getProto().getTechnology();
Poly [] polys = tech.getShapeOfNode(bottomNi);
Poly poly = polys[0];
if (wasWiped) bottomNi.setWiped();
Layer layer = poly.getLayer().getNonPseudoLayer();
selectLayer(layer);
int textLayer, pinLayer;
textLayer = pinLayer = IOTool.getGDSOutDefaultTextLayer();
if (currentLayerNumbers.text >= 0) textLayer = currentLayerNumbers.text;
if (currentLayerNumbers.pin >= 0) pinLayer = currentLayerNumbers.pin;
// put out a pin if requested
if (IOTool.isGDSOutWritesExportPins())
{
poly.transform(trans);
writePoly(poly, pinLayer);
}
outputHeader(HDR_TEXT, 0);
outputHeader(HDR_LAYER, textLayer);
outputHeader(HDR_TEXTTYPE, 0);
outputHeader(HDR_PRESENTATION, EXPORTPRESENTATION);
// now the orientation
NodeInst ni = pp.getOriginalPort().getNodeInst();
int transValue = 0;
int angle = ni.getAngle();
if (ni.isXMirrored() != ni.isYMirrored()) transValue |= STRANS_REFLX;
if (ni.isYMirrored()) angle = (3600 - angle)%3600;
if (ni.isXMirrored()) angle = (1800 - angle)%3600;
outputHeader(HDR_STRANS, transValue);
// reduce the size of export text by a factor of 2
outputMag(0.5);
outputAngle(angle);
outputShort((short)12);
outputShort(HDR_XY);
Poly portPoly = pp.getOriginalPort().getPoly();
- outputInt((int)(scaleFactor*portPoly.getCenterX()));
- outputInt((int)(scaleFactor*portPoly.getCenterY()));
+ outputInt((int)(scaleDBUnit(portPoly.getCenterX())));
+ outputInt((int)(scaleDBUnit(portPoly.getCenterY())));
// now the string
String str = pp.getName();
int j = str.length();
if (j > 512) j = 512;
// pad with a blank
outputShort((short)(4+j));
outputShort(HDR_STRING);
outputString(str, j);
outputHeader(HDR_ENDEL, 0);
}
}
outputHeader(HDR_ENDSTR, 0);
}
/**
* Method to determine whether or not to merge geometry.
*/
protected boolean mergeGeom(int hierLevelsFromBottom)
{
return IOTool.isGDSOutMergesBoxes();
}
protected boolean selectLayer(Layer layer)
{
boolean validLayer = true;
GDSLayers numbers = (GDSLayers)layerNumbers.get(layer);
if (numbers == null)
{
String layerName = layer.getGDSLayer();
if (layerName == null)
{
numbers = new GDSLayers();
numbers.normal = numbers.pin = numbers.text = -1;
validLayer = false;
} else
{
numbers = parseLayerString(layerName);
}
layerNumbers.put(layer, numbers);
}
currentLayerNumbers = numbers;
return validLayer;
}
protected void writePoly(Poly poly, int layerNumber)
{
// ignore negative layer numbers
if (layerNumber < 0) return;
Point2D [] points = poly.getPoints();
if (poly.getStyle() == Poly.Type.DISC)
{
// Make a square of the size of the diameter
double r = points[0].distance(points[1]);
if (r <= 0) return;
Poly newPoly = new Poly(points[0].getX(), points[0].getY(), r*2, r*2);
outputBoundary(newPoly, layerNumber);
return;
}
Rectangle2D polyBounds = poly.getBox();
if (polyBounds != null)
{
// rectangular manhattan shape: make sure it has positive area
if (polyBounds.getWidth() == 0 || polyBounds.getHeight() == 0) return;
outputBoundary(poly, layerNumber);
return;
}
// non-manhattan or worse .. direct output
if (points.length == 1)
{
System.out.println("WARNING: Single point cannot be written in GDS-II");
return;
}
if (points.length > 200)
{
System.out.println("WARNING: GDS-II Polygons may not have more than 200 points (this has " + points.length + ")");
return;
}
if (points.length == 2) outputPath(poly, layerNumber); else
outputBoundary(poly, layerNumber);
}
protected void writeNodable(Nodable no)
{
NodeInst ni = (NodeInst)no; // In layout cell all Nodables are NodeInsts
Cell subCell = (Cell)ni.getProto();
// figure out transformation
int transValue = 0;
int angle = ni.getAngle();
if (ni.isXMirrored() != ni.isYMirrored()) transValue |= STRANS_REFLX;
if (ni.isYMirrored()) angle = (3600 - angle)%3600;
if (ni.isXMirrored()) angle = (1800 - angle)%3600;
// write a call to a cell
outputHeader(HDR_SREF, 0);
String name = (String)cellNames.get(subCell);
outputName(HDR_SNAME, name, HDR_M_SNAME);
outputHeader(HDR_STRANS, transValue);
outputAngle(angle);
outputShort((short)12);
outputShort(HDR_XY);
- outputInt((int)(scaleFactor*ni.getAnchorCenterX()));
- outputInt((int)(scaleFactor*ni.getAnchorCenterY()));
+ outputInt((int)(scaleDBUnit(ni.getAnchorCenterX())));
+ outputInt((int)(scaleDBUnit(ni.getAnchorCenterY())));
outputHeader(HDR_ENDEL, 0);
}
/****************************** VISITOR SUBCLASS ******************************/
private BloatVisitor makeBloatVisitor(int maxDepth)
{
BloatVisitor visitor = new BloatVisitor(this, maxDepth);
return visitor;
}
/**
* Class to override the Geometry visitor and add bloating to all polygons.
* Currently, no bloating is being done.
*/
private class BloatVisitor extends Geometry.Visitor
{
BloatVisitor(Geometry outGeom, int maxHierDepth)
{
super(outGeom, maxHierDepth);
}
public void addNodeInst(NodeInst ni, AffineTransform trans)
{
PrimitiveNode prim = (PrimitiveNode)ni.getProto();
Technology tech = prim.getTechnology();
Poly [] polys = tech.getShapeOfNode(ni, null);
Layer firstLayer = null;
for (int i=0; i<polys.length; i++)
{
Poly poly = polys[i];
Layer thisLayer = poly.getLayer();
if (thisLayer != null && firstLayer == null) firstLayer = thisLayer;
if (poly.getStyle().isText())
{
// dump this text field
outputHeader(HDR_TEXT, 0);
if (firstLayer != null) selectLayer(firstLayer);
outputHeader(HDR_LAYER, currentLayerNumbers.normal);
outputHeader(HDR_TEXTTYPE, 0);
outputHeader(HDR_PRESENTATION, EXPORTPRESENTATION);
// figure out transformation
int transValue = 0;
int angle = ni.getAngle();
if (ni.isXMirrored() != ni.isYMirrored()) transValue |= STRANS_REFLX;
if (ni.isYMirrored()) angle = (3600 - angle)%3600;
if (ni.isXMirrored()) angle = (1800 - angle)%3600;
outputHeader(HDR_STRANS, transValue);
outputAngle(angle);
outputShort((short)12);
outputShort(HDR_XY);
Point2D [] points = poly.getPoints();
- outputInt((int)(scaleFactor*points[0].getX()));
- outputInt((int)(scaleFactor*points[0].getY()));
+ outputInt((int)(scaleDBUnit(points[0].getX())));
+ outputInt((int)(scaleDBUnit(points[0].getY())));
// now the string
String str = poly.getString();
int j = str.length();
if (j > 512) j = 512;
outputShort((short)(4+j));
outputShort(HDR_STRING);
outputString(str, j);
outputHeader(HDR_ENDEL, 0);
}
poly.transform(trans);
}
cellGeom.addPolys(polys);
}
public void addArcInst(ArcInst ai)
{
ArcProto ap = ai.getProto();
Technology tech = ap.getTechnology();
Poly [] polys = tech.getShapeOfArc(ai);
cellGeom.addPolys(polys);
}
}
/*************************** GDS OUTPUT ROUTINES ***************************/
// Initialize various fields, get some standard values
private void initOutput()
{
blockCount = 0;
bufferPosition = 0;
// all zeroes
for (int i=0; i<DSIZE; i++) emptyBuffer[i] = 0;
Technology tech = Technology.getCurrent();
scaleFactor = tech.getScale();
layerNumbers = new HashMap();
// precache the layers in this technology
boolean foundValid = false;
for(Iterator it = tech.getLayers(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
if (selectLayer(layer)) foundValid = true;
}
if (!foundValid)
{
System.out.println("Warning: there are no GDS II layers defined for the " +
tech.getTechName() + " technology");
}
// make a hashmap of all names to use for cells
cellNames = new HashMap();
for(Iterator it = Library.getCurrent().getCells(); it.hasNext(); )
{
Cell cell = (Cell)it.next();
cellNames.put(cell, makeUniqueName(cell));
}
for(Iterator it = Library.getLibraries(); it.hasNext(); )
{
Library lib = (Library)it.next();
if (lib == Library.getCurrent()) continue;
if (lib.isHidden()) continue;
for(Iterator cIt = lib.getCells(); cIt.hasNext(); )
{
Cell cell = (Cell)cIt.next();
cellNames.put(cell, makeUniqueName(cell));
}
}
}
String makeUniqueName(Cell cell)
{
String name = makeGDSName(cell.getName());
if (cell.getNewestVersion() != cell)
name += "_" + cell.getVersion();
// see if the name is unique
String baseName = name;
for(int index = 1; ; index++)
{
boolean found = false;
for(Iterator it = cellNames.values().iterator(); it.hasNext(); )
{
String str = (String)it.next();
if (str.equals(name)) { found = true; break; }
}
if (!found) break;
name = baseName + "_" + index;
}
// add this name to the list
cellNames.put(cell, name);
return name;
}
/**
* function to create proper GDSII names with restricted character set
* from input string str.
* Uses only 'A'-'Z', '_', $, ?, and '0'-'9'
*/
private String makeGDSName(String str)
{
// filter the name string for the GDS output cell
String ret = "";
for(int k=0; k<str.length(); k++)
{
char ch = str.charAt(k);
if (IOTool.isGDSOutUpperCase()) ch = Character.toUpperCase(ch);
if (ch != '$' && !Character.isDigit(ch) && ch != '?' && !Character.isLetter(ch))
ch = '_';
ret += ch;
}
return ret;
}
/*
* Close the file, pad to make the file match the tape format
*/
private void doneWritingOutput()
{
try
{
// Write out the current buffer
if (bufferPosition > 0)
{
// Pack with zeroes
for (int i = bufferPosition; i < DSIZE; i++) dataBufferGDS[i] = 0;
dataOutputStream.write(dataBufferGDS, 0, DSIZE);
blockCount++;
}
// Pad to 2048
while (blockCount%4 != 0)
{
dataOutputStream.write(emptyBuffer, 0, DSIZE);
blockCount++;
}
} catch (IOException e)
{
System.out.println("End of file reached while finishing GDS");
}
}
// Write a library header, get the date information
private void outputBeginLibrary(Cell cell)
{
/* GDS floating point values - -
* 0x3E418937,0x4BC6A7EF = 0.001
* 0x3944B82F,0xA09B5A53 = 1e-9
* 0x3F28F5C2,0x8F5C28F6 = 0.01
* 0x3A2AF31D,0xC4611874 = 1e-8
*/
// set units
int [] units01 = convertFloatToArray(1e-3);
int [] units23 = convertFloatToArray(1.0e-9);
outputHeader(HDR_HEADER, GDSVERSION);
outputHeader(HDR_BGNLIB, 0);
outputDate(cell.getCreationDate());
outputDate(cell.getRevisionDate());
outputName(HDR_LIBNAME, makeGDSName(cell.getName()), HDR_M_ASCII);
outputShort(HDR_N_UNITS);
outputShort(HDR_UNITS);
outputIntArray(units01, 2);
outputIntArray(units23, 2);
}
void outputBeginStruct(Cell cell)
{
outputHeader(HDR_BGNSTR, 0);
outputDate(cell.getCreationDate());
outputDate(cell.getRevisionDate());
String name = (String)cellNames.get(cell);
outputName(HDR_STRNAME, name, HDR_M_STRNAME);
}
// Output date information
private void outputDate(Date val)
{
short [] date = new short[6];
Calendar cal = Calendar.getInstance();
cal.setTime(val);
date[0] = (short)cal.get(Calendar.YEAR);
date[1] = (short)cal.get(Calendar.MONTH);
date[2] = (short)cal.get(Calendar.DAY_OF_MONTH);
date[3] = (short)cal.get(Calendar.HOUR);
date[4] = (short)cal.get(Calendar.MINUTE);
date[5] = (short)cal.get(Calendar.SECOND);
outputShortArray(date, 6);
}
/*
* Write a simple header, with a fixed length
* Enter with the header as argument, the routine will output
* the count, the header, and the argument (if present) in p1.
*/
private void outputHeader(short header, int p1)
{
int type = header & BYTEMASK;
short count = 4;
if (type != DTYP_NONE)
{
switch (header)
{
case HDR_HEADER:
case HDR_LAYER:
case HDR_DATATYPE:
case HDR_TEXTTYPE:
case HDR_STRANS:
case HDR_PRESENTATION:
count = 6;
break;
case HDR_BGNSTR:
case HDR_BGNLIB:
count = HDR_N_BGNLIB;
break;
case HDR_UNITS:
count = HDR_N_UNITS;
break;
default:
System.out.println("No entry for header " + header);
return;
}
}
outputShort(count);
outputShort(header);
if (type == DTYP_NONE) return;
if (count == 6) outputShort((short)p1);
if (count == 8) outputInt(p1);
}
/*
* Add a name (STRNAME, LIBNAME, etc.) to the file. The header
* to be used is in header; the string starts at p1
* if there is an odd number of bytes, then output the 0 at
* the end of the string as a pad. The maximum length of string is "max"
*/
private void outputName(int header, String p1, int max)
{
int count = Math.min(p1.length(), max);
if ((count&1) != 0) count++;
outputShort((short)(count+4));
outputShort((short)header);
outputString(p1, count);
}
// Output an angle as part of a STRANS
private void outputAngle(int ang)
{
double gdfloat = ang / 10.0;
outputShort(HDR_N_ANGLE);
outputShort(HDR_ANGLE);
int [] units = convertFloatToArray(gdfloat);
outputIntArray(units, 2);
}
// Output a magnification as part of a STRANS
private void outputMag(double scale)
{
outputShort(HDR_N_MAG);
outputShort(HDR_MAG);
int [] units = convertFloatToArray(scale);
outputIntArray(units, 2);
}
// Output the pairs of XY points to the file
private void outputBoundary(Poly poly, int layerNumber)
{
Point2D [] points = poly.getPoints();
int count = points.length;
if (count > MAXPOINTS)
{
// getbbox(poly, &lx, &hx, &ly, &hy);
// if (hx-lx > hy-ly)
// {
// if (polysplitvert((lx+hx)/2, poly, &side1, &side2)) return;
// } else
// {
// if (polysplithoriz((ly+hy)/2, poly, &side1, &side2)) return;
// }
// outputBoundary(side1, layerNumber);
// outputBoundary(side2, layerNumber);
// freepolygon(side1);
// freepolygon(side2);
return;
}
int start = 0;
for(;;)
{
// look for a closed section
int sofar = start+1;
for( ; sofar<count; sofar++)
if (points[sofar].getX() == points[start].getX() && points[sofar].getY() == points[start].getY()) break;
if (sofar < count) sofar++;
outputHeader(HDR_BOUNDARY, 0);
outputHeader(HDR_LAYER, layerNumber);
outputHeader(HDR_DATATYPE, 0);
outputShort((short)(8 * (sofar+1) + 4));
outputShort(HDR_XY);
for (int i = start; i <= sofar; i++)
{
int j = i;
if (i == sofar) j = 0;
- outputInt((int)(scaleFactor*points[j].getX()));
- outputInt((int)(scaleFactor*points[j].getY()));
+ outputInt((int)(scaleDBUnit(points[j].getX())));
+ outputInt((int)(scaleDBUnit(points[j].getY())));
}
outputHeader(HDR_ENDEL, 0);
if (sofar >= count) break;
count -= sofar;
start = sofar;
}
}
private void outputPath(Poly poly, int layerNumber)
{
outputHeader(HDR_PATH, 0);
outputHeader(HDR_LAYER, layerNumber);
outputHeader(HDR_DATATYPE, 0);
Point2D [] points = poly.getPoints();
int count = 8 * points.length + 4;
outputShort((short)count);
outputShort(HDR_XY);
for (int i = 0; i < points.length; i ++)
{
- outputInt((int)(scaleFactor*points[i].getX()));
- outputInt((int)(scaleFactor*points[i].getY()));
+ outputInt((int)(scaleDBUnit(points[i].getX())));
+ outputInt((int)(scaleDBUnit(points[i].getY())));
}
outputHeader(HDR_ENDEL, 0);
}
// Add one byte to the file
private void outputByte(byte val)
{
dataBufferGDS[bufferPosition++] = val;
if (bufferPosition >= DSIZE)
{
try
{
dataOutputStream.write(dataBufferGDS, 0, DSIZE);
} catch (IOException e)
{
System.out.println("End of file reached while writing GDS");
}
blockCount++;
bufferPosition = 0;
}
}
+ private int scaleDBUnit(double dbunit) {
+ // scale according to technology
+ double scaled = scaleFactor*dbunit;
+ // round to nearest nanometer
+ int unit = (int)Math.round(scaled);
+ return unit;
+ }
+
/*************************** GDS LOW-LEVEL OUTPUT ROUTINES ***************************/
// Add a 2-byte integer
private void outputShort(short val)
{
outputByte((byte)((val>>8)&BYTEMASK));
outputByte((byte)(val&BYTEMASK));
}
// Four byte integer
private void outputInt(int val)
{
outputShort((short)(val>>16));
outputShort((short)val);
}
// Array of 2 byte integers in array ptr, count n
private void outputShortArray(short [] ptr, int n)
{
for (int i = 0; i < n; i++) outputShort(ptr[i]);
}
// Array of 4-byte integers or floating numbers in array ptr, count n
private void outputIntArray(int [] ptr, int n)
{
for (int i = 0; i < n; i++) outputInt(ptr[i]);
}
/*
* String of n bytes, starting at ptr
* Revised 90-11-23 to convert to upper case (SRP)
*/
private void outputString(String ptr, int n)
{
int i = 0;
if (IOTool.isGDSOutUpperCase())
{
// convert to upper case
for( ; i<ptr.length(); i++)
outputByte((byte)Character.toUpperCase(ptr.charAt(i)));
} else
{
for( ; i<ptr.length(); i++)
outputByte((byte)ptr.charAt(i));
}
for ( ; i < n; i++)
outputByte((byte)0);
}
/*
* Create 8-byte GDS representation of a floating point number
*/
private int [] convertFloatToArray(double a)
{
int [] ret = new int[2];
// handle default
if (a == 0)
{
ret[0] = 0x40000000;
ret[1] = 0;
return ret;
}
// identify sign
double temp = a;
boolean negsign = false;
if (temp < 0)
{
negsign = true;
temp = -temp;
}
// establish the excess-64 exponent value
int exponent = 64;
// scale the exponent and mantissa
for (; temp < 0.0625 && exponent > 0; exponent--) temp *= 16.0;
if (exponent == 0) System.out.println("Exponent underflow");
for (; temp >= 1 && exponent < 128; exponent++) temp /= 16.0;
if (exponent > 127) System.out.println("Exponent overflow");
// set the sign
if (negsign) exponent |= 0x80;
// convert temp to 7-byte binary integer
double top = temp;
for (int i = 0; i < 24; i++) top *= 2;
int highmantissa = (int)top;
double frac = top - highmantissa;
for (int i = 0; i < 32; i++) frac *= 2;
ret[0] = highmantissa | (exponent<<24);
ret[1] = (int)frac;
return ret;
}
/**
* Method to parse the GDS layer string and get the 3 layer numbers (plain, text, and pin).
* @param string the GDS layer string, of the form NUM[,NUMt][,NUMp]
* @return an array of 3 integers:
* [0] is the regular layer number;
* [1] is the pin layer number;
* [2] is the text layer number.
*/
public static GDSLayers parseLayerString(String string)
{
GDSLayers answers = new GDSLayers();
answers.normal = answers.pin = answers.text = -1;
for(;;)
{
String trimmed = string.trim();
if (trimmed.length() == 0) break;
int number = TextUtils.atoi(trimmed);
int endPos = trimmed.indexOf(',');
if (endPos < 0) endPos = trimmed.length();
char lastch = trimmed.charAt(endPos-1);
if (lastch == 't')
{
answers.text = number;
} else if (lastch == 'p')
{
answers.pin = number;
} else
{
answers.normal = number;
}
if (endPos == trimmed.length()) break;
string = trimmed.substring(endPos+1);
}
return answers;
}
}
| false | false | null | null |
diff --git a/src/org/fao/geonet/guiservices/search/GetDefaults.java b/src/org/fao/geonet/guiservices/search/GetDefaults.java
index 976e468c7f..8290db8ead 100644
--- a/src/org/fao/geonet/guiservices/search/GetDefaults.java
+++ b/src/org/fao/geonet/guiservices/search/GetDefaults.java
@@ -1,62 +1,62 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.guiservices.search;
import org.jdom.*;
import jeeves.interfaces.*;
import jeeves.server.*;
import jeeves.server.context.*;
import org.fao.geonet.services.util.MainUtil;
//=============================================================================
/** Called for the main.search service. Returns the information stored
* into the session
*/
public class GetDefaults implements Service
{
//--------------------------------------------------------------------------
//---
//--- Init
//---
//--------------------------------------------------------------------------
public void init(String appPath, ServiceConfig params) throws Exception {}
//--------------------------------------------------------------------------
//---
//--- Service
//---
//--------------------------------------------------------------------------
public Element exec(Element params, ServiceContext context) throws Exception
{
- return (Element)MainUtil.getDefaultSearch(context, params).clone();
+ return (Element)MainUtil.getDefaultSearch(context, null).clone();
}
}
//=============================================================================
diff --git a/src/org/fao/geonet/services/main/Search.java b/src/org/fao/geonet/services/main/Search.java
index aaf8f1fb10..9e85b85171 100644
--- a/src/org/fao/geonet/services/main/Search.java
+++ b/src/org/fao/geonet/services/main/Search.java
@@ -1,121 +1,121 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.services.main;
import org.jdom.*;
import jeeves.interfaces.*;
import jeeves.server.*;
import jeeves.server.context.*;
import org.fao.geonet.constants.*;
import org.fao.geonet.kernel.SelectionManager;
import org.fao.geonet.kernel.search.*;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.services.util.MainUtil;
//=============================================================================
/** main.search service. Perform a search
*/
public class Search implements Service
{
private ServiceConfig _config;
//--------------------------------------------------------------------------
//---
//--- Init
//---
//--------------------------------------------------------------------------
public void init(String appPath, ServiceConfig config) throws Exception
{
_config = config;
}
//--------------------------------------------------------------------------
//---
//--- Service
//---
//--------------------------------------------------------------------------
public Element exec(Element params, ServiceContext context) throws Exception
{
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
SearchManager searchMan = gc.getSearchmanager();
Element elData = MainUtil.getDefaultSearch(context, params);
String sRemote = elData.getChildText(Geonet.SearchResult.REMOTE);
boolean remote = sRemote != null && sRemote.equals(Geonet.Text.ON);
Element title = params.getChild(Geonet.SearchResult.TITLE);
Element abstr = params.getChild(Geonet.SearchResult.ABSTRACT);
Element any = params.getChild(Geonet.SearchResult.ANY);
if (title != null)
title.setText(MainUtil.splitWord(title.getText()));
if (abstr != null)
abstr.setText(MainUtil.splitWord(abstr.getText()));
if (any != null)
any.setText(MainUtil.splitWord(any.getText()));
// possibly close old searcher
UserSession session = context.getUserSession();
MetaSearcher oldSearcher = (MetaSearcher)session.getProperty(Geonet.Session.SEARCH_RESULT);
if (oldSearcher != null)
oldSearcher.close();
// possibly close old selection
SelectionManager oldSelection = (SelectionManager)session.getProperty(Geonet.Session.SELECTED_RESULT);
if (oldSelection != null){
oldSelection.close();
oldSelection = null;
}
// perform the search and save search result into session
MetaSearcher searcher;
context.info("Creating searchers");
if (remote) searcher = searchMan.newSearcher(SearchManager.Z3950, Geonet.File.SEARCH_Z3950_CLIENT);
else searcher = searchMan.newSearcher(SearchManager.LUCENE, Geonet.File.SEARCH_LUCENE);
- searcher.search(context, params, _config);
+ searcher.search(context, elData, _config);
session.setProperty(Geonet.Session.SEARCH_RESULT, searcher);
context.info("Getting summary");
return searcher.getSummary();
}
}
//=============================================================================
| false | false | null | null |
diff --git a/grails/src/commons/org/codehaus/groovy/grails/commons/DefaultGrailsApplication.java b/grails/src/commons/org/codehaus/groovy/grails/commons/DefaultGrailsApplication.java
index 44d66301e..436803cd8 100644
--- a/grails/src/commons/org/codehaus/groovy/grails/commons/DefaultGrailsApplication.java
+++ b/grails/src/commons/org/codehaus/groovy/grails/commons/DefaultGrailsApplication.java
@@ -1,621 +1,621 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.commons;
import groovy.lang.GroovyClassLoader;
import groovy.lang.MetaClass;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.Phases;
import org.codehaus.groovy.grails.commons.spring.GrailsResourceHolder;
import org.codehaus.groovy.grails.exceptions.GrailsConfigurationException;
import org.codehaus.groovy.grails.injection.GrailsInjectionOperation;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainConfigurationUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
* Default implementation of the GrailsApplication interface that manages application loading,
* state, and artifact instances.
*
* @author Steven Devijver
* @author Graeme Rocher
*
* @since Jul 2, 2005
*/
public class DefaultGrailsApplication implements GrailsApplication {
private GroovyClassLoader cl = null;
private GrailsControllerClass[] controllerClasses = null;
private GrailsPageFlowClass[] pageFlows = null;
private GrailsDomainClass[] domainClasses = null;
private GrailsCodecClass[] codecClasses;
//private GrailsDataSource[] dataSources = null;
private GrailsServiceClass[] services = null;
private GrailsBootstrapClass[] bootstrapClasses = null;
private GrailsTagLibClass[] taglibClasses = null;
private GrailsTaskClass[] taskClasses = null;
private Map controllerMap = null;
private Map domainMap = null;
private Map pageFlowMap = null;
private Map serviceMap = null;
private Map taglibMap = null;
private Map taskMap = null;
private Map dataSourceMap = null;
private Map codecMap = null;
private Class[] allClasses = null;
private static Log log = LogFactory.getLog(DefaultGrailsApplication.class);
private Map tag2libMap;
private ApplicationContext parentContext;
private MetaClass[] metaClasses;
private Set loadedClasses = new HashSet();
public DefaultGrailsApplication(final Class[] classes, GroovyClassLoader classLoader) {
if(classes == null)
throw new IllegalArgumentException("Constructor argument 'classes' cannot be null");
configureLoadedClasses(classes);
this.cl = classLoader;
}
public DefaultGrailsApplication(final Resource[] resources) throws IOException {
this(resources,null);
}
public DefaultGrailsApplication(final Resource[] resources, final GrailsInjectionOperation injectionOperation) throws IOException {
super();
log.debug("Loading Grails application.");
final GrailsResourceLoader resourceLoader = new GrailsResourceLoader(resources);
GrailsResourceHolder resourceHolder = new GrailsResourceHolder();
if(injectionOperation == null) {
this.cl = new GroovyClassLoader();
}else {
this.cl = new GroovyClassLoader() {
/* (non-Javadoc)
* @see groovy.lang.GroovyClassLoader#createCompilationUnit(org.codehaus.groovy.control.CompilerConfiguration, java.security.CodeSource)
*/
protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource source) {
CompilationUnit cu = super.createCompilationUnit(config, source);
injectionOperation.setResourceLoader(resourceLoader);
cu.addPhaseOperation(injectionOperation, Phases.CONVERSION);
return cu;
}
};
}
this.cl.setShouldRecompile(Boolean.TRUE);
this.cl.setResourceLoader(resourceLoader);
Collection loadedResources = new ArrayList();
this.loadedClasses = new HashSet();
for (int i = 0; resources != null && i < resources.length; i++) {
log.debug("Loading groovy file :[" + resources[i].getFile().getAbsolutePath() + "]");
if (!loadedResources.contains(resources[i])) {
try {
String className = resourceHolder.getClassName(resources[i]);
if(!StringUtils.isBlank(className)) {
Class c = cl.loadClass(className,true,false);
Assert.notNull(c,"Groovy Bug! GCL loadClass method returned a null class!");
loadedClasses.add(c);
loadedResources = resourceLoader.getLoadedResources();
}
} catch (ClassNotFoundException e) {
throw new org.codehaus.groovy.grails.exceptions.CompilationFailedException("Compilation error parsing file ["+resources[i].getFilename()+"]: " + e.getMessage(), e);
}
}
else {
Class c;
try {
c = cl.loadClass(resourceHolder.getClassName(resources[i]));
} catch (ClassNotFoundException e) {
throw new GrailsConfigurationException("Groovy Bug! Resource ["+resources[i]+"] loaded, but not returned by GCL.");
}
loadedClasses.add(c);
}
}
// get all the classes that were loaded
if(log.isDebugEnabled())
log.debug( "loaded classes: ["+loadedClasses+"]" );
Class[] classes = populateAllClasses();
configureLoadedClasses(classes);
}
private Class[] populateAllClasses() {
this.allClasses = (Class[])loadedClasses.toArray(new Class[loadedClasses.size()]);
return allClasses;
}
private void configureLoadedClasses(Class[] classes) {
this.allClasses = classes;
// first load the domain classes
this.domainMap = new HashMap();
log.debug("Going to inspect domain classes.");
for (int i = 0; i < classes.length; i++) {
log.debug("Inspecting [" + classes[i].getName() + "]");
if (Modifier.isAbstract(classes[i].getModifiers())) {
log.debug("[" + classes[i].getName() + "] is abstract.");
continue;
}
// check that it is a domain class
if(GrailsClassUtils.isDomainClass(classes[i])) {
log.debug("[" + classes[i].getName() + "] is a domain class.");
GrailsDomainClass grailsDomainClass = new DefaultGrailsDomainClass(classes[i]);
this.domainMap.put(grailsDomainClass.getFullName(), grailsDomainClass);
} else {
log.debug("[" + classes[i].getName() + "] is not a domain class.");
}
}
this.controllerMap = new HashMap();
this.pageFlowMap = new HashMap();
this.serviceMap = new HashMap();
Map bootstrapMap = new HashMap();
this.taglibMap = new HashMap();
this.taskMap = new HashMap();
this.dataSourceMap = new HashMap();
this.codecMap = new HashMap();
for (int i = 0; i < classes.length; i++) {
if (Modifier.isAbstract(classes[i].getModifiers()) ||
GrailsClassUtils.isDomainClass(classes[i])) {
continue;
}
if (GrailsClassUtils.isControllerClass(classes[i]) /* && not ends with FromController */) {
GrailsControllerClass grailsControllerClass = new DefaultGrailsControllerClass(classes[i]);
if (grailsControllerClass.getAvailable()) {
this.controllerMap.put(grailsControllerClass.getFullName(), grailsControllerClass);
}
} else if (GrailsClassUtils.isPageFlowClass(classes[i])) {
GrailsPageFlowClass grailsPageFlowClass = new DefaultGrailsPageFlowClass(classes[i]);
if (grailsPageFlowClass.getAvailable()) {
this.pageFlowMap.put(grailsPageFlowClass.getFullName(), grailsPageFlowClass);
}
} else if (GrailsClassUtils.isDataSource(classes[i])) {
GrailsDataSource tmpDataSource = new DefaultGrailsDataSource(classes[i]);
this.dataSourceMap.put(GrailsClassUtils.getPropertyNameRepresentation(tmpDataSource.getName()),tmpDataSource);
} else if (GrailsClassUtils.isService(classes[i])) {
GrailsServiceClass grailsServiceClass = new DefaultGrailsServiceClass(classes[i]);
serviceMap.put(grailsServiceClass.getFullName(), grailsServiceClass);
}
else if(GrailsClassUtils.isBootstrapClass(classes[i])) {
GrailsBootstrapClass grailsBootstrapClass = new DefaultGrailsBootstrapClass(classes[i]);
bootstrapMap.put(grailsBootstrapClass.getFullName(),grailsBootstrapClass);
}
else if(GrailsClassUtils.isTagLibClass(classes[i])) {
GrailsTagLibClass grailsTagLibClass = new DefaultGrailsTagLibClass(classes[i]);
this.taglibMap.put(grailsTagLibClass.getFullName(),grailsTagLibClass);
}
else if(GrailsClassUtils.isTaskClass(classes[i])){
GrailsTaskClass grailsTaskClass = new DefaultGrailsTaskClass(classes[i]);
taskMap.put(grailsTaskClass.getFullName(), grailsTaskClass);
log.debug("[" + classes[i].getName() + "] is a task class.");
}
else if(GrailsClassUtils.isCodecClass(classes[i])) {
GrailsCodecClass grailsCodecClass = new DefaultGrailsCodecClass(classes[i]);
codecMap.put(grailsCodecClass.getFullName(), grailsCodecClass);
log.debug("[" + classes[i].getName() + "] is a codec class.");
}
}
this.controllerClasses = ((GrailsControllerClass[])controllerMap.values().toArray(new GrailsControllerClass[controllerMap.size()]));
this.pageFlows = ((GrailsPageFlowClass[])pageFlowMap.values().toArray(new GrailsPageFlowClass[pageFlowMap.size()]));
this.domainClasses = ((GrailsDomainClass[])this.domainMap.values().toArray(new GrailsDomainClass[domainMap.size()]));
this.services = ((GrailsServiceClass[])this.serviceMap.values().toArray(new GrailsServiceClass[serviceMap.size()]));
this.bootstrapClasses = ((GrailsBootstrapClass[])bootstrapMap.values().toArray(new GrailsBootstrapClass[bootstrapMap.size()]));
this.taglibClasses = ((GrailsTagLibClass[])this.taglibMap.values().toArray(new GrailsTagLibClass[taglibMap.size()]));
this.taskClasses = ((GrailsTaskClass[])this.taskMap.values().toArray(new GrailsTaskClass[taskMap.size()]));
this.codecClasses = ((GrailsCodecClass[])this.codecMap.values().toArray(new GrailsCodecClass[codecMap.size()]));
configureDomainClassRelationships();
configureTagLibraries();
}
public GrailsControllerClass addControllerClass(Class controllerClass) {
if (Modifier.isAbstract(controllerClass.getModifiers())) {
return null;
}
if (GrailsClassUtils.isControllerClass(controllerClass)) {
GrailsControllerClass grailsControllerClass = new DefaultGrailsControllerClass(controllerClass);
if (grailsControllerClass.getAvailable()) {
this.controllerMap.put(grailsControllerClass.getFullName(), grailsControllerClass);
}
// reset controller list
this.controllerClasses = ((GrailsControllerClass[])controllerMap.values().toArray(new GrailsControllerClass[controllerMap.size()]));
addToLoaded(controllerClass);
return grailsControllerClass;
}
else {
throw new GrailsConfigurationException("Cannot load controller class ["+controllerClass+"]. It is not a controller!");
}
}
private void addToLoaded(Class clazz) {
this.loadedClasses.add(clazz);
populateAllClasses();
}
public GrailsTagLibClass addTagLibClass(Class tagLibClass) {
if (Modifier.isAbstract(tagLibClass.getModifiers())) {
return null;
}
if (GrailsClassUtils.isTagLibClass(tagLibClass)) {
GrailsTagLibClass grailsTagLibClass = new DefaultGrailsTagLibClass(tagLibClass);
if (grailsTagLibClass.getAvailable()) {
this.taglibMap.put(grailsTagLibClass.getFullName(), grailsTagLibClass);
}
// reset taglib list
this.taglibClasses = ((GrailsTagLibClass[])this.taglibMap.values().toArray(new GrailsTagLibClass[taglibMap.size()]));
// reconfigure controller mappings
configureTagLibraries();
addToLoaded(tagLibClass);
return grailsTagLibClass;
}
else {
throw new GrailsConfigurationException("Cannot load taglib class ["+tagLibClass+"]. It is not a taglib!");
}
}
public GrailsCodecClass addCodecClass(Class codecClass) {
if (Modifier.isAbstract(codecClass.getModifiers())) {
return null;
}
if (GrailsClassUtils.isCodecClass(codecClass)) {
GrailsCodecClass grailsCodecClass = new DefaultGrailsCodecClass(codecClass);
if (grailsCodecClass.getAvailable()) {
this.codecMap.put(grailsCodecClass.getFullName(), grailsCodecClass);
}
// reset taglib list
this.codecClasses = ((GrailsCodecClass[])this.codecMap.values().toArray(new GrailsCodecClass[codecMap.size()]));
// reconfigure controller mappings
addToLoaded(codecClass);
return grailsCodecClass;
}
else {
throw new GrailsConfigurationException("Cannot load codec class ["+codecClass+"]. It is not a codec!");
}
}
public GrailsServiceClass addServiceClass(Class serviceClass) {
if (Modifier.isAbstract(serviceClass.getModifiers())) {
return null;
}
if (GrailsClassUtils.isService(serviceClass)) {
GrailsServiceClass grailsServiceClass = new DefaultGrailsServiceClass(serviceClass);
if (grailsServiceClass.getAvailable()) {
this.serviceMap.put(grailsServiceClass.getFullName(), grailsServiceClass);
}
// reset services list
this.services = ((GrailsServiceClass[])this.serviceMap.values().toArray(new GrailsServiceClass[serviceMap.size()]));
addToLoaded(serviceClass);
return grailsServiceClass;
}
else {
throw new GrailsConfigurationException("Cannot load service class ["+serviceClass+"]. It is not a valid service class!");
}
}
public GrailsDomainClass addDomainClass(Class domainClass) {
if (Modifier.isAbstract(domainClass.getModifiers())) {
return null;
}
if (GrailsClassUtils.isDomainClass(domainClass)) {
GrailsDomainClass grailsDomainClass = new DefaultGrailsDomainClass(domainClass);
this.domainMap.put(grailsDomainClass.getFullName(), grailsDomainClass);
// reset domain class list
this.domainClasses = ((GrailsDomainClass[])this.domainMap.values().toArray(new GrailsDomainClass[domainMap.size()]));
// reconfigure relationships
configureDomainClassRelationships();
addToLoaded(domainClass);
return grailsDomainClass;
}
else {
throw new GrailsConfigurationException("Cannot load domain class ["+domainClass+"]. It is not a valid domain class!");
}
}
public GrailsDomainClass addDomainClass(GrailsDomainClass domainClass) {
if(domainClass != null) {
this.domainMap.put(domainClass.getFullName(),domainClass);
// reset domain class list
this.domainClasses = ((GrailsDomainClass[])this.domainMap.values().toArray(new GrailsDomainClass[domainMap.size()]));
// if(!(domainClass instanceof ExternalGrailsDomainClass)) {
// reconfigure relationships
configureDomainClassRelationships();
// }
}
return domainClass;
}
public GrailsControllerClass getScaffoldingController(GrailsDomainClass domainClass) {
if(domainClass == null)
return null;
for (int i = 0; i < controllerClasses.length; i++) {
GrailsControllerClass controllerClass = controllerClasses[i];
if(controllerClass.isScaffolding()) {
Class scaffoldedClass = controllerClass.getScaffoldedClass();
if(scaffoldedClass != null) {
if(domainClass.getClazz().getName().equals(scaffoldedClass.getName())) {
return controllerClass;
}
}
else if(domainClass.getName().equals(controllerClass.getName())) {
return controllerClass;
}
}
}
return null;
}
/**
* Creates a map of tags to tag libraries
*/
private void configureTagLibraries() {
this.tag2libMap = new HashMap();
for (int i = 0; i < taglibClasses.length; i++) {
GrailsTagLibClass taglibClass = taglibClasses[i];
for (Iterator j = taglibClass.getTagNames().iterator(); j.hasNext();) {
String tagName = (String) j.next();
if(!this.taglibMap.containsKey(tagName)) {
this.tag2libMap.put(tagName,taglibClass);
}
else {
GrailsTagLibClass current = (GrailsTagLibClass)this.taglibMap.get(tagName);
if(!taglibClass.equals(current)) {
this.tag2libMap.put(tagName,taglibClass);
}
else {
throw new GrailsConfigurationException("Cannot configure tag library ["+taglibClass.getName()+"]. Library ["+current.getName()+"] already contains a tag called ["+tagName+"]");
}
}
}
}
}
/**
* Sets up the relationships between the domain classes, this has to be done after
* the intial creation to avoid looping
*
*/
private void configureDomainClassRelationships() {
GrailsDomainConfigurationUtil.configureDomainClassRelationships(this.domainClasses,this.domainMap);
}
public GrailsControllerClass[] getControllers() {
return this.controllerClasses;
}
public GrailsControllerClass getController(String name) {
return (GrailsControllerClass)this.controllerMap.get(name);
}
public GrailsControllerClass getControllerByURI(String uri) {
for (int i = 0; i < controllerClasses.length; i++) {
if (controllerClasses[i].mapsToURI(uri)) {
return controllerClasses[i];
}
}
return null;
}
public GrailsPageFlowClass getPageFlow(String fullname) {
return (GrailsPageFlowClass)this.pageFlowMap.get(fullname);
}
public GrailsPageFlowClass[] getPageFlows() {
return this.pageFlows;
}
public GroovyClassLoader getClassLoader() {
return this.cl;
}
public GrailsDomainClass[] getGrailsDomainClasses() {
return this.domainClasses;
}
public GrailsCodecClass[] getGrailsCodecClasses() {
return this.codecClasses;
}
public boolean isGrailsDomainClass(Class domainClass) {
if(domainClass == null)
return false;
return domainMap.containsKey(domainClass.getName());
}
public GrailsDomainClass getGrailsDomainClass(String name) {
return (GrailsDomainClass)this.domainMap.get(name);
}
public GrailsDataSource getGrailsDataSource() {
String environment = System.getProperty(GrailsApplication.ENVIRONMENT);
if(log.isDebugEnabled()) {
log.debug("[GrailsApplication] Retrieving data source for environment: " + environment);
}
if(StringUtils.isBlank(environment)) {
- GrailsDataSource devDataSource = (GrailsDataSource)this.dataSourceMap.get(GrailsApplication.ENV_DEVELOPMENT);
+ GrailsDataSource devDataSource = (GrailsDataSource)this.dataSourceMap.get(GrailsApplication.ENV_PRODUCTION);
if(devDataSource == null)
devDataSource = (GrailsDataSource)this.dataSourceMap.get(GrailsApplication.ENV_APPLICATION);
if(this.dataSourceMap.size() == 1 && devDataSource == null) {
devDataSource = (GrailsDataSource)this.dataSourceMap.get(this.dataSourceMap.keySet().iterator().next());
}
return devDataSource;
}
else {
GrailsDataSource dataSource = (GrailsDataSource)this.dataSourceMap.get(environment);
if(dataSource == null && GrailsApplication.ENV_DEVELOPMENT.equalsIgnoreCase(environment)) {
dataSource = (GrailsDataSource)this.dataSourceMap.get(GrailsApplication.ENV_APPLICATION);
}
if(dataSource == null) {
log.warn("No data source found for environment ["+environment+"]. Please specify alternative via -Dgrails.env=myenvironment");
}
return dataSource;
}
}
public GrailsServiceClass[] getGrailsServiceClasses() {
return this.services;
}
public GrailsServiceClass getGrailsServiceClass(String name) {
return (GrailsServiceClass)this.serviceMap.get(name);
}
public Class[] getAllClasses() {
return this.allClasses;
}
public GrailsBootstrapClass[] getGrailsBootstrapClasses() { //
return this.bootstrapClasses;
}
public GrailsTagLibClass[] getGrailsTabLibClasses() {
return this.taglibClasses;
}
public GrailsTagLibClass getGrailsTagLibClass(String tagLibName) {
return (GrailsTagLibClass)this.taglibMap.get(tagLibName);
}
public GrailsCodecClass getGrailsCodecClass(String codecName) {
return (GrailsCodecClass)this.codecMap.get(codecName);
}
public GrailsTagLibClass getTagLibClassForTag(String tagName) {
return (GrailsTagLibClass)this.tag2libMap.get(tagName);
}
public GrailsTaskClass[] getGrailsTasksClasses() {
return this.taskClasses;
}
public GrailsTaskClass getGrailsTaskClass(String name) {
return (GrailsTaskClass)this.taskMap.get(name);
}
public GrailsTaskClass addTaskClass(Class loadedClass) {
if (Modifier.isAbstract(loadedClass.getModifiers())) {
return null;
}
if (GrailsClassUtils.isTaskClass(loadedClass)) {
GrailsTaskClass grailsTaskClass = new DefaultGrailsTaskClass(loadedClass);
if (grailsTaskClass.getAvailable()) {
this.taskMap.put(grailsTaskClass.getFullName(), grailsTaskClass);
}
this.taskClasses = ((GrailsTaskClass[])this.taskMap.values().toArray(new GrailsTaskClass[taskMap.size()]));
return grailsTaskClass;
}
else {
throw new GrailsConfigurationException("Cannot load task class ["+loadedClass+"]. It is not a task!");
}
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.parentContext = applicationContext;
}
public ApplicationContext getParentContext() {
return this.parentContext;
}
public GrailsBootstrapClass[] getBootstraps() {
return getGrailsBootstrapClasses();
}
public GrailsDomainClass getDomainClass(String name) {
return getGrailsDomainClass(name);
}
public GrailsDomainClass[] getDomainClasses() {
return getGrailsDomainClasses();
}
public GrailsCodecClass[] getCodecClasses() {
return getGrailsCodecClasses();
}
public GrailsServiceClass getService(String name) {
return getGrailsServiceClass(name);
}
public GrailsServiceClass[] getServices() {
return getGrailsServiceClasses();
}
public GrailsTagLibClass getTagLib(String name) {
return getGrailsTagLibClass(name);
}
public GrailsTagLibClass[] getTagLibs() {
return getGrailsTabLibClasses();
}
public Class getClassForName(String className) {
if(StringUtils.isBlank(className))return null;
for (int i = 0; i < allClasses.length; i++) {
Class c = allClasses[i];
if(c.getName().equals(className))return c;
}
return null;
}
}
diff --git a/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsApplication.java b/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsApplication.java
index 8245ceda7..811c1d9a3 100644
--- a/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsApplication.java
+++ b/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsApplication.java
@@ -1,327 +1,332 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.commons;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import groovy.lang.GroovyClassLoader;
/**
* <p>Exposes all classes for a Grails application.
*
* @author Steven Devijver
* @author Graeme Rocher
*
* @since 0.1
*
* Created: Jul 2, 2005
*/
public interface GrailsApplication extends ApplicationContextAware {
/**
* The id of the grails application within a bean context
*/
String APPLICATION_ID = "grailsApplication";
/**
* Constant used to resolve the environment via System.getProperty(ENVIRONMENT)
*/
String ENVIRONMENT = "grails.env";
/**
* Constant for the development environment
*/
String ENV_DEVELOPMENT = "development";
/**
* Constant for the application data source, primarly for backward compatability for those applications
* that use ApplicationDataSource.groovy
*/
String ENV_APPLICATION = "application";
+
+ /**
+ * Constant for the production environment
+ */
+ String ENV_PRODUCTION = "production";
/**
* <p>Returns all controllers in an application
*
* @return controllers in an application
*/
public GrailsControllerClass[] getControllers();
/**
* <p>Returns the controller with the given full name or null if no controller was found with that name.
*
* @param fullname the controller full name
* @return the controller or null if no controller was found.
*/
public GrailsControllerClass getController(String fullname);
/**
* <p>Returns the controllers that maps to the given URI or null if no controller was found with that name.
*
* @param uri the uri of the request
* @return the controller or null if no controller was found
*/
public GrailsControllerClass getControllerByURI(String uri);
/**
* <p>Returns all tasks in an application.</p>
*
* @return page flows in an application.
*/
public GrailsTaskClass[] getGrailsTasksClasses();
/**
* <p>Returns the task class with the given full name or null if no task was found with that name.
*
* @param fullname name of the task class to retrieve
* @return the retrieved task class
*/
public GrailsTaskClass getGrailsTaskClass( String fullname );
/**
* <p>Returns all page flows in an application.
*
* @return page flows in an application.
* @deprecated Will be removed in future version
*/
public GrailsPageFlowClass[] getPageFlows();
/**
* <p>Returns the page flow with the given full name or null if no page flow was found with that name.
*
* @param fullname the page flow full name
* @return the page flow or null if no controller was found.
*
* @deprecated Will be removed in future version
*/
public GrailsPageFlowClass getPageFlow(String fullname);
/**
* <p>Returns an array of all the Grails Domain classes</p>
*
* @return The domain classes in the domain
*
*/
public GrailsDomainClass[] getGrailsDomainClasses();
/**
* The same as getGrailsDomainClasses which may be deprecated in future
* @return The GrailsDomainClass instances
*/
public GrailsDomainClass[] getDomainClasses();
/**
*
* @return The GrailsCodecClass instances
*/
public GrailsCodecClass[] getCodecClasses();
/**
* Check whether the specified class is a grails domain class
* @param domainClass The class to check
* @return True if it is
*/
public boolean isGrailsDomainClass(Class domainClass);
/**
* <p>Retrieves a domain class for the specified name</p>
*
* @param name The name of the domain class to retrieve
* @return The retrieved domain class
*/
public GrailsDomainClass getGrailsDomainClass(String name);
/**
* The same as getGrailsDomainClass which may be deprecated in future
*/
public GrailsDomainClass getDomainClass( String name );
/**
* <p>Returns the active data source for this Grails application or null if not available.
*
* @return the active data source or null if not available.
*/
public GrailsDataSource getGrailsDataSource();
/**
* <p>Returns the class loader instance for the Grails application</p>
*
* @return The GroovyClassLoader instance
*/
public GroovyClassLoader getClassLoader();
/**
* <p>Returns all service classes for the Grails application.
*
* @return service class for Grails application
*/
public GrailsServiceClass[] getGrailsServiceClasses();
/**
*
* @return All the GrailsServiceClass instances
*/
public GrailsServiceClass[] getServices();
/**
* <p>Returns the service with the specified full name.
*
* @param name the full name of the service class
* @return the service class
*/
public GrailsServiceClass getGrailsServiceClass(String name);
/**
* The same as getGrailsServiceClass which may be deprecated in future
*
* @param name The name of the service clas
* @return The GrailsServiceClass instance or null
*/
public GrailsServiceClass getService(String name);
/**
* <p>Returns all the bootstrap classes for the Grails application
*
* @return An array of BootStrap classes
*/
public GrailsBootstrapClass[] getGrailsBootstrapClasses();
/**
* The same as getGrailsBoostrapClasses() which may be deprecated in future
* @return The bootstrap classes in the system
*/
public GrailsBootstrapClass[] getBootstraps();
/**
* <p>Returns all the tag lib classes for the Grails application
*
* @return An array of TagLib classes
*/
public GrailsTagLibClass[] getGrailsTabLibClasses();
/**
* Sames as getGrailsTagLibClasses() which may be deprecated in future
*
* @return The GrailsTagLibClass instances
*/
public GrailsTagLibClass[] getTagLibs();
/**
* <p>Returns a tag lib class for the specified name
*
* @param tagLibName The name of the taglib class
* @return A taglib class instance or null if non exists
*/
public GrailsTagLibClass getGrailsTagLibClass(String tagLibName);
/**
*
* @param codecName The name of the codec class
* @return A codec class instance or null if non exists
*/
public GrailsCodecClass getGrailsCodecClass(String codecName);
/**
* Adds a new Grails codec class to the application. If it already exists the old one will be replaced
*
* @param codecClass The codec class to add
* @return The newly added class
*/
public GrailsCodecClass addCodecClass(Class codecClass);
/**
* Same as getGrailsTagLibClass which may be deprected in future
*
* @param name The name of the taglib
* @return The tag lib class or null
*/
public GrailsTagLibClass getTagLib(String name);
/**
* <p>Retrieves the tag lib class for the specified tag
*
* @param tagName The name of the tag
* @return A array of tag lib classes
*/
public GrailsTagLibClass getTagLibClassForTag(String tagName);
/**
* Adds a new Grails controller class to the application
* @param controllerClass The grails controller class to add
* @return A GrailsControllerClass instance
*/
GrailsControllerClass addControllerClass(Class controllerClass);
/**
* Adds a new Grails taglib class to the application. If it already exists the old one will be replaced
*
* @param tagLibClass The taglib class to add
* @return The newly added class
*/
GrailsTagLibClass addTagLibClass(Class tagLibClass);
/**
* Adds a new Grails service class to the application. If it already exists the old one will be replaced
*
* @param serviceClass The service class to add
* @return The newly added class or null if the class is abstract and was not added
*/
GrailsServiceClass addServiceClass(Class serviceClass);
/**
* Adds a new domain class to the grails application
* @param domainClass The domain class to add
* @return The GrailsDomainClass instance or null if the class is abstract and was not added
*/
GrailsDomainClass addDomainClass(Class domainClass);
/**
* Adds a new domain class to the grails application
* @param domainClass The domain class to add
* @return The GrailsDomainClass instance or null if the class is abstract and was not added
*/
GrailsDomainClass addDomainClass(GrailsDomainClass domainClass);
/**
* Retrieves the controller that is scaffolding the specified domain class
*
* @param domainClass The domain class to check
* @return An instance of GrailsControllerClass
*/
GrailsControllerClass getScaffoldingController(GrailsDomainClass domainClass);
/**
* Adds a new task class to the grails application
* @param loadedClass The task class to add
* @return The GrailsDomainClass instance or null if the class is abstract and was not added
*/
public GrailsTaskClass addTaskClass(Class loadedClass);
/**
* Retrieves all java.lang.Class instances loaded by the Grails class loader
* @return An array of classes
*/
public Class[] getAllClasses();
/**
*
* @return The parent application context
*/
ApplicationContext getParentContext();
/**
* Retrieves a class for the given name within the GrailsApplication or returns null
*
* @param className The name of the class
* @return The class or null
*/
public Class getClassForName(String className);
}
| false | false | null | null |