diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/dsd-maven-plugin/src/main/java/org/melati/poem/prepro/ReferenceFieldDef.java b/dsd-maven-plugin/src/main/java/org/melati/poem/prepro/ReferenceFieldDef.java
index cbd0663b5..c37b28a30 100644
--- a/dsd-maven-plugin/src/main/java/org/melati/poem/prepro/ReferenceFieldDef.java
+++ b/dsd-maven-plugin/src/main/java/org/melati/poem/prepro/ReferenceFieldDef.java
@@ -1,153 +1,156 @@
/*
* $Source$
* $Revision$
*
* Copyright (C) 2000 William Chesters
*
* Part of Melati (http://melati.org), a framework for the rapid
* development of clean, maintainable web applications.
*
* Melati is free software; Permission is granted to copy, distribute
* and/or modify this software under the terms either:
*
* a) 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,
*
* or
*
* b) any version of the Melati Software License, as published
* at http://melati.org
*
* You should have received a copy of the GNU General Public License and
* the Melati Software License along with this program;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the
* GNU General Public License and visit http://melati.org to obtain the
* Melati Software License.
*
* Feel free to contact the Developers of Melati (http://melati.org),
* if you would like to work out a different arrangement than the options
* outlined here. It is our intention to allow Melati to be used by as
* wide an audience as possible.
*
* 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.
*
* Contact details for copyright holder:
*
* William Chesters <[email protected]>
* http://paneris.org/~williamc
* Obrechtstraat 114, 2517VX Den Haag, The Netherlands
*/
package org.melati.poem.prepro;
import java.util.*;
import java.io.*;
import org.melati.poem.StandardIntegrityFix;
public class ReferenceFieldDef extends FieldDef {
StandardIntegrityFix integrityfix;
public ReferenceFieldDef(TableDef table, String name, int displayOrder,
String type, Vector qualifiers)
throws IllegalityException {
super(table, name, type, "Integer", displayOrder, qualifiers);
}
protected void generateColRawAccessors(Writer w) throws IOException {
super.generateColRawAccessors(w);
w.write(
"\n" +
" public Object getRaw(Persistent g)\n" +
" throws AccessPoemException {\n" +
" return ((" + mainClass + ")g).get" + suffix + "Troid();\n" +
" }\n" +
"\n" +
" public void setRaw(Persistent g, Object raw)\n" +
" throws AccessPoemException {\n" +
" ((" + mainClass + ")g).set" + suffix + "Troid((" +
rawType + ")raw);\n" +
" }\n");
if (integrityfix != null)
w.write(
"\n" +
" public StandardIntegrityFix defaultIntegrityFix() {\n" +
" return StandardIntegrityFix." + integrityfix.name + ";\n" +
" }\n");
}
private String targetCast() {
TableDef targetTable = (TableDef)table.dsd.tableOfClass.get(type);
return targetTable == null || targetTable.superclass == null ?
"" : "(" + type + ")";
}
public void generateBaseMethods(Writer w) throws IOException {
super.generateBaseMethods(w);
// FIXME the definition of these is duplicated from TableDef
String targetTableAccessorMethod = "get" + type + "Table";
String targetSuffix = type;
String db = "get" + table.dsd.databaseClass + "()";
w.write("\n" +
" public Integer get" + suffix + "Troid()\n" +
" throws AccessPoemException {\n" +
" readLock();\n" +
" return get" + suffix + "_unsafe();\n" +
" }\n" +
"\n" +
" public void set" + suffix + "Troid(Integer raw)\n" +
" throws AccessPoemException {\n" +
" set" + suffix + "(" +
- "raw == null ? null : " +
+ "raw == null ? null : \n" +
+ // This cast is necessary when the target table is
+ // an "extends"
+ " " + targetCast() +
db + "." + targetTableAccessorMethod + "()." +
"get" + targetSuffix + "Object(raw));\n" +
" }\n" +
"\n" +
" public " + type + " get" + suffix + "()\n" +
" throws AccessPoemException, NoSuchRowPoemException {\n" +
" Integer troid = get" + suffix + "Troid();\n" +
" return troid == null ? null :\n" +
// This cast is necessary when the target table is
// an "extends"
" " + targetCast() +
db + "." +
targetTableAccessorMethod + "()." +
"get" + targetSuffix + "Object(troid);\n" +
" }\n" +
"\n" +
" public void set" + suffix + "(" + type + " cooked)\n" +
" throws AccessPoemException {\n" +
" _" + tableAccessorMethod + "().get" + suffix + "Column()." +
"getType().assertValidCooked(cooked);\n" +
" writeLock();\n" +
" if (cooked == null)\n" +
" set" + suffix + "_unsafe(null);\n" +
" else {\n" +
" cooked.existenceLock();\n" +
" set" + suffix + "_unsafe(cooked.troid());\n" +
" }\n" +
" }\n");
}
public void generateJavaDeclaration(Writer w) throws IOException {
w.write("Integer " + name);
}
public String poemTypeJava() {
// FIXME the definition of these is duplicated from TableDef
String targetTableAccessorMethod = "get" + type + "Table";
return
"new ReferencePoemType(((" + table.dsd.databaseClass + ")getDatabase())." +
targetTableAccessorMethod + "(), " + isNullable + ")";
}
}
| true | true | public void generateBaseMethods(Writer w) throws IOException {
super.generateBaseMethods(w);
// FIXME the definition of these is duplicated from TableDef
String targetTableAccessorMethod = "get" + type + "Table";
String targetSuffix = type;
String db = "get" + table.dsd.databaseClass + "()";
w.write("\n" +
" public Integer get" + suffix + "Troid()\n" +
" throws AccessPoemException {\n" +
" readLock();\n" +
" return get" + suffix + "_unsafe();\n" +
" }\n" +
"\n" +
" public void set" + suffix + "Troid(Integer raw)\n" +
" throws AccessPoemException {\n" +
" set" + suffix + "(" +
"raw == null ? null : " +
db + "." + targetTableAccessorMethod + "()." +
"get" + targetSuffix + "Object(raw));\n" +
" }\n" +
"\n" +
" public " + type + " get" + suffix + "()\n" +
" throws AccessPoemException, NoSuchRowPoemException {\n" +
" Integer troid = get" + suffix + "Troid();\n" +
" return troid == null ? null :\n" +
// This cast is necessary when the target table is
// an "extends"
" " + targetCast() +
db + "." +
targetTableAccessorMethod + "()." +
"get" + targetSuffix + "Object(troid);\n" +
" }\n" +
"\n" +
" public void set" + suffix + "(" + type + " cooked)\n" +
" throws AccessPoemException {\n" +
" _" + tableAccessorMethod + "().get" + suffix + "Column()." +
"getType().assertValidCooked(cooked);\n" +
" writeLock();\n" +
" if (cooked == null)\n" +
" set" + suffix + "_unsafe(null);\n" +
" else {\n" +
" cooked.existenceLock();\n" +
" set" + suffix + "_unsafe(cooked.troid());\n" +
" }\n" +
" }\n");
}
| public void generateBaseMethods(Writer w) throws IOException {
super.generateBaseMethods(w);
// FIXME the definition of these is duplicated from TableDef
String targetTableAccessorMethod = "get" + type + "Table";
String targetSuffix = type;
String db = "get" + table.dsd.databaseClass + "()";
w.write("\n" +
" public Integer get" + suffix + "Troid()\n" +
" throws AccessPoemException {\n" +
" readLock();\n" +
" return get" + suffix + "_unsafe();\n" +
" }\n" +
"\n" +
" public void set" + suffix + "Troid(Integer raw)\n" +
" throws AccessPoemException {\n" +
" set" + suffix + "(" +
"raw == null ? null : \n" +
// This cast is necessary when the target table is
// an "extends"
" " + targetCast() +
db + "." + targetTableAccessorMethod + "()." +
"get" + targetSuffix + "Object(raw));\n" +
" }\n" +
"\n" +
" public " + type + " get" + suffix + "()\n" +
" throws AccessPoemException, NoSuchRowPoemException {\n" +
" Integer troid = get" + suffix + "Troid();\n" +
" return troid == null ? null :\n" +
// This cast is necessary when the target table is
// an "extends"
" " + targetCast() +
db + "." +
targetTableAccessorMethod + "()." +
"get" + targetSuffix + "Object(troid);\n" +
" }\n" +
"\n" +
" public void set" + suffix + "(" + type + " cooked)\n" +
" throws AccessPoemException {\n" +
" _" + tableAccessorMethod + "().get" + suffix + "Column()." +
"getType().assertValidCooked(cooked);\n" +
" writeLock();\n" +
" if (cooked == null)\n" +
" set" + suffix + "_unsafe(null);\n" +
" else {\n" +
" cooked.existenceLock();\n" +
" set" + suffix + "_unsafe(cooked.troid());\n" +
" }\n" +
" }\n");
}
|
diff --git a/src/java/net/percederberg/mibble/value/NumberValue.java b/src/java/net/percederberg/mibble/value/NumberValue.java
index 0942497..171e5b0 100644
--- a/src/java/net/percederberg/mibble/value/NumberValue.java
+++ b/src/java/net/percederberg/mibble/value/NumberValue.java
@@ -1,179 +1,179 @@
/*
* NumberValue.java
*
* This work 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 work 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
*
* Copyright (c) 2004-2005 Per Cederberg. All rights reserved.
*/
package net.percederberg.mibble.value;
import java.math.BigDecimal;
import java.math.BigInteger;
import net.percederberg.mibble.MibLoaderLog;
import net.percederberg.mibble.MibValue;
/**
* A numeric MIB value.
*
* @author Per Cederberg, <per at percederberg dot net>
* @version 2.6
* @since 2.0
*/
public class NumberValue extends MibValue {
/**
* The number value.
*/
private Number value;
/**
* Creates a new number value.
*
* @param value the number value
*/
public NumberValue(Number value) {
super("Number");
this.value = value;
}
/**
* Initializes the MIB value. This will remove all levels of
* indirection present, such as references to other values. No
* value information is lost by this operation. This method may
* modify this object as a side-effect, and will return the basic
* value.<p>
*
* <strong>NOTE:</strong> This is an internal method that should
* only be called by the MIB loader.
*
* @param log the MIB loader log
*
* @return the basic MIB value
*/
public MibValue initialize(MibLoaderLog log) {
return this;
}
/**
* Creates a value reference to this value. The value reference
* is normally an identical value. Only certain values support
* being referenced, and the default implementation of this
* method throws an exception.<p>
*
* <strong>NOTE:</strong> This is an internal method that should
* only be called by the MIB loader.
*
* @return the MIB value reference
*
* @since 2.2
*/
public MibValue createReference() {
return new NumberValue(value);
}
/**
* Compares this object with the specified object for order. This
* method will attempt to compare by numerical value, but will
* use a string comparison as the default comparison operation.
*
* @param obj the object to compare to
*
* @return less than zero if this object is less than the specified,
* zero if the objects are equal, or
* greater than zero otherwise
*
* @since 2.6
*/
public int compareTo(Object obj) {
if (obj instanceof NumberValue) {
return compareToNumber(((NumberValue) obj).value);
} else if (obj instanceof Number) {
return compareToNumber((Number) obj);
} else {
return toString().compareTo(obj.toString());
}
}
/**
* Compares this object with the specified number for order.
*
* @param num the number to compare to
*
* @return less than zero if this number is less than the specified,
* zero if the numbers are equal, or
* greater than zero otherwise
*/
private int compareToNumber(Number num) {
BigDecimal num1;
BigDecimal num2;
if (value instanceof Integer && num instanceof Integer) {
- return ((Integer) value).compareTo(num);
+ return ((Integer) value).compareTo((Integer) num);
} else if (value instanceof Long && num instanceof Long) {
- return ((Long) value).compareTo(num);
+ return ((Long) value).compareTo((Long) num);
} else if (value instanceof BigInteger
&& num instanceof BigInteger) {
- return ((BigInteger) value).compareTo(num);
+ return ((BigInteger) value).compareTo((BigInteger) num);
} else {
num1 = new BigDecimal(value.toString());
num2 = new BigDecimal(num.toString());
return num1.compareTo(num2);
}
}
/**
* Checks if this object equals another object. This method will
* compare the string representations for equality.
*
* @param obj the object to compare with
*
* @return true if the objects are equal, or
* false otherwise
*/
public boolean equals(Object obj) {
return compareTo(obj) == 0;
}
/**
* Returns a hash code for this object.
*
* @return a hash code for this object
*/
public int hashCode() {
return value.hashCode();
}
/**
* Returns a Java Number representation of this value.
*
* @return a Java Number representation of this value
*/
public Object toObject() {
return value;
}
/**
* Returns a string representation of this value.
*
* @return a string representation of this value
*/
public String toString() {
return value.toString();
}
}
| false | true | private int compareToNumber(Number num) {
BigDecimal num1;
BigDecimal num2;
if (value instanceof Integer && num instanceof Integer) {
return ((Integer) value).compareTo(num);
} else if (value instanceof Long && num instanceof Long) {
return ((Long) value).compareTo(num);
} else if (value instanceof BigInteger
&& num instanceof BigInteger) {
return ((BigInteger) value).compareTo(num);
} else {
num1 = new BigDecimal(value.toString());
num2 = new BigDecimal(num.toString());
return num1.compareTo(num2);
}
}
| private int compareToNumber(Number num) {
BigDecimal num1;
BigDecimal num2;
if (value instanceof Integer && num instanceof Integer) {
return ((Integer) value).compareTo((Integer) num);
} else if (value instanceof Long && num instanceof Long) {
return ((Long) value).compareTo((Long) num);
} else if (value instanceof BigInteger
&& num instanceof BigInteger) {
return ((BigInteger) value).compareTo((BigInteger) num);
} else {
num1 = new BigDecimal(value.toString());
num2 = new BigDecimal(num.toString());
return num1.compareTo(num2);
}
}
|
diff --git a/sensappdroid/src/main/java/org/sensapp/android/sensappdroid/restrequests/PutMeasuresTask.java b/sensappdroid/src/main/java/org/sensapp/android/sensappdroid/restrequests/PutMeasuresTask.java
index c8b1c07..b3ab985 100644
--- a/sensappdroid/src/main/java/org/sensapp/android/sensappdroid/restrequests/PutMeasuresTask.java
+++ b/sensappdroid/src/main/java/org/sensapp/android/sensappdroid/restrequests/PutMeasuresTask.java
@@ -1,227 +1,229 @@
package org.sensapp.android.sensappdroid.restrequests;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.sensapp.android.sensappdroid.R;
import org.sensapp.android.sensappdroid.activities.SensorsActivity;
import org.sensapp.android.sensappdroid.contentprovider.SensAppCPContract;
import org.sensapp.android.sensappdroid.datarequests.DatabaseRequest;
import org.sensapp.android.sensappdroid.json.JsonPrinter;
import org.sensapp.android.sensappdroid.json.MeasureJsonModel;
import org.sensapp.android.sensappdroid.json.NumericalMeasureJsonModel;
import org.sensapp.android.sensappdroid.json.StringMeasureJsonModel;
import org.sensapp.android.sensappdroid.models.Sensor;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class PutMeasuresTask extends AsyncTask<Integer, Integer, Integer> {
private static final String TAG = PutMeasuresTask.class.getSimpleName();
private static final int INTEGER_SIZE = 4;
private static final int LONG_SIZE = 12;
private static final int DEFAULT_SIZE_LIMIT = 200000;
private static final int NOTIFICATION_ID = 10;
private static final int NOTIFICATION_FINAL_ID = 20;
private Context context;
private Uri uri;
private NotificationManager notificationManager;
private Notification notification;
public PutMeasuresTask(Context context, Uri uri) {
super();
this.context = context;
this.uri = uri;
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
private boolean sensorExists(String sensorName) {
String[] projection = {SensAppCPContract.Sensor.NAME};
Cursor cursor = context.getContentResolver().query(Uri.parse(SensAppCPContract.Sensor.CONTENT_URI + "/" + sensorName), projection, null, null, null);
if (cursor != null) {
boolean exists = cursor.getCount() > 0;
cursor.close();
return exists;
}
return false;
}
private List<Long> getBasetimes(String sensorName) {
List<Long> basetimes = new ArrayList<Long>();
String[] projection = {"DISTINCT " + SensAppCPContract.Measure.BASETIME};
Cursor cursor = context.getContentResolver().query(Uri.parse(SensAppCPContract.Measure.CONTENT_URI + "/" + sensorName), projection, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
basetimes.add(cursor.getLong(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.BASETIME)));
}
cursor.close();
}
return basetimes;
}
@Override
protected void onPreExecute() {
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, SensorsActivity.class), 0);
notification = new Notification(R.drawable.ic_launcher, "Starting upload", System.currentTimeMillis());
notification.contentIntent = pendingIntent;
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(context.getPackageName(), R.layout.upload_notification_layout);
notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_launcher);
notification.contentView.setTextViewText(R.id.status_text, "Uploading measures...");
notification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
notificationManager.notify(NOTIFICATION_ID, notification);
}
@Override
protected Integer doInBackground(Integer... params) {
int rowTotal = 0;
Cursor cursor = context.getContentResolver().query(uri, new String[]{SensAppCPContract.Measure.ID}, SensAppCPContract.Measure.UPLOADED + " = 0", null, null);
if (cursor != null) {
rowTotal = cursor.getCount();
cursor.close();
}
notification.contentView.setTextViewText(R.id.status_text, "Uploading " + rowTotal + " measures...");
notificationManager.notify(NOTIFICATION_ID, notification);
int rowsUploaded = 0;
+ int progress = 0;
int sizeLimit = DEFAULT_SIZE_LIMIT;
if (params.length > 0) {
sizeLimit = params[0];
}
ArrayList<String> sensorNames = new ArrayList<String>();
cursor = context.getContentResolver().query(uri, new String[]{"DISTINCT " + SensAppCPContract.Measure.SENSOR}, SensAppCPContract.Measure.UPLOADED + " = 0", null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
sensorNames.add(cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.SENSOR)));
}
cursor.close();
}
Sensor sensor;
for (String sensorName : sensorNames) {
if (!sensorExists(sensorName)) {
Log.e(TAG, "Incorrect database: sensor " + sensorName + " does not exit");
return null;
}
sensor = DatabaseRequest.SensorRQ.getSensor(context, sensorName);
if (!sensor.isUploaded()) {
Uri postSensorResult = null;
try {
postSensorResult = new PostSensorRestTask(context, sensorName).executeOnExecutor(THREAD_POOL_EXECUTOR).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (postSensorResult == null) {
Log.e(TAG, "Post sensor failed");
return null;
}
}
MeasureJsonModel model = null;
if (sensor.getTemplate().equals("Numerical")) {
model = new NumericalMeasureJsonModel(sensorName, sensor.getUnit());
} else if (sensor.getTemplate().equals("String")) {
model = new StringMeasureJsonModel(sensorName, sensor.getUnit());
} else {
Log.e(TAG, "Incorrect sensor template");
return null;
}
List<Integer> ids = new ArrayList<Integer>();
for (Long basetime : getBasetimes(sensorName)) {
model.setBt(basetime);
String[] projection = {SensAppCPContract.Measure.ID, SensAppCPContract.Measure.VALUE, SensAppCPContract.Measure.TIME};
String selection = SensAppCPContract.Measure.SENSOR + " = \"" + model.getBn() + "\" AND " + SensAppCPContract.Measure.BASETIME + " = " + model.getBt() + " AND " + SensAppCPContract.Measure.UPLOADED + " = 0";
cursor = context.getContentResolver().query(uri, projection, selection, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
int size = 0;
while (size == 0) {
while (cursor.moveToNext()) {
ids.add(cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.ID)));
long time = cursor.getLong(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.TIME));
if (model instanceof NumericalMeasureJsonModel) {
int value = cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.VALUE));
((NumericalMeasureJsonModel) model).appendMeasure(value, time);
size += INTEGER_SIZE;
} else if (model instanceof StringMeasureJsonModel) {
String value = cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.VALUE));
((StringMeasureJsonModel) model).appendMeasure(value, time);
size += value.length();
}
size += LONG_SIZE;
if (size > sizeLimit && !cursor.isLast()) {
size = 0;
break;
}
}
try {
RestRequest.putData(sensor.getUri(), JsonPrinter.measuresToJson(model));
} catch (RequestErrorException e) {
Log.e(TAG, e.getMessage());
if (e.getCause() != null) {
Log.e(TAG, e.getCause().getMessage());
}
return null;
}
- ContentValues values = new ContentValues();
- values.put(SensAppCPContract.Measure.UPLOADED, 1);
- selection = SensAppCPContract.Measure.ID + " IN " + ids.toString().replace('[', '(').replace(']', ')');
- rowsUploaded += context.getContentResolver().update(uri, values, selection, null);
- publishProgress((int) ((float) rowsUploaded / rowTotal * 100));
- ids.clear();
model.clearValues();
+ publishProgress((int) ((float) (progress + ids.size()) / rowTotal * 100));
}
+ ContentValues values = new ContentValues();
+ values.put(SensAppCPContract.Measure.UPLOADED, 1);
+ selection = SensAppCPContract.Measure.ID + " IN " + ids.toString().replace('[', '(').replace(']', ')');
+ rowsUploaded += context.getContentResolver().update(uri, values, selection, null);
+ progress += ids.size();
+ ids.clear();
}
cursor.close();
}
}
}
return rowsUploaded;
}
@Override
protected void onProgressUpdate(Integer... values) {
notification.contentView.setProgressBar(R.id.status_progress, 100, values[0], false);
notificationManager.notify(NOTIFICATION_ID, notification);
}
@Override
protected void onPostExecute(Integer result) {
notificationManager.cancel(NOTIFICATION_ID);
if (result == null) {
Log.e(TAG, "Put data error");
Toast.makeText(context, "Upload failed", Toast.LENGTH_LONG).show();
} else {
Log.i(TAG, "Put data succed: " + result + " measures uploaded");
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, SensorsActivity.class), 0);
Notification notificationFinal = new Notification(R.drawable.ic_launcher, "Upload finished", System.currentTimeMillis());
notificationFinal.setLatestEventInfo(context, "Upload succeed", result + " measures uploaded", pendingIntent);
notificationManager.notify(NOTIFICATION_FINAL_ID, notificationFinal);
Toast.makeText(context, "Upload succeed: " + result + " measures uploaded", Toast.LENGTH_LONG).show();
}
}
}
| false | true | protected Integer doInBackground(Integer... params) {
int rowTotal = 0;
Cursor cursor = context.getContentResolver().query(uri, new String[]{SensAppCPContract.Measure.ID}, SensAppCPContract.Measure.UPLOADED + " = 0", null, null);
if (cursor != null) {
rowTotal = cursor.getCount();
cursor.close();
}
notification.contentView.setTextViewText(R.id.status_text, "Uploading " + rowTotal + " measures...");
notificationManager.notify(NOTIFICATION_ID, notification);
int rowsUploaded = 0;
int sizeLimit = DEFAULT_SIZE_LIMIT;
if (params.length > 0) {
sizeLimit = params[0];
}
ArrayList<String> sensorNames = new ArrayList<String>();
cursor = context.getContentResolver().query(uri, new String[]{"DISTINCT " + SensAppCPContract.Measure.SENSOR}, SensAppCPContract.Measure.UPLOADED + " = 0", null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
sensorNames.add(cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.SENSOR)));
}
cursor.close();
}
Sensor sensor;
for (String sensorName : sensorNames) {
if (!sensorExists(sensorName)) {
Log.e(TAG, "Incorrect database: sensor " + sensorName + " does not exit");
return null;
}
sensor = DatabaseRequest.SensorRQ.getSensor(context, sensorName);
if (!sensor.isUploaded()) {
Uri postSensorResult = null;
try {
postSensorResult = new PostSensorRestTask(context, sensorName).executeOnExecutor(THREAD_POOL_EXECUTOR).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (postSensorResult == null) {
Log.e(TAG, "Post sensor failed");
return null;
}
}
MeasureJsonModel model = null;
if (sensor.getTemplate().equals("Numerical")) {
model = new NumericalMeasureJsonModel(sensorName, sensor.getUnit());
} else if (sensor.getTemplate().equals("String")) {
model = new StringMeasureJsonModel(sensorName, sensor.getUnit());
} else {
Log.e(TAG, "Incorrect sensor template");
return null;
}
List<Integer> ids = new ArrayList<Integer>();
for (Long basetime : getBasetimes(sensorName)) {
model.setBt(basetime);
String[] projection = {SensAppCPContract.Measure.ID, SensAppCPContract.Measure.VALUE, SensAppCPContract.Measure.TIME};
String selection = SensAppCPContract.Measure.SENSOR + " = \"" + model.getBn() + "\" AND " + SensAppCPContract.Measure.BASETIME + " = " + model.getBt() + " AND " + SensAppCPContract.Measure.UPLOADED + " = 0";
cursor = context.getContentResolver().query(uri, projection, selection, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
int size = 0;
while (size == 0) {
while (cursor.moveToNext()) {
ids.add(cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.ID)));
long time = cursor.getLong(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.TIME));
if (model instanceof NumericalMeasureJsonModel) {
int value = cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.VALUE));
((NumericalMeasureJsonModel) model).appendMeasure(value, time);
size += INTEGER_SIZE;
} else if (model instanceof StringMeasureJsonModel) {
String value = cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.VALUE));
((StringMeasureJsonModel) model).appendMeasure(value, time);
size += value.length();
}
size += LONG_SIZE;
if (size > sizeLimit && !cursor.isLast()) {
size = 0;
break;
}
}
try {
RestRequest.putData(sensor.getUri(), JsonPrinter.measuresToJson(model));
} catch (RequestErrorException e) {
Log.e(TAG, e.getMessage());
if (e.getCause() != null) {
Log.e(TAG, e.getCause().getMessage());
}
return null;
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Measure.UPLOADED, 1);
selection = SensAppCPContract.Measure.ID + " IN " + ids.toString().replace('[', '(').replace(']', ')');
rowsUploaded += context.getContentResolver().update(uri, values, selection, null);
publishProgress((int) ((float) rowsUploaded / rowTotal * 100));
ids.clear();
model.clearValues();
}
}
cursor.close();
}
}
}
return rowsUploaded;
}
@Override
protected void onProgressUpdate(Integer... values) {
notification.contentView.setProgressBar(R.id.status_progress, 100, values[0], false);
notificationManager.notify(NOTIFICATION_ID, notification);
}
@Override
protected void onPostExecute(Integer result) {
notificationManager.cancel(NOTIFICATION_ID);
if (result == null) {
Log.e(TAG, "Put data error");
Toast.makeText(context, "Upload failed", Toast.LENGTH_LONG).show();
} else {
Log.i(TAG, "Put data succed: " + result + " measures uploaded");
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, SensorsActivity.class), 0);
Notification notificationFinal = new Notification(R.drawable.ic_launcher, "Upload finished", System.currentTimeMillis());
notificationFinal.setLatestEventInfo(context, "Upload succeed", result + " measures uploaded", pendingIntent);
notificationManager.notify(NOTIFICATION_FINAL_ID, notificationFinal);
Toast.makeText(context, "Upload succeed: " + result + " measures uploaded", Toast.LENGTH_LONG).show();
}
}
}
| protected Integer doInBackground(Integer... params) {
int rowTotal = 0;
Cursor cursor = context.getContentResolver().query(uri, new String[]{SensAppCPContract.Measure.ID}, SensAppCPContract.Measure.UPLOADED + " = 0", null, null);
if (cursor != null) {
rowTotal = cursor.getCount();
cursor.close();
}
notification.contentView.setTextViewText(R.id.status_text, "Uploading " + rowTotal + " measures...");
notificationManager.notify(NOTIFICATION_ID, notification);
int rowsUploaded = 0;
int progress = 0;
int sizeLimit = DEFAULT_SIZE_LIMIT;
if (params.length > 0) {
sizeLimit = params[0];
}
ArrayList<String> sensorNames = new ArrayList<String>();
cursor = context.getContentResolver().query(uri, new String[]{"DISTINCT " + SensAppCPContract.Measure.SENSOR}, SensAppCPContract.Measure.UPLOADED + " = 0", null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
sensorNames.add(cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.SENSOR)));
}
cursor.close();
}
Sensor sensor;
for (String sensorName : sensorNames) {
if (!sensorExists(sensorName)) {
Log.e(TAG, "Incorrect database: sensor " + sensorName + " does not exit");
return null;
}
sensor = DatabaseRequest.SensorRQ.getSensor(context, sensorName);
if (!sensor.isUploaded()) {
Uri postSensorResult = null;
try {
postSensorResult = new PostSensorRestTask(context, sensorName).executeOnExecutor(THREAD_POOL_EXECUTOR).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (postSensorResult == null) {
Log.e(TAG, "Post sensor failed");
return null;
}
}
MeasureJsonModel model = null;
if (sensor.getTemplate().equals("Numerical")) {
model = new NumericalMeasureJsonModel(sensorName, sensor.getUnit());
} else if (sensor.getTemplate().equals("String")) {
model = new StringMeasureJsonModel(sensorName, sensor.getUnit());
} else {
Log.e(TAG, "Incorrect sensor template");
return null;
}
List<Integer> ids = new ArrayList<Integer>();
for (Long basetime : getBasetimes(sensorName)) {
model.setBt(basetime);
String[] projection = {SensAppCPContract.Measure.ID, SensAppCPContract.Measure.VALUE, SensAppCPContract.Measure.TIME};
String selection = SensAppCPContract.Measure.SENSOR + " = \"" + model.getBn() + "\" AND " + SensAppCPContract.Measure.BASETIME + " = " + model.getBt() + " AND " + SensAppCPContract.Measure.UPLOADED + " = 0";
cursor = context.getContentResolver().query(uri, projection, selection, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
int size = 0;
while (size == 0) {
while (cursor.moveToNext()) {
ids.add(cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.ID)));
long time = cursor.getLong(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.TIME));
if (model instanceof NumericalMeasureJsonModel) {
int value = cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.VALUE));
((NumericalMeasureJsonModel) model).appendMeasure(value, time);
size += INTEGER_SIZE;
} else if (model instanceof StringMeasureJsonModel) {
String value = cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.VALUE));
((StringMeasureJsonModel) model).appendMeasure(value, time);
size += value.length();
}
size += LONG_SIZE;
if (size > sizeLimit && !cursor.isLast()) {
size = 0;
break;
}
}
try {
RestRequest.putData(sensor.getUri(), JsonPrinter.measuresToJson(model));
} catch (RequestErrorException e) {
Log.e(TAG, e.getMessage());
if (e.getCause() != null) {
Log.e(TAG, e.getCause().getMessage());
}
return null;
}
model.clearValues();
publishProgress((int) ((float) (progress + ids.size()) / rowTotal * 100));
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Measure.UPLOADED, 1);
selection = SensAppCPContract.Measure.ID + " IN " + ids.toString().replace('[', '(').replace(']', ')');
rowsUploaded += context.getContentResolver().update(uri, values, selection, null);
progress += ids.size();
ids.clear();
}
cursor.close();
}
}
}
return rowsUploaded;
}
@Override
protected void onProgressUpdate(Integer... values) {
notification.contentView.setProgressBar(R.id.status_progress, 100, values[0], false);
notificationManager.notify(NOTIFICATION_ID, notification);
}
@Override
protected void onPostExecute(Integer result) {
notificationManager.cancel(NOTIFICATION_ID);
if (result == null) {
Log.e(TAG, "Put data error");
Toast.makeText(context, "Upload failed", Toast.LENGTH_LONG).show();
} else {
Log.i(TAG, "Put data succed: " + result + " measures uploaded");
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, SensorsActivity.class), 0);
Notification notificationFinal = new Notification(R.drawable.ic_launcher, "Upload finished", System.currentTimeMillis());
notificationFinal.setLatestEventInfo(context, "Upload succeed", result + " measures uploaded", pendingIntent);
notificationManager.notify(NOTIFICATION_FINAL_ID, notificationFinal);
Toast.makeText(context, "Upload succeed: " + result + " measures uploaded", Toast.LENGTH_LONG).show();
}
}
}
|
diff --git a/src/main/java/com/widen/examples/ValetExample.java b/src/main/java/com/widen/examples/ValetExample.java
index 569af38..dad6c9b 100644
--- a/src/main/java/com/widen/examples/ValetExample.java
+++ b/src/main/java/com/widen/examples/ValetExample.java
@@ -1,93 +1,93 @@
package com.widen.examples;
import java.util.ArrayList;
import java.util.List;
import com.widen.valet.RecordType;
import com.widen.valet.Route53Driver;
import com.widen.valet.Zone;
import com.widen.valet.ZoneChangeStatus;
import com.widen.valet.ZoneResource;
import com.widen.valet.ZoneUpdateAction;
import com.widen.valet.util.NameQueryByRoute53APIService;
import com.widen.valet.util.NameQueryService;
/**
* Simple example usage of using Valet API to create and update DNS zones in AWS Route53
*/
public class ValetExample
{
private static final String AWS_ACCESS_KEY = "";
private static final String AWS_SECRET_KEY = "";
public static void main(String[] args)
{
new ValetExample().run();
}
private void run()
{
String domain = "foodomain.com.";
String resource = "www";
String resourceValue = "127.0.0.2";
//Route53Driver is the API abstraction for accessing Route53
Route53Driver driver = new Route53Driver(AWS_ACCESS_KEY, AWS_SECRET_KEY);
Zone zone = driver.zoneDetailsForDomain(domain);
if (zone.equals(Zone.NON_EXISTENT_ZONE))
{
//create the Route53 zone if it does not exist
//WARNING: Route53 allows you to create multiple zones using the same domain
ZoneChangeStatus createStatus = driver.createZone(domain, "Create zone " + domain);
//you should not modify zones that are not INSYNC
driver.waitForSync(createStatus);
zone = driver.zoneDetails(createStatus.getZoneId());
}
System.out.println("zone: " + zone);
//Simple query service to search for existing resources within the zone
NameQueryService queryService = new NameQueryByRoute53APIService(driver, zone);
- NameQueryService.LookupRecord lookup = queryService.lookup(resource, RecordType.A);
+ NameQueryService.LookupRecord lookup = queryService.lookup(resource + "." + domain, RecordType.A);
//Holds the commands to run within the update transaction
List<ZoneUpdateAction> actions = new ArrayList<ZoneUpdateAction>();
if (lookup.exists)
{
//if the resource exists it must be deleted within the update transaction
- ZoneUpdateAction delete = new ZoneUpdateAction.Builder().withData(resource, RecordType.A, lookup.values).withTtl(lookup.ttl).buildDeleteAction();
+ ZoneUpdateAction delete = new ZoneUpdateAction.Builder().withData(resource + "." + domain, RecordType.A, lookup.values).withTtl(lookup.ttl).buildDeleteAction();
//ZoneUpdateAction.deleteAction(resource, RecordType.A, 600, lookup.getFirstValue());
actions.add(delete);
}
ZoneUpdateAction create = new ZoneUpdateAction.Builder().withData(resource, zone, RecordType.A, resourceValue).buildCreateAction();
actions.add(create);
//Update zone will throw a ValetException if Route53 rejects the transaction block
ZoneChangeStatus updateChangeStatus = driver.updateZone(zone, "Update WWW record", actions);
driver.waitForSync(updateChangeStatus);
List<ZoneResource> zoneResources = driver.listZoneRecords(zone);
System.out.println("Update complete...");
for (ZoneResource zoneResource : zoneResources)
{
System.out.println(zoneResource);
}
}
}
| false | true | private void run()
{
String domain = "foodomain.com.";
String resource = "www";
String resourceValue = "127.0.0.2";
//Route53Driver is the API abstraction for accessing Route53
Route53Driver driver = new Route53Driver(AWS_ACCESS_KEY, AWS_SECRET_KEY);
Zone zone = driver.zoneDetailsForDomain(domain);
if (zone.equals(Zone.NON_EXISTENT_ZONE))
{
//create the Route53 zone if it does not exist
//WARNING: Route53 allows you to create multiple zones using the same domain
ZoneChangeStatus createStatus = driver.createZone(domain, "Create zone " + domain);
//you should not modify zones that are not INSYNC
driver.waitForSync(createStatus);
zone = driver.zoneDetails(createStatus.getZoneId());
}
System.out.println("zone: " + zone);
//Simple query service to search for existing resources within the zone
NameQueryService queryService = new NameQueryByRoute53APIService(driver, zone);
NameQueryService.LookupRecord lookup = queryService.lookup(resource, RecordType.A);
//Holds the commands to run within the update transaction
List<ZoneUpdateAction> actions = new ArrayList<ZoneUpdateAction>();
if (lookup.exists)
{
//if the resource exists it must be deleted within the update transaction
ZoneUpdateAction delete = new ZoneUpdateAction.Builder().withData(resource, RecordType.A, lookup.values).withTtl(lookup.ttl).buildDeleteAction();
//ZoneUpdateAction.deleteAction(resource, RecordType.A, 600, lookup.getFirstValue());
actions.add(delete);
}
ZoneUpdateAction create = new ZoneUpdateAction.Builder().withData(resource, zone, RecordType.A, resourceValue).buildCreateAction();
actions.add(create);
//Update zone will throw a ValetException if Route53 rejects the transaction block
ZoneChangeStatus updateChangeStatus = driver.updateZone(zone, "Update WWW record", actions);
driver.waitForSync(updateChangeStatus);
List<ZoneResource> zoneResources = driver.listZoneRecords(zone);
System.out.println("Update complete...");
for (ZoneResource zoneResource : zoneResources)
{
System.out.println(zoneResource);
}
}
| private void run()
{
String domain = "foodomain.com.";
String resource = "www";
String resourceValue = "127.0.0.2";
//Route53Driver is the API abstraction for accessing Route53
Route53Driver driver = new Route53Driver(AWS_ACCESS_KEY, AWS_SECRET_KEY);
Zone zone = driver.zoneDetailsForDomain(domain);
if (zone.equals(Zone.NON_EXISTENT_ZONE))
{
//create the Route53 zone if it does not exist
//WARNING: Route53 allows you to create multiple zones using the same domain
ZoneChangeStatus createStatus = driver.createZone(domain, "Create zone " + domain);
//you should not modify zones that are not INSYNC
driver.waitForSync(createStatus);
zone = driver.zoneDetails(createStatus.getZoneId());
}
System.out.println("zone: " + zone);
//Simple query service to search for existing resources within the zone
NameQueryService queryService = new NameQueryByRoute53APIService(driver, zone);
NameQueryService.LookupRecord lookup = queryService.lookup(resource + "." + domain, RecordType.A);
//Holds the commands to run within the update transaction
List<ZoneUpdateAction> actions = new ArrayList<ZoneUpdateAction>();
if (lookup.exists)
{
//if the resource exists it must be deleted within the update transaction
ZoneUpdateAction delete = new ZoneUpdateAction.Builder().withData(resource + "." + domain, RecordType.A, lookup.values).withTtl(lookup.ttl).buildDeleteAction();
//ZoneUpdateAction.deleteAction(resource, RecordType.A, 600, lookup.getFirstValue());
actions.add(delete);
}
ZoneUpdateAction create = new ZoneUpdateAction.Builder().withData(resource, zone, RecordType.A, resourceValue).buildCreateAction();
actions.add(create);
//Update zone will throw a ValetException if Route53 rejects the transaction block
ZoneChangeStatus updateChangeStatus = driver.updateZone(zone, "Update WWW record", actions);
driver.waitForSync(updateChangeStatus);
List<ZoneResource> zoneResources = driver.listZoneRecords(zone);
System.out.println("Update complete...");
for (ZoneResource zoneResource : zoneResources)
{
System.out.println(zoneResource);
}
}
|
diff --git a/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java b/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java
index 149e8e4..f0fabc0 100644
--- a/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java
+++ b/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java
@@ -1,570 +1,571 @@
/*
* Copyright 2011 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.powertac.factoredcustomer;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import org.apache.log4j.Logger;
import org.powertac.common.Tariff;
import org.powertac.common.TariffSubscription;
import org.powertac.common.TimeService;
import org.powertac.common.Timeslot;
import org.powertac.common.repo.RandomSeedRepo;
import org.powertac.common.repo.TariffSubscriptionRepo;
import org.powertac.common.repo.TimeslotRepo;
import org.powertac.common.interfaces.TariffMarket;
import org.powertac.common.enumerations.PowerType;
import org.powertac.common.spring.SpringApplicationContext;
import org.powertac.common.state.Domain;
import org.powertac.common.state.StateChange;
import org.powertac.factoredcustomer.interfaces.*;
import org.powertac.factoredcustomer.TariffSubscriberStructure.AllocationMethod;
/**
* Key class responsible for managing the tariff(s) for one customer across
* multiple capacity bundles if necessary.
*
* @author Prashant Reddy
*/
@Domain
class DefaultUtilityOptimizer implements UtilityOptimizer
{
protected Logger log = Logger.getLogger(DefaultUtilityOptimizer.class.getName());
protected final FactoredCustomerService factoredCustomerService;
protected final TariffMarket tariffMarketService;
protected final TariffSubscriptionRepo tariffSubscriptionRepo;
protected final TimeslotRepo timeslotRepo;
protected final RandomSeedRepo randomSeedRepo;
protected static final int NUM_HOURS_IN_DAY = 24;
protected static final long MEAN_TARIFF_DURATION = 5; // number of days
protected final CustomerStructure customerStructure;
protected final List<CapacityBundle> capacityBundles;
protected final List<Tariff> ignoredTariffs = new ArrayList<Tariff>();
protected Random inertiaSampler;
protected Random tariffSelector;
protected final List<Tariff> allTariffs = new ArrayList<Tariff>();
private int tariffEvaluationCounter = 0;
DefaultUtilityOptimizer(CustomerStructure structure, List<CapacityBundle> bundles)
{
customerStructure = structure;
capacityBundles = bundles;
factoredCustomerService = (FactoredCustomerService) SpringApplicationContext.getBean("factoredCustomerService");
tariffMarketService = (TariffMarket) SpringApplicationContext.getBean("tariffMarketService");
tariffSubscriptionRepo = (TariffSubscriptionRepo) SpringApplicationContext.getBean("tariffSubscriptionRepo");
timeslotRepo = (TimeslotRepo) SpringApplicationContext.getBean("timeslotRepo");
randomSeedRepo = (RandomSeedRepo) SpringApplicationContext.getBean("randomSeedRepo");
}
@Override
public void initialize()
{
inertiaSampler = new Random(randomSeedRepo.getRandomSeed("factoredcustomer.DefaultUtilityOptimizer",
customerStructure.structureId, "InertiaSampler").getValue());
tariffSelector = new Random(randomSeedRepo.getRandomSeed("factoredcustomer.DefaultUtilityOptimizer",
customerStructure.structureId, "TariffSelector").getValue());
subscribeDefault();
}
///////////////// TARIFF EVALUATION //////////////////////
@StateChange
protected void subscribe(Tariff tariff, CapacityBundle bundle, int customerCount, boolean verbose)
{
tariffMarketService.subscribeToTariff(tariff, bundle.getCustomerInfo(), customerCount);
if (verbose) log.info(bundle.getName() + ": Subscribed " + customerCount + " customers to tariff " + tariff.getId() + " successfully");
}
@StateChange
protected void unsubscribe(TariffSubscription subscription, CapacityBundle bundle, int customerCount, boolean verbose)
{
subscription.unsubscribe(customerCount);
if (verbose) log.info(bundle.getName() + ": Unsubscribed " + customerCount + " customers from tariff " + subscription.getTariff().getId() + " successfully");
}
/** @Override hook **/
protected void subscribeDefault()
{
for (CapacityBundle bundle: capacityBundles) {
PowerType powerType = bundle.getPowerType();
if (tariffMarketService.getDefaultTariff(powerType) != null) {
log.info(bundle.getName() + ": Subscribing " + bundle.getPopulation() + " customers to default " + powerType + " tariff");
subscribe(tariffMarketService.getDefaultTariff(powerType), bundle, bundle.getPopulation(), false);
} else {
log.info(bundle.getName() + ": No default tariff for power type " + powerType + "; trying generic type");
PowerType genericType = powerType.getGenericType();
if (tariffMarketService.getDefaultTariff(genericType) == null) {
log.error(bundle.getName() + ": No default tariff for generic power type " + genericType + " either!");
} else {
log.info(bundle.getName() + ": Subscribing " + bundle.getPopulation() + " customers to default " + genericType + " tariff");
subscribe(tariffMarketService.getDefaultTariff(genericType), bundle, bundle.getPopulation(), false);
}
}
}
}
@Override
public void handleNewTariffs (List<Tariff> newTariffs)
{
++tariffEvaluationCounter;
for (Tariff tariff: newTariffs) {
allTariffs.add(tariff);
}
for (CapacityBundle bundle: capacityBundles) {
evaluateTariffs(bundle, newTariffs);
}
}
private void evaluateTariffs(CapacityBundle bundle, List<Tariff> newTariffs)
{
if ((tariffEvaluationCounter % bundle.getSubscriberStructure().reconsiderationPeriod) == 0) {
reevaluateAllTariffs(bundle);
}
else if (! ignoredTariffs.isEmpty()) {
evaluateCurrentTariffs(bundle, newTariffs);
}
else if (! newTariffs.isEmpty()) {
boolean ignoringNewTariffs = true;
for (Tariff tariff: newTariffs) {
if (isTariffApplicable(tariff, bundle)) {
ignoringNewTariffs = false;
evaluateCurrentTariffs(bundle, newTariffs);
break;
}
}
if (ignoringNewTariffs) log.info(bundle.getName() + ": New tariffs are not applicable; skipping evaluation");
}
}
private void reevaluateAllTariffs(CapacityBundle bundle)
{
log.info(bundle.getName() + ": Reevaluating all tariffs for " + bundle.getPowerType() + " subscriptions");
List<Tariff> evalTariffs = new ArrayList<Tariff>();
for (Tariff tariff: allTariffs) {
if (! tariff.isRevoked() && ! tariff.isExpired() && isTariffApplicable(tariff, bundle)) {
evalTariffs.add(tariff);
}
}
assertNotEmpty(bundle, evalTariffs);
manageSubscriptions(bundle, evalTariffs);
}
private boolean isTariffApplicable(Tariff tariff, CapacityBundle bundle)
{
PowerType bundlePowerType = bundle.getCustomerInfo().getPowerType();
if (tariff.getPowerType() == bundlePowerType ||
tariff.getPowerType() == bundlePowerType.getGenericType()) {
return true;
}
return false;
}
private void evaluateCurrentTariffs(CapacityBundle bundle, List<Tariff> newTariffs)
{
if (bundle.getSubscriberStructure().inertiaDistribution != null) {
double inertia = bundle.getSubscriberStructure().inertiaDistribution.drawSample();
if (inertiaSampler.nextDouble() < inertia) {
log.info(bundle.getName() + ": Skipping " + bundle.getCustomerInfo().getPowerType() + " tariff reevaluation due to inertia");
for (Tariff newTariff: newTariffs) {
ignoredTariffs.add(newTariff);
}
return;
}
}
// Include previously ignored tariffs and currently subscribed tariffs in evaluation.
// Use map instead of list to eliminate duplicate tariffs.
Map<Long, Tariff> currTariffs = new HashMap<Long, Tariff>();
for (Tariff ignoredTariff: ignoredTariffs) {
currTariffs.put(ignoredTariff.getId(), ignoredTariff);
}
ignoredTariffs.clear();
List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findSubscriptionsForCustomer(bundle.getCustomerInfo());
for (TariffSubscription subscription: subscriptions) {
currTariffs.put(subscription.getTariff().getId(), subscription.getTariff());
}
for (Tariff newTariff: newTariffs) {
currTariffs.put(newTariff.getId(), newTariff);
}
List<Tariff> evalTariffs = new ArrayList<Tariff>();
for (Tariff tariff: currTariffs.values()) {
if (isTariffApplicable(tariff, bundle)) {
evalTariffs.add(tariff);
}
}
assertNotEmpty(bundle, evalTariffs);
manageSubscriptions(bundle, evalTariffs);
}
private void assertNotEmpty(CapacityBundle bundle, List<Tariff> evalTariffs)
{
if (evalTariffs.isEmpty()) {
throw new Error(bundle.getName() + ": The evaluation tariffs list is unexpectedly empty!");
}
}
private void manageSubscriptions(CapacityBundle bundle, List<Tariff> evalTariffs)
{
Collections.shuffle(evalTariffs);
PowerType powerType = bundle.getCustomerInfo().getPowerType();
List<Long> tariffIds = new ArrayList<Long>(evalTariffs.size());
for (Tariff tariff: evalTariffs) tariffIds.add(tariff.getId());
logAllocationDetails(bundle.getName() + ": " + powerType + " tariffs for evaluation: " + tariffIds);
List<Double> estimatedPayments = estimatePayments(bundle, evalTariffs);
logAllocationDetails(bundle.getName() + ": Estimated payments for evaluated tariffs: " + estimatedPayments);
List<Integer> allocations = determineAllocations(bundle, evalTariffs, estimatedPayments);
logAllocationDetails(bundle.getName() + ": Allocations for evaluated tariffs: " + allocations);
int overAllocations = 0;
for (int i=0; i < evalTariffs.size(); ++i) {
Tariff evalTariff = evalTariffs.get(i);
int allocation = allocations.get(i);
TariffSubscription subscription = tariffSubscriptionRepo.findSubscriptionForTariffAndCustomer(evalTariff, bundle.getCustomerInfo()); // could be null
int currentCommitted = (subscription != null) ? subscription.getCustomersCommitted() : 0;
int numChange = allocation - currentCommitted;
log.debug(bundle.getName() + ": evalTariff = " + evalTariff.getId() + ", numChange = " + numChange +
", currentCommitted = " + currentCommitted + ", allocation = " + allocation);
if (numChange == 0) {
if (currentCommitted > 0) {
log.info(bundle.getName() + ": Maintaining " + currentCommitted + " " + powerType + " customers in tariff " + evalTariff.getId());
} else {
log.info(bundle.getName() + ": Not allocating any " + powerType + " customers to tariff " + evalTariff.getId());
}
} else if (numChange > 0) {
if (evalTariff.isExpired()) {
overAllocations += numChange;
if (currentCommitted > 0) {
log.info(bundle.getName() + ": Maintaining " + currentCommitted + " " + powerType + " customers in expired tariff " + evalTariff.getId());
}
log.info(bundle.getName() + ": Reallocating " + numChange + " " + powerType + " customers from expired tariff " + evalTariff.getId() + " to other tariffs");
} else {
log.info(bundle.getName() + ": Subscribing " + numChange + " " + powerType + " customers to tariff " + evalTariff.getId());
subscribe(evalTariff, bundle, numChange, false);
}
} else if (numChange < 0) {
log.info(bundle.getName() + ": Unsubscribing " + -numChange + " " + powerType + " customers from tariff " + evalTariff.getId());
unsubscribe(subscription, bundle, -numChange, false);
}
}
if (overAllocations > 0) {
int minIndex = 0;
double minEstimate = Double.POSITIVE_INFINITY;
for (int i=0; i < estimatedPayments.size(); ++i) {
if (estimatedPayments.get(i) < minEstimate && ! evalTariffs.get(i).isExpired()) {
minIndex = i;
minEstimate = estimatedPayments.get(i);
}
}
log.info(bundle.getName() + ": Subscribing " + overAllocations + " over-allocated customers to tariff " + evalTariffs.get(minIndex).getId());
subscribe(evalTariffs.get(minIndex), bundle, overAllocations, false);
}
}
private List<Double> estimatePayments(CapacityBundle bundle, List<Tariff> evalTariffs)
{
List<Double> estimatedPayments = new ArrayList<Double>(evalTariffs.size());
for (int i=0; i < evalTariffs.size(); ++i) {
Tariff tariff = evalTariffs.get(i);
if (tariff.isExpired()) {
if (bundle.getCustomerInfo().getPowerType().isConsumption()) {
estimatedPayments.add(Double.POSITIVE_INFINITY); // assume worst case
} else { // PRODUCTION or STORAGE
estimatedPayments.add(Double.NEGATIVE_INFINITY); // assume worst case
}
} else {
double fixedPayments = estimateFixedTariffPayments(tariff);
double variablePayment = forecastDailyUsageCharge(bundle, tariff);
double totalPayment = truncateTo2Decimals(fixedPayments + variablePayment);
estimatedPayments.add(totalPayment);
}
}
return estimatedPayments;
}
private double estimateFixedTariffPayments(Tariff tariff)
{
double lifecyclePayment = tariff.getEarlyWithdrawPayment() + tariff.getSignupPayment();
double minDuration;
if (tariff.getMinDuration() == 0) minDuration = MEAN_TARIFF_DURATION * TimeService.DAY;
else minDuration = tariff.getMinDuration();
return ((double) tariff.getPeriodicPayment() + (lifecyclePayment / minDuration));
}
private double forecastDailyUsageCharge(CapacityBundle bundle, Tariff tariff)
{
Timeslot hourlyTimeslot = timeslotRepo.currentTimeslot();
double totalUsage = 0.0;
double totalCharge = 0.0;
for (CapacityOriginator capacityOriginator: bundle.getCapacityOriginators()) {
CapacityProfile forecast = capacityOriginator.getCurrentForecast();
for (int i=0; i < CapacityProfile.NUM_TIMESLOTS; ++i) {
double usageSign = bundle.getPowerType().isConsumption() ? +1 : -1;
double hourlyUsage = usageSign * forecast.getCapacity(i);
totalCharge += tariff.getUsageCharge(hourlyTimeslot.getStartInstant(), hourlyUsage, totalUsage);
totalUsage += hourlyUsage;
}
}
return totalCharge;
}
private List<Integer> determineAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
if (evalTariffs.size() == 1) {
List<Integer> allocations = new ArrayList<Integer>();
allocations.add(bundle.getPopulation());
return allocations;
} else {
if (bundle.getSubscriberStructure().allocationMethod == AllocationMethod.TOTAL_ORDER) {
return determineTotalOrderAllocations(bundle, evalTariffs, estimatedPayments);
} else { // LOGIT_CHOICE
return determineLogitChoiceAllocations(bundle, evalTariffs, estimatedPayments);
}
}
}
private List<Integer> determineTotalOrderAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
int numTariffs = evalTariffs.size();
List<Double> allocationRule;
if (bundle.getSubscriberStructure().totalOrderRules.isEmpty()) {
allocationRule = new ArrayList<Double>(numTariffs);
allocationRule.add(1.0);
for (int i=1; i < numTariffs; ++i) {
allocationRule.add(0.0);
}
} else if (numTariffs <= bundle.getSubscriberStructure().totalOrderRules.size()) {
allocationRule = bundle.getSubscriberStructure().totalOrderRules.get(numTariffs - 1);
} else {
allocationRule = new ArrayList<Double>(numTariffs);
List<Double> largestRule = bundle.getSubscriberStructure().totalOrderRules.get(bundle.getSubscriberStructure().totalOrderRules.size() - 1);
for (int i=0; i < numTariffs; ++i) {
if (i < largestRule.size()) {
allocationRule.add(largestRule.get(i));
} else {
allocationRule.add(0.0);
}
}
}
// payments are positive for production, so sorting is still valid
List<Double> sortedPayments = new ArrayList<Double>(numTariffs);
for (double estimatedPayment: estimatedPayments) {
sortedPayments.add(estimatedPayment);
}
Collections.sort(sortedPayments, Collections.reverseOrder()); // we want descending order
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
for (int i=0; i < numTariffs; ++i) {
if (allocationRule.get(i) > 0) {
double nextBest = sortedPayments.get(i);
for (int j=0; j < numTariffs; ++j) {
if (estimatedPayments.get(j) == nextBest) {
allocations.add((int) Math.round(bundle.getCustomerInfo().getPopulation() * allocationRule.get(i)));
}
}
}
else allocations.add(0);
}
return allocations;
}
private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
// logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i))
int numTariffs = evalTariffs.size();
double bestPayment = Collections.max(estimatedPayments);
double worstPayment = Collections.min(estimatedPayments);
List<Double> probabilities = new ArrayList<Double>(numTariffs);
if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero
for (int i=0; i < numTariffs; ++i) {
probabilities.add(1.0 / numTariffs);
}
} else {
double sumPayments = 0.0;
for (int i=0; i < numTariffs; ++i) {
sumPayments += estimatedPayments.get(i);
}
double meanPayment = sumPayments / numTariffs;
double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational]
List<Double> numerators = new ArrayList<Double>(numTariffs);
double denominator = 0.0;
for (int i=0; i < numTariffs; ++i) {
double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment));
double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0]
double numerator = Math.exp(lambda * utility);
numerators.add(numerator);
denominator += numerator;
}
for (int i=0; i < numTariffs; ++i) {
probabilities.add(numerators.get(i) / denominator);
}
}
// Now determine allocations based on above probabilities
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
int population = bundle.getPopulation();
if (bundle.getCustomerInfo().isMultiContracting())
{
int sumAllocations = 0;
for (int i=0; i < numTariffs; ++i) {
int allocation;
- if (i < (numTariffs - 1)) {
+ if (sumAllocations == population) {
+ allocation = 0;
+ } else if (i < (numTariffs - 1)) {
allocation = (int) Math.round(population * probabilities.get(i));
if ((sumAllocations + allocation) > population) {
allocation = population - sumAllocations;
}
sumAllocations += allocation;
- if (sumAllocations == population) break;
} else {
allocation = population - sumAllocations;
}
allocations.add(allocation);
}
} else {
double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0]
double cumProbability = 0.0;
for (int i=0; i < numTariffs; ++i) {
cumProbability += probabilities.get(i);
if (r <= cumProbability) {
allocations.add(population);
for (int j=i+1; j < numTariffs; ++j) {
allocations.add(0);
}
break;
} else {
allocations.add(0);
}
}
}
return allocations;
}
///////////////// TIMESLOT ACTIVITY //////////////////////
@Override
public void handleNewTimeslot(Timeslot timeslot)
{
checkRevokedSubscriptions();
usePower(timeslot);
}
private void checkRevokedSubscriptions()
{
for (CapacityBundle bundle: capacityBundles) {
List<TariffSubscription> revoked = tariffSubscriptionRepo.getRevokedSubscriptionList(bundle.getCustomerInfo());
for (TariffSubscription revokedSubscription : revoked) {
revokedSubscription.handleRevokedTariff();
}
}
}
private void usePower(Timeslot timeslot)
{
for (CapacityBundle bundle: capacityBundles) {
List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findSubscriptionsForCustomer(bundle.getCustomerInfo());
double totalCapacity = 0.0;
double totalUsageCharge = 0.0;
for (TariffSubscription subscription: subscriptions) {
if (subscription.getCustomersCommitted() > 0) {
double usageSign = bundle.getPowerType().isConsumption() ? +1 : -1;
double currCapacity = usageSign * useCapacity(subscription, bundle);
if (factoredCustomerService.getUsageChargesLogging() == true) {
double charge = subscription.getTariff().getUsageCharge(currCapacity, subscription.getTotalUsage(), false);
totalUsageCharge += charge;
}
subscription.usePower(currCapacity);
totalCapacity += currCapacity;
}
}
log.info(bundle.getName() + ": Total " + bundle.getPowerType() + " capacity for timeslot " + timeslot.getSerialNumber() + " = " + totalCapacity);
logUsageCharges(bundle.getName() + ": Total " + bundle.getPowerType() + " usage charge for timeslot " + timeslot.getSerialNumber() + " = " + totalUsageCharge);
}
}
public double useCapacity(TariffSubscription subscription, CapacityBundle bundle)
{
double capacity = 0;
for (CapacityOriginator capacityOriginator: bundle.getCapacityOriginators()) {
capacity += capacityOriginator.useCapacity(subscription);
}
return capacity;
}
protected String getCustomerName()
{
return customerStructure.name;
}
protected double truncateTo2Decimals(double x)
{
double fract, whole;
if (x > 0) {
whole = Math.floor(x);
fract = Math.floor((x - whole) * 100) / 100;
} else {
whole = Math.ceil(x);
fract = Math.ceil((x - whole) * 100) / 100;
}
return whole + fract;
}
private void logAllocationDetails(String msg)
{
if (factoredCustomerService.getAllocationDetailsLogging() == true) {
log.info(msg);
}
}
private void logUsageCharges(String msg)
{
if (factoredCustomerService.getUsageChargesLogging() == true) {
log.info(msg);
}
}
@Override
public String toString()
{
return this.getClass().getCanonicalName() + ":" + getCustomerName();
}
} // end class
| false | true | private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
// logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i))
int numTariffs = evalTariffs.size();
double bestPayment = Collections.max(estimatedPayments);
double worstPayment = Collections.min(estimatedPayments);
List<Double> probabilities = new ArrayList<Double>(numTariffs);
if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero
for (int i=0; i < numTariffs; ++i) {
probabilities.add(1.0 / numTariffs);
}
} else {
double sumPayments = 0.0;
for (int i=0; i < numTariffs; ++i) {
sumPayments += estimatedPayments.get(i);
}
double meanPayment = sumPayments / numTariffs;
double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational]
List<Double> numerators = new ArrayList<Double>(numTariffs);
double denominator = 0.0;
for (int i=0; i < numTariffs; ++i) {
double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment));
double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0]
double numerator = Math.exp(lambda * utility);
numerators.add(numerator);
denominator += numerator;
}
for (int i=0; i < numTariffs; ++i) {
probabilities.add(numerators.get(i) / denominator);
}
}
// Now determine allocations based on above probabilities
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
int population = bundle.getPopulation();
if (bundle.getCustomerInfo().isMultiContracting())
{
int sumAllocations = 0;
for (int i=0; i < numTariffs; ++i) {
int allocation;
if (i < (numTariffs - 1)) {
allocation = (int) Math.round(population * probabilities.get(i));
if ((sumAllocations + allocation) > population) {
allocation = population - sumAllocations;
}
sumAllocations += allocation;
if (sumAllocations == population) break;
} else {
allocation = population - sumAllocations;
}
allocations.add(allocation);
}
} else {
double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0]
double cumProbability = 0.0;
for (int i=0; i < numTariffs; ++i) {
cumProbability += probabilities.get(i);
if (r <= cumProbability) {
allocations.add(population);
for (int j=i+1; j < numTariffs; ++j) {
allocations.add(0);
}
break;
} else {
allocations.add(0);
}
}
}
return allocations;
}
| private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
// logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i))
int numTariffs = evalTariffs.size();
double bestPayment = Collections.max(estimatedPayments);
double worstPayment = Collections.min(estimatedPayments);
List<Double> probabilities = new ArrayList<Double>(numTariffs);
if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero
for (int i=0; i < numTariffs; ++i) {
probabilities.add(1.0 / numTariffs);
}
} else {
double sumPayments = 0.0;
for (int i=0; i < numTariffs; ++i) {
sumPayments += estimatedPayments.get(i);
}
double meanPayment = sumPayments / numTariffs;
double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational]
List<Double> numerators = new ArrayList<Double>(numTariffs);
double denominator = 0.0;
for (int i=0; i < numTariffs; ++i) {
double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment));
double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0]
double numerator = Math.exp(lambda * utility);
numerators.add(numerator);
denominator += numerator;
}
for (int i=0; i < numTariffs; ++i) {
probabilities.add(numerators.get(i) / denominator);
}
}
// Now determine allocations based on above probabilities
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
int population = bundle.getPopulation();
if (bundle.getCustomerInfo().isMultiContracting())
{
int sumAllocations = 0;
for (int i=0; i < numTariffs; ++i) {
int allocation;
if (sumAllocations == population) {
allocation = 0;
} else if (i < (numTariffs - 1)) {
allocation = (int) Math.round(population * probabilities.get(i));
if ((sumAllocations + allocation) > population) {
allocation = population - sumAllocations;
}
sumAllocations += allocation;
} else {
allocation = population - sumAllocations;
}
allocations.add(allocation);
}
} else {
double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0]
double cumProbability = 0.0;
for (int i=0; i < numTariffs; ++i) {
cumProbability += probabilities.get(i);
if (r <= cumProbability) {
allocations.add(population);
for (int j=i+1; j < numTariffs; ++j) {
allocations.add(0);
}
break;
} else {
allocations.add(0);
}
}
}
return allocations;
}
|
diff --git a/src/main/java/org/fusesource/camel/component/salesforce/internal/BulkApiProcessor.java b/src/main/java/org/fusesource/camel/component/salesforce/internal/BulkApiProcessor.java
index 1b3bc4b..144fd31 100644
--- a/src/main/java/org/fusesource/camel/component/salesforce/internal/BulkApiProcessor.java
+++ b/src/main/java/org/fusesource/camel/component/salesforce/internal/BulkApiProcessor.java
@@ -1,320 +1,320 @@
/**
* 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.fusesource.camel.component.salesforce.internal;
import org.apache.camel.*;
import org.apache.camel.converter.stream.StreamCacheConverter;
import org.fusesource.camel.component.salesforce.SalesforceEndpoint;
import org.fusesource.camel.component.salesforce.SalesforceEndpointConfig;
import org.fusesource.camel.component.salesforce.api.BulkApiClient;
import org.fusesource.camel.component.salesforce.api.DefaultBulkApiClient;
import org.fusesource.camel.component.salesforce.api.RestException;
import org.fusesource.camel.component.salesforce.api.dto.bulk.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.fusesource.camel.component.salesforce.SalesforceEndpointConfig.*;
public class BulkApiProcessor extends AbstractSalesforceProcessor {
private BulkApiClient bulkClient;
public BulkApiProcessor(SalesforceEndpoint endpoint) {
super(endpoint);
this.bulkClient = new DefaultBulkApiClient(
endpointConfig.get(SalesforceEndpointConfig.API_VERSION), session, httpClient);
}
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
switch (apiName) {
case CREATE_JOB:
OperationEnum operation;
ContentType contentType;
String sObjectName;
JobInfo jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
operation = jobBody.getOperation();
contentType = jobBody.getContentType();
sObjectName = jobBody.getObject();
} else {
operation = OperationEnum.fromValue(
getParameter(BULK_OPERATION, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
sObjectName = getParameter(SOBJECT_NAME, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
JobInfo jobInfo = bulkClient.createJob(operation,
sObjectName, contentType);
createResponse(exchange, jobInfo);
break;
case GET_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
String jobId;
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.getJob(jobId);
createResponse(exchange, jobInfo);
break;
case CLOSE_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.closeJob(jobId);
createResponse(exchange, jobInfo);
break;
case ABORT_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.abortJob(jobId);
createResponse(exchange, jobInfo);
break;
case CREATE_BATCH:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
contentType = jobBody.getContentType();
} else {
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
InputStream request = null;
try {
request = exchange.getIn().getMandatoryBody(InputStream.class);
} catch (CamelException e) {
String msg = "Error preparing batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
BatchInfo batchInfo = bulkClient.createBatch(request,
- jobId, ContentType.fromValue(contentType));
+ jobId, contentType);
createResponse(exchange, batchInfo);
break;
case GET_BATCH:
BatchInfo batchBody = exchange.getIn().getBody(BatchInfo.class);
String batchId;
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
batchInfo = bulkClient.getBatch(jobId, batchId);
createResponse(exchange, batchInfo);
break;
case GET_ALL_BATCHES:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<BatchInfo> batches = bulkClient.getAllBatches(jobId);
createResponse(exchange, batches);
break;
case GET_REQUEST:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
request = bulkClient.getRequest(jobId, batchId);
// read the request stream into a StreamCache temp file
// ensures the connection is read
try {
createResponse(exchange, StreamCacheConverter.convertToStreamCache(request, exchange));
} catch (IOException e) {
String msg = "Error retrieving batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} finally {
// close the input stream to release the Http connection
try {
request.close();
} catch (IOException e) {
// ignore
}
}
break;
case GET_RESULTS:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<Result> results = bulkClient.getResults(jobId, batchId);
createResponse(exchange, results);
break;
case CREATE_BATCH_QUERY:
jobBody = exchange.getIn().getBody(JobInfo.class);
String soqlQuery;
if (jobBody != null) {
jobId = jobBody.getId();
contentType = jobBody.getContentType();
soqlQuery = getParameter(SOBJECT_QUERY, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
// reuse SOBJECT_QUERY property
soqlQuery = getParameter(SOBJECT_QUERY, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
batchInfo = bulkClient.createBatchQuery(jobId,
soqlQuery, contentType);
createResponse(exchange, batchInfo);
break;
case QUERY_RESULT_LIST:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<String> resultIdList = bulkClient.queryResultList(jobId, batchId);
createResponse(exchange, resultIdList);
break;
case QUERY_RESULT:
batchBody = exchange.getIn().getBody(BatchInfo.class);
String resultId;
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
resultId = getParameter(RESULT_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
resultId = getParameter(RESULT_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
InputStream result = bulkClient.queryResult(jobId, batchId, resultId);
// read the result stream into a StreamCache temp file
// ensures the connection is read
try {
createResponse(exchange, StreamCacheConverter.convertToStreamCache(result, exchange));
} catch (IOException e) {
String msg = "Error retrieving batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} finally {
// close the input stream to release the Http connection
try {
result.close();
} catch (IOException e) {
// ignore
}
}
break;
}
} catch (RestException e) {
String msg = String.format("Error processing %s: [%s] \"%s\"",
apiName, e.getStatusCode(), e.getMessage());
LOG.error(msg, e);
exchange.setException(e);
} catch (RuntimeException e) {
String msg = String.format("Unexpected Error processing %s: \"%s\"",
apiName, e.getMessage());
LOG.error(msg, e);
exchange.setException(new RestException(msg, e));
} finally {
callback.done(false);
}
}
});
// continue routing asynchronously
return false;
}
private void createResponse(Exchange exchange, Object body) {
exchange.getOut().setBody(body);
// copy headers and attachments
exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
exchange.getOut().getAttachments().putAll(exchange.getIn().getAttachments());
}
}
| true | true | public boolean process(final Exchange exchange, final AsyncCallback callback) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
switch (apiName) {
case CREATE_JOB:
OperationEnum operation;
ContentType contentType;
String sObjectName;
JobInfo jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
operation = jobBody.getOperation();
contentType = jobBody.getContentType();
sObjectName = jobBody.getObject();
} else {
operation = OperationEnum.fromValue(
getParameter(BULK_OPERATION, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
sObjectName = getParameter(SOBJECT_NAME, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
JobInfo jobInfo = bulkClient.createJob(operation,
sObjectName, contentType);
createResponse(exchange, jobInfo);
break;
case GET_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
String jobId;
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.getJob(jobId);
createResponse(exchange, jobInfo);
break;
case CLOSE_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.closeJob(jobId);
createResponse(exchange, jobInfo);
break;
case ABORT_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.abortJob(jobId);
createResponse(exchange, jobInfo);
break;
case CREATE_BATCH:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
contentType = jobBody.getContentType();
} else {
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
InputStream request = null;
try {
request = exchange.getIn().getMandatoryBody(InputStream.class);
} catch (CamelException e) {
String msg = "Error preparing batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
BatchInfo batchInfo = bulkClient.createBatch(request,
jobId, ContentType.fromValue(contentType));
createResponse(exchange, batchInfo);
break;
case GET_BATCH:
BatchInfo batchBody = exchange.getIn().getBody(BatchInfo.class);
String batchId;
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
batchInfo = bulkClient.getBatch(jobId, batchId);
createResponse(exchange, batchInfo);
break;
case GET_ALL_BATCHES:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<BatchInfo> batches = bulkClient.getAllBatches(jobId);
createResponse(exchange, batches);
break;
case GET_REQUEST:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
request = bulkClient.getRequest(jobId, batchId);
// read the request stream into a StreamCache temp file
// ensures the connection is read
try {
createResponse(exchange, StreamCacheConverter.convertToStreamCache(request, exchange));
} catch (IOException e) {
String msg = "Error retrieving batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} finally {
// close the input stream to release the Http connection
try {
request.close();
} catch (IOException e) {
// ignore
}
}
break;
case GET_RESULTS:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<Result> results = bulkClient.getResults(jobId, batchId);
createResponse(exchange, results);
break;
case CREATE_BATCH_QUERY:
jobBody = exchange.getIn().getBody(JobInfo.class);
String soqlQuery;
if (jobBody != null) {
jobId = jobBody.getId();
contentType = jobBody.getContentType();
soqlQuery = getParameter(SOBJECT_QUERY, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
// reuse SOBJECT_QUERY property
soqlQuery = getParameter(SOBJECT_QUERY, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
batchInfo = bulkClient.createBatchQuery(jobId,
soqlQuery, contentType);
createResponse(exchange, batchInfo);
break;
case QUERY_RESULT_LIST:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<String> resultIdList = bulkClient.queryResultList(jobId, batchId);
createResponse(exchange, resultIdList);
break;
case QUERY_RESULT:
batchBody = exchange.getIn().getBody(BatchInfo.class);
String resultId;
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
resultId = getParameter(RESULT_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
resultId = getParameter(RESULT_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
InputStream result = bulkClient.queryResult(jobId, batchId, resultId);
// read the result stream into a StreamCache temp file
// ensures the connection is read
try {
createResponse(exchange, StreamCacheConverter.convertToStreamCache(result, exchange));
} catch (IOException e) {
String msg = "Error retrieving batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} finally {
// close the input stream to release the Http connection
try {
result.close();
} catch (IOException e) {
// ignore
}
}
break;
}
} catch (RestException e) {
String msg = String.format("Error processing %s: [%s] \"%s\"",
apiName, e.getStatusCode(), e.getMessage());
LOG.error(msg, e);
exchange.setException(e);
} catch (RuntimeException e) {
String msg = String.format("Unexpected Error processing %s: \"%s\"",
apiName, e.getMessage());
LOG.error(msg, e);
exchange.setException(new RestException(msg, e));
} finally {
callback.done(false);
}
}
});
// continue routing asynchronously
return false;
}
| public boolean process(final Exchange exchange, final AsyncCallback callback) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
switch (apiName) {
case CREATE_JOB:
OperationEnum operation;
ContentType contentType;
String sObjectName;
JobInfo jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
operation = jobBody.getOperation();
contentType = jobBody.getContentType();
sObjectName = jobBody.getObject();
} else {
operation = OperationEnum.fromValue(
getParameter(BULK_OPERATION, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
sObjectName = getParameter(SOBJECT_NAME, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
JobInfo jobInfo = bulkClient.createJob(operation,
sObjectName, contentType);
createResponse(exchange, jobInfo);
break;
case GET_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
String jobId;
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.getJob(jobId);
createResponse(exchange, jobInfo);
break;
case CLOSE_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.closeJob(jobId);
createResponse(exchange, jobInfo);
break;
case ABORT_JOB:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
jobInfo = bulkClient.abortJob(jobId);
createResponse(exchange, jobInfo);
break;
case CREATE_BATCH:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
contentType = jobBody.getContentType();
} else {
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
InputStream request = null;
try {
request = exchange.getIn().getMandatoryBody(InputStream.class);
} catch (CamelException e) {
String msg = "Error preparing batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
BatchInfo batchInfo = bulkClient.createBatch(request,
jobId, contentType);
createResponse(exchange, batchInfo);
break;
case GET_BATCH:
BatchInfo batchBody = exchange.getIn().getBody(BatchInfo.class);
String batchId;
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
batchInfo = bulkClient.getBatch(jobId, batchId);
createResponse(exchange, batchInfo);
break;
case GET_ALL_BATCHES:
jobBody = exchange.getIn().getBody(JobInfo.class);
if (jobBody != null) {
jobId = jobBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<BatchInfo> batches = bulkClient.getAllBatches(jobId);
createResponse(exchange, batches);
break;
case GET_REQUEST:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
request = bulkClient.getRequest(jobId, batchId);
// read the request stream into a StreamCache temp file
// ensures the connection is read
try {
createResponse(exchange, StreamCacheConverter.convertToStreamCache(request, exchange));
} catch (IOException e) {
String msg = "Error retrieving batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} finally {
// close the input stream to release the Http connection
try {
request.close();
} catch (IOException e) {
// ignore
}
}
break;
case GET_RESULTS:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<Result> results = bulkClient.getResults(jobId, batchId);
createResponse(exchange, results);
break;
case CREATE_BATCH_QUERY:
jobBody = exchange.getIn().getBody(JobInfo.class);
String soqlQuery;
if (jobBody != null) {
jobId = jobBody.getId();
contentType = jobBody.getContentType();
soqlQuery = getParameter(SOBJECT_QUERY, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
contentType = ContentType.fromValue(
getParameter(CONTENT_TYPE, exchange, IGNORE_IN_BODY, NOT_OPTIONAL));
// reuse SOBJECT_QUERY property
soqlQuery = getParameter(SOBJECT_QUERY, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
batchInfo = bulkClient.createBatchQuery(jobId,
soqlQuery, contentType);
createResponse(exchange, batchInfo);
break;
case QUERY_RESULT_LIST:
batchBody = exchange.getIn().getBody(BatchInfo.class);
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
List<String> resultIdList = bulkClient.queryResultList(jobId, batchId);
createResponse(exchange, resultIdList);
break;
case QUERY_RESULT:
batchBody = exchange.getIn().getBody(BatchInfo.class);
String resultId;
if (batchBody != null) {
jobId = batchBody.getJobId();
batchId = batchBody.getId();
resultId = getParameter(RESULT_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
} else {
jobId = getParameter(JOB_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
batchId = getParameter(BATCH_ID, exchange, IGNORE_IN_BODY, NOT_OPTIONAL);
resultId = getParameter(RESULT_ID, exchange, USE_IN_BODY, NOT_OPTIONAL);
}
InputStream result = bulkClient.queryResult(jobId, batchId, resultId);
// read the result stream into a StreamCache temp file
// ensures the connection is read
try {
createResponse(exchange, StreamCacheConverter.convertToStreamCache(result, exchange));
} catch (IOException e) {
String msg = "Error retrieving batch request: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} finally {
// close the input stream to release the Http connection
try {
result.close();
} catch (IOException e) {
// ignore
}
}
break;
}
} catch (RestException e) {
String msg = String.format("Error processing %s: [%s] \"%s\"",
apiName, e.getStatusCode(), e.getMessage());
LOG.error(msg, e);
exchange.setException(e);
} catch (RuntimeException e) {
String msg = String.format("Unexpected Error processing %s: \"%s\"",
apiName, e.getMessage());
LOG.error(msg, e);
exchange.setException(new RestException(msg, e));
} finally {
callback.done(false);
}
}
});
// continue routing asynchronously
return false;
}
|
diff --git a/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java b/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java
index 6a13920a..40197142 100644
--- a/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java
+++ b/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java
@@ -1,748 +1,748 @@
/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://jwsdp.dev.java.net/CDDLv1.0.html
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/
package com.sun.tools.xjc.generator.bean;
import java.io.Serializable;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAttachmentRef;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlMimeType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JAnnotatable;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassAlreadyExistsException;
import com.sun.codemodel.JClassContainer;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JEnumConstant;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JForEach;
import com.sun.codemodel.JInvocation;
import com.sun.codemodel.JJavaName;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
import com.sun.codemodel.fmt.JStaticJavaFile;
import com.sun.tools.xjc.AbortException;
import com.sun.tools.xjc.ErrorReceiver;
import com.sun.tools.xjc.generator.annotation.spec.XmlAnyAttributeWriter;
import com.sun.tools.xjc.generator.annotation.spec.XmlEnumValueWriter;
import com.sun.tools.xjc.generator.annotation.spec.XmlEnumWriter;
import com.sun.tools.xjc.generator.annotation.spec.XmlJavaTypeAdapterWriter;
import com.sun.tools.xjc.generator.annotation.spec.XmlMimeTypeWriter;
import com.sun.tools.xjc.generator.annotation.spec.XmlRootElementWriter;
import com.sun.tools.xjc.generator.annotation.spec.XmlTypeWriter;
import com.sun.tools.xjc.generator.bean.field.FieldRenderer;
import com.sun.tools.xjc.model.CAdapter;
import com.sun.tools.xjc.model.CAttributePropertyInfo;
import com.sun.tools.xjc.model.CClassInfo;
import com.sun.tools.xjc.model.CClassInfoParent;
import com.sun.tools.xjc.model.CElementInfo;
import com.sun.tools.xjc.model.CEnumConstant;
import com.sun.tools.xjc.model.CEnumLeafInfo;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.model.CTypeRef;
import com.sun.tools.xjc.model.Model;
import com.sun.tools.xjc.outline.Aspect;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.EnumConstantOutline;
import com.sun.tools.xjc.outline.EnumOutline;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.tools.xjc.outline.Outline;
import com.sun.tools.xjc.outline.PackageOutline;
import com.sun.tools.xjc.util.CodeModelClassFactory;
import com.sun.xml.bind.v2.model.core.PropertyInfo;
import com.sun.xml.bind.v2.runtime.SwaRefAdapter;
import com.sun.xml.xsom.XmlString;
/**
* Generates fields and accessors.
*/
public final class BeanGenerator implements Outline
{
/** Simplifies class/interface creation and collision detection. */
private final CodeModelClassFactory codeModelClassFactory;
private final ErrorReceiver errorReceiver;
/** all {@link PackageOutline}s keyed by their {@link PackageOutline#_package}. */
private final Map<JPackage,PackageOutlineImpl> packageContexts = new HashMap<JPackage,PackageOutlineImpl>();
/** all {@link ClassOutline}s keyed by their {@link ClassOutline#target}. */
private final Map<CClassInfo,ClassOutlineImpl> classes = new HashMap<CClassInfo,ClassOutlineImpl>();
/** all {@link EnumOutline}s keyed by their {@link EnumOutline#target}. */
private final Map<CEnumLeafInfo,EnumOutline> enums = new HashMap<CEnumLeafInfo,EnumOutline>();
/**
* Generated runtime classes.
*/
private final Map<Class,JClass> generatedRuntime = new HashMap<Class, JClass>();
/** the model object which we are processing. */
private final Model model;
private final JCodeModel codeModel;
/**
* for each property, the information about the generated field.
*/
private final Map<CPropertyInfo,FieldOutline> fields = new HashMap<CPropertyInfo,FieldOutline>();
/**
* elements that generate classes to the generated classes.
*/
/*package*/ final Map<CElementInfo,ElementOutlineImpl> elements = new HashMap<CElementInfo,ElementOutlineImpl>();
/**
* Generates beans into code model according to the BGM,
* and produces the reflection model.
*
* @param _errorReceiver
* This object will receive all the errors discovered
* during the back-end stage.
*
* @return
* returns a {@link Outline} which will in turn
* be used to further generate marshaller/unmarshaller,
* or null if the processing fails (errors should have been
* reported to the error recevier.)
*/
public static Outline generate(Model model, ErrorReceiver _errorReceiver) {
try {
return new BeanGenerator(model, _errorReceiver);
} catch( AbortException e ) {
return null;
}
}
private BeanGenerator(Model _model, ErrorReceiver _errorReceiver) {
this.model = _model;
this.codeModel = model.codeModel;
this.errorReceiver = _errorReceiver;
this.codeModelClassFactory = new CodeModelClassFactory(errorReceiver);
// build enum classes
for( CEnumLeafInfo p : model.enums().values() )
enums.put( p, generateEnum(p) );
JPackage[] packages = getUsedPackages(Aspect.EXPOSED);
// generates per-package code and remember the results as contexts.
for( JPackage pkg : packages )
getPackageContext(pkg);
// create the class definitions for all the beans first.
// this should also fill in PackageContext#getClasses
for( CClassInfo bean : model.beans().values() )
getClazz(bean);
// compute the package-level setting
for (PackageOutlineImpl p : packageContexts.values())
p.calcDefaultValues();
JClass OBJECT = codeModel.ref(Object.class);
// inheritance relationship needs to be set before we generate fields, or otherwise
// we'll fail to compute the correct type signature (namely the common base type computation)
for( ClassOutlineImpl cc : getClasses() ) {
// setup inheritance between implementation hierarchy.
CClassInfo superClass = cc.target.getBaseClass();
if(superClass!=null) {
// use the specified super class
model.strategy._extends(cc,getClazz(superClass));
} else {
// use the default one, if any
if( model.rootClass!=null && cc.implClass._extends().equals(OBJECT) )
cc.implClass._extends(model.rootClass);
if( model.rootInterface!=null)
cc.ref._implements(model.rootInterface);
}
}
// fill in implementation classes
for( ClassOutlineImpl co : getClasses() )
generateClassBody(co);
// create factories for the impl-less elements
for( CElementInfo ei : model.getAllElements())
getPackageContext(ei._package()).objectFactoryGenerator().populate(ei);
if(model.options.debugMode)
generateClassList();
}
/**
* Generates a class that knows how to create an instance of JAXBContext
*
* <p>
* This is used in the debug mode so that a new properly configured
* {@link JAXBContext} object can be used.
*/
private void generateClassList() {
try {
JDefinedClass jc = codeModel.rootPackage()._class("JAXBDebug");
JMethod m = jc.method(JMod.PUBLIC|JMod.STATIC,JAXBContext.class,"createContext");
JVar $classLoader = m.param(ClassLoader.class,"classLoader");
m._throws(JAXBException.class);
JInvocation inv = codeModel.ref(JAXBContext.class).staticInvoke("newInstance");
m.body()._return(inv);
switch(model.strategy) {
case INTF_AND_IMPL:
{
StringBuilder buf = new StringBuilder();
for( PackageOutlineImpl po : packageContexts.values() ) {
if(buf.length()>0) buf.append(':');
buf.append(po._package().name());
}
inv.arg(buf.toString()).arg($classLoader);
break;
}
case BEAN_ONLY:
for( ClassOutlineImpl cc : getClasses() )
inv.arg(cc.implRef.dotclass());
for( PackageOutlineImpl po : packageContexts.values() )
inv.arg(po.objectFactory().dotclass());
break;
default:
throw new IllegalStateException();
}
} catch (JClassAlreadyExistsException e) {
e.printStackTrace();
// after all, we are in the debug mode. a little sloppiness is OK.
// this error is not fatal. just continue.
}
}
public Model getModel() {
return model;
}
public JCodeModel getCodeModel() {
return codeModel;
}
public JClassContainer getContainer(CClassInfoParent parent, Aspect aspect) {
CClassInfoParent.Visitor<JClassContainer> v;
switch(aspect) {
case EXPOSED:
v = exposedContainerBuilder;
break;
case IMPLEMENTATION:
v = implContainerBuilder;
break;
default:
assert false;
throw new IllegalStateException();
}
return parent.accept(v);
}
public final JType resolve(CTypeRef ref,Aspect a) {
return ref.getTarget().getType().toType(this,a);
}
private final CClassInfoParent.Visitor<JClassContainer> exposedContainerBuilder =
new CClassInfoParent.Visitor<JClassContainer>() {
public JClassContainer onBean(CClassInfo bean) {
return getClazz(bean).ref;
}
public JClassContainer onElement(CElementInfo element) {
// hmm...
return getElement(element).implClass;
}
public JClassContainer onPackage(JPackage pkg) {
return model.strategy.getPackage(pkg,Aspect.EXPOSED);
}
};
private final CClassInfoParent.Visitor<JClassContainer> implContainerBuilder =
new CClassInfoParent.Visitor<JClassContainer>() {
public JClassContainer onBean(CClassInfo bean) {
return getClazz(bean).implClass;
}
public JClassContainer onElement(CElementInfo element) {
return getElement(element).implClass;
}
public JClassContainer onPackage(JPackage pkg) {
return model.strategy.getPackage(pkg,Aspect.IMPLEMENTATION);
}
};
/**
* Returns all <i>used</i> JPackages.
*
* A JPackage is considered as "used" if a ClassItem or
* a InterfaceItem resides in that package.
*
* This value is dynamically calculated every time because
* one can freely remove ClassItem/InterfaceItem.
*
* @return
* Given the same input, the order of packages in the array
* is always the same regardless of the environment.
*/
public final JPackage[] getUsedPackages( Aspect aspect ) {
Set<JPackage> s = new TreeSet<JPackage>();
for( CClassInfo bean : model.beans().values() ) {
JClassContainer cont = getContainer(bean.parent(),aspect);
if(cont.isPackage())
s.add( (JPackage)cont );
}
for( CElementInfo e : model.getElementMappings(null).values() ) {
// at the first glance you might think we should be iterating all elements,
// not just global ones, but if you think about it, local ones live inside
// another class, so those packages are already enumerated when we were
// walking over CClassInfos.
s.add( e._package() );
}
return s.toArray(new JPackage[s.size()]);
}
public ErrorReceiver getErrorReceiver() { return errorReceiver; }
public CodeModelClassFactory getClassFactory() { return codeModelClassFactory; }
public PackageOutlineImpl getPackageContext( JPackage p ) {
PackageOutlineImpl r = packageContexts.get(p);
if(r==null) {
r=new PackageOutlineImpl(this,model,p);
packageContexts.put(p,r);
}
return r;
}
/**
* Generates the minimum {@link JDefinedClass} skeleton
* without filling in its body.
*/
private ClassOutlineImpl generateClassDef(CClassInfo bean) {
ImplStructureStrategy.Result r = model.strategy.createClasses(this,bean);
JClass implRef;
if( bean.getUserSpecifiedImplClass()!=null ) {
// create a place holder for a user-specified class.
JDefinedClass usr;
try {
usr = codeModel._class(bean.getUserSpecifiedImplClass());
// but hide that file so that it won't be generated.
usr.hide();
} catch( JClassAlreadyExistsException e ) {
// it's OK for this to collide.
usr = e.getExistingClass();
}
usr._extends(r.implementation);
implRef = usr;
} else
implRef = r.implementation;
return new ClassOutlineImpl(this,bean,r.exposed,r.implementation,implRef);
}
public Collection<ClassOutlineImpl> getClasses() {
// make sure that classes are fully populated
assert model.beans().size()==classes.size();
return classes.values();
}
public ClassOutlineImpl getClazz( CClassInfo bean ) {
ClassOutlineImpl r = classes.get(bean);
if(r==null)
classes.put( bean, r=generateClassDef(bean) );
return r;
}
public ElementOutlineImpl getElement(CElementInfo ei) {
ElementOutlineImpl def = elements.get(ei);
if(def==null && ei.hasClass()) {
// create one. in the constructor it adds itself to the elements.
def = new ElementOutlineImpl(this,ei);
}
return def;
}
public EnumOutline getEnum(CEnumLeafInfo eli) {
return enums.get(eli);
}
public Collection<EnumOutline> getEnums() {
return enums.values();
}
public Iterable<? extends PackageOutline> getAllPackageContexts() {
return packageContexts.values();
}
public FieldOutline getField( CPropertyInfo prop ) {
return fields.get(prop);
}
/**
* Generates the body of a class.
*
*/
private void generateClassBody( ClassOutlineImpl cc ) {
CClassInfo target = cc.target;
// if serialization support is turned on, generate
// [RESULT]
// class ... implements Serializable {
// private static final long serialVersionUID = <id>;
// ....
// }
if( model.serializable ) {
cc.implClass._implements(Serializable.class);
if( model.serialVersionUID!=null ) {
cc.implClass.field(
JMod.PRIVATE|JMod.STATIC|JMod.FINAL,
codeModel.LONG,
"serialVersionUID",
JExpr.lit(model.serialVersionUID));
}
}
// used to simplify the generated annotations
String mostUsedNamespaceURI = cc._package().getMostUsedNamespaceURI();
// [RESULT]
// @XmlType(name="foo", targetNamespace="bar://baz")
XmlTypeWriter xtw = cc.implClass.annotate2(XmlTypeWriter.class);
QName typeName = cc.target.getTypeName();
if(typeName==null) {
xtw.name("");
} else {
xtw.name(typeName.getLocalPart());
final String typeNameURI = typeName.getNamespaceURI();
if(!typeNameURI.equals(mostUsedNamespaceURI)) // only generate if necessary
xtw.namespace(typeNameURI);
}
if(target.isElement()) {
String namespaceURI = target.getElementName().getNamespaceURI();
String localPart = target.getElementName().getLocalPart();
// [RESULT]
// @XmlRootElement(name="foo", targetNamespace="bar://baz")
XmlRootElementWriter xrew = cc.implClass.annotate2(XmlRootElementWriter.class);
xrew.name(localPart);
if(!namespaceURI.equals(mostUsedNamespaceURI)) // only generate if necessary
xrew.namespace(namespaceURI);
}
if(target.isOrdered()) {
for(CPropertyInfo p : target.getProperties() ) {
if( ! (p instanceof CAttributePropertyInfo )) {
xtw.propOrder(p.getName(false));
}
}
} else {
// produce empty array
xtw.getAnnotationUse().paramArray("propOrder");
}
for( CPropertyInfo prop : target.getProperties() ) {
generateFieldDecl(cc,prop);
}
if( target.declaresAttributeWildcard() ) {
generateAttributeWildcard(cc);
}
// generate some class level javadoc
cc.ref.javadoc().append(target.javadoc);
cc._package().objectFactoryGenerator().populate(cc);
}
/**
* Generates an attribute wildcard property on a class.
*/
private void generateAttributeWildcard( ClassOutlineImpl cc ) {
String FIELD_NAME = "otherAttributes";
String METHOD_SEED = model.getNameConverter().toClassName(FIELD_NAME);
JClass mapType = codeModel.ref(Map.class).narrow(QName.class,String.class);
JClass mapImpl = codeModel.ref(HashMap.class).narrow(QName.class,String.class);
// [RESULT]
// Map<QName,String> m = new HashMap<QName,String>();
JFieldVar $ref = cc.implClass.field(JMod.PRIVATE,
mapType, FIELD_NAME, JExpr._new(mapImpl) );
$ref.annotate2(XmlAnyAttributeWriter.class);
MethodWriter writer = cc.createMethodWriter();
JMethod $get = writer.declareMethod( mapType, "get"+METHOD_SEED );
$get.javadoc().append(
"Gets a map that contains attributes that aren't bound to any typed property on this class.\n\n" +
"<p>\n" +
"the map is keyed by the name of the attribute and \n" +
"the value is the string value of the attribute.\n" +
"\n" +
"the map returned by this method is live, and you can add new attribute\n" +
"by updating the map directly. Because of this design, there's no setter.\n");
$get.javadoc().addReturn().append("always non-null");
$get.body()._return($ref);
}
private EnumOutline generateEnum(CEnumLeafInfo e) {
JDefinedClass type;
// since constant values are never null, no point in using the boxed types.
JType baseExposedType = e.base.toType(this,Aspect.EXPOSED).unboxify();
JType baseImplType = e.base.toType(this,Aspect.IMPLEMENTATION).unboxify();
type = getClassFactory().createClass(
getContainer(e.parent,Aspect.EXPOSED),e.shortName,e.getLocator(), ClassType.ENUM);
type.javadoc().append(e.javadoc);
XmlEnumWriter xew = type.annotate2(XmlEnumWriter.class);
xew.value(baseExposedType);
JCodeModel codeModel = model.codeModel;
EnumOutline enumOutline = new EnumOutline(e, type) {};
boolean needsValue = e.needsValueField();
// for each member <m>,
// [RESULT]
// <EnumName>(<deserializer of m>(<value>));
Set<String> enumFieldNames = new HashSet<String>(); // record generated field names to detect collision
for( CEnumConstant mem : e.members ) {
String constName = mem.getName();
if(!JJavaName.isJavaIdentifier(constName)) {
// didn't produce a name.
getErrorReceiver().error( e.getLocator(),
Messages.ERR_UNUSABLE_NAME.format(mem.getLexicalValue(), constName ) );
}
if( !enumFieldNames.add(constName) )
getErrorReceiver().error( e.getLocator(), Messages.ERR_NAME_COLLISION.format(constName));
// [RESULT]
// <Const>(...)
// ASSUMPTION: datatype is outline-independent
JEnumConstant constRef = type.enumConstant(constName);
if(needsValue)
constRef.arg(e.base.createConstant(this, new XmlString(mem.getLexicalValue())));
if(!mem.getLexicalValue().equals(constName))
constRef.annotate2(XmlEnumValueWriter.class).value(mem.getLexicalValue());
// set javadoc
if( mem.javadoc!=null )
constRef.javadoc().append(mem.javadoc);
enumOutline.constants.add(new EnumConstantOutline(mem,constRef){});
}
if(needsValue) {
// [RESULT]
// final <valueType> value;
JFieldVar $value = type.field( JMod.PRIVATE|JMod.FINAL, baseExposedType, "value" );
// [RESULT]
// public <valuetype> value() { return value; }
type.method(JMod.PUBLIC, baseExposedType, "value" ).body()._return($value);
// [RESULT]
// <constructor>(<valueType> v) {
// this.value=v;
// }
{
JMethod m = type.constructor(0);
m.body().assign( $value, m.param( baseImplType, "v" ) );
}
// [RESULT]
// public static <Const> fromValue(<valueType> v) {
// for( <Const> c : <Const>.values() ) {
// if(c.value == v) // or equals
// return c;
// }
// throw new IllegalArgumentException(...);
// }
{
JMethod m = type.method(JMod.PUBLIC|JMod.STATIC , type, "fromValue" );
JVar $v = m.param(baseExposedType,"v");
JForEach fe = m.body().forEach(type,"c", type.staticInvoke("values") );
JExpression eq;
if(baseExposedType.isPrimitive())
eq = fe.var().ref($value).eq($v);
else
eq = fe.var().ref($value).invoke("equals").arg($v);
fe.body()._if(eq)._then()._return(fe.var());
JInvocation ex = JExpr._new(codeModel.ref(IllegalArgumentException.class));
if(baseExposedType.isPrimitive()) {
m.body()._throw(ex.arg(codeModel.ref(String.class).staticInvoke("valueOf").arg($v)));
} else {
m.body()._throw(ex.arg($v.invoke("toString")));
}
}
} else {
// [RESULT]
// public String value() { return name(); }
type.method(JMod.PUBLIC, String.class, "value" ).body()._return(JExpr.invoke("name"));
// [RESULT]
// public <Const> fromValue(String v) { return valueOf(v); }
- JMethod m = type.method(JMod.PUBLIC, type, "fromValue" );
+ JMethod m = type.method(JMod.PUBLIC|JMod.STATIC, type, "fromValue" );
m.body()._return( JExpr.invoke("valueOf").arg(m.param(String.class,"v")));
}
return enumOutline;
}
/**
* Determines the FieldRenderer used for the given FieldUse,
* then generates the field declaration and accessor methods.
*
* The <code>fields</code> map will be updated with the newly
* created FieldRenderer.
*/
private FieldOutline generateFieldDecl( ClassOutlineImpl cc, CPropertyInfo prop ) {
FieldRenderer fr = prop.realization;
if(fr==null)
// none is specified. use the default factory
fr = model.options.getFieldRendererFactory().getDefault();
FieldOutline field = fr.generate(cc,prop);
fields.put(prop,field);
return field;
}
/**
* Generates {@link XmlJavaTypeAdapter} from {@link PropertyInfo} if necessary.
* Also generates other per-property annotations
* (such as {@link XmlID}, {@link XmlIDREF}, and {@link XmlMimeType} if necessary.
*/
public final void generateAdapterIfNecessary(CPropertyInfo prop, JAnnotatable field) {
CAdapter adapter = prop.getAdapter();
if (adapter != null ) {
if(adapter.getAdapterIfKnown()==SwaRefAdapter.class) {
field.annotate(XmlAttachmentRef.class);
} else {
// [RESULT]
// @XmlJavaTypeAdapter( Foo.class )
XmlJavaTypeAdapterWriter xjtw = field.annotate2(XmlJavaTypeAdapterWriter.class);
xjtw.value(adapter.adapterType.toType(this,Aspect.EXPOSED));
}
}
switch(prop.id()) {
case ID:
field.annotate(XmlID.class);
break;
case IDREF:
field.annotate(XmlIDREF.class);
break;
}
if(prop.getExpectedMimeType()!=null)
field.annotate2(XmlMimeTypeWriter.class).value(prop.getExpectedMimeType().toString());
}
public final JClass addRuntime(Class clazz) {
JClass g = generatedRuntime.get(clazz);
if(g==null) {
// put code into a separate package to avoid name conflicts.
JPackage implPkg = getUsedPackages(Aspect.IMPLEMENTATION)[0].subPackage("runtime");
g = generateStaticClass(clazz,implPkg);
generatedRuntime.put(clazz,g);
}
return g;
}
public JClass generateStaticClass(Class src, JPackage out) {
String shortName = getShortName(src.getName());
// some people didn't like our jars to contain files with .java extension,
// so when we build jars, we'' use ".java_". But when we run from the workspace,
// we want the original source code to be used, so we check both here.
// see bug 6211503.
URL res = src.getResource(shortName+".java");
if(res==null)
res = src.getResource(shortName+".java_");
if(res==null)
throw new InternalError("Unable to load source code of "+src.getName()+" as a resource");
JStaticJavaFile sjf = new JStaticJavaFile(out,shortName, res, null );
out.addResourceFile(sjf);
return sjf.getJClass();
}
private String getShortName( String name ) {
return name.substring(name.lastIndexOf('.')+1);
}
}
| true | true | private EnumOutline generateEnum(CEnumLeafInfo e) {
JDefinedClass type;
// since constant values are never null, no point in using the boxed types.
JType baseExposedType = e.base.toType(this,Aspect.EXPOSED).unboxify();
JType baseImplType = e.base.toType(this,Aspect.IMPLEMENTATION).unboxify();
type = getClassFactory().createClass(
getContainer(e.parent,Aspect.EXPOSED),e.shortName,e.getLocator(), ClassType.ENUM);
type.javadoc().append(e.javadoc);
XmlEnumWriter xew = type.annotate2(XmlEnumWriter.class);
xew.value(baseExposedType);
JCodeModel codeModel = model.codeModel;
EnumOutline enumOutline = new EnumOutline(e, type) {};
boolean needsValue = e.needsValueField();
// for each member <m>,
// [RESULT]
// <EnumName>(<deserializer of m>(<value>));
Set<String> enumFieldNames = new HashSet<String>(); // record generated field names to detect collision
for( CEnumConstant mem : e.members ) {
String constName = mem.getName();
if(!JJavaName.isJavaIdentifier(constName)) {
// didn't produce a name.
getErrorReceiver().error( e.getLocator(),
Messages.ERR_UNUSABLE_NAME.format(mem.getLexicalValue(), constName ) );
}
if( !enumFieldNames.add(constName) )
getErrorReceiver().error( e.getLocator(), Messages.ERR_NAME_COLLISION.format(constName));
// [RESULT]
// <Const>(...)
// ASSUMPTION: datatype is outline-independent
JEnumConstant constRef = type.enumConstant(constName);
if(needsValue)
constRef.arg(e.base.createConstant(this, new XmlString(mem.getLexicalValue())));
if(!mem.getLexicalValue().equals(constName))
constRef.annotate2(XmlEnumValueWriter.class).value(mem.getLexicalValue());
// set javadoc
if( mem.javadoc!=null )
constRef.javadoc().append(mem.javadoc);
enumOutline.constants.add(new EnumConstantOutline(mem,constRef){});
}
if(needsValue) {
// [RESULT]
// final <valueType> value;
JFieldVar $value = type.field( JMod.PRIVATE|JMod.FINAL, baseExposedType, "value" );
// [RESULT]
// public <valuetype> value() { return value; }
type.method(JMod.PUBLIC, baseExposedType, "value" ).body()._return($value);
// [RESULT]
// <constructor>(<valueType> v) {
// this.value=v;
// }
{
JMethod m = type.constructor(0);
m.body().assign( $value, m.param( baseImplType, "v" ) );
}
// [RESULT]
// public static <Const> fromValue(<valueType> v) {
// for( <Const> c : <Const>.values() ) {
// if(c.value == v) // or equals
// return c;
// }
// throw new IllegalArgumentException(...);
// }
{
JMethod m = type.method(JMod.PUBLIC|JMod.STATIC , type, "fromValue" );
JVar $v = m.param(baseExposedType,"v");
JForEach fe = m.body().forEach(type,"c", type.staticInvoke("values") );
JExpression eq;
if(baseExposedType.isPrimitive())
eq = fe.var().ref($value).eq($v);
else
eq = fe.var().ref($value).invoke("equals").arg($v);
fe.body()._if(eq)._then()._return(fe.var());
JInvocation ex = JExpr._new(codeModel.ref(IllegalArgumentException.class));
if(baseExposedType.isPrimitive()) {
m.body()._throw(ex.arg(codeModel.ref(String.class).staticInvoke("valueOf").arg($v)));
} else {
m.body()._throw(ex.arg($v.invoke("toString")));
}
}
} else {
// [RESULT]
// public String value() { return name(); }
type.method(JMod.PUBLIC, String.class, "value" ).body()._return(JExpr.invoke("name"));
// [RESULT]
// public <Const> fromValue(String v) { return valueOf(v); }
JMethod m = type.method(JMod.PUBLIC, type, "fromValue" );
m.body()._return( JExpr.invoke("valueOf").arg(m.param(String.class,"v")));
}
return enumOutline;
}
| private EnumOutline generateEnum(CEnumLeafInfo e) {
JDefinedClass type;
// since constant values are never null, no point in using the boxed types.
JType baseExposedType = e.base.toType(this,Aspect.EXPOSED).unboxify();
JType baseImplType = e.base.toType(this,Aspect.IMPLEMENTATION).unboxify();
type = getClassFactory().createClass(
getContainer(e.parent,Aspect.EXPOSED),e.shortName,e.getLocator(), ClassType.ENUM);
type.javadoc().append(e.javadoc);
XmlEnumWriter xew = type.annotate2(XmlEnumWriter.class);
xew.value(baseExposedType);
JCodeModel codeModel = model.codeModel;
EnumOutline enumOutline = new EnumOutline(e, type) {};
boolean needsValue = e.needsValueField();
// for each member <m>,
// [RESULT]
// <EnumName>(<deserializer of m>(<value>));
Set<String> enumFieldNames = new HashSet<String>(); // record generated field names to detect collision
for( CEnumConstant mem : e.members ) {
String constName = mem.getName();
if(!JJavaName.isJavaIdentifier(constName)) {
// didn't produce a name.
getErrorReceiver().error( e.getLocator(),
Messages.ERR_UNUSABLE_NAME.format(mem.getLexicalValue(), constName ) );
}
if( !enumFieldNames.add(constName) )
getErrorReceiver().error( e.getLocator(), Messages.ERR_NAME_COLLISION.format(constName));
// [RESULT]
// <Const>(...)
// ASSUMPTION: datatype is outline-independent
JEnumConstant constRef = type.enumConstant(constName);
if(needsValue)
constRef.arg(e.base.createConstant(this, new XmlString(mem.getLexicalValue())));
if(!mem.getLexicalValue().equals(constName))
constRef.annotate2(XmlEnumValueWriter.class).value(mem.getLexicalValue());
// set javadoc
if( mem.javadoc!=null )
constRef.javadoc().append(mem.javadoc);
enumOutline.constants.add(new EnumConstantOutline(mem,constRef){});
}
if(needsValue) {
// [RESULT]
// final <valueType> value;
JFieldVar $value = type.field( JMod.PRIVATE|JMod.FINAL, baseExposedType, "value" );
// [RESULT]
// public <valuetype> value() { return value; }
type.method(JMod.PUBLIC, baseExposedType, "value" ).body()._return($value);
// [RESULT]
// <constructor>(<valueType> v) {
// this.value=v;
// }
{
JMethod m = type.constructor(0);
m.body().assign( $value, m.param( baseImplType, "v" ) );
}
// [RESULT]
// public static <Const> fromValue(<valueType> v) {
// for( <Const> c : <Const>.values() ) {
// if(c.value == v) // or equals
// return c;
// }
// throw new IllegalArgumentException(...);
// }
{
JMethod m = type.method(JMod.PUBLIC|JMod.STATIC , type, "fromValue" );
JVar $v = m.param(baseExposedType,"v");
JForEach fe = m.body().forEach(type,"c", type.staticInvoke("values") );
JExpression eq;
if(baseExposedType.isPrimitive())
eq = fe.var().ref($value).eq($v);
else
eq = fe.var().ref($value).invoke("equals").arg($v);
fe.body()._if(eq)._then()._return(fe.var());
JInvocation ex = JExpr._new(codeModel.ref(IllegalArgumentException.class));
if(baseExposedType.isPrimitive()) {
m.body()._throw(ex.arg(codeModel.ref(String.class).staticInvoke("valueOf").arg($v)));
} else {
m.body()._throw(ex.arg($v.invoke("toString")));
}
}
} else {
// [RESULT]
// public String value() { return name(); }
type.method(JMod.PUBLIC, String.class, "value" ).body()._return(JExpr.invoke("name"));
// [RESULT]
// public <Const> fromValue(String v) { return valueOf(v); }
JMethod m = type.method(JMod.PUBLIC|JMod.STATIC, type, "fromValue" );
m.body()._return( JExpr.invoke("valueOf").arg(m.param(String.class,"v")));
}
return enumOutline;
}
|
diff --git a/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java b/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java
index 7e9b23d..db88d01 100644
--- a/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java
+++ b/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java
@@ -1,777 +1,777 @@
package ljdp.minechem.common.recipe;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ljdp.minechem.api.core.Chemical;
import ljdp.minechem.api.core.Element;
import ljdp.minechem.api.core.EnumElement;
import ljdp.minechem.api.core.EnumMolecule;
import ljdp.minechem.api.core.Molecule;
import ljdp.minechem.api.recipe.DecomposerRecipe;
import ljdp.minechem.api.recipe.DecomposerRecipeChance;
import ljdp.minechem.api.recipe.DecomposerRecipeSelect;
import ljdp.minechem.api.recipe.SynthesisRecipe;
import ljdp.minechem.api.util.Util;
import ljdp.minechem.common.MinechemBlocks;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.blueprint.MinechemBlueprint;
import ljdp.minechem.common.items.ItemElement;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.Loader;
public class MinechemRecipes {
private static final MinechemRecipes instance = new MinechemRecipes();
public ArrayList unbondingRecipes = new ArrayList();
public ArrayList synthesisRecipes = new ArrayList();
private SynthesisRecipe recipeIron;
private SynthesisRecipe recipeGold;
private SynthesisRecipe recipeCoalChunk;
public static MinechemRecipes getInstance() {
return instance;
}
public void RegisterRecipes() {
ItemStack var1 = new ItemStack(Block.stone);
new ItemStack(Block.cobblestone);
ItemStack var3 = new ItemStack(Block.dirt);
ItemStack var4 = new ItemStack(Block.sand);
ItemStack var5 = new ItemStack(Block.gravel);
ItemStack var6 = new ItemStack(Block.glass);
ItemStack var7 = new ItemStack(Block.thinGlass);
ItemStack oreIron = new ItemStack(Block.oreIron);
ItemStack oreGold = new ItemStack(Block.oreGold);
ItemStack var10 = new ItemStack(Block.oreDiamond);
ItemStack var11 = new ItemStack(Block.oreEmerald);
ItemStack oreCoal = new ItemStack(Block.oreCoal);
ItemStack var13 = new ItemStack(Block.oreRedstone);
ItemStack var14 = new ItemStack(Block.oreLapis);
ItemStack ingotIron = new ItemStack(Item.ingotIron);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator);
ItemStack var18 = new ItemStack(Item.redstone);
ItemStack var19 = new ItemStack(MinechemItems.testTube, 16);
ItemStack paper = new ItemStack(Item.paper);
ItemStack bdye = new ItemStack(Item.dyePowder, 1, 6);
GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
// GameRegistry.addRecipe(new ItemStack(MinechemItems.blueprint, 1, 1), new Object[] { "ZZZ", "SSS", "ZZZ", Character.valueOf('Z'), paper, Character.valueOf('S'), bdye });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
- GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.EmptyPillz,2), new Object[] { new ItemStack(Item.sugar), ItemStack(Item.slimeBall) });
+ GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.EmptyPillz,2), new Object[] { new ItemStack(Item.sugar), new ItemStack(Item.slimeBall) });
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
Element var21 = this.element(EnumElement.C, 64);
// DecomposerRecipe.add(new DecomposerRecipe(var8, new
// Chemical[]{this.element(EnumElement.Fe, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) }));
// DecomposerRecipe.add(new DecomposerRecipe(var9, new
// Chemical[]{this.element(EnumElement.Au, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) }));
ItemStack ingotGold = new ItemStack(Item.ingotGold);
ItemStack var23 = new ItemStack(Item.diamond);
ItemStack var24 = new ItemStack(Item.emerald);
ItemStack chunkCoal = new ItemStack(Item.coal);
ItemStack fusionblue = new ItemStack(MinechemItems.blueprint, 1, MinechemBlueprint.fusion.id);
ItemStack fusionBlock1 = new ItemStack(MinechemBlocks.fusion, 0);
ItemStack fusionBlock2 = new ItemStack(MinechemBlocks.fusion, 1);
// DecomposerRecipe.add(new DecomposerRecipe(var15, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotIron, new Chemical[] { this.element(EnumElement.Fe, 16) }));
// DecomposerRecipe.add(new DecomposerRecipe(var22, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotGold, new Chemical[] { this.element(EnumElement.Au, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) }));
// DecomposerRecipe.add(new DecomposerRecipe(var25, new
// Chemical[]{this.element(EnumElement.C, 8)}));
DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) }));
// SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
this.recipeIron = new SynthesisRecipe(ingotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) });
this.recipeGold = new SynthesisRecipe(ingotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) });
SynthesisRecipe.add(recipeIron);
SynthesisRecipe.add(recipeGold);
SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null }));
SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockSteel), new
// Chemical[]{this.element(EnumElement.Fe, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockGold), new
// Chemical[]{this.element(EnumElement.Au, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) }));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockSteel), true, 5000, new
// Chemical[]{this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockGold), true, 5000, new
// Chemical[]{this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) }));
ItemStack var26 = new ItemStack(Block.sandStone);
ItemStack var27 = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4);
Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4);
SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) }));
ItemStack var30 = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) }));
ItemStack var31 = new ItemStack(Item.arrow);
ItemStack var32 = new ItemStack(Item.paper);
ItemStack var33 = new ItemStack(Item.leather);
ItemStack var34 = new ItemStack(Item.snowball);
ItemStack var35 = new ItemStack(Item.brick);
ItemStack var36 = new ItemStack(Item.clay);
ItemStack var37 = new ItemStack(Block.mycelium);
ItemStack var38 = new ItemStack(Block.sapling, 1, -1);
DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null }));
ItemStack var39 = new ItemStack(Item.slimeBall);
ItemStack var40 = new ItemStack(Item.blazeRod);
ItemStack var41 = new ItemStack(Item.blazePowder);
ItemStack var42 = new ItemStack(Item.magmaCream);
ItemStack var43 = new ItemStack(Item.ghastTear);
ItemStack var44 = new ItemStack(Item.netherStar);
ItemStack var45 = new ItemStack(Item.spiderEye);
ItemStack var46 = new ItemStack(Item.fermentedSpiderEye);
ItemStack var47 = new ItemStack(Item.netherStalkSeeds);
ItemStack var48 = new ItemStack(Block.glowStone);
ItemStack var49 = new ItemStack(Item.lightStoneDust);
ItemStack var50 = new ItemStack(Item.potion, 1, 0);
ItemStack var51 = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) }));
DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) }));
DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) }));
Element var52 = this.element(EnumElement.H, 64);
Element var53 = this.element(EnumElement.He, 64);
DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 }));
DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) }));
DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) }));
DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) }));
DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null }));
SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null }));
SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 }));
SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null }));
ItemStack var54 = new ItemStack(Item.sugar);
ItemStack var55 = new ItemStack(Item.reed);
ItemStack var56 = new ItemStack(Block.pumpkin);
ItemStack var57 = new ItemStack(Block.melon);
ItemStack var58 = new ItemStack(Item.speckledMelon);
ItemStack var59 = new ItemStack(Item.melon);
ItemStack var60 = new ItemStack(Item.carrot);
ItemStack var61 = new ItemStack(Item.goldenCarrot);
ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3);
ItemStack var63 = new ItemStack(Item.potato);
ItemStack var64 = new ItemStack(Item.bread);
ItemStack var65 = new ItemStack(Item.appleRed);
ItemStack var66 = new ItemStack(Item.appleGold, 1, 0);
// new ItemStack(Item.appleGold, 1, 1);
ItemStack var68 = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) }));
DecomposerRecipe.add(new DecomposerRecipe(var62, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) }));
DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var60, 0.05F, new Chemical[] { this.molecule(EnumMolecule.ret) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var61, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64), this.element(EnumElement.Np) }));
DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
ItemStack var69 = new ItemStack(Item.gunpowder);
ItemStack var70 = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) }));
DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null }));
ItemStack var71 = new ItemStack(Block.wood, 1, -1);
ItemStack var72 = new ItemStack(Block.planks, 1, -1);
ItemStack var140 = new ItemStack(Block.planks, 1, 0);
ItemStack var141 = new ItemStack(Block.planks, 1, 1);
ItemStack var142 = new ItemStack(Block.planks, 1, 2);
ItemStack var143 = new ItemStack(Block.planks, 1, 3);
ItemStack var73 = new ItemStack(Item.stick);
ItemStack var74 = new ItemStack(Block.wood, 1, 0);
ItemStack var75 = new ItemStack(Block.wood, 1, 1);
ItemStack var76 = new ItemStack(Block.wood, 1, 2);
ItemStack var77 = new ItemStack(Block.wood, 1, 3);
ItemStack var78 = new ItemStack(Item.doorWood);
ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1);
DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) }));
Molecule var81 = this.molecule(EnumMolecule.cellulose, 1);
SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null }));
ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0);
ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1);
ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2);
ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4);
ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5);
ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6);
ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7);
ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8);
ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9);
ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10);
ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11);
ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12);
ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13);
ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14);
ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
ItemStack var97 = new ItemStack(Block.cloth, 1, 0);
ItemStack var98 = new ItemStack(Block.cloth, 1, 1);
ItemStack var99 = new ItemStack(Block.cloth, 1, 2);
ItemStack var100 = new ItemStack(Block.cloth, 1, 3);
ItemStack var101 = new ItemStack(Block.cloth, 1, 4);
ItemStack var102 = new ItemStack(Block.cloth, 1, 5);
ItemStack var103 = new ItemStack(Block.cloth, 1, 6);
ItemStack var104 = new ItemStack(Block.cloth, 1, 7);
ItemStack var105 = new ItemStack(Block.cloth, 1, 8);
ItemStack var106 = new ItemStack(Block.cloth, 1, 9);
ItemStack var107 = new ItemStack(Block.cloth, 1, 10);
ItemStack var108 = new ItemStack(Block.cloth, 1, 11);
ItemStack var109 = new ItemStack(Block.cloth, 1, 12);
ItemStack var110 = new ItemStack(Block.cloth, 1, 13);
ItemStack var111 = new ItemStack(Block.cloth, 1, 14);
ItemStack var112 = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride);
ItemStack var114 = new ItemStack(Item.record13);
ItemStack var115 = new ItemStack(Item.recordCat);
ItemStack var116 = new ItemStack(Item.recordFar);
ItemStack var117 = new ItemStack(Item.recordMall);
ItemStack var118 = new ItemStack(Item.recordMellohi);
ItemStack var119 = new ItemStack(Item.recordStal);
ItemStack var120 = new ItemStack(Item.recordStrad);
ItemStack var121 = new ItemStack(Item.recordWard);
ItemStack var122 = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(var114, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var115, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var116, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var117, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var118, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var119, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var120, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var121, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var122, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var114, false, 1000, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var115, false, 1000, new Chemical[] { null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var116, false, 1000, new Chemical[] { null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var117, false, 1000, new Chemical[] { null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var118, false, 1000, new Chemical[] { null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var119, false, 1000, new Chemical[] { null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var120, false, 1000, new Chemical[] { null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var121, false, 1000, new Chemical[] { null, null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var122, false, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 }));
ItemStack var123 = new ItemStack(Block.mushroomBrown);
ItemStack var124 = new ItemStack(Block.mushroomRed);
ItemStack var125 = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.molecule(EnumMolecule.strontiumNitrate, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.molecule(EnumMolecule.strontiumNitrate) }));
SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.molecule(EnumMolecule.strontiumNitrate), null, null, null, null }));
ItemStack var126 = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) }));
ItemStack var127 = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) }));
ItemStack var128 = new ItemStack(Item.bone);
ItemStack var129 = new ItemStack(Item.silk);
// new ItemStack(Block.cloth, 1, -1);
// new ItemStack(Block.cloth, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
ItemStack var132 = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) }));
ItemStack var133 = new ItemStack(Block.netherrack);
ItemStack var134 = new ItemStack(Block.slowSand);
ItemStack var135 = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
ItemStack var136 = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
ItemStack var137 = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
//
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
}
private void addDecomposerRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
Chemical[] var6 = (Chemical[]) var5.toArray(new Chemical[var5.size()]);
ItemStack var7 = new ItemStack(MinechemItems.molecule, 1, var4.id());
DecomposerRecipe.add(new DecomposerRecipe(var7, var6));
}
}
private void addSynthesisRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
ItemStack var6 = new ItemStack(MinechemItems.molecule, 1, var4.id());
SynthesisRecipe.add(new SynthesisRecipe(var6, false, 50, var5));
}
}
private void addUnusedSynthesisRecipes() {
Iterator var1 = DecomposerRecipe.recipes.iterator();
while (var1.hasNext()) {
DecomposerRecipe var2 = (DecomposerRecipe) var1.next();
if (var2.getInput().getItemDamage() != -1) {
boolean var3 = false;
Iterator var4 = SynthesisRecipe.recipes.iterator();
while (true) {
if (var4.hasNext()) {
SynthesisRecipe var5 = (SynthesisRecipe) var4.next();
if (!Util.stacksAreSameKind(var5.getOutput(), var2.getInput())) {
continue;
}
var3 = true;
}
if (!var3) {
ArrayList var6 = var2.getOutputRaw();
if (var6 != null) {
SynthesisRecipe.add(new SynthesisRecipe(var2.getInput(), false, 100, var6));
}
}
break;
}
}
}
}
private ItemStack createPoisonedItemStack(Item var1, int var2, EnumMolecule var3) {
ItemStack var4 = new ItemStack(MinechemItems.molecule, 1, var3.id());
ItemStack var5 = new ItemStack(var1, 1, var2);
ItemStack var6 = new ItemStack(var1, 1, var2);
NBTTagCompound var7 = new NBTTagCompound();
var7.setBoolean("minechem.isPoisoned", true);
var7.setInteger("minechem.effectType", var3.id());
var6.setTagCompound(var7);
GameRegistry.addShapelessRecipe(var6, new Object[]{var4, var5});
return var6;
}
private void registerPoisonRecipes(EnumMolecule var1) {
this.createPoisonedItemStack(Item.appleRed, 0, var1);
this.createPoisonedItemStack(Item.porkCooked, 0, var1);
this.createPoisonedItemStack(Item.beefCooked, 0, var1);
this.createPoisonedItemStack(Item.carrot, 0, var1);
this.createPoisonedItemStack(Item.bakedPotato, 0, var1);
this.createPoisonedItemStack(Item.bread, 0, var1);
this.createPoisonedItemStack(Item.potato, 0, var1);
this.createPoisonedItemStack(Item.bucketMilk, 0, var1);
this.createPoisonedItemStack(Item.fishCooked, 0, var1);
this.createPoisonedItemStack(Item.cookie, 0, var1);
this.createPoisonedItemStack(Item.pumpkinPie, 0, var1);
this.createPoisonedItemStack(MinechemItems.EmptyPillz, 0, var1);
}
@ForgeSubscribe
public void oreEvent(OreDictionary.OreRegisterEvent var1) { // THIS IS A FUCKING MESS BUT IT WILL WORK FOR NOW!!!!!!
String[] compounds = {"Aluminium","Titanium","Chrome",
"Tungsten", "Lead", "Zinc",
"Platinum", "Nickel", "Osmium",
"Iron", "Gold", "Coal",
"Copper", "Tin", "Silver",
"RefinedIron",
"Steel",
"Bronze", "Brass", "Electrum",
"Invar"};//,"Iridium"};
EnumElement[][] elements = {{EnumElement.Al}, {EnumElement.Ti}, {EnumElement.Cr},
{EnumElement.W}, {EnumElement.Pb}, {EnumElement.Zn},
{EnumElement.Pt}, {EnumElement.Ni}, {EnumElement.Os},
{EnumElement.Fe}, {EnumElement.Au}, {EnumElement.C},
{EnumElement.Cu}, {EnumElement.Sn}, {EnumElement.Ag},
{EnumElement.Fe},
{EnumElement.Fe, EnumElement.C}, //Steel
{EnumElement.Sn, EnumElement.Cu},
{EnumElement.Cu},//Bronze
{EnumElement.Zn, EnumElement.Cu}, //Brass
{EnumElement.Ag, EnumElement.Au}, //Electrum
{EnumElement.Fe, EnumElement.Ni} //Invar
};//, EnumElement.Ir
int[][] proportions = {{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},
{4,4},
{1,3},{1,3},{2,2},{2,1}};
String[] itemTypes = {"dustSmall", "dust", "ore" , "ingot", "block", "gear", "plate"}; //"nugget", "plate"
boolean[] craftable = {true, true, false, false, false, false, false};
int[] sizeCoeff = {1, 4, 8, 4, 36, 16, 4};
for (int i=0; i<compounds.length; i++){
for (int j=0; j<itemTypes.length; j++){
if(var1.Name.equals(itemTypes[j]+compounds[i])){
System.out.print("Adding recipe for " + itemTypes[j] + compounds[i]);
List<Chemical> _elems = new ArrayList<Chemical>();
for (int k=0; k<elements[i].length; k++){
_elems.add(this.element(elements[i][k], proportions[i][k]*sizeCoeff[j]));
}
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, _elems.toArray(new Chemical[_elems.size()])));
if(compounds[i].equals("Iron") && itemTypes[j].equals("dust")){
SynthesisRecipe.recipes.remove(recipeIron);
}
if(compounds[i].equals("Gold") && itemTypes[j].equals("dust")){
SynthesisRecipe.recipes.remove(recipeGold);
}
if(compounds[i].equals("Coal") && itemTypes[j].equals("dust")){
SynthesisRecipe.remove(new ItemStack(Item.coal));
SynthesisRecipe.remove(new ItemStack(Block.oreCoal));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.coal), true, 2000, new Chemical[]{this.element(EnumElement.C,4), null, this.element(EnumElement.C,4),
null, null, null,
this.element(EnumElement.C,4), null, this.element(EnumElement.C,4)}));
}
if (craftable[j]){
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000*sizeCoeff[j], _elems.toArray(new Chemical[_elems.size()])));
}
return;
}
}
}
// BEGIN ORE DICTONARY BULLSHIT
if(var1.Name.contains("uraniumOre")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 4)}));
} else if(var1.Name.contains("uraniumIngot")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)}));
} else if(var1.Name.contains("itemDropUranium")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)}));
} else if(var1.Name.contains("gemApatite")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)}));
// } else if(var1.Name.contains("Iridium")) {
// DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ir, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ir, 2)}));
} else if(var1.Name.contains("Ruby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
} else if(var1.Name.contains("Sapphire")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)}));
} else if(var1.Name.contains("plateSilicon")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Si, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Si, 2)}));
} else if(var1.Name.contains("xychoriumBlue")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)}));
} else if(var1.Name.contains("xychoriumRed")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)}));
} else if(var1.Name.contains("xychoriumGreen")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)}));
} else if(var1.Name.contains("xychoriumDark")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)}));
} else if(var1.Name.contains("xychoriumLight")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)}));
} else if(var1.Name.contains("ingotCobalt")) { // Tungsten - Cobalt Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)}));
} else if(var1.Name.contains("ingotArdite")) { // Tungsten - Iron - Silicon Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)}));
} else if(var1.Name.contains("ingotManyullyn")) { // Tungsten - Iron - Silicon - Cobalt Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 7000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)}));
}
else if(var1.Name.contains("gemRuby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
}
else if(var1.Name.contains("gemSapphire")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide)}));
}
else if(var1.Name.contains("gemPeridot")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.olivine)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.olivine)}));
}
else if(var1.Name.contains("cropMaloberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose)}));
}
else if(var1.Name.contains("cropDuskberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2)}));
}
else if(var1.Name.contains("cropSkyberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2)}));
}
else if(var1.Name.contains("cropBlightberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.asprin), this.element(EnumElement.S, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.asprin), this.element(EnumElement.S, 2)}));
}
else if(var1.Name.contains("cropBlueberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
}
else if(var1.Name.contains("cropRaspberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
}
else if(var1.Name.contains("cropBlackberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
}
// cropStingberry
}
// END
// BEGIN MISC FUNCTIONS
private Element element(EnumElement var1, int var2) {
return new Element(var1, var2);
}
private Element element(EnumElement var1) {
return new Element(var1, 1);
}
private Molecule molecule(EnumMolecule var1, int var2) {
return new Molecule(var1, var2);
}
private Molecule molecule(EnumMolecule var1) {
return new Molecule(var1, 1);
}
// END
} // EOF
| true | true | public void RegisterRecipes() {
ItemStack var1 = new ItemStack(Block.stone);
new ItemStack(Block.cobblestone);
ItemStack var3 = new ItemStack(Block.dirt);
ItemStack var4 = new ItemStack(Block.sand);
ItemStack var5 = new ItemStack(Block.gravel);
ItemStack var6 = new ItemStack(Block.glass);
ItemStack var7 = new ItemStack(Block.thinGlass);
ItemStack oreIron = new ItemStack(Block.oreIron);
ItemStack oreGold = new ItemStack(Block.oreGold);
ItemStack var10 = new ItemStack(Block.oreDiamond);
ItemStack var11 = new ItemStack(Block.oreEmerald);
ItemStack oreCoal = new ItemStack(Block.oreCoal);
ItemStack var13 = new ItemStack(Block.oreRedstone);
ItemStack var14 = new ItemStack(Block.oreLapis);
ItemStack ingotIron = new ItemStack(Item.ingotIron);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator);
ItemStack var18 = new ItemStack(Item.redstone);
ItemStack var19 = new ItemStack(MinechemItems.testTube, 16);
ItemStack paper = new ItemStack(Item.paper);
ItemStack bdye = new ItemStack(Item.dyePowder, 1, 6);
GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
// GameRegistry.addRecipe(new ItemStack(MinechemItems.blueprint, 1, 1), new Object[] { "ZZZ", "SSS", "ZZZ", Character.valueOf('Z'), paper, Character.valueOf('S'), bdye });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.EmptyPillz,2), new Object[] { new ItemStack(Item.sugar), ItemStack(Item.slimeBall) });
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
Element var21 = this.element(EnumElement.C, 64);
// DecomposerRecipe.add(new DecomposerRecipe(var8, new
// Chemical[]{this.element(EnumElement.Fe, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) }));
// DecomposerRecipe.add(new DecomposerRecipe(var9, new
// Chemical[]{this.element(EnumElement.Au, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) }));
ItemStack ingotGold = new ItemStack(Item.ingotGold);
ItemStack var23 = new ItemStack(Item.diamond);
ItemStack var24 = new ItemStack(Item.emerald);
ItemStack chunkCoal = new ItemStack(Item.coal);
ItemStack fusionblue = new ItemStack(MinechemItems.blueprint, 1, MinechemBlueprint.fusion.id);
ItemStack fusionBlock1 = new ItemStack(MinechemBlocks.fusion, 0);
ItemStack fusionBlock2 = new ItemStack(MinechemBlocks.fusion, 1);
// DecomposerRecipe.add(new DecomposerRecipe(var15, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotIron, new Chemical[] { this.element(EnumElement.Fe, 16) }));
// DecomposerRecipe.add(new DecomposerRecipe(var22, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotGold, new Chemical[] { this.element(EnumElement.Au, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) }));
// DecomposerRecipe.add(new DecomposerRecipe(var25, new
// Chemical[]{this.element(EnumElement.C, 8)}));
DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) }));
// SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
this.recipeIron = new SynthesisRecipe(ingotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) });
this.recipeGold = new SynthesisRecipe(ingotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) });
SynthesisRecipe.add(recipeIron);
SynthesisRecipe.add(recipeGold);
SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null }));
SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockSteel), new
// Chemical[]{this.element(EnumElement.Fe, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockGold), new
// Chemical[]{this.element(EnumElement.Au, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) }));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockSteel), true, 5000, new
// Chemical[]{this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockGold), true, 5000, new
// Chemical[]{this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) }));
ItemStack var26 = new ItemStack(Block.sandStone);
ItemStack var27 = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4);
Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4);
SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) }));
ItemStack var30 = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) }));
ItemStack var31 = new ItemStack(Item.arrow);
ItemStack var32 = new ItemStack(Item.paper);
ItemStack var33 = new ItemStack(Item.leather);
ItemStack var34 = new ItemStack(Item.snowball);
ItemStack var35 = new ItemStack(Item.brick);
ItemStack var36 = new ItemStack(Item.clay);
ItemStack var37 = new ItemStack(Block.mycelium);
ItemStack var38 = new ItemStack(Block.sapling, 1, -1);
DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null }));
ItemStack var39 = new ItemStack(Item.slimeBall);
ItemStack var40 = new ItemStack(Item.blazeRod);
ItemStack var41 = new ItemStack(Item.blazePowder);
ItemStack var42 = new ItemStack(Item.magmaCream);
ItemStack var43 = new ItemStack(Item.ghastTear);
ItemStack var44 = new ItemStack(Item.netherStar);
ItemStack var45 = new ItemStack(Item.spiderEye);
ItemStack var46 = new ItemStack(Item.fermentedSpiderEye);
ItemStack var47 = new ItemStack(Item.netherStalkSeeds);
ItemStack var48 = new ItemStack(Block.glowStone);
ItemStack var49 = new ItemStack(Item.lightStoneDust);
ItemStack var50 = new ItemStack(Item.potion, 1, 0);
ItemStack var51 = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) }));
DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) }));
DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) }));
Element var52 = this.element(EnumElement.H, 64);
Element var53 = this.element(EnumElement.He, 64);
DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 }));
DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) }));
DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) }));
DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) }));
DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null }));
SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null }));
SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 }));
SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null }));
ItemStack var54 = new ItemStack(Item.sugar);
ItemStack var55 = new ItemStack(Item.reed);
ItemStack var56 = new ItemStack(Block.pumpkin);
ItemStack var57 = new ItemStack(Block.melon);
ItemStack var58 = new ItemStack(Item.speckledMelon);
ItemStack var59 = new ItemStack(Item.melon);
ItemStack var60 = new ItemStack(Item.carrot);
ItemStack var61 = new ItemStack(Item.goldenCarrot);
ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3);
ItemStack var63 = new ItemStack(Item.potato);
ItemStack var64 = new ItemStack(Item.bread);
ItemStack var65 = new ItemStack(Item.appleRed);
ItemStack var66 = new ItemStack(Item.appleGold, 1, 0);
// new ItemStack(Item.appleGold, 1, 1);
ItemStack var68 = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) }));
DecomposerRecipe.add(new DecomposerRecipe(var62, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) }));
DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var60, 0.05F, new Chemical[] { this.molecule(EnumMolecule.ret) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var61, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64), this.element(EnumElement.Np) }));
DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
ItemStack var69 = new ItemStack(Item.gunpowder);
ItemStack var70 = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) }));
DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null }));
ItemStack var71 = new ItemStack(Block.wood, 1, -1);
ItemStack var72 = new ItemStack(Block.planks, 1, -1);
ItemStack var140 = new ItemStack(Block.planks, 1, 0);
ItemStack var141 = new ItemStack(Block.planks, 1, 1);
ItemStack var142 = new ItemStack(Block.planks, 1, 2);
ItemStack var143 = new ItemStack(Block.planks, 1, 3);
ItemStack var73 = new ItemStack(Item.stick);
ItemStack var74 = new ItemStack(Block.wood, 1, 0);
ItemStack var75 = new ItemStack(Block.wood, 1, 1);
ItemStack var76 = new ItemStack(Block.wood, 1, 2);
ItemStack var77 = new ItemStack(Block.wood, 1, 3);
ItemStack var78 = new ItemStack(Item.doorWood);
ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1);
DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) }));
Molecule var81 = this.molecule(EnumMolecule.cellulose, 1);
SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null }));
ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0);
ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1);
ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2);
ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4);
ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5);
ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6);
ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7);
ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8);
ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9);
ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10);
ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11);
ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12);
ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13);
ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14);
ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
ItemStack var97 = new ItemStack(Block.cloth, 1, 0);
ItemStack var98 = new ItemStack(Block.cloth, 1, 1);
ItemStack var99 = new ItemStack(Block.cloth, 1, 2);
ItemStack var100 = new ItemStack(Block.cloth, 1, 3);
ItemStack var101 = new ItemStack(Block.cloth, 1, 4);
ItemStack var102 = new ItemStack(Block.cloth, 1, 5);
ItemStack var103 = new ItemStack(Block.cloth, 1, 6);
ItemStack var104 = new ItemStack(Block.cloth, 1, 7);
ItemStack var105 = new ItemStack(Block.cloth, 1, 8);
ItemStack var106 = new ItemStack(Block.cloth, 1, 9);
ItemStack var107 = new ItemStack(Block.cloth, 1, 10);
ItemStack var108 = new ItemStack(Block.cloth, 1, 11);
ItemStack var109 = new ItemStack(Block.cloth, 1, 12);
ItemStack var110 = new ItemStack(Block.cloth, 1, 13);
ItemStack var111 = new ItemStack(Block.cloth, 1, 14);
ItemStack var112 = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride);
ItemStack var114 = new ItemStack(Item.record13);
ItemStack var115 = new ItemStack(Item.recordCat);
ItemStack var116 = new ItemStack(Item.recordFar);
ItemStack var117 = new ItemStack(Item.recordMall);
ItemStack var118 = new ItemStack(Item.recordMellohi);
ItemStack var119 = new ItemStack(Item.recordStal);
ItemStack var120 = new ItemStack(Item.recordStrad);
ItemStack var121 = new ItemStack(Item.recordWard);
ItemStack var122 = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(var114, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var115, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var116, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var117, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var118, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var119, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var120, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var121, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var122, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var114, false, 1000, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var115, false, 1000, new Chemical[] { null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var116, false, 1000, new Chemical[] { null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var117, false, 1000, new Chemical[] { null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var118, false, 1000, new Chemical[] { null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var119, false, 1000, new Chemical[] { null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var120, false, 1000, new Chemical[] { null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var121, false, 1000, new Chemical[] { null, null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var122, false, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 }));
ItemStack var123 = new ItemStack(Block.mushroomBrown);
ItemStack var124 = new ItemStack(Block.mushroomRed);
ItemStack var125 = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.molecule(EnumMolecule.strontiumNitrate, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.molecule(EnumMolecule.strontiumNitrate) }));
SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.molecule(EnumMolecule.strontiumNitrate), null, null, null, null }));
ItemStack var126 = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) }));
ItemStack var127 = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) }));
ItemStack var128 = new ItemStack(Item.bone);
ItemStack var129 = new ItemStack(Item.silk);
// new ItemStack(Block.cloth, 1, -1);
// new ItemStack(Block.cloth, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
ItemStack var132 = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) }));
ItemStack var133 = new ItemStack(Block.netherrack);
ItemStack var134 = new ItemStack(Block.slowSand);
ItemStack var135 = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
ItemStack var136 = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
ItemStack var137 = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
//
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
}
| public void RegisterRecipes() {
ItemStack var1 = new ItemStack(Block.stone);
new ItemStack(Block.cobblestone);
ItemStack var3 = new ItemStack(Block.dirt);
ItemStack var4 = new ItemStack(Block.sand);
ItemStack var5 = new ItemStack(Block.gravel);
ItemStack var6 = new ItemStack(Block.glass);
ItemStack var7 = new ItemStack(Block.thinGlass);
ItemStack oreIron = new ItemStack(Block.oreIron);
ItemStack oreGold = new ItemStack(Block.oreGold);
ItemStack var10 = new ItemStack(Block.oreDiamond);
ItemStack var11 = new ItemStack(Block.oreEmerald);
ItemStack oreCoal = new ItemStack(Block.oreCoal);
ItemStack var13 = new ItemStack(Block.oreRedstone);
ItemStack var14 = new ItemStack(Block.oreLapis);
ItemStack ingotIron = new ItemStack(Item.ingotIron);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator);
ItemStack var18 = new ItemStack(Item.redstone);
ItemStack var19 = new ItemStack(MinechemItems.testTube, 16);
ItemStack paper = new ItemStack(Item.paper);
ItemStack bdye = new ItemStack(Item.dyePowder, 1, 6);
GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
// GameRegistry.addRecipe(new ItemStack(MinechemItems.blueprint, 1, 1), new Object[] { "ZZZ", "SSS", "ZZZ", Character.valueOf('Z'), paper, Character.valueOf('S'), bdye });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.EmptyPillz,2), new Object[] { new ItemStack(Item.sugar), new ItemStack(Item.slimeBall) });
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
Element var21 = this.element(EnumElement.C, 64);
// DecomposerRecipe.add(new DecomposerRecipe(var8, new
// Chemical[]{this.element(EnumElement.Fe, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) }));
// DecomposerRecipe.add(new DecomposerRecipe(var9, new
// Chemical[]{this.element(EnumElement.Au, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) }));
ItemStack ingotGold = new ItemStack(Item.ingotGold);
ItemStack var23 = new ItemStack(Item.diamond);
ItemStack var24 = new ItemStack(Item.emerald);
ItemStack chunkCoal = new ItemStack(Item.coal);
ItemStack fusionblue = new ItemStack(MinechemItems.blueprint, 1, MinechemBlueprint.fusion.id);
ItemStack fusionBlock1 = new ItemStack(MinechemBlocks.fusion, 0);
ItemStack fusionBlock2 = new ItemStack(MinechemBlocks.fusion, 1);
// DecomposerRecipe.add(new DecomposerRecipe(var15, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotIron, new Chemical[] { this.element(EnumElement.Fe, 16) }));
// DecomposerRecipe.add(new DecomposerRecipe(var22, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotGold, new Chemical[] { this.element(EnumElement.Au, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) }));
// DecomposerRecipe.add(new DecomposerRecipe(var25, new
// Chemical[]{this.element(EnumElement.C, 8)}));
DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) }));
// SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
this.recipeIron = new SynthesisRecipe(ingotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) });
this.recipeGold = new SynthesisRecipe(ingotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) });
SynthesisRecipe.add(recipeIron);
SynthesisRecipe.add(recipeGold);
SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null }));
SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockSteel), new
// Chemical[]{this.element(EnumElement.Fe, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockGold), new
// Chemical[]{this.element(EnumElement.Au, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) }));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockSteel), true, 5000, new
// Chemical[]{this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockGold), true, 5000, new
// Chemical[]{this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) }));
ItemStack var26 = new ItemStack(Block.sandStone);
ItemStack var27 = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4);
Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4);
SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) }));
ItemStack var30 = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) }));
ItemStack var31 = new ItemStack(Item.arrow);
ItemStack var32 = new ItemStack(Item.paper);
ItemStack var33 = new ItemStack(Item.leather);
ItemStack var34 = new ItemStack(Item.snowball);
ItemStack var35 = new ItemStack(Item.brick);
ItemStack var36 = new ItemStack(Item.clay);
ItemStack var37 = new ItemStack(Block.mycelium);
ItemStack var38 = new ItemStack(Block.sapling, 1, -1);
DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null }));
ItemStack var39 = new ItemStack(Item.slimeBall);
ItemStack var40 = new ItemStack(Item.blazeRod);
ItemStack var41 = new ItemStack(Item.blazePowder);
ItemStack var42 = new ItemStack(Item.magmaCream);
ItemStack var43 = new ItemStack(Item.ghastTear);
ItemStack var44 = new ItemStack(Item.netherStar);
ItemStack var45 = new ItemStack(Item.spiderEye);
ItemStack var46 = new ItemStack(Item.fermentedSpiderEye);
ItemStack var47 = new ItemStack(Item.netherStalkSeeds);
ItemStack var48 = new ItemStack(Block.glowStone);
ItemStack var49 = new ItemStack(Item.lightStoneDust);
ItemStack var50 = new ItemStack(Item.potion, 1, 0);
ItemStack var51 = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) }));
DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) }));
DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) }));
Element var52 = this.element(EnumElement.H, 64);
Element var53 = this.element(EnumElement.He, 64);
DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 }));
DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) }));
DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) }));
DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) }));
DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null }));
SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null }));
SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 }));
SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null }));
ItemStack var54 = new ItemStack(Item.sugar);
ItemStack var55 = new ItemStack(Item.reed);
ItemStack var56 = new ItemStack(Block.pumpkin);
ItemStack var57 = new ItemStack(Block.melon);
ItemStack var58 = new ItemStack(Item.speckledMelon);
ItemStack var59 = new ItemStack(Item.melon);
ItemStack var60 = new ItemStack(Item.carrot);
ItemStack var61 = new ItemStack(Item.goldenCarrot);
ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3);
ItemStack var63 = new ItemStack(Item.potato);
ItemStack var64 = new ItemStack(Item.bread);
ItemStack var65 = new ItemStack(Item.appleRed);
ItemStack var66 = new ItemStack(Item.appleGold, 1, 0);
// new ItemStack(Item.appleGold, 1, 1);
ItemStack var68 = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) }));
DecomposerRecipe.add(new DecomposerRecipe(var62, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) }));
DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var60, 0.05F, new Chemical[] { this.molecule(EnumMolecule.ret) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var61, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64), this.element(EnumElement.Np) }));
DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
ItemStack var69 = new ItemStack(Item.gunpowder);
ItemStack var70 = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) }));
DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null }));
ItemStack var71 = new ItemStack(Block.wood, 1, -1);
ItemStack var72 = new ItemStack(Block.planks, 1, -1);
ItemStack var140 = new ItemStack(Block.planks, 1, 0);
ItemStack var141 = new ItemStack(Block.planks, 1, 1);
ItemStack var142 = new ItemStack(Block.planks, 1, 2);
ItemStack var143 = new ItemStack(Block.planks, 1, 3);
ItemStack var73 = new ItemStack(Item.stick);
ItemStack var74 = new ItemStack(Block.wood, 1, 0);
ItemStack var75 = new ItemStack(Block.wood, 1, 1);
ItemStack var76 = new ItemStack(Block.wood, 1, 2);
ItemStack var77 = new ItemStack(Block.wood, 1, 3);
ItemStack var78 = new ItemStack(Item.doorWood);
ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1);
DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) }));
Molecule var81 = this.molecule(EnumMolecule.cellulose, 1);
SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null }));
ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0);
ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1);
ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2);
ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4);
ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5);
ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6);
ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7);
ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8);
ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9);
ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10);
ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11);
ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12);
ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13);
ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14);
ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
ItemStack var97 = new ItemStack(Block.cloth, 1, 0);
ItemStack var98 = new ItemStack(Block.cloth, 1, 1);
ItemStack var99 = new ItemStack(Block.cloth, 1, 2);
ItemStack var100 = new ItemStack(Block.cloth, 1, 3);
ItemStack var101 = new ItemStack(Block.cloth, 1, 4);
ItemStack var102 = new ItemStack(Block.cloth, 1, 5);
ItemStack var103 = new ItemStack(Block.cloth, 1, 6);
ItemStack var104 = new ItemStack(Block.cloth, 1, 7);
ItemStack var105 = new ItemStack(Block.cloth, 1, 8);
ItemStack var106 = new ItemStack(Block.cloth, 1, 9);
ItemStack var107 = new ItemStack(Block.cloth, 1, 10);
ItemStack var108 = new ItemStack(Block.cloth, 1, 11);
ItemStack var109 = new ItemStack(Block.cloth, 1, 12);
ItemStack var110 = new ItemStack(Block.cloth, 1, 13);
ItemStack var111 = new ItemStack(Block.cloth, 1, 14);
ItemStack var112 = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride);
ItemStack var114 = new ItemStack(Item.record13);
ItemStack var115 = new ItemStack(Item.recordCat);
ItemStack var116 = new ItemStack(Item.recordFar);
ItemStack var117 = new ItemStack(Item.recordMall);
ItemStack var118 = new ItemStack(Item.recordMellohi);
ItemStack var119 = new ItemStack(Item.recordStal);
ItemStack var120 = new ItemStack(Item.recordStrad);
ItemStack var121 = new ItemStack(Item.recordWard);
ItemStack var122 = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(var114, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var115, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var116, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var117, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var118, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var119, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var120, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var121, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var122, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var114, false, 1000, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var115, false, 1000, new Chemical[] { null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var116, false, 1000, new Chemical[] { null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var117, false, 1000, new Chemical[] { null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var118, false, 1000, new Chemical[] { null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var119, false, 1000, new Chemical[] { null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var120, false, 1000, new Chemical[] { null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var121, false, 1000, new Chemical[] { null, null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var122, false, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 }));
ItemStack var123 = new ItemStack(Block.mushroomBrown);
ItemStack var124 = new ItemStack(Block.mushroomRed);
ItemStack var125 = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.molecule(EnumMolecule.strontiumNitrate, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.molecule(EnumMolecule.strontiumNitrate) }));
SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.molecule(EnumMolecule.strontiumNitrate), null, null, null, null }));
ItemStack var126 = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) }));
ItemStack var127 = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) }));
ItemStack var128 = new ItemStack(Item.bone);
ItemStack var129 = new ItemStack(Item.silk);
// new ItemStack(Block.cloth, 1, -1);
// new ItemStack(Block.cloth, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
ItemStack var132 = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) }));
ItemStack var133 = new ItemStack(Block.netherrack);
ItemStack var134 = new ItemStack(Block.slowSand);
ItemStack var135 = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
ItemStack var136 = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
ItemStack var137 = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
//
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
}
|
diff --git a/src/test/java/com/ning/http/client/async/RemoteSiteTest.java b/src/test/java/com/ning/http/client/async/RemoteSiteTest.java
index 148f839cb..ebf49b6ee 100644
--- a/src/test/java/com/ning/http/client/async/RemoteSiteTest.java
+++ b/src/test/java/com/ning/http/client/async/RemoteSiteTest.java
@@ -1,261 +1,261 @@
/*
* Copyright 2010 Ning, Inc.
*
* Ning 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 com.ning.http.client.async;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.util.AsyncHttpProviderUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* Unit tests for remote site.
* <p/>
* see http://github.com/MSch/ning-async-http-client-bug/tree/master
*
* @author Martin Schurrer
*/
public abstract class RemoteSiteTest extends AbstractBasicTest{
public static final String URL = "http://google.com?q=";
public static final String REQUEST_PARAM = "github github \n" +
"github";
@Test(groups = {"online", "default_provider"})
public void testGoogleCom() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(10000).build());
// Works
Response response = c.prepareGet("http://www.google.com/").execute().get(10,TimeUnit.SECONDS);
assertNotNull(response);
}
@Test(groups = {"online", "default_provider"})
public void testMailGoogleCom() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(10000).build());
Response response = c.prepareGet("http://mail.google.com/").execute().get(10,TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(response.getStatusCode(), 200);
}
@Test(groups = {"online", "default_provider"})
public void testMicrosoftCom() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(10000).build());
// Works
Response response = c.prepareGet("http://microsoft.com/").execute().get(10,TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(response.getStatusCode(), 301);
}
@Test(groups = {"online", "default_provider"})
public void testWwwMicrosoftCom() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(10000).build());
Response response = c.prepareGet("http://www.microsoft.com/").execute().get(10,TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(response.getStatusCode(), 302);
}
@Test(groups = {"online", "default_provider"})
public void testUpdateMicrosoftCom() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(10000).build());
Response response = c.prepareGet("http://update.microsoft.com/").execute().get(10,TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(response.getStatusCode(), 302);
}
@Test(groups = {"online", "default_provider"})
public void testGoogleComWithTimeout() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(10000).build());
// Works
Response response = c.prepareGet("http://google.com/").execute().get(10,TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(response.getStatusCode(), 301);
}
@Test(groups = {"online", "default_provider"})
public void asyncStatusHEADContentLenghtTest() throws Throwable {
AsyncHttpClient p = getAsyncHttpClient(
new AsyncHttpClientConfig.Builder().setFollowRedirects(true).build());
final CountDownLatch l = new CountDownLatch(1);
Request request = new RequestBuilder("HEAD")
.setUrl("http://www.google.com/")
.build();
p.executeRequest(request, new AsyncCompletionHandlerAdapter() {
@Override
public Response onCompleted(Response response) throws Exception {
Assert.assertEquals(response.getStatusCode(), 200);
l.countDown();
return response;
}
}).get();
if (!l.await(5, TimeUnit.SECONDS)) {
Assert.fail("Timeout out");
}
p.close();
}
@Test(groups = {"online", "default_provider"})
public void invalidStreamTest2() throws Throwable {
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
.setRequestTimeoutInMs(10000)
.setFollowRedirects(true)
.setAllowPoolingConnection(false)
.setMaximumNumberOfRedirects(6)
.build();
AsyncHttpClient c = getAsyncHttpClient(config);
try {
Response response = c.prepareGet("http://bit.ly/aUjTtG").execute().get();
if (response != null) {
System.out.println(response);
}
} catch (Throwable t) {
t.printStackTrace();
assertNotNull(t.getCause());
assertEquals(t.getCause().getMessage(), "invalid version format: ICY");
}
c.close();
}
@Test(groups = {"online", "default_provider"})
public void asyncFullBodyProperlyRead() throws Throwable {
final AsyncHttpClient client = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().build());
Response r = client.prepareGet("http://www.cyberpresse.ca/").execute().get();
InputStream stream = r.getResponseBodyAsStream();
int available = stream.available();
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(stream, lengthWrapper);
int byteToRead = lengthWrapper[0];
Assert.assertEquals(available, byteToRead);
client.close();
}
@Test(groups = {"online", "default_provider"})
public void testUrlRequestParametersEncoding() throws Throwable {
AsyncHttpClient client = getAsyncHttpClient(null);
String requestUrl2 = URL + URLEncoder.encode(REQUEST_PARAM, "UTF-8");
log.info(String.format("Executing request [%s] ...", requestUrl2));
Response response = client.prepareGet(requestUrl2).execute().get();
Assert.assertEquals(response.getStatusCode(), 301);
}
/**
* See https://issues.sonatype.org/browse/AHC-61
* @throws Throwable
*/
@Test(groups = {"online", "default_provider"})
public void testAHC60() throws Throwable {
AsyncHttpClient client = getAsyncHttpClient(null);
Response response = client.prepareGet("http://www.meetup.com/stackoverflow/Mountain-View-CA/").execute().get();
Assert.assertEquals(response.getStatusCode(), 200);
}
@Test(groups = {"online", "default_provider"})
public void stripQueryStringTest() throws Throwable {
AsyncHttpClientConfig cg = new AsyncHttpClientConfig.Builder().setFollowRedirects(true).build();
AsyncHttpClient c = getAsyncHttpClient(cg);
Response response = c.prepareGet("http://www.freakonomics.com/?p=55846")
.execute().get();
assertNotNull(response);
assertEquals(response.getStatusCode(), 200);
c.close();
}
@Test(groups = {"online", "default_provider"})
public void stripQueryStringNegativeTest() throws Throwable {
AsyncHttpClientConfig cg = new AsyncHttpClientConfig.Builder()
.setRemoveQueryParamsOnRedirect(false).setFollowRedirects(true).build();
AsyncHttpClient c = getAsyncHttpClient(cg);
Response response = c.prepareGet("http://www.freakonomics.com/?p=55846")
.execute().get();
assertNotNull(response);
assertEquals(response.getStatusCode(), 301);
c.close();
}
@Test(groups = {"online", "default_provider"})
public void testAHC62Com() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setFollowRedirects(true).build());
// Works
Response response = c.prepareGet("http://api.crunchbase.com/v/1/financial-organization/kinsey-hills-group.js").execute(new AsyncHandler<Response>() {
private Response.ResponseBuilder builder = new Response.ResponseBuilder();
public void onThrowable(Throwable t) {
t.printStackTrace();
}
public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
System.out.println(bodyPart.getBodyPartBytes().length);
builder.accumulate(bodyPart);
return STATE.CONTINUE;
}
public STATE onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
builder.accumulate(responseStatus);
return STATE.CONTINUE;
}
public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
builder.accumulate(headers);
return STATE.CONTINUE;
}
public Response onCompleted() throws Exception {
return builder.build();
}
}).get(10, TimeUnit.SECONDS);
assertNotNull(response);
- assertEquals(response.getResponseBody().length(), 3876);
+ assertEquals(response.getResponseBody().length(), 3873);
}
}
| true | true | public void testAHC62Com() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setFollowRedirects(true).build());
// Works
Response response = c.prepareGet("http://api.crunchbase.com/v/1/financial-organization/kinsey-hills-group.js").execute(new AsyncHandler<Response>() {
private Response.ResponseBuilder builder = new Response.ResponseBuilder();
public void onThrowable(Throwable t) {
t.printStackTrace();
}
public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
System.out.println(bodyPart.getBodyPartBytes().length);
builder.accumulate(bodyPart);
return STATE.CONTINUE;
}
public STATE onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
builder.accumulate(responseStatus);
return STATE.CONTINUE;
}
public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
builder.accumulate(headers);
return STATE.CONTINUE;
}
public Response onCompleted() throws Exception {
return builder.build();
}
}).get(10, TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(response.getResponseBody().length(), 3876);
}
| public void testAHC62Com() throws Throwable {
AsyncHttpClient c = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().setFollowRedirects(true).build());
// Works
Response response = c.prepareGet("http://api.crunchbase.com/v/1/financial-organization/kinsey-hills-group.js").execute(new AsyncHandler<Response>() {
private Response.ResponseBuilder builder = new Response.ResponseBuilder();
public void onThrowable(Throwable t) {
t.printStackTrace();
}
public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
System.out.println(bodyPart.getBodyPartBytes().length);
builder.accumulate(bodyPart);
return STATE.CONTINUE;
}
public STATE onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
builder.accumulate(responseStatus);
return STATE.CONTINUE;
}
public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
builder.accumulate(headers);
return STATE.CONTINUE;
}
public Response onCompleted() throws Exception {
return builder.build();
}
}).get(10, TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(response.getResponseBody().length(), 3873);
}
|
diff --git a/org.iucn.sis.client/src/org/iucn/sis/client/panels/dem/DEMToolbar.java b/org.iucn.sis.client/src/org/iucn/sis/client/panels/dem/DEMToolbar.java
index 981d429a..a6b7c1f8 100644
--- a/org.iucn.sis.client/src/org/iucn/sis/client/panels/dem/DEMToolbar.java
+++ b/org.iucn.sis.client/src/org/iucn/sis/client/panels/dem/DEMToolbar.java
@@ -1,741 +1,741 @@
package org.iucn.sis.client.panels.dem;
import org.iucn.sis.client.api.assessment.AssessmentClientSaveUtils;
import org.iucn.sis.client.api.assessment.ReferenceableAssessment;
import org.iucn.sis.client.api.caches.AssessmentCache;
import org.iucn.sis.client.api.caches.AuthorizationCache;
import org.iucn.sis.client.api.caches.TaxonomyCache;
import org.iucn.sis.client.api.caches.ViewCache;
import org.iucn.sis.client.api.container.SISClientBase;
import org.iucn.sis.client.api.ui.users.panels.ManageCreditsWindow;
import org.iucn.sis.client.api.ui.views.SISView;
import org.iucn.sis.client.container.SimpleSISClient;
import org.iucn.sis.client.panels.ClientUIContainer;
import org.iucn.sis.client.panels.assessments.AssessmentAttachmentPanel;
import org.iucn.sis.client.panels.assessments.NewAssessmentPanel;
import org.iucn.sis.client.panels.assessments.TrackChangesPanel;
import org.iucn.sis.client.panels.criteracalculator.ExpertPanel;
import org.iucn.sis.client.panels.images.ImageManagerPanel;
import org.iucn.sis.client.panels.taxomatic.TaxonCommonNameEditor;
import org.iucn.sis.client.panels.taxomatic.TaxonSynonymEditor;
import org.iucn.sis.shared.api.acl.InsufficientRightsException;
import org.iucn.sis.shared.api.acl.UserPreferences;
import org.iucn.sis.shared.api.acl.base.AuthorizableObject;
import org.iucn.sis.shared.api.debug.Debug;
import org.iucn.sis.shared.api.integrity.ClientAssessmentValidator;
import org.iucn.sis.shared.api.models.Assessment;
import org.iucn.sis.shared.api.models.AssessmentType;
import org.iucn.sis.shared.api.models.TaxonLevel;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.InfoConfig;
import com.extjs.gxt.ui.client.widget.Popup;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.menu.CheckMenuItem;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.solertium.lwxml.shared.GenericCallback;
import com.solertium.util.events.ComplexListener;
import com.solertium.util.events.SimpleListener;
import com.solertium.util.extjs.client.WindowUtils;
public class DEMToolbar extends ToolBar {
public enum EditStatus {
READ_ONLY, EDIT_DATA
}
private final AutosaveTimer autoSave;
private Integer autoSaveInterval = 2;
private Button editViewButton;
private ComplexListener<EditStatus> refreshListener;
private SimpleListener saveListener;
public DEMToolbar() {
this.autoSave = new AutosaveTimer();
setAutoSaveInterval(SISClientBase.currentUser.getPreference(UserPreferences.AUTO_SAVE_TIMER, "2"));
}
private void setAutoSaveInterval(String interval) {
if ("-1".equals(interval))
autoSaveInterval = null;
else {
try {
this.autoSaveInterval = Integer.valueOf(interval);
} catch (Exception e) {
this.autoSaveInterval = 2;
}
if (autoSaveInterval.intValue() < 0)
autoSaveInterval = null;
}
}
public void setRefreshListener(ComplexListener<EditStatus> refreshListener) {
this.refreshListener = refreshListener;
}
public void setSaveListener(SimpleListener saveListener) {
this.saveListener = saveListener;
}
public void build() {
editViewButton = new Button();
editViewButton.setText("Read Only Mode");
editViewButton.setIconStyle("icon-read-only");
editViewButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
Assessment cur = AssessmentCache.impl.getCurrentAssessment();
Button source = ce.getButton();
if (cur != null && !AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, cur)) {
WindowUtils.errorAlert("You do not have rights to edit this assessment.");
} else {
EditStatus eventData;
if ("Read Only Mode".equals(source.getText())) {
source.setText("Edit Data Mode");
source.setIconStyle("icon-unlocked");
eventData = EditStatus.READ_ONLY;
} else {
source.setText("Read Only Mode");
source.setIconStyle("icon-read-only");
eventData = EditStatus.EDIT_DATA;
}
if (refreshListener != null)
refreshListener.handleEvent(eventData);
}
}
});
add(editViewButton);
add(new SeparatorToolItem());
Button item = new Button();
item.setText("New");
item.setIconStyle("icon-new-document");
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
WindowUtils.errorAlert("Please select a taxon to create an assessment for. "
+ "You can select a taxon using the navigator, the search function, " + " or the browser.");
}
else if (TaxonomyCache.impl.getCurrentTaxon().getFootprint().length < TaxonLevel.GENUS) {
WindowUtils.errorAlert("You must select a species or lower taxa to assess. "
+ "You can select a different taxon using the navigator, the search function, "
+ " or the browser.");
} else {
final NewAssessmentPanel panel = new NewAssessmentPanel();
panel.show();
}
}
});
add(item);
add(new SeparatorToolItem());
item = new Button("Save");
item.setIconStyle("icon-save");
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (AssessmentCache.impl.getCurrentAssessment() == null)
return;
try {
boolean save = ViewCache.impl.getCurrentView() != null && AssessmentClientSaveUtils.shouldSaveCurrentAssessment(
ViewCache.impl.getCurrentView().getCurPage().getMyFields());
if (save) {
stopAutosaveTimer();
WindowUtils.showLoadingAlert("Saving assessment...");
AssessmentClientSaveUtils.saveAssessment(ViewCache.impl.getCurrentView().getCurPage().getMyFields(),
AssessmentCache.impl.getCurrentAssessment(), new GenericCallback<Object>() {
public void onFailure(Throwable arg0) {
WindowUtils.hideLoadingAlert();
layout();
WindowUtils.errorAlert("Save Failed", "Failed to save assessment! " + arg0.getMessage());
resetAutosaveTimer();
}
public void onSuccess(Object arg0) {
WindowUtils.hideLoadingAlert();
Info.display("Save Complete", "Successfully saved assessment {0}.",
AssessmentCache.impl.getCurrentAssessment().getSpeciesName());
Debug.println("Explicit save happened at {0}", AssessmentCache.impl.getCurrentAssessment().getLastEdit().getCreatedDate());
resetAutosaveTimer();
//TODO: ClientUIContainer.headerContainer.update();
if (saveListener != null)
saveListener.handleEvent();
}
});
} else {
WindowUtils.hideLoadingAlert();
layout();
Info.display(new InfoConfig("Save not needed", "No changes were made."));
resetAutosaveTimer();
}
} catch (InsufficientRightsException e) {
WindowUtils.errorAlert("Sorry, but you do not have sufficient rights " + "to perform this action.");
}
}
});
add(item);
add(new SeparatorToolItem());
item = new Button();
item.setIconStyle("icon-attachment");
item.setText("Attachments");
item.setEnabled(SimpleSISClient.iAmOnline);
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
final AssessmentAttachmentPanel attachPanel = new AssessmentAttachmentPanel(AssessmentCache.impl.getCurrentAssessment().getInternalId());
attachPanel.draw(new AsyncCallback<String>() {
public void onSuccess(String result) {
final Window uploadShell = WindowUtils.getWindow(true, true, "");
uploadShell.setLayout(new FitLayout());
uploadShell.setWidth(800);
uploadShell.setHeight(400);
uploadShell.setHeading("Attachments");
uploadShell.add(attachPanel);
uploadShell.show();
uploadShell.center();
uploadShell.layout();
}
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Server error: Unable to get file attachments for this assessment");
}
});
}
});
add(item);
add(new Button());
item = new Button();
item.setIconStyle("icon-information");
item.setText("Summary");
Menu mainMenu = new Menu();
item.setMenu(mainMenu);
MenuItem mItem = new MenuItem();
mItem.setIconStyle("icon-expert");
mItem.setText("Quick " + ExpertPanel.titleText + " Result");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (AssessmentCache.impl.getCurrentAssessment() == null) {
WindowUtils.infoAlert("Alert", "Please select an assessment first.");
return;
}
ExpertPanel expertPanel = new ExpertPanel();
expertPanel.update();
Window s = WindowUtils.getWindow(true, false, ExpertPanel.titleText);
s.setLayout(new BorderLayout());
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.WEST, 20));
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.NORTH, 5));
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.SOUTH, 5));
s.setSize(520, 360);
s.add(expertPanel, new BorderLayoutData(LayoutRegion.CENTER));
s.show();
s.center();
}
});
mainMenu.add(mItem);
add(item);
add(new SeparatorToolItem());
//add(new SeparatorToolItem());
item = new Button();
item.setText("Tools");
item.setIconStyle("icon-preferences-wrench");
mainMenu = new Menu();
item.setMenu(mainMenu);
mItem = new MenuItem();
mItem.setText("Edit Common Names");
mItem.setIconStyle("icon-text-bold");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
Info.display(new InfoConfig("No Taxa Selected", "Please select a taxa first."));
return;
}
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
TaxonCommonNameEditor editor = new TaxonCommonNameEditor();
editor.show();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Edit Synonyms");
mItem.setIconStyle("icon-text-bold");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
Info.display(new InfoConfig("No Taxa Selected", "Please select a taxa first."));
return;
}
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
TaxonSynonymEditor editor = new TaxonSynonymEditor();
editor.show();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Attach Image");
mItem.setIconStyle("icon-image");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
Popup imagePopup = new Popup();
if (!imagePopup.isRendered()) {
ImageManagerPanel imageManager =
new ImageManagerPanel(TaxonomyCache.impl.getCurrentTaxon());
imagePopup.add(imageManager);
}
imagePopup.show();
imagePopup.center();
}
});
mainMenu.add(mItem);
// mItem = new MenuItem(Style.PUSH);
// mItem.setText("View Bibliography");
// mItem.setIconStyle("icon-book-open");
// mItem.addSelectionListener(new SelectionListener() {
// public void widgetSelected(BaseEvent be) {
// DEMToolsPopups.buildBibliographyPopup();
// }
// });
// mainMenu.add(mItem);
//
// mItem = new MenuItem(Style.PUSH);
// mItem.setText("View References By Field");
// mItem.setIconStyle("icon-book-open");
// mItem.addSelectionListener(new SelectionListener() {
// public void widgetSelected(BaseEvent be) {
// DEMToolsPopups.buildReferencePopup();
// }
// });
// mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Manage References");
mItem.setIconStyle("icon-book");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
GenericCallback<Object> callback = new GenericCallback<Object>() {
public void onFailure(Throwable caught) {
startAutosaveTimer();
WindowUtils.errorAlert("Error committing changes to the "
+ "server. Ensure you are connected to the server, then try " + "the process again.");
}
public void onSuccess(Object result) {
startAutosaveTimer();
WindowUtils.infoAlert("Successfully committed reference changes.");
}
};
ClientUIContainer.bodyContainer.openReferenceManager(
new ReferenceableAssessment(AssessmentCache.impl.getCurrentAssessment()),
"Manage References -- Add to Global References", callback, callback);
stopAutosaveTimer();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("View Notes");
mItem.setIconStyle("icon-note");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
DEMToolsPopups.buildNotePopup();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setIconStyle("icon-changes");
mItem.setText("Changes");
mItem.addListener(Events.Select, new Listener<BaseEvent>() {
public void handleEvent(BaseEvent be) {
if( SimpleSISClient.iAmOnline ) {
TrackChangesPanel panel = new TrackChangesPanel(AssessmentCache.impl.getCurrentAssessment());
panel.show();
/*final AssessmentChangesPanel panel = new AssessmentChangesPanel();
final Window window = WindowUtils.getWindow(true, false, "Assessment Changes");
window.setClosable(true);
window.setSize(900, 500);
window.setLayout(new FillLayout());
panel.draw(new DrawsLazily.DoneDrawingCallback() {
public void isDrawn() {
window.add(panel);
window.show();
}
});*/
} else {
WindowUtils.errorAlert("Not available offline.", "Sorry, this feature is not " +
"available offline.");
}
}
});
mainMenu.add(mItem);
// mItem = new MenuItem();
// mItem.setIconStyle("icon-comments");
// mItem.setText("Comments");
// mItem.addListener(Events.Select, new Listener<BaseEvent>() {
// public void handleEvent(BaseEvent be) {
// Assessment a = AssessmentCache.impl.getCurrentAssessment();
// Window alert = WindowUtils.getWindow(false, false, "Assessment #" + a.getId());
// LayoutContainer c = alert;
// c.setLayout(new FillLayout());
// c.setSize(300, 450);
// TabItem item = new TabItem();
// item.setIconStyle("icon-comments");
// item.setText("Comments");
// String target = "/comments/browse/assessment/"
// + FilenameStriper.getIDAsStripedPath(a.getId()) + ".comments.xml";
// SysDebugger.getInstance().println(target);
// item.setUrl(target);
// TabPanel tf = new TabPanel();
// tf.add(item);
// c.add(tf);
// alert.show();
// return;
// }
// });
// mainMenu.add(mItem);
add(item);
/*
* The three items below are not and will not
* be ready for SIS 2.0 launch.
*/
/*
mItem = new MenuItem();
mItem.setText("View Report");
mItem.setIconStyle("icon-report");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
fetchReport();
}
});
mainMenu.add(mItem);
final MenuItem integrity = new MenuItem();
integrity.setText("Validate Assessment");
integrity.setIconStyle("icon-integrity");
integrity.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
runIntegrityValidator();
}
});
mainMenu.add(integrity);
final MenuItem workflow = new MenuItem();
workflow.setText("Submission Process Notes");
workflow.setIconStyle("icon-workflow");
workflow.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
final WorkflowNotesWindow window =
new WorkflowNotesWindow(AssessmentCache.impl.getCurrentAssessment().getId()+"");
window.show();
}
});
mainMenu.add(workflow);*/
add(new SeparatorToolItem());
Button mcbutton = new Button();
mcbutton.setText("Manage Credits");
mcbutton.setIconStyle("icon-user-group");
mcbutton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
final ManageCreditsWindow panel = new ManageCreditsWindow();
panel.show();
}
});
add(mcbutton);
add(new SeparatorToolItem());
Button saveMode = new Button("Auto-Save Options"); {
MenuItem timedAutoSave = new MenuItem("Timed Auto-Save"); {
Menu timedMenu = new Menu();
SelectionListener<MenuEvent> listener = new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
String newPreference = ce.getItem().getData("value");
SimpleSISClient.currentUser.setProperty(UserPreferences.AUTO_SAVE_TIMER, newPreference);
setAutoSaveInterval(newPreference);
resetAutosaveTimer();
}
};
for (String value : new String[] {"-1", "2", "5", "10"}) {
CheckMenuItem interval = new CheckMenuItem("-1".equals(value) ? "Off" : "Every " + value + " minutes.");
interval.setData("value", value);
interval.setGroup(UserPreferences.AUTO_SAVE_TIMER);
interval.setChecked("-1".equals(value) ? autoSaveInterval == null : Integer.valueOf(value).equals(autoSaveInterval));
interval.addSelectionListener(listener);
timedMenu.add(interval);
}
timedAutoSave.setSubMenu(timedMenu);
}
MenuItem onPageChange = new MenuItem("On Page Change..."); {
Menu pageChangeMenu = new Menu();
String savePreference =
SimpleSISClient.currentUser.getPreference(UserPreferences.AUTO_SAVE, UserPreferences.PROMPT);
SelectionListener<MenuEvent> listener = new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
String newPreference = ce.getItem().getData("value");
SimpleSISClient.currentUser.setProperty(UserPreferences.AUTO_SAVE, newPreference);
}
};
CheckMenuItem autoSave = new CheckMenuItem("Auto-Save");
autoSave.setData("value", UserPreferences.DO_ACTION);
autoSave.setGroup(UserPreferences.AUTO_SAVE);
autoSave.setChecked(savePreference.equals(UserPreferences.DO_ACTION));
autoSave.addSelectionListener(listener);
autoSave.setToolTip("When switching pages or assessments, any unsaved changes to an " +
"assessment will automatically be saved.");
pageChangeMenu.add(autoSave);
CheckMenuItem autoPrompt = new CheckMenuItem("Prompt Before Auto-Save");
autoPrompt.setData("value", UserPreferences.PROMPT);
autoPrompt.setGroup(UserPreferences.AUTO_SAVE);
autoPrompt.setChecked(savePreference.equals(UserPreferences.PROMPT));
autoPrompt.addSelectionListener(listener);
autoPrompt.setToolTip("When switching pages or assessments, you will be prompted " +
"to save your changes if any unsaved changes are detected.");
pageChangeMenu.add(autoPrompt);
CheckMenuItem ignore = new CheckMenuItem("Ignore");
ignore.setData("value", UserPreferences.IGNORE);
ignore.setGroup(UserPreferences.AUTO_SAVE);
- ignore.setChecked(savePreference.equals(UserPreferences.AUTO_SAVE));
+ ignore.setChecked(savePreference.equals(UserPreferences.IGNORE));
ignore.addSelectionListener(listener);
ignore.setToolTip("When switching pages or assessments, any unsaved changes to an " +
"assessment will be thrown away; you will not be prompted to save them, nor " +
"will they be automatically saved. Only clicking the \"Save\" button will save " +
"changes.");
pageChangeMenu.add(ignore);
onPageChange.setSubMenu(pageChangeMenu);
}
Menu saveModeOptions = new Menu();
saveModeOptions.add(onPageChange);
saveModeOptions.add(timedAutoSave);
saveMode.setMenu(saveModeOptions);
}
add(saveMode);
add(new FillToolItem());
}
public void resetAutosaveTimer() {
autoSave.cancel();
startAutosaveTimer();
}
public void startAutosaveTimer() {
if (autoSaveInterval != null && AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, AssessmentCache.impl.getCurrentAssessment())) {
Debug.println("Starting autosave.");
autoSave.schedule(autoSaveInterval.intValue() * 60 * 1000);
}
}
public void stopAutosaveTimer() {
Debug.println("Stopping autosave.");
autoSave.cancel();
}
public void setViewOnly(boolean viewOnly) {
if (viewOnly) {
editViewButton.setText("Edit Data Mode");
editViewButton.setIconStyle("icon-unlocked");
}
else {
editViewButton.setText("Read Only Mode");
editViewButton.setIconStyle("icon-read-only");
}
}
@SuppressWarnings("unused")
private void runIntegrityValidator() {
final Assessment data = AssessmentCache.impl.getCurrentAssessment();
//Popup new window:
ClientAssessmentValidator.validate(data.getId(), data.getType());
}
@SuppressWarnings("unused")
private void fetchReport() {
final CheckBox useLimited = new CheckBox();
useLimited.setValue(Boolean.valueOf(true));
useLimited.setFieldLabel("Use limited field set (more compact report)");
final CheckBox showEmpty = new CheckBox();
showEmpty.setFieldLabel("Show empty fields");
final FormPanel form = new FormPanel();
form.setLabelSeparator("?");
form.setLabelWidth(300);
form.setFieldWidth(50);
form.setHeaderVisible(false);
form.setBorders(false);
form.add(useLimited);
form.add(showEmpty);
final Window w = WindowUtils.getWindow(true, false, "Report Options");
form.addButton(new Button("Submit", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
Assessment a = AssessmentCache.impl.getCurrentAssessment();
String target = "/reports/";
if (a.getType().equals(AssessmentType.DRAFT_ASSESSMENT_TYPE)) {
target += "draft/";
} else if (a.getType().equals(AssessmentType.PUBLISHED_ASSESSMENT_TYPE)) {
target += "published/";
} else if (a.getType().equals(AssessmentType.USER_ASSESSMENT_TYPE)) {
target += "user/" + SimpleSISClient.currentUser.getUsername() + "/";
}
w.hide();
com.google.gwt.user.client.Window.open(target + AssessmentCache.impl.getCurrentAssessment().getId()
+ "?empty=" + showEmpty.getValue() + "&limited=" + useLimited.getValue(),
"_blank", "");
}
}));
form.addButton(new Button("Cancel", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
w.hide();
}
}));
w.add(form);
w.setSize(400, 250);
w.show();
w.center();
}
private class AutosaveTimer extends Timer {
public void run() {
if (WindowUtils.loadingBox != null && WindowUtils.loadingBox.isVisible()) {
// loading panel is up ... don't shoot!
resetAutosaveTimer();
return;
}
try {
if (!ClientUIContainer.bodyContainer.isAssessmentEditor())
return;
final SISView currentView = ViewCache.impl.getCurrentView();
boolean save = currentView != null && currentView.getCurPage() != null &&
AssessmentClientSaveUtils.shouldSaveCurrentAssessment(currentView.getCurPage().getMyFields());
if (save) {
AssessmentClientSaveUtils.saveAssessment(currentView.getCurPage().getMyFields(),
AssessmentCache.impl.getCurrentAssessment(), new GenericCallback<Object>() {
public void onFailure(Throwable arg0) {
WindowUtils.errorAlert("Save Failed", "Failed to save assessment! " + arg0.getMessage());
startAutosaveTimer();
}
public void onSuccess(Object arg0) {
Info.display("Auto-save Complete", "Successfully auto-saved assessment {0}.",
AssessmentCache.impl.getCurrentAssessment().getSpeciesName());
startAutosaveTimer();
if (saveListener != null)
saveListener.handleEvent();
}
});
} else {
startAutosaveTimer();
}
} catch (InsufficientRightsException e) {
WindowUtils.errorAlert("Auto-save failed. You do not have sufficient "
+ "rights to perform this action.");
} catch (NullPointerException e1) {
Debug.println(
"Auto-save failed, on NPE. Probably logged " + "out and didn't stop the timer. {0}", e1);
}
}
}
}
| true | true | public void build() {
editViewButton = new Button();
editViewButton.setText("Read Only Mode");
editViewButton.setIconStyle("icon-read-only");
editViewButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
Assessment cur = AssessmentCache.impl.getCurrentAssessment();
Button source = ce.getButton();
if (cur != null && !AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, cur)) {
WindowUtils.errorAlert("You do not have rights to edit this assessment.");
} else {
EditStatus eventData;
if ("Read Only Mode".equals(source.getText())) {
source.setText("Edit Data Mode");
source.setIconStyle("icon-unlocked");
eventData = EditStatus.READ_ONLY;
} else {
source.setText("Read Only Mode");
source.setIconStyle("icon-read-only");
eventData = EditStatus.EDIT_DATA;
}
if (refreshListener != null)
refreshListener.handleEvent(eventData);
}
}
});
add(editViewButton);
add(new SeparatorToolItem());
Button item = new Button();
item.setText("New");
item.setIconStyle("icon-new-document");
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
WindowUtils.errorAlert("Please select a taxon to create an assessment for. "
+ "You can select a taxon using the navigator, the search function, " + " or the browser.");
}
else if (TaxonomyCache.impl.getCurrentTaxon().getFootprint().length < TaxonLevel.GENUS) {
WindowUtils.errorAlert("You must select a species or lower taxa to assess. "
+ "You can select a different taxon using the navigator, the search function, "
+ " or the browser.");
} else {
final NewAssessmentPanel panel = new NewAssessmentPanel();
panel.show();
}
}
});
add(item);
add(new SeparatorToolItem());
item = new Button("Save");
item.setIconStyle("icon-save");
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (AssessmentCache.impl.getCurrentAssessment() == null)
return;
try {
boolean save = ViewCache.impl.getCurrentView() != null && AssessmentClientSaveUtils.shouldSaveCurrentAssessment(
ViewCache.impl.getCurrentView().getCurPage().getMyFields());
if (save) {
stopAutosaveTimer();
WindowUtils.showLoadingAlert("Saving assessment...");
AssessmentClientSaveUtils.saveAssessment(ViewCache.impl.getCurrentView().getCurPage().getMyFields(),
AssessmentCache.impl.getCurrentAssessment(), new GenericCallback<Object>() {
public void onFailure(Throwable arg0) {
WindowUtils.hideLoadingAlert();
layout();
WindowUtils.errorAlert("Save Failed", "Failed to save assessment! " + arg0.getMessage());
resetAutosaveTimer();
}
public void onSuccess(Object arg0) {
WindowUtils.hideLoadingAlert();
Info.display("Save Complete", "Successfully saved assessment {0}.",
AssessmentCache.impl.getCurrentAssessment().getSpeciesName());
Debug.println("Explicit save happened at {0}", AssessmentCache.impl.getCurrentAssessment().getLastEdit().getCreatedDate());
resetAutosaveTimer();
//TODO: ClientUIContainer.headerContainer.update();
if (saveListener != null)
saveListener.handleEvent();
}
});
} else {
WindowUtils.hideLoadingAlert();
layout();
Info.display(new InfoConfig("Save not needed", "No changes were made."));
resetAutosaveTimer();
}
} catch (InsufficientRightsException e) {
WindowUtils.errorAlert("Sorry, but you do not have sufficient rights " + "to perform this action.");
}
}
});
add(item);
add(new SeparatorToolItem());
item = new Button();
item.setIconStyle("icon-attachment");
item.setText("Attachments");
item.setEnabled(SimpleSISClient.iAmOnline);
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
final AssessmentAttachmentPanel attachPanel = new AssessmentAttachmentPanel(AssessmentCache.impl.getCurrentAssessment().getInternalId());
attachPanel.draw(new AsyncCallback<String>() {
public void onSuccess(String result) {
final Window uploadShell = WindowUtils.getWindow(true, true, "");
uploadShell.setLayout(new FitLayout());
uploadShell.setWidth(800);
uploadShell.setHeight(400);
uploadShell.setHeading("Attachments");
uploadShell.add(attachPanel);
uploadShell.show();
uploadShell.center();
uploadShell.layout();
}
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Server error: Unable to get file attachments for this assessment");
}
});
}
});
add(item);
add(new Button());
item = new Button();
item.setIconStyle("icon-information");
item.setText("Summary");
Menu mainMenu = new Menu();
item.setMenu(mainMenu);
MenuItem mItem = new MenuItem();
mItem.setIconStyle("icon-expert");
mItem.setText("Quick " + ExpertPanel.titleText + " Result");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (AssessmentCache.impl.getCurrentAssessment() == null) {
WindowUtils.infoAlert("Alert", "Please select an assessment first.");
return;
}
ExpertPanel expertPanel = new ExpertPanel();
expertPanel.update();
Window s = WindowUtils.getWindow(true, false, ExpertPanel.titleText);
s.setLayout(new BorderLayout());
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.WEST, 20));
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.NORTH, 5));
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.SOUTH, 5));
s.setSize(520, 360);
s.add(expertPanel, new BorderLayoutData(LayoutRegion.CENTER));
s.show();
s.center();
}
});
mainMenu.add(mItem);
add(item);
add(new SeparatorToolItem());
//add(new SeparatorToolItem());
item = new Button();
item.setText("Tools");
item.setIconStyle("icon-preferences-wrench");
mainMenu = new Menu();
item.setMenu(mainMenu);
mItem = new MenuItem();
mItem.setText("Edit Common Names");
mItem.setIconStyle("icon-text-bold");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
Info.display(new InfoConfig("No Taxa Selected", "Please select a taxa first."));
return;
}
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
TaxonCommonNameEditor editor = new TaxonCommonNameEditor();
editor.show();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Edit Synonyms");
mItem.setIconStyle("icon-text-bold");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
Info.display(new InfoConfig("No Taxa Selected", "Please select a taxa first."));
return;
}
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
TaxonSynonymEditor editor = new TaxonSynonymEditor();
editor.show();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Attach Image");
mItem.setIconStyle("icon-image");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
Popup imagePopup = new Popup();
if (!imagePopup.isRendered()) {
ImageManagerPanel imageManager =
new ImageManagerPanel(TaxonomyCache.impl.getCurrentTaxon());
imagePopup.add(imageManager);
}
imagePopup.show();
imagePopup.center();
}
});
mainMenu.add(mItem);
// mItem = new MenuItem(Style.PUSH);
// mItem.setText("View Bibliography");
// mItem.setIconStyle("icon-book-open");
// mItem.addSelectionListener(new SelectionListener() {
// public void widgetSelected(BaseEvent be) {
// DEMToolsPopups.buildBibliographyPopup();
// }
// });
// mainMenu.add(mItem);
//
// mItem = new MenuItem(Style.PUSH);
// mItem.setText("View References By Field");
// mItem.setIconStyle("icon-book-open");
// mItem.addSelectionListener(new SelectionListener() {
// public void widgetSelected(BaseEvent be) {
// DEMToolsPopups.buildReferencePopup();
// }
// });
// mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Manage References");
mItem.setIconStyle("icon-book");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
GenericCallback<Object> callback = new GenericCallback<Object>() {
public void onFailure(Throwable caught) {
startAutosaveTimer();
WindowUtils.errorAlert("Error committing changes to the "
+ "server. Ensure you are connected to the server, then try " + "the process again.");
}
public void onSuccess(Object result) {
startAutosaveTimer();
WindowUtils.infoAlert("Successfully committed reference changes.");
}
};
ClientUIContainer.bodyContainer.openReferenceManager(
new ReferenceableAssessment(AssessmentCache.impl.getCurrentAssessment()),
"Manage References -- Add to Global References", callback, callback);
stopAutosaveTimer();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("View Notes");
mItem.setIconStyle("icon-note");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
DEMToolsPopups.buildNotePopup();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setIconStyle("icon-changes");
mItem.setText("Changes");
mItem.addListener(Events.Select, new Listener<BaseEvent>() {
public void handleEvent(BaseEvent be) {
if( SimpleSISClient.iAmOnline ) {
TrackChangesPanel panel = new TrackChangesPanel(AssessmentCache.impl.getCurrentAssessment());
panel.show();
/*final AssessmentChangesPanel panel = new AssessmentChangesPanel();
final Window window = WindowUtils.getWindow(true, false, "Assessment Changes");
window.setClosable(true);
window.setSize(900, 500);
window.setLayout(new FillLayout());
panel.draw(new DrawsLazily.DoneDrawingCallback() {
public void isDrawn() {
window.add(panel);
window.show();
}
});*/
} else {
WindowUtils.errorAlert("Not available offline.", "Sorry, this feature is not " +
"available offline.");
}
}
});
mainMenu.add(mItem);
// mItem = new MenuItem();
// mItem.setIconStyle("icon-comments");
// mItem.setText("Comments");
// mItem.addListener(Events.Select, new Listener<BaseEvent>() {
// public void handleEvent(BaseEvent be) {
// Assessment a = AssessmentCache.impl.getCurrentAssessment();
// Window alert = WindowUtils.getWindow(false, false, "Assessment #" + a.getId());
// LayoutContainer c = alert;
// c.setLayout(new FillLayout());
// c.setSize(300, 450);
// TabItem item = new TabItem();
// item.setIconStyle("icon-comments");
// item.setText("Comments");
// String target = "/comments/browse/assessment/"
// + FilenameStriper.getIDAsStripedPath(a.getId()) + ".comments.xml";
// SysDebugger.getInstance().println(target);
// item.setUrl(target);
// TabPanel tf = new TabPanel();
// tf.add(item);
// c.add(tf);
// alert.show();
// return;
// }
// });
// mainMenu.add(mItem);
add(item);
/*
* The three items below are not and will not
* be ready for SIS 2.0 launch.
*/
/*
mItem = new MenuItem();
mItem.setText("View Report");
mItem.setIconStyle("icon-report");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
fetchReport();
}
});
mainMenu.add(mItem);
final MenuItem integrity = new MenuItem();
integrity.setText("Validate Assessment");
integrity.setIconStyle("icon-integrity");
integrity.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
runIntegrityValidator();
}
});
mainMenu.add(integrity);
final MenuItem workflow = new MenuItem();
workflow.setText("Submission Process Notes");
workflow.setIconStyle("icon-workflow");
workflow.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
final WorkflowNotesWindow window =
new WorkflowNotesWindow(AssessmentCache.impl.getCurrentAssessment().getId()+"");
window.show();
}
});
mainMenu.add(workflow);*/
add(new SeparatorToolItem());
Button mcbutton = new Button();
mcbutton.setText("Manage Credits");
mcbutton.setIconStyle("icon-user-group");
mcbutton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
final ManageCreditsWindow panel = new ManageCreditsWindow();
panel.show();
}
});
add(mcbutton);
add(new SeparatorToolItem());
Button saveMode = new Button("Auto-Save Options"); {
MenuItem timedAutoSave = new MenuItem("Timed Auto-Save"); {
Menu timedMenu = new Menu();
SelectionListener<MenuEvent> listener = new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
String newPreference = ce.getItem().getData("value");
SimpleSISClient.currentUser.setProperty(UserPreferences.AUTO_SAVE_TIMER, newPreference);
setAutoSaveInterval(newPreference);
resetAutosaveTimer();
}
};
for (String value : new String[] {"-1", "2", "5", "10"}) {
CheckMenuItem interval = new CheckMenuItem("-1".equals(value) ? "Off" : "Every " + value + " minutes.");
interval.setData("value", value);
interval.setGroup(UserPreferences.AUTO_SAVE_TIMER);
interval.setChecked("-1".equals(value) ? autoSaveInterval == null : Integer.valueOf(value).equals(autoSaveInterval));
interval.addSelectionListener(listener);
timedMenu.add(interval);
}
timedAutoSave.setSubMenu(timedMenu);
}
MenuItem onPageChange = new MenuItem("On Page Change..."); {
Menu pageChangeMenu = new Menu();
String savePreference =
SimpleSISClient.currentUser.getPreference(UserPreferences.AUTO_SAVE, UserPreferences.PROMPT);
SelectionListener<MenuEvent> listener = new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
String newPreference = ce.getItem().getData("value");
SimpleSISClient.currentUser.setProperty(UserPreferences.AUTO_SAVE, newPreference);
}
};
CheckMenuItem autoSave = new CheckMenuItem("Auto-Save");
autoSave.setData("value", UserPreferences.DO_ACTION);
autoSave.setGroup(UserPreferences.AUTO_SAVE);
autoSave.setChecked(savePreference.equals(UserPreferences.DO_ACTION));
autoSave.addSelectionListener(listener);
autoSave.setToolTip("When switching pages or assessments, any unsaved changes to an " +
"assessment will automatically be saved.");
pageChangeMenu.add(autoSave);
CheckMenuItem autoPrompt = new CheckMenuItem("Prompt Before Auto-Save");
autoPrompt.setData("value", UserPreferences.PROMPT);
autoPrompt.setGroup(UserPreferences.AUTO_SAVE);
autoPrompt.setChecked(savePreference.equals(UserPreferences.PROMPT));
autoPrompt.addSelectionListener(listener);
autoPrompt.setToolTip("When switching pages or assessments, you will be prompted " +
"to save your changes if any unsaved changes are detected.");
pageChangeMenu.add(autoPrompt);
CheckMenuItem ignore = new CheckMenuItem("Ignore");
ignore.setData("value", UserPreferences.IGNORE);
ignore.setGroup(UserPreferences.AUTO_SAVE);
ignore.setChecked(savePreference.equals(UserPreferences.AUTO_SAVE));
ignore.addSelectionListener(listener);
ignore.setToolTip("When switching pages or assessments, any unsaved changes to an " +
"assessment will be thrown away; you will not be prompted to save them, nor " +
"will they be automatically saved. Only clicking the \"Save\" button will save " +
"changes.");
pageChangeMenu.add(ignore);
onPageChange.setSubMenu(pageChangeMenu);
}
Menu saveModeOptions = new Menu();
saveModeOptions.add(onPageChange);
saveModeOptions.add(timedAutoSave);
saveMode.setMenu(saveModeOptions);
}
add(saveMode);
add(new FillToolItem());
}
| public void build() {
editViewButton = new Button();
editViewButton.setText("Read Only Mode");
editViewButton.setIconStyle("icon-read-only");
editViewButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
Assessment cur = AssessmentCache.impl.getCurrentAssessment();
Button source = ce.getButton();
if (cur != null && !AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, cur)) {
WindowUtils.errorAlert("You do not have rights to edit this assessment.");
} else {
EditStatus eventData;
if ("Read Only Mode".equals(source.getText())) {
source.setText("Edit Data Mode");
source.setIconStyle("icon-unlocked");
eventData = EditStatus.READ_ONLY;
} else {
source.setText("Read Only Mode");
source.setIconStyle("icon-read-only");
eventData = EditStatus.EDIT_DATA;
}
if (refreshListener != null)
refreshListener.handleEvent(eventData);
}
}
});
add(editViewButton);
add(new SeparatorToolItem());
Button item = new Button();
item.setText("New");
item.setIconStyle("icon-new-document");
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
WindowUtils.errorAlert("Please select a taxon to create an assessment for. "
+ "You can select a taxon using the navigator, the search function, " + " or the browser.");
}
else if (TaxonomyCache.impl.getCurrentTaxon().getFootprint().length < TaxonLevel.GENUS) {
WindowUtils.errorAlert("You must select a species or lower taxa to assess. "
+ "You can select a different taxon using the navigator, the search function, "
+ " or the browser.");
} else {
final NewAssessmentPanel panel = new NewAssessmentPanel();
panel.show();
}
}
});
add(item);
add(new SeparatorToolItem());
item = new Button("Save");
item.setIconStyle("icon-save");
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (AssessmentCache.impl.getCurrentAssessment() == null)
return;
try {
boolean save = ViewCache.impl.getCurrentView() != null && AssessmentClientSaveUtils.shouldSaveCurrentAssessment(
ViewCache.impl.getCurrentView().getCurPage().getMyFields());
if (save) {
stopAutosaveTimer();
WindowUtils.showLoadingAlert("Saving assessment...");
AssessmentClientSaveUtils.saveAssessment(ViewCache.impl.getCurrentView().getCurPage().getMyFields(),
AssessmentCache.impl.getCurrentAssessment(), new GenericCallback<Object>() {
public void onFailure(Throwable arg0) {
WindowUtils.hideLoadingAlert();
layout();
WindowUtils.errorAlert("Save Failed", "Failed to save assessment! " + arg0.getMessage());
resetAutosaveTimer();
}
public void onSuccess(Object arg0) {
WindowUtils.hideLoadingAlert();
Info.display("Save Complete", "Successfully saved assessment {0}.",
AssessmentCache.impl.getCurrentAssessment().getSpeciesName());
Debug.println("Explicit save happened at {0}", AssessmentCache.impl.getCurrentAssessment().getLastEdit().getCreatedDate());
resetAutosaveTimer();
//TODO: ClientUIContainer.headerContainer.update();
if (saveListener != null)
saveListener.handleEvent();
}
});
} else {
WindowUtils.hideLoadingAlert();
layout();
Info.display(new InfoConfig("Save not needed", "No changes were made."));
resetAutosaveTimer();
}
} catch (InsufficientRightsException e) {
WindowUtils.errorAlert("Sorry, but you do not have sufficient rights " + "to perform this action.");
}
}
});
add(item);
add(new SeparatorToolItem());
item = new Button();
item.setIconStyle("icon-attachment");
item.setText("Attachments");
item.setEnabled(SimpleSISClient.iAmOnline);
item.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
final AssessmentAttachmentPanel attachPanel = new AssessmentAttachmentPanel(AssessmentCache.impl.getCurrentAssessment().getInternalId());
attachPanel.draw(new AsyncCallback<String>() {
public void onSuccess(String result) {
final Window uploadShell = WindowUtils.getWindow(true, true, "");
uploadShell.setLayout(new FitLayout());
uploadShell.setWidth(800);
uploadShell.setHeight(400);
uploadShell.setHeading("Attachments");
uploadShell.add(attachPanel);
uploadShell.show();
uploadShell.center();
uploadShell.layout();
}
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Server error: Unable to get file attachments for this assessment");
}
});
}
});
add(item);
add(new Button());
item = new Button();
item.setIconStyle("icon-information");
item.setText("Summary");
Menu mainMenu = new Menu();
item.setMenu(mainMenu);
MenuItem mItem = new MenuItem();
mItem.setIconStyle("icon-expert");
mItem.setText("Quick " + ExpertPanel.titleText + " Result");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (AssessmentCache.impl.getCurrentAssessment() == null) {
WindowUtils.infoAlert("Alert", "Please select an assessment first.");
return;
}
ExpertPanel expertPanel = new ExpertPanel();
expertPanel.update();
Window s = WindowUtils.getWindow(true, false, ExpertPanel.titleText);
s.setLayout(new BorderLayout());
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.WEST, 20));
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.NORTH, 5));
s.add(new Html(" "), new BorderLayoutData(LayoutRegion.SOUTH, 5));
s.setSize(520, 360);
s.add(expertPanel, new BorderLayoutData(LayoutRegion.CENTER));
s.show();
s.center();
}
});
mainMenu.add(mItem);
add(item);
add(new SeparatorToolItem());
//add(new SeparatorToolItem());
item = new Button();
item.setText("Tools");
item.setIconStyle("icon-preferences-wrench");
mainMenu = new Menu();
item.setMenu(mainMenu);
mItem = new MenuItem();
mItem.setText("Edit Common Names");
mItem.setIconStyle("icon-text-bold");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
Info.display(new InfoConfig("No Taxa Selected", "Please select a taxa first."));
return;
}
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
TaxonCommonNameEditor editor = new TaxonCommonNameEditor();
editor.show();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Edit Synonyms");
mItem.setIconStyle("icon-text-bold");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (TaxonomyCache.impl.getCurrentTaxon() == null) {
Info.display(new InfoConfig("No Taxa Selected", "Please select a taxa first."));
return;
}
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
TaxonSynonymEditor editor = new TaxonSynonymEditor();
editor.show();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Attach Image");
mItem.setIconStyle("icon-image");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
if (!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, TaxonomyCache.impl.getCurrentTaxon())) {
WindowUtils
.errorAlert("Sorry. You do not have sufficient permissions " + "to perform this action.");
return;
}
Popup imagePopup = new Popup();
if (!imagePopup.isRendered()) {
ImageManagerPanel imageManager =
new ImageManagerPanel(TaxonomyCache.impl.getCurrentTaxon());
imagePopup.add(imageManager);
}
imagePopup.show();
imagePopup.center();
}
});
mainMenu.add(mItem);
// mItem = new MenuItem(Style.PUSH);
// mItem.setText("View Bibliography");
// mItem.setIconStyle("icon-book-open");
// mItem.addSelectionListener(new SelectionListener() {
// public void widgetSelected(BaseEvent be) {
// DEMToolsPopups.buildBibliographyPopup();
// }
// });
// mainMenu.add(mItem);
//
// mItem = new MenuItem(Style.PUSH);
// mItem.setText("View References By Field");
// mItem.setIconStyle("icon-book-open");
// mItem.addSelectionListener(new SelectionListener() {
// public void widgetSelected(BaseEvent be) {
// DEMToolsPopups.buildReferencePopup();
// }
// });
// mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("Manage References");
mItem.setIconStyle("icon-book");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
GenericCallback<Object> callback = new GenericCallback<Object>() {
public void onFailure(Throwable caught) {
startAutosaveTimer();
WindowUtils.errorAlert("Error committing changes to the "
+ "server. Ensure you are connected to the server, then try " + "the process again.");
}
public void onSuccess(Object result) {
startAutosaveTimer();
WindowUtils.infoAlert("Successfully committed reference changes.");
}
};
ClientUIContainer.bodyContainer.openReferenceManager(
new ReferenceableAssessment(AssessmentCache.impl.getCurrentAssessment()),
"Manage References -- Add to Global References", callback, callback);
stopAutosaveTimer();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setText("View Notes");
mItem.setIconStyle("icon-note");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
DEMToolsPopups.buildNotePopup();
}
});
mainMenu.add(mItem);
mItem = new MenuItem();
mItem.setIconStyle("icon-changes");
mItem.setText("Changes");
mItem.addListener(Events.Select, new Listener<BaseEvent>() {
public void handleEvent(BaseEvent be) {
if( SimpleSISClient.iAmOnline ) {
TrackChangesPanel panel = new TrackChangesPanel(AssessmentCache.impl.getCurrentAssessment());
panel.show();
/*final AssessmentChangesPanel panel = new AssessmentChangesPanel();
final Window window = WindowUtils.getWindow(true, false, "Assessment Changes");
window.setClosable(true);
window.setSize(900, 500);
window.setLayout(new FillLayout());
panel.draw(new DrawsLazily.DoneDrawingCallback() {
public void isDrawn() {
window.add(panel);
window.show();
}
});*/
} else {
WindowUtils.errorAlert("Not available offline.", "Sorry, this feature is not " +
"available offline.");
}
}
});
mainMenu.add(mItem);
// mItem = new MenuItem();
// mItem.setIconStyle("icon-comments");
// mItem.setText("Comments");
// mItem.addListener(Events.Select, new Listener<BaseEvent>() {
// public void handleEvent(BaseEvent be) {
// Assessment a = AssessmentCache.impl.getCurrentAssessment();
// Window alert = WindowUtils.getWindow(false, false, "Assessment #" + a.getId());
// LayoutContainer c = alert;
// c.setLayout(new FillLayout());
// c.setSize(300, 450);
// TabItem item = new TabItem();
// item.setIconStyle("icon-comments");
// item.setText("Comments");
// String target = "/comments/browse/assessment/"
// + FilenameStriper.getIDAsStripedPath(a.getId()) + ".comments.xml";
// SysDebugger.getInstance().println(target);
// item.setUrl(target);
// TabPanel tf = new TabPanel();
// tf.add(item);
// c.add(tf);
// alert.show();
// return;
// }
// });
// mainMenu.add(mItem);
add(item);
/*
* The three items below are not and will not
* be ready for SIS 2.0 launch.
*/
/*
mItem = new MenuItem();
mItem.setText("View Report");
mItem.setIconStyle("icon-report");
mItem.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
fetchReport();
}
});
mainMenu.add(mItem);
final MenuItem integrity = new MenuItem();
integrity.setText("Validate Assessment");
integrity.setIconStyle("icon-integrity");
integrity.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
runIntegrityValidator();
}
});
mainMenu.add(integrity);
final MenuItem workflow = new MenuItem();
workflow.setText("Submission Process Notes");
workflow.setIconStyle("icon-workflow");
workflow.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
final WorkflowNotesWindow window =
new WorkflowNotesWindow(AssessmentCache.impl.getCurrentAssessment().getId()+"");
window.show();
}
});
mainMenu.add(workflow);*/
add(new SeparatorToolItem());
Button mcbutton = new Button();
mcbutton.setText("Manage Credits");
mcbutton.setIconStyle("icon-user-group");
mcbutton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
final ManageCreditsWindow panel = new ManageCreditsWindow();
panel.show();
}
});
add(mcbutton);
add(new SeparatorToolItem());
Button saveMode = new Button("Auto-Save Options"); {
MenuItem timedAutoSave = new MenuItem("Timed Auto-Save"); {
Menu timedMenu = new Menu();
SelectionListener<MenuEvent> listener = new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
String newPreference = ce.getItem().getData("value");
SimpleSISClient.currentUser.setProperty(UserPreferences.AUTO_SAVE_TIMER, newPreference);
setAutoSaveInterval(newPreference);
resetAutosaveTimer();
}
};
for (String value : new String[] {"-1", "2", "5", "10"}) {
CheckMenuItem interval = new CheckMenuItem("-1".equals(value) ? "Off" : "Every " + value + " minutes.");
interval.setData("value", value);
interval.setGroup(UserPreferences.AUTO_SAVE_TIMER);
interval.setChecked("-1".equals(value) ? autoSaveInterval == null : Integer.valueOf(value).equals(autoSaveInterval));
interval.addSelectionListener(listener);
timedMenu.add(interval);
}
timedAutoSave.setSubMenu(timedMenu);
}
MenuItem onPageChange = new MenuItem("On Page Change..."); {
Menu pageChangeMenu = new Menu();
String savePreference =
SimpleSISClient.currentUser.getPreference(UserPreferences.AUTO_SAVE, UserPreferences.PROMPT);
SelectionListener<MenuEvent> listener = new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
String newPreference = ce.getItem().getData("value");
SimpleSISClient.currentUser.setProperty(UserPreferences.AUTO_SAVE, newPreference);
}
};
CheckMenuItem autoSave = new CheckMenuItem("Auto-Save");
autoSave.setData("value", UserPreferences.DO_ACTION);
autoSave.setGroup(UserPreferences.AUTO_SAVE);
autoSave.setChecked(savePreference.equals(UserPreferences.DO_ACTION));
autoSave.addSelectionListener(listener);
autoSave.setToolTip("When switching pages or assessments, any unsaved changes to an " +
"assessment will automatically be saved.");
pageChangeMenu.add(autoSave);
CheckMenuItem autoPrompt = new CheckMenuItem("Prompt Before Auto-Save");
autoPrompt.setData("value", UserPreferences.PROMPT);
autoPrompt.setGroup(UserPreferences.AUTO_SAVE);
autoPrompt.setChecked(savePreference.equals(UserPreferences.PROMPT));
autoPrompt.addSelectionListener(listener);
autoPrompt.setToolTip("When switching pages or assessments, you will be prompted " +
"to save your changes if any unsaved changes are detected.");
pageChangeMenu.add(autoPrompt);
CheckMenuItem ignore = new CheckMenuItem("Ignore");
ignore.setData("value", UserPreferences.IGNORE);
ignore.setGroup(UserPreferences.AUTO_SAVE);
ignore.setChecked(savePreference.equals(UserPreferences.IGNORE));
ignore.addSelectionListener(listener);
ignore.setToolTip("When switching pages or assessments, any unsaved changes to an " +
"assessment will be thrown away; you will not be prompted to save them, nor " +
"will they be automatically saved. Only clicking the \"Save\" button will save " +
"changes.");
pageChangeMenu.add(ignore);
onPageChange.setSubMenu(pageChangeMenu);
}
Menu saveModeOptions = new Menu();
saveModeOptions.add(onPageChange);
saveModeOptions.add(timedAutoSave);
saveMode.setMenu(saveModeOptions);
}
add(saveMode);
add(new FillToolItem());
}
|
diff --git a/oxalis/oxalis-start-outbound/src/test/java/eu/peppol/outbound/smp/SmpTest.java b/oxalis/oxalis-start-outbound/src/test/java/eu/peppol/outbound/smp/SmpTest.java
index 928214e1..f906d78b 100644
--- a/oxalis/oxalis-start-outbound/src/test/java/eu/peppol/outbound/smp/SmpTest.java
+++ b/oxalis/oxalis-start-outbound/src/test/java/eu/peppol/outbound/smp/SmpTest.java
@@ -1,59 +1,59 @@
package eu.peppol.outbound.smp;
import eu.peppol.outbound.util.TestBase;
import eu.peppol.start.identifier.DocumentId;
import eu.peppol.start.identifier.ParticipantId;
import org.testng.annotations.Test;
import java.net.URL;
import java.security.cert.X509Certificate;
import static org.testng.Assert.*;
/**
* User: nigel
* Date: Oct 25, 2011
* Time: 9:05:52 AM
*/
@Test
public class SmpTest extends TestBase{
private static DocumentId invoice = DocumentId.INVOICE;
//private static ParticipantId alfa1lab = Identifiers.getParticipantIdentifier("9902:DK28158815");
private static ParticipantId alfa1lab = new ParticipantId("9902:DK28158815");
private static ParticipantId helseVest = new ParticipantId("9908:983974724");
private static ParticipantId sendRegning = new ParticipantId("9908:976098897");
public void test01() throws Throwable {
try {
URL endpointAddress;
endpointAddress = new SmpLookupManager().getEndpointAddress(alfa1lab, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://start-ap.alfa1lab.com:443/accesspointService");
endpointAddress = new SmpLookupManager().getEndpointAddress(helseVest, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://peppolap.ibxplatform.net:8443/accesspointService");
endpointAddress = new SmpLookupManager().getEndpointAddress(sendRegning, invoice);
- assertEquals(endpointAddress.toExternalForm(), "https://aksesspunkt.sendregning.no:8443/oxalis/accesspointService");
+ assertEquals(endpointAddress.toExternalForm(), "https://aksesspunkt.sendregning.no:8443/oxalis/accessPointService");
} catch (Throwable t) {
signal(t);
}
}
public void test02() throws Throwable {
try {
X509Certificate endpointCertificate;
endpointCertificate = new SmpLookupManager().getEndpointCertificate(alfa1lab, invoice);
assertEquals(endpointCertificate.getSerialNumber().toString(), "97394193891150626641360283873417712042");
endpointCertificate = new SmpLookupManager().getEndpointCertificate(helseVest, invoice);
assertEquals(endpointCertificate.getSerialNumber().toString(), "37276025795984990954710880598937203007");
} catch (Throwable t) {
signal(t);
}
}
}
| true | true | public void test01() throws Throwable {
try {
URL endpointAddress;
endpointAddress = new SmpLookupManager().getEndpointAddress(alfa1lab, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://start-ap.alfa1lab.com:443/accesspointService");
endpointAddress = new SmpLookupManager().getEndpointAddress(helseVest, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://peppolap.ibxplatform.net:8443/accesspointService");
endpointAddress = new SmpLookupManager().getEndpointAddress(sendRegning, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://aksesspunkt.sendregning.no:8443/oxalis/accesspointService");
} catch (Throwable t) {
signal(t);
}
}
| public void test01() throws Throwable {
try {
URL endpointAddress;
endpointAddress = new SmpLookupManager().getEndpointAddress(alfa1lab, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://start-ap.alfa1lab.com:443/accesspointService");
endpointAddress = new SmpLookupManager().getEndpointAddress(helseVest, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://peppolap.ibxplatform.net:8443/accesspointService");
endpointAddress = new SmpLookupManager().getEndpointAddress(sendRegning, invoice);
assertEquals(endpointAddress.toExternalForm(), "https://aksesspunkt.sendregning.no:8443/oxalis/accessPointService");
} catch (Throwable t) {
signal(t);
}
}
|
diff --git a/src/nu/staldal/lsp/struts/LSPRequestProcessor.java b/src/nu/staldal/lsp/struts/LSPRequestProcessor.java
index a7c3763..f59e274 100644
--- a/src/nu/staldal/lsp/struts/LSPRequestProcessor.java
+++ b/src/nu/staldal/lsp/struts/LSPRequestProcessor.java
@@ -1,90 +1,88 @@
package nu.staldal.lsp.struts;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.xml.sax.SAXException;
import org.apache.struts.config.*;
import org.apache.struts.action.*;
import nu.staldal.lsp.LSPPage;
import nu.staldal.lsp.servlet.LSPManager;
public class LSPRequestProcessor extends RequestProcessor
{
private LSPManager lspManager;
public void init(ActionServlet servlet, ModuleConfig moduleConfig)
throws ServletException
{
super.init(servlet, moduleConfig);
lspManager = LSPManager.getInstance(
servlet.getServletContext(),
Thread.currentThread().getContextClassLoader());
}
protected void processForwardConfig(HttpServletRequest request,
HttpServletResponse response,
ForwardConfig forward)
throws java.io.IOException, ServletException
{
if (forward == null)
{
return;
}
String forwardPath = forward.getPath();
if (forwardPath.endsWith(".lsp") && !forward.getRedirect())
{
if (forwardPath.charAt(0) == '/')
forwardPath = forwardPath.substring(1);
// Remove ".lsp"
String pageName = forwardPath.substring(0, forwardPath.length()-4);
LSPPage thePage = lspManager.getPage(pageName);
if (thePage == null)
{
throw new ServletException("Unable to find LSP page: " + pageName);
}
response.setContentType(lspManager.getContentType(thePage));
response.resetBuffer();
Map lspParams = new HashMap();
for (Enumeration e = request.getAttributeNames(); e.hasMoreElements(); )
{
String name = (String)e.nextElement();
Object value = request.getAttribute(name);
- System.out.println("reqAttr: " + name
- + " -- " + value.getClass().getName());
lspParams.put(name, value);
}
try {
lspManager.executePage(thePage,
lspParams,
response);
}
catch (SAXException e)
{
throw new ServletException(e);
}
response.flushBuffer();
}
else
{
super.processForwardConfig(request, response, forward);
}
}
}
| true | true | protected void processForwardConfig(HttpServletRequest request,
HttpServletResponse response,
ForwardConfig forward)
throws java.io.IOException, ServletException
{
if (forward == null)
{
return;
}
String forwardPath = forward.getPath();
if (forwardPath.endsWith(".lsp") && !forward.getRedirect())
{
if (forwardPath.charAt(0) == '/')
forwardPath = forwardPath.substring(1);
// Remove ".lsp"
String pageName = forwardPath.substring(0, forwardPath.length()-4);
LSPPage thePage = lspManager.getPage(pageName);
if (thePage == null)
{
throw new ServletException("Unable to find LSP page: " + pageName);
}
response.setContentType(lspManager.getContentType(thePage));
response.resetBuffer();
Map lspParams = new HashMap();
for (Enumeration e = request.getAttributeNames(); e.hasMoreElements(); )
{
String name = (String)e.nextElement();
Object value = request.getAttribute(name);
System.out.println("reqAttr: " + name
+ " -- " + value.getClass().getName());
lspParams.put(name, value);
}
try {
lspManager.executePage(thePage,
lspParams,
response);
}
catch (SAXException e)
{
throw new ServletException(e);
}
response.flushBuffer();
}
else
{
super.processForwardConfig(request, response, forward);
}
}
| protected void processForwardConfig(HttpServletRequest request,
HttpServletResponse response,
ForwardConfig forward)
throws java.io.IOException, ServletException
{
if (forward == null)
{
return;
}
String forwardPath = forward.getPath();
if (forwardPath.endsWith(".lsp") && !forward.getRedirect())
{
if (forwardPath.charAt(0) == '/')
forwardPath = forwardPath.substring(1);
// Remove ".lsp"
String pageName = forwardPath.substring(0, forwardPath.length()-4);
LSPPage thePage = lspManager.getPage(pageName);
if (thePage == null)
{
throw new ServletException("Unable to find LSP page: " + pageName);
}
response.setContentType(lspManager.getContentType(thePage));
response.resetBuffer();
Map lspParams = new HashMap();
for (Enumeration e = request.getAttributeNames(); e.hasMoreElements(); )
{
String name = (String)e.nextElement();
Object value = request.getAttribute(name);
lspParams.put(name, value);
}
try {
lspManager.executePage(thePage,
lspParams,
response);
}
catch (SAXException e)
{
throw new ServletException(e);
}
response.flushBuffer();
}
else
{
super.processForwardConfig(request, response, forward);
}
}
|
diff --git a/src/org/apache/xerces/impl/XMLEntityManager.java b/src/org/apache/xerces/impl/XMLEntityManager.java
index aabd4666..5430e461 100644
--- a/src/org/apache/xerces/impl/XMLEntityManager.java
+++ b/src/org/apache/xerces/impl/XMLEntityManager.java
@@ -1,3564 +1,3564 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.impl;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FilterReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Stack;
import java.util.Vector;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.io.ASCIIReader;
import org.apache.xerces.impl.io.UCSReader;
import org.apache.xerces.impl.io.UTF8Reader;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.impl.validation.ValidationManager;
import org.apache.xerces.util.EncodingMap;
import org.apache.xerces.util.XMLStringBuffer;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.URI;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.XMLResourceIdentifierImpl;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLInputSource;
/**
* The entity manager handles the registration of general and parameter
* entities; resolves entities; and starts entities. The entity manager
* is a central component in a standard parser configuration and this
* class works directly with the entity scanner to manage the underlying
* xni.
* <p>
* This component requires the following features and properties from the
* component manager that uses it:
* <ul>
* <li>http://xml.org/sax/features/validation</li>
* <li>http://xml.org/sax/features/external-general-entities</li>
* <li>http://xml.org/sax/features/external-parameter-entities</li>
* <li>http://apache.org/xml/features/allow-java-encodings</li>
* <li>http://apache.org/xml/properties/internal/symbol-table</li>
* <li>http://apache.org/xml/properties/internal/error-reporter</li>
* <li>http://apache.org/xml/properties/internal/entity-resolver</li>
* </ul>
*
*
* @author Andy Clark, IBM
* @author Arnaud Le Hors, IBM
*
* @version $Id$
*/
public class XMLEntityManager
implements XMLComponent, XMLEntityResolver {
//
// Constants
//
/** Default buffer size (2048). */
public static final int DEFAULT_BUFFER_SIZE = 2048;
/** Default buffer size before we've finished with the XMLDecl: */
public static final int DEFAULT_XMLDECL_BUFFER_SIZE = 64;
/** Default internal entity buffer size (1024). */
public static final int DEFAULT_INTERNAL_BUFFER_SIZE = 1024;
// feature identifiers
/** Feature identifier: validation. */
protected static final String VALIDATION =
Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE;
/** Feature identifier: external general entities. */
protected static final String EXTERNAL_GENERAL_ENTITIES =
Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE;
/** Feature identifier: external parameter entities. */
protected static final String EXTERNAL_PARAMETER_ENTITIES =
Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE;
/** Feature identifier: allow Java encodings. */
protected static final String ALLOW_JAVA_ENCODINGS =
Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE;
/** Feature identifier: warn on duplicate EntityDef */
protected static final String WARN_ON_DUPLICATE_ENTITYDEF =
Constants.XERCES_FEATURE_PREFIX +Constants.WARN_ON_DUPLICATE_ENTITYDEF_FEATURE;
// property identifiers
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: entity resolver. */
protected static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
// property identifier: ValidationManager
protected static final String VALIDATION_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
/** property identifier: buffer size. */
protected static final String BUFFER_SIZE =
Constants.XERCES_PROPERTY_PREFIX + Constants.BUFFER_SIZE_PROPERTY;
// recognized features and properties
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
VALIDATION,
EXTERNAL_GENERAL_ENTITIES,
EXTERNAL_PARAMETER_ENTITIES,
ALLOW_JAVA_ENCODINGS,
WARN_ON_DUPLICATE_ENTITYDEF
};
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
SYMBOL_TABLE,
ERROR_REPORTER,
ENTITY_RESOLVER,
VALIDATION_MANAGER,
BUFFER_SIZE
};
private static final String XMLEntity = "[xml]".intern();
private static final String DTDEntity = "[dtd]".intern();
// debugging
/**
* Debug printing of buffer. This debugging flag works best when you
* resize the DEFAULT_BUFFER_SIZE down to something reasonable like
* 64 characters.
*/
private static final boolean DEBUG_BUFFER = false;
/** Debug some basic entities. */
private static final boolean DEBUG_ENTITIES = false;
/** Debug switching readers for encodings. */
private static final boolean DEBUG_ENCODINGS = false;
// should be diplayed trace resolving messages
private static final boolean DEBUG_RESOLVER = false;
//
// Data
//
// features
/**
* Validation. This feature identifier is:
* http://xml.org/sax/features/validation
*/
protected boolean fValidation;
/**
* External general entities. This feature identifier is:
* http://xml.org/sax/features/external-general-entities
*/
protected boolean fExternalGeneralEntities;
/**
* External parameter entities. This feature identifier is:
* http://xml.org/sax/features/external-parameter-entities
*/
protected boolean fExternalParameterEntities;
/**
* Allow Java encoding names. This feature identifier is:
* http://apache.org/xml/features/allow-java-encodings
*/
protected boolean fAllowJavaEncodings;
/** warn on duplicate Entity declaration.
* http://apache.org/xml/features/warn-on-duplicate-entitydef
*/
protected boolean fWarnDuplicateEntityDef;
// properties
/**
* Symbol table. This property identifier is:
* http://apache.org/xml/properties/internal/symbol-table
*/
protected SymbolTable fSymbolTable;
/**
* Error reporter. This property identifier is:
* http://apache.org/xml/properties/internal/error-reporter
*/
protected XMLErrorReporter fErrorReporter;
/**
* Entity resolver. This property identifier is:
* http://apache.org/xml/properties/internal/entity-resolver
*/
protected XMLEntityResolver fEntityResolver;
/**
* Validation manager. This property identifier is:
* http://apache.org/xml/properties/internal/validation-manager
*/
protected ValidationManager fValidationManager;
// settings
/**
* Buffer size. We get this value from a property. The default size
* is used if the input buffer size property is not specified.
* REVISIT: do we need a property for internal entity buffer size?
*/
protected int fBufferSize = DEFAULT_BUFFER_SIZE;
/**
* True if the document entity is standalone. This should really
* only be set by the document source (e.g. XMLDocumentScanner).
*/
protected boolean fStandalone;
// handlers
/** Entity handler. */
protected XMLEntityHandler fEntityHandler;
// scanner
/** Entity scanner. */
protected XMLEntityScanner fEntityScanner;
// entities
/** Entities. */
protected Hashtable fEntities = new Hashtable();
/** Entity stack. */
protected Stack fEntityStack = new Stack();
/** Current entity. */
protected ScannedEntity fCurrentEntity;
// shared context
/** Shared declared entities. */
protected Hashtable fDeclaredEntities;
// temp vars
/** Resource identifer. */
private final XMLResourceIdentifierImpl fResourceIdentifier = new XMLResourceIdentifierImpl();
//
// Constructors
//
/** Default constructor. */
public XMLEntityManager() {
this(null);
} // <init>()
/**
* Constructs an entity manager that shares the specified entity
* declarations during each parse.
* <p>
* <strong>REVISIT:</strong> We might want to think about the "right"
* way to expose the list of declared entities. For now, the knowledge
* how to access the entity declarations is implicit.
*/
public XMLEntityManager(XMLEntityManager entityManager) {
// create scanner
fEntityScanner = createEntityScanner();
// save shared entity declarations
fDeclaredEntities = entityManager != null
? entityManager.getDeclaredEntities() : null;
} // <init>(XMLEntityManager)
//
// Public methods
//
/**
* Sets whether the document entity is standalone.
*
* @param standalone True if document entity is standalone.
*/
public void setStandalone(boolean standalone) {
fStandalone = standalone;
} // setStandalone(boolean)
/** Returns true if the document entity is standalone. */
public boolean isStandalone() {
return fStandalone;
} // isStandalone():boolean
/**
* Sets the entity handler. When an entity starts and ends, the
* entity handler is notified of the change.
*
* @param entityHandler The new entity handler.
*/
public void setEntityHandler(XMLEntityHandler entityHandler) {
fEntityHandler = entityHandler;
} // setEntityHandler(XMLEntityHandler)
/**
* Adds an internal entity declaration.
* <p>
* <strong>Note:</strong> This method ignores subsequent entity
* declarations.
* <p>
* <strong>Note:</strong> The name should be a unique symbol. The
* SymbolTable can be used for this purpose.
*
* @param name The name of the entity.
* @param text The text of the entity.
*
* @see SymbolTable
*/
public void addInternalEntity(String name, String text) {
if (!fEntities.containsKey(name)) {
Entity entity = new InternalEntity(name, text);
fEntities.put(name, entity);
}
else{
if(fWarnDuplicateEntityDef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ENTITY_DEFINITION",
new Object[]{ name },
XMLErrorReporter.SEVERITY_WARNING );
}
}
} // addInternalEntity(String,String)
/**
* Adds an external entity declaration.
* <p>
* <strong>Note:</strong> This method ignores subsequent entity
* declarations.
* <p>
* <strong>Note:</strong> The name should be a unique symbol. The
* SymbolTable can be used for this purpose.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity.
* @param literalSystemId The system identifier of the entity.
* @param baseSystemId The base system identifier of the entity.
* This is the system identifier of the entity
* where <em>the entity being added</em> and
* is used to expand the system identifier when
* the system identifier is a relative URI.
* When null the system identifier of the first
* external entity on the stack is used instead.
*
* @see SymbolTable
*/
public void addExternalEntity(String name,
String publicId, String literalSystemId,
String baseSystemId) {
if (!fEntities.containsKey(name)) {
if (baseSystemId == null) {
// search for the first external entity on the stack
int size = fEntityStack.size();
if (size == 0 && fCurrentEntity != null && fCurrentEntity.entityLocation != null) {
baseSystemId = fCurrentEntity.entityLocation.getExpandedSystemId();
}
for (int i = size - 1; i >= 0 ; i--) {
ScannedEntity externalEntity =
(ScannedEntity)fEntityStack.elementAt(i);
if (externalEntity.entityLocation != null && externalEntity.entityLocation.getExpandedSystemId() != null) {
baseSystemId = externalEntity.entityLocation.getExpandedSystemId();
break;
}
}
}
Entity entity = new ExternalEntity(name,
new XMLResourceIdentifierImpl(publicId, literalSystemId, baseSystemId, expandSystemId(literalSystemId, baseSystemId)), null);
fEntities.put(name, entity);
}
else{
if(fWarnDuplicateEntityDef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ENTITY_DEFINITION",
new Object[]{ name },
XMLErrorReporter.SEVERITY_WARNING );
}
}
} // addExternalEntity(String,String,String,String)
/**
* Checks whether an entity given by name is external.
*
* @param entityName The name of the entity to check.
* @returns True if the entity is external, false otherwise
* (including when the entity is not declared).
*/
public boolean isExternalEntity(String entityName) {
Entity entity = (Entity)fEntities.get(entityName);
if (entity == null) {
return false;
}
return entity.isExternal();
}
/**
* Adds an unparsed entity declaration.
* <p>
* <strong>Note:</strong> This method ignores subsequent entity
* declarations.
* <p>
* <strong>Note:</strong> The name should be a unique symbol. The
* SymbolTable can be used for this purpose.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity.
* @param systemId The system identifier of the entity.
* @param notation The name of the notation.
*
* @see SymbolTable
*/
public void addUnparsedEntity(String name,
String publicId, String systemId,
String baseSystemId, String notation) {
if (!fEntities.containsKey(name)) {
Entity entity = new ExternalEntity(name, new XMLResourceIdentifierImpl(publicId, systemId, baseSystemId, null), notation);
fEntities.put(name, entity);
}
else{
if(fWarnDuplicateEntityDef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ENTITY_DEFINITION",
new Object[]{ name },
XMLErrorReporter.SEVERITY_WARNING );
}
}
} // addUnparsedEntity(String,String,String,String)
/**
* Checks whether an entity given by name is unparsed.
*
* @param entityName The name of the entity to check.
* @returns True if the entity is unparsed, false otherwise
* (including when the entity is not declared).
*/
public boolean isUnparsedEntity(String entityName) {
Entity entity = (Entity)fEntities.get(entityName);
if (entity == null) {
return false;
}
return entity.isUnparsed();
}
/**
* Checks whether an entity given by name is declared.
*
* @param entityName The name of the entity to check.
* @returns True if the entity is declared, false otherwise.
*/
public boolean isDeclaredEntity(String entityName) {
Entity entity = (Entity)fEntities.get(entityName);
return entity != null;
}
/**
* Resolves the specified public and system identifiers. This
* method first attempts to resolve the entity based on the
* EntityResolver registered by the application. If no entity
* resolver is registered or if the registered entity handler
* is unable to resolve the entity, then default entity
* resolution will occur.
*
* @param publicId The public identifier of the entity.
* @param systemId The system identifier of the entity.
* @param baseSystemId The base system identifier of the entity.
* This is the system identifier of the current
* entity and is used to expand the system
* identifier when the system identifier is a
* relative URI.
*
* @return Returns an input source that wraps the resolved entity.
* This method will never return null.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity resolver to signal an error.
*/
public XMLInputSource resolveEntity(XMLResourceIdentifier resourceIdentifier)
throws IOException, XNIException {
if(resourceIdentifier == null ) return null;
String publicId = resourceIdentifier.getPublicId();
String literalSystemId = resourceIdentifier.getLiteralSystemId();
String baseSystemId = resourceIdentifier.getBaseSystemId();
String expandedSystemId = resourceIdentifier.getExpandedSystemId();
// if no base systemId given, assume that it's relative
// to the systemId of the current scanned entity
// Sometimes the system id is not (properly) expanded.
// We need to expand the system id if:
// a. the expanded one was null; or
// b. the base system id was null, but becomes non-null from the current entity.
boolean needExpand = (expandedSystemId == null);
// REVISIT: why would the baseSystemId ever be null? if we
// didn't have to make this check we wouldn't have to reuse the
// fXMLResourceIdentifier object...
if (baseSystemId == null && fCurrentEntity != null && fCurrentEntity.entityLocation != null) {
baseSystemId = fCurrentEntity.entityLocation.getExpandedSystemId();
if (baseSystemId != null)
needExpand = true;
}
if (needExpand)
expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
// give the entity resolver a chance
XMLInputSource xmlInputSource = null;
if (fEntityResolver != null) {
XMLResourceIdentifierImpl ri = null;
if (resourceIdentifier instanceof XMLResourceIdentifierImpl) {
ri = (XMLResourceIdentifierImpl)resourceIdentifier;
}
else {
fResourceIdentifier.clear();
ri = fResourceIdentifier;
}
ri.setValues(publicId, literalSystemId, baseSystemId, expandedSystemId);
xmlInputSource = fEntityResolver.resolveEntity(ri);
}
// do default resolution
// REVISIT: what's the correct behavior if the user provided an entity
// resolver (fEntityResolver != null), but resolveEntity doesn't return
// an input source (xmlInputSource == null)?
// do we do default resolution, or do we just return null? -SG
if (xmlInputSource == null) {
// REVISIT: when systemId is null, I think we should return null.
// is this the right solution? -SG
//if (systemId != null)
xmlInputSource = new XMLInputSource(publicId, literalSystemId, baseSystemId);
}
if (DEBUG_RESOLVER) {
System.err.println("XMLEntityManager.resolveEntity(" + publicId + ")");
System.err.println(" = " + xmlInputSource);
}
return xmlInputSource;
} // resolveEntity(XMLResourceIdentifier):XMLInputSource
/**
* Starts a named entity.
*
* @param entityName The name of the entity to start.
* @param literal True if this entity is started within a literal
* value.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startEntity(String entityName, boolean literal)
throws IOException, XNIException {
// was entity declared?
Entity entity = (Entity)fEntities.get(entityName);
if (entity == null) {
if (fEntityHandler != null) {
String encoding = null;
fResourceIdentifier.clear();
fEntityHandler.startEntity(entityName, fResourceIdentifier, encoding);
fEntityHandler.endEntity(entityName);
}
return;
}
// should we skip external entities?
boolean external = entity.isExternal();
if (external && (fValidationManager == null || !fValidationManager.isCachedDTD())) {
boolean unparsed = entity.isUnparsed();
boolean parameter = entityName.startsWith("%");
boolean general = !parameter;
if (unparsed || (general && !fExternalGeneralEntities) ||
(parameter && !fExternalParameterEntities)) {
if (fEntityHandler != null) {
fResourceIdentifier.clear();
final String encoding = null;
ExternalEntity externalEntity = (ExternalEntity)entity;
//REVISIT: since we're storing expandedSystemId in the
// externalEntity, how could this have got here if it wasn't already
// expanded??? - neilg
String extLitSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getLiteralSystemId() : null);
String extBaseSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getBaseSystemId() : null);
String expandedSystemId = expandSystemId(extLitSysId, extBaseSysId);
fResourceIdentifier.setValues(
(externalEntity.entityLocation != null ? externalEntity.entityLocation.getPublicId() : null),
extLitSysId, extBaseSysId, expandedSystemId);
fEntityHandler.startEntity(entityName, fResourceIdentifier, encoding);
fEntityHandler.endEntity(entityName);
}
return;
}
}
// is entity recursive?
int size = fEntityStack.size();
for (int i = size; i >= 0; i--) {
Entity activeEntity = i == size
? fCurrentEntity
: (Entity)fEntityStack.elementAt(i);
if (activeEntity.name == entityName) {
String path = entityName;
for (int j = i + 1; j < size; j++) {
activeEntity = (Entity)fEntityStack.elementAt(j);
path = path + " -> " + activeEntity.name;
}
path = path + " -> " + fCurrentEntity.name;
path = path + " -> " + entityName;
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"RecursiveReference",
new Object[] { entityName, path },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
if (fEntityHandler != null) {
fResourceIdentifier.clear();
final String encoding = null;
if (external) {
ExternalEntity externalEntity = (ExternalEntity)entity;
// REVISIT: for the same reason above...
String extLitSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getLiteralSystemId() : null);
String extBaseSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getBaseSystemId() : null);
String expandedSystemId = expandSystemId(extLitSysId, extBaseSysId);
fResourceIdentifier.setValues(
(externalEntity.entityLocation != null ? externalEntity.entityLocation.getPublicId() : null),
extLitSysId, extBaseSysId, expandedSystemId);
}
fEntityHandler.startEntity(entityName, fResourceIdentifier, encoding);
fEntityHandler.endEntity(entityName);
}
return;
}
}
// resolve external entity
XMLInputSource xmlInputSource = null;
if (external) {
ExternalEntity externalEntity = (ExternalEntity)entity;
xmlInputSource = resolveEntity(externalEntity.entityLocation);
}
// wrap internal entity
else {
InternalEntity internalEntity = (InternalEntity)entity;
Reader reader = new StringReader(internalEntity.text);
xmlInputSource = new XMLInputSource(null, null, null, reader, null);
}
// start the entity
startEntity(entityName, xmlInputSource, literal, external);
} // startEntity(String,boolean)
/**
* Starts the document entity. The document entity has the "[xml]"
* pseudo-name.
*
* @param xmlInputSource The input source of the document entity.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startDocumentEntity(XMLInputSource xmlInputSource)
throws IOException, XNIException {
startEntity(XMLEntity, xmlInputSource, false, true);
} // startDocumentEntity(XMLInputSource)
/**
* Starts the DTD entity. The DTD entity has the "[dtd]"
* pseudo-name.
*
* @param xmlInputSource The input source of the DTD entity.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startDTDEntity(XMLInputSource xmlInputSource)
throws IOException, XNIException {
startEntity(DTDEntity, xmlInputSource, false, true);
} // startDTDEntity(XMLInputSource)
/**
* Starts an entity.
* <p>
* This method can be used to insert an application defined XML
* entity stream into the parsing stream.
*
* @param name The name of the entity.
* @param xmlInputSource The input source of the entity.
* @param literal True if this entity is started within a
* literal value.
* @param isExternal whether this entity should be treated as an internal or external entity.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startEntity(String name,
XMLInputSource xmlInputSource,
boolean literal, boolean isExternal)
throws IOException, XNIException {
// get information
final String publicId = xmlInputSource.getPublicId();
final String literalSystemId = xmlInputSource.getSystemId();
String baseSystemId = xmlInputSource.getBaseSystemId();
String encoding = xmlInputSource.getEncoding();
Boolean isBigEndian = null;
// create reader
InputStream stream = null;
Reader reader = xmlInputSource.getCharacterStream();
String expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
if (baseSystemId == null) {
baseSystemId = expandedSystemId;
}
if (reader == null) {
stream = xmlInputSource.getByteStream();
if (stream == null) {
stream = new URL(expandedSystemId).openStream();
}
// wrap this stream in RewindableInputStream
stream = new RewindableInputStream(stream);
// perform auto-detect of encoding if necessary
if (encoding == null) {
// read first four bytes and determine encoding
final byte[] b4 = new byte[4];
int count = 0;
for (; count<4; count++ ) {
b4[count] = (byte)stream.read();
}
if (count == 4) {
Object [] encodingDesc = getEncodingName(b4, count);
encoding = (String)(encodingDesc[0]);
isBigEndian = (Boolean)(encodingDesc[1]);
// removed use of pushback inputstream--neilg
/*****
// push back the characters we read
if (DEBUG_ENCODINGS) {
System.out.println("$$$ wrapping input stream in PushbackInputStream");
}
PushbackInputStream pbstream = new PushbackInputStream(stream, 4);
*****/
stream.reset();
int offset = 0;
// Special case UTF-8 files with BOM created by Microsoft
// tools. It's more efficient to consume the BOM than make
// the reader perform extra checks. -Ac
if (count > 2 && encoding.equals("UTF-8")) {
int b0 = b4[0] & 0xFF;
int b1 = b4[1] & 0xFF;
int b2 = b4[2] & 0xFF;
if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) {
// ignore first three bytes...
stream.skip(3);
/********
offset = 3;
count -= offset;
***/
}
}
reader = createReader(stream, encoding, isBigEndian);
}
else {
reader = createReader(stream, encoding, isBigEndian);
}
}
// use specified encoding
else {
reader = createReader(stream, encoding, isBigEndian);
}
// read one character at a time so we don't jump too far
// ahead, converting characters from the byte stream in
// the wrong encoding
if (DEBUG_ENCODINGS) {
System.out.println("$$$ no longer wrapping reader in OneCharReader");
}
//reader = new OneCharReader(reader);
}
// we've seen a new Reader. put it in a list, so that
// we can close it later.
fOwnReaders.addElement(reader);
// push entity on stack
if (fCurrentEntity != null) {
fEntityStack.push(fCurrentEntity);
}
// create entity
fCurrentEntity = new ScannedEntity(name,
new XMLResourceIdentifierImpl(publicId, literalSystemId, baseSystemId, expandedSystemId),
stream, reader, encoding, literal, false, isExternal);
// call handler
if (fEntityHandler != null) {
fResourceIdentifier.setValues(publicId, literalSystemId, baseSystemId, expandedSystemId);
fEntityHandler.startEntity(name, fResourceIdentifier, encoding);
}
} // startEntity(String,XMLInputSource)
/** Returns the entity scanner. */
public XMLEntityScanner getEntityScanner() {
return fEntityScanner;
} // getEntityScanner():XMLEntityScanner
// a list of Readers ever seen
protected Vector fOwnReaders = new Vector();
/**
* Close all opened InputStreams and Readers opened by this parser.
*/
public void closeReaders() {
// close all readers
for (int i = fOwnReaders.size()-1; i >= 0; i--) {
try {
((Reader)fOwnReaders.elementAt(i)).close();
} catch (IOException e) {
// ignore
}
}
// and clear the list
fOwnReaders.removeAllElements();
}
//
// XMLComponent methods
//
/**
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws SAXException Thrown by component on initialization error.
* For example, if a feature or property is
* required for the operation of the component, the
* component manager may throw a
* SAXNotRecognizedException or a
* SAXNotSupportedException.
*/
public void reset(XMLComponentManager componentManager)
throws XMLConfigurationException {
// sax features
try {
fValidation = componentManager.getFeature(VALIDATION);
}
catch (XMLConfigurationException e) {
fValidation = false;
}
try {
fExternalGeneralEntities = componentManager.getFeature(EXTERNAL_GENERAL_ENTITIES);
}
catch (XMLConfigurationException e) {
fExternalGeneralEntities = true;
}
try {
fExternalParameterEntities = componentManager.getFeature(EXTERNAL_PARAMETER_ENTITIES);
}
catch (XMLConfigurationException e) {
fExternalParameterEntities = true;
}
// xerces features
try {
fAllowJavaEncodings = componentManager.getFeature(ALLOW_JAVA_ENCODINGS);
}
catch (XMLConfigurationException e) {
fAllowJavaEncodings = false;
}
try {
fWarnDuplicateEntityDef = componentManager.getFeature(WARN_ON_DUPLICATE_ENTITYDEF);
}
catch (XMLConfigurationException e) {
fWarnDuplicateEntityDef = false;
}
// xerces properties
fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
try {
fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_RESOLVER);
}
catch (XMLConfigurationException e) {
fEntityResolver = null;
}
try {
fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER);
}
catch (XMLConfigurationException e) {
fValidationManager = null;
}
// initialize state
fStandalone = false;
fEntities.clear();
fEntityStack.removeAllElements();
fCurrentEntity = null;
// DEBUG
if (DEBUG_ENTITIES) {
addInternalEntity("text", "Hello, World.");
addInternalEntity("empty-element", "<foo/>");
addInternalEntity("balanced-element", "<foo></foo>");
addInternalEntity("balanced-element-with-text", "<foo>Hello, World</foo>");
addInternalEntity("balanced-element-with-entity", "<foo>&text;</foo>");
addInternalEntity("unbalanced-entity", "<foo>");
addInternalEntity("recursive-entity", "<foo>&recursive-entity2;</foo>");
addInternalEntity("recursive-entity2", "<bar>&recursive-entity3;</bar>");
addInternalEntity("recursive-entity3", "<baz>&recursive-entity;</baz>");
addExternalEntity("external-text", null, "external-text.ent", "test/external-text.xml");
addExternalEntity("external-balanced-element", null, "external-balanced-element.ent", "test/external-balanced-element.xml");
addExternalEntity("one", null, "ent/one.ent", "test/external-entity.xml");
addExternalEntity("two", null, "ent/two.ent", "test/ent/one.xml");
}
// copy declared entities
if (fDeclaredEntities != null) {
java.util.Enumeration keys = fDeclaredEntities.keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = fDeclaredEntities.get(key);
fEntities.put(key, value);
}
}
} // reset(XMLComponentManager)
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return (String[])(RECOGNIZED_FEATURES.clone());
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
// xerces features
if (featureId.startsWith(Constants.XERCES_FEATURE_PREFIX)) {
String feature = featureId.substring(Constants.XERCES_FEATURE_PREFIX.length());
if (feature.equals(Constants.ALLOW_JAVA_ENCODINGS_FEATURE)) {
fAllowJavaEncodings = state;
}
}
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return (String[])(RECOGNIZED_PROPERTIES.clone());
} // getRecognizedProperties():String[]
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
// Xerces properties
if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) {
String property = propertyId.substring(Constants.XERCES_PROPERTY_PREFIX.length());
if (property.equals(Constants.SYMBOL_TABLE_PROPERTY)) {
fSymbolTable = (SymbolTable)value;
return;
}
if (property.equals(Constants.ERROR_REPORTER_PROPERTY)) {
fErrorReporter = (XMLErrorReporter)value;
return;
}
if (property.equals(Constants.ENTITY_RESOLVER_PROPERTY)) {
fEntityResolver = (XMLEntityResolver)value;
return;
}
if (property.equals(Constants.BUFFER_SIZE_PROPERTY)) {
Integer bufferSize = (Integer)value;
if (bufferSize != null && bufferSize.intValue() > 0) {
fBufferSize = bufferSize.intValue();
}
}
}
} // setProperty(String,Object)
//
// Public static methods
//
/**
* Expands a system id and returns the system id as a URI, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URI string representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
public static String expandSystemId(String systemId) {
return expandSystemId(systemId, null);
} // expandSystemId(String):String
// current value of the "user.dir" property
private static String gUserDir;
// escaped value of the current "user.dir" property
private static String gEscapedUserDir;
// which ASCII characters need to be escaped
private static boolean gNeedEscaping[] = new boolean[128];
// the first hex character if a character needs to be escaped
private static char gAfterEscaping1[] = new char[128];
// the second hex character if a character needs to be escaped
private static char gAfterEscaping2[] = new char[128];
// initialize the above 3 arrays
static {
char[] hexChs = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
for (int i = 0; i <= 0x1f; i++) {
gNeedEscaping[i] = true;
gAfterEscaping1[i] = hexChs[i/16];
gAfterEscaping2[i] = hexChs[i%16];
}
gNeedEscaping[0x7f] = true;
gAfterEscaping1[0x7f] = '7';
gAfterEscaping2[0x7f] = 'F';
char[] escChs = {' ', '<', '>', '#', '%', '"', '"', '}',
'|', '\\', '^', '~', '[', ']', '`'};
int len = escChs.length;
char ch;
for (int i = 0; i < len; i++) {
ch = escChs[i];
gNeedEscaping[ch] = true;
gAfterEscaping1[ch] = hexChs[ch/16];
gAfterEscaping2[ch] = hexChs[ch%16];
}
}
// To escape the "user.dir" system property, by using %HH to represent
// special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', '#', '%'
// and '"'. It's a static method, so needs to be synchronized.
// this method looks heavy, but since the system property isn't expected
// to change often, so in most cases, we only need to return the string
// that was escaped before.
// According to the URI spec, non-ASCII characters (whose value >= 128)
// need to be escaped too.
// REVISIT: don't know how to escape non-ASCII characters, especially
// which encoding to use. Leave them for now.
private static synchronized String getUserDir() {
String userDir = System.getProperty("user.dir");
// return null if property value is null.
if (userDir == null)
return null;
// compute the new escaped value if the new property value doesn't
// match the previous one
if (!userDir.equals(gUserDir)) {
// record the new value as the global property value
gUserDir = userDir;
int len = userDir.length();
StringBuffer buffer = new StringBuffer(len*3);
char ch, separator = java.io.File.separatorChar;
boolean escaped = false;
// for each character in the property value, check whether it
// needs escaping.
for (int i = 0; i < len; i++) {
ch = userDir.charAt(i);
if (ch == separator && ch != '/') {
buffer.append('/');
escaped = true;
}
else if (ch < 128 && gNeedEscaping[ch]) {
buffer.append('%');
buffer.append(gAfterEscaping1[ch]);
buffer.append(gAfterEscaping2[ch]);
// record the fact that it's escaped
escaped = true;
}
else {
buffer.append(ch);
}
}
// only create a new string if some characters were escaped,
// otherwise use the property value.
gEscapedUserDir = escaped ? buffer.toString() : userDir;
}
return gEscapedUserDir;
}
/**
* Expands a system id and returns the system id as a URI, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URI string representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
public static String expandSystemId(String systemId, String baseSystemId) {
// check for bad parameters id
if (systemId == null || systemId.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
URI uri = new URI(systemId);
if (uri != null) {
return systemId;
}
}
catch (URI.MalformedURIException e) {
// continue on...
}
// normalize id
String id = fixURI(systemId);
// normalize base
URI base = null;
URI uri = null;
try {
if (baseSystemId == null || baseSystemId.length() == 0 ||
baseSystemId.equals(systemId)) {
String dir;
try {
dir = fixURI(getUserDir());
}
catch (SecurityException se) {
dir = "";
}
if (!dir.endsWith("/")) {
dir = dir + "/";
}
base = new URI("file", "", dir, null, null);
}
else {
try {
base = new URI(fixURI(baseSystemId));
}
catch (URI.MalformedURIException e) {
String dir;
try {
dir = fixURI(getUserDir());
}
catch (SecurityException se) {
dir = "";
}
if (baseSystemId.indexOf(':') != -1) {
// for xml schemas we might have baseURI with
// a specified drive
base = new URI("file", "", fixURI(baseSystemId), null, null);
}
else {
if (!dir.endsWith("/")) {
dir = dir + "/";
}
dir = dir + fixURI(baseSystemId);
base = new URI("file", "", dir, null, null);
}
}
}
// expand id
uri = new URI(base, id);
}
catch (Exception e) {
// let it go through
}
if (uri == null) {
return systemId;
}
return uri.toString();
} // expandSystemId(String,String):String
//
// Protected methods
//
/**
* Ends an entity.
*
* @throws XNIException Thrown by entity handler to signal an error.
*/
protected void endEntity() throws XNIException {
// call handler
if (DEBUG_BUFFER) {
System.out.print("(endEntity: ");
print();
System.out.println();
}
if (fEntityHandler != null) {
fEntityHandler.endEntity(fCurrentEntity.name);
}
// pop stack
// REVISIT: we are done with the current entity, should close
// the associated reader
//fCurrentEntity.reader.close();
// Now we close all readers after we finish parsing
fCurrentEntity = fEntityStack.size() > 0
? (ScannedEntity)fEntityStack.pop() : null;
if (DEBUG_BUFFER) {
System.out.print(")endEntity: ");
print();
System.out.println();
}
} // endEntity()
/**
* Returns the IANA encoding name that is auto-detected from
* the bytes specified, with the endian-ness of that encoding where appropriate.
*
* @param b4 The first four bytes of the input.
* @param count The number of bytes actually read.
* @return a 2-element array: the first element, an IANA-encoding string,
* the second element a Boolean which is true iff the document is big endian, false
* if it's little-endian, and null if the distinction isn't relevant.
*/
protected Object[] getEncodingName(byte[] b4, int count) {
if (count < 2) {
return new Object[]{"UTF-8", null};
}
// UTF-16, with BOM
int b0 = b4[0] & 0xFF;
int b1 = b4[1] & 0xFF;
if (b0 == 0xFE && b1 == 0xFF) {
// UTF-16, big-endian
return new Object [] {"UTF-16BE", new Boolean(true)};
}
if (b0 == 0xFF && b1 == 0xFE) {
// UTF-16, little-endian
return new Object [] {"UTF-16LE", new Boolean(false)};
}
// default to UTF-8 if we don't have enough bytes to make a
// good determination of the encoding
if (count < 3) {
return new Object [] {"UTF-8", null};
}
// UTF-8 with a BOM
int b2 = b4[2] & 0xFF;
if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) {
return new Object [] {"UTF-8", null};
}
// default to UTF-8 if we don't have enough bytes to make a
// good determination of the encoding
if (count < 4) {
return new Object [] {"UTF-8", null};
}
// other encodings
int b3 = b4[3] & 0xFF;
if (b0 == 0x00 && b1 == 0x00 && b2 == 0x00 && b3 == 0x3C) {
// UCS-4, big endian (1234)
return new Object [] {"ISO-10646-UCS-4", new Boolean(true)};
}
if (b0 == 0x3C && b1 == 0x00 && b2 == 0x00 && b3 == 0x00) {
// UCS-4, little endian (4321)
return new Object [] {"ISO-10646-UCS-4", new Boolean(false)};
}
if (b0 == 0x00 && b1 == 0x00 && b2 == 0x3C && b3 == 0x00) {
// UCS-4, unusual octet order (2143)
// REVISIT: What should this be?
return new Object [] {"ISO-10646-UCS-4", null};
}
if (b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x00) {
// UCS-4, unusual octect order (3412)
// REVISIT: What should this be?
return new Object [] {"ISO-10646-UCS-4", null};
}
if (b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x3F) {
// UTF-16, big-endian, no BOM
// (or could turn out to be UCS-2...
// REVISIT: What should this be?
return new Object [] {"UTF-16BE", new Boolean(true)};
}
if (b0 == 0x3C && b1 == 0x00 && b2 == 0x3F && b3 == 0x00) {
// UTF-16, little-endian, no BOM
// (or could turn out to be UCS-2...
return new Object [] {"UTF-16LE", new Boolean(false)};
}
if (b0 == 0x4C && b1 == 0x6F && b2 == 0xA7 && b3 == 0x94) {
// EBCDIC
// a la xerces1, return CP037 instead of EBCDIC here
return new Object [] {"CP037", null};
}
// default encoding
return new Object [] {"UTF-8", null};
} // getEncodingName(byte[],int):Object[]
/**
* Creates a reader capable of reading the given input stream in
* the specified encoding.
*
* @param inputStream The input stream.
* @param encoding The encoding name that the input stream is
* encoded using. If the user has specified that
* Java encoding names are allowed, then the
* encoding name may be a Java encoding name;
* otherwise, it is an ianaEncoding name.
* @param isBigEndian For encodings (like uCS-4), whose names cannot
* specify a byte order, this tells whether the order is bigEndian. null menas
* unknown or not relevant.
*
* @return Returns a reader.
*/
protected Reader createReader(InputStream inputStream, String encoding, Boolean isBigEndian)
throws IOException {
// normalize encoding name
if (encoding == null) {
encoding = "UTF-8";
}
// try to use an optimized reader
String ENCODING = encoding.toUpperCase(Locale.ENGLISH);
if (ENCODING.equals("UTF-8")) {
if (DEBUG_ENCODINGS) {
System.out.println("$$$ creating UTF8Reader");
}
return new UTF8Reader(inputStream, fBufferSize, fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN), fErrorReporter.getLocale() );
}
if (ENCODING.equals("US-ASCII")) {
if (DEBUG_ENCODINGS) {
System.out.println("$$$ creating ASCIIReader");
}
return new ASCIIReader(inputStream, fBufferSize, fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN), fErrorReporter.getLocale());
}
if(ENCODING.equals("ISO-10646-UCS-4")) {
if(isBigEndian != null) {
boolean isBE = isBigEndian.booleanValue();
if(isBE) {
return new UCSReader(inputStream, UCSReader.UCS4BE);
} else {
return new UCSReader(inputStream, UCSReader.UCS4LE);
}
} else {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingByteOrderUnsupported",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
}
if(ENCODING.equals("ISO-10646-UCS-2")) {
if(isBigEndian != null) { // sould never happen with this encoding...
boolean isBE = isBigEndian.booleanValue();
if(isBE) {
return new UCSReader(inputStream, UCSReader.UCS2BE);
} else {
return new UCSReader(inputStream, UCSReader.UCS2LE);
}
} else {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingByteOrderUnsupported",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
}
// check for valid name
boolean validIANA = XMLChar.isValidIANAEncoding(encoding);
boolean validJava = XMLChar.isValidJavaEncoding(encoding);
if (!validIANA || (fAllowJavaEncodings && !validJava)) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingDeclInvalid",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
// NOTE: AndyH suggested that, on failure, we use ISO Latin 1
// because every byte is a valid ISO Latin 1 character.
// It may not translate correctly but if we failed on
// the encoding anyway, then we're expecting the content
// of the document to be bad. This will just prevent an
// invalid UTF-8 sequence to be detected. This is only
// important when continue-after-fatal-error is turned
// on. -Ac
encoding = "ISO-8859-1";
}
// try to use a Java reader
String javaEncoding = EncodingMap.getIANA2JavaMapping(ENCODING);
if (javaEncoding == null) {
if(fAllowJavaEncodings) {
javaEncoding = encoding;
} else {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingDeclInvalid",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
// see comment above.
javaEncoding = "ISO8859_1";
}
}
if (DEBUG_ENCODINGS) {
System.out.print("$$$ creating Java InputStreamReader: encoding="+javaEncoding);
if (javaEncoding == encoding) {
System.out.print(" (IANA encoding)");
}
System.out.println();
}
return new InputStreamReader(inputStream, javaEncoding);
} // createReader(InputStream,String, Boolean): Reader
// returns an instance of XMLEntityScanner
protected XMLEntityScanner createEntityScanner() {
return new EntityScanner();
} // createEntityScanner(): XMLEntityScanner
//
// Protected static methods
//
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
protected static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
// Windows fix
if (str.length() >= 2) {
char ch1 = str.charAt(1);
// change "C:blah" to "/C:blah"
if (ch1 == ':') {
char ch0 = Character.toUpperCase(str.charAt(0));
if (ch0 >= 'A' && ch0 <= 'Z') {
str = "/" + str;
}
}
// change "//blah" to "file://blah"
else if (ch1 == '/' && str.charAt(0) == '/') {
str = "file:" + str;
}
}
// done
return str;
} // fixURI(String):String
//
// Package visible methods
//
/**
* Returns the hashtable of declared entities.
* <p>
* <strong>REVISIT:</strong>
* This should be done the "right" way by designing a better way to
* enumerate the declared entities. For now, this method is needed
* by the constructor that takes an XMLEntityManager parameter.
*/
Hashtable getDeclaredEntities() {
return fEntities;
} // getDeclaredEntities():Hashtable
/** Prints the contents of the buffer. */
final void print() {
if (DEBUG_BUFFER) {
if (fCurrentEntity != null) {
System.out.print('[');
System.out.print(fCurrentEntity.count);
System.out.print(' ');
System.out.print(fCurrentEntity.position);
if (fCurrentEntity.count > 0) {
System.out.print(" \"");
for (int i = 0; i < fCurrentEntity.count; i++) {
if (i == fCurrentEntity.position) {
System.out.print('^');
}
char c = fCurrentEntity.ch[i];
switch (c) {
case '\n': {
System.out.print("\\n");
break;
}
case '\r': {
System.out.print("\\r");
break;
}
case '\t': {
System.out.print("\\t");
break;
}
case '\\': {
System.out.print("\\\\");
break;
}
default: {
System.out.print(c);
}
}
}
if (fCurrentEntity.position == fCurrentEntity.count) {
System.out.print('^');
}
System.out.print('"');
}
System.out.print(']');
System.out.print(" @ ");
System.out.print(fCurrentEntity.lineNumber);
System.out.print(',');
System.out.print(fCurrentEntity.columnNumber);
}
else {
System.out.print("*NO CURRENT ENTITY*");
}
}
} // print()
//
// Classes
//
/**
* Entity information.
*
* @author Andy Clark, IBM
*/
protected static abstract class Entity {
//
// Data
//
/** Entity name. */
public String name;
//
// Constructors
//
/** Default constructor. */
public Entity() {
clear();
} // <init>()
/** Constructs an entity. */
public Entity(String name) {
this.name = name;
} // <init>(String)
//
// Public methods
//
/** Returns true if this is an external entity. */
public abstract boolean isExternal();
/** Returns true if this is an unparsed entity. */
public abstract boolean isUnparsed();
/** Clears the entity. */
public void clear() {
name = null;
} // clear()
/** Sets the values of the entity. */
public void setValues(Entity entity) {
name = entity.name;
} // setValues(Entity)
} // class Entity
/**
* Internal entity.
*
* @author Andy Clark, IBM
*/
protected static class InternalEntity
extends Entity {
//
// Data
//
/** Text value of entity. */
public String text;
//
// Constructors
//
/** Default constructor. */
public InternalEntity() {
clear();
} // <init>()
/** Constructs an internal entity. */
public InternalEntity(String name, String text) {
super(name);
this.text = text;
} // <init>(String,String)
//
// Entity methods
//
/** Returns true if this is an external entity. */
public final boolean isExternal() {
return false;
} // isExternal():boolean
/** Returns true if this is an unparsed entity. */
public final boolean isUnparsed() {
return false;
} // isUnparsed():boolean
/** Clears the entity. */
public void clear() {
super.clear();
text = null;
} // clear()
/** Sets the values of the entity. */
public void setValues(Entity entity) {
super.setValues(entity);
text = null;
} // setValues(Entity)
/** Sets the values of the entity. */
public void setValues(InternalEntity entity) {
super.setValues(entity);
text = entity.text;
} // setValues(InternalEntity)
} // class InternalEntity
/**
* External entity.
*
* @author Andy Clark, IBM
*/
protected static class ExternalEntity
extends Entity {
//
// Data
//
/** container for all relevant entity location information. */
public XMLResourceIdentifier entityLocation;
/** Notation name for unparsed entity. */
public String notation;
//
// Constructors
//
/** Default constructor. */
public ExternalEntity() {
clear();
} // <init>()
/** Constructs an internal entity. */
public ExternalEntity(String name, XMLResourceIdentifier entityLocation,
String notation) {
super(name);
this.entityLocation = entityLocation;
this.notation = notation;
} // <init>(String,XMLResourceIdentifier, String)
//
// Entity methods
//
/** Returns true if this is an external entity. */
public final boolean isExternal() {
return true;
} // isExternal():boolean
/** Returns true if this is an unparsed entity. */
public final boolean isUnparsed() {
return notation != null;
} // isUnparsed():boolean
/** Clears the entity. */
public void clear() {
super.clear();
entityLocation = null;
notation = null;
} // clear()
/** Sets the values of the entity. */
public void setValues(Entity entity) {
super.setValues(entity);
entityLocation = null;
notation = null;
} // setValues(Entity)
/** Sets the values of the entity. */
public void setValues(ExternalEntity entity) {
super.setValues(entity);
entityLocation = entity.entityLocation;
notation = entity.notation;
} // setValues(ExternalEntity)
} // class ExternalEntity
/**
* Entity state.
*
* @author Andy Clark, IBM
*/
protected class ScannedEntity
extends Entity {
//
// Data
//
// i/o
/** Input stream. */
public InputStream stream;
/** Reader. */
public Reader reader;
// locator information
/** entity location information */
public XMLResourceIdentifier entityLocation;
/** Line number. */
public int lineNumber = 1;
/** Column number. */
public int columnNumber = 1;
// encoding
/** Auto-detected encoding. */
public String encoding;
// status
/** True if in a literal. */
public boolean literal;
// whether this is an external or internal scanned entity
public boolean isExternal;
// buffer
/** Character buffer. */
public char[] ch = null;
/** Position in character buffer. */
public int position;
/** Count of characters in buffer. */
public int count;
// to allow the reader/inputStream to behave efficiently:
public boolean mayReadChunks;
//
// Constructors
//
/** Constructs a scanned entity. */
public ScannedEntity(String name,
XMLResourceIdentifier entityLocation,
InputStream stream, Reader reader,
String encoding, boolean literal, boolean mayReadChunks, boolean isExternal) {
super(name);
this.entityLocation = entityLocation;
this.stream = stream;
this.reader = reader;
this.encoding = encoding;
this.literal = literal;
this.mayReadChunks = mayReadChunks;
this.isExternal = isExternal;
this.ch = new char[isExternal ? fBufferSize : DEFAULT_INTERNAL_BUFFER_SIZE];
} // <init>(StringXMLResourceIdentifier,InputStream,Reader,String,boolean, boolean)
//
// Entity methods
//
/** Returns true if this is an external entity. */
public final boolean isExternal() {
return isExternal;
} // isExternal():boolean
/** Returns true if this is an unparsed entity. */
public final boolean isUnparsed() {
return false;
} // isUnparsed():boolean
//
// Object methods
//
/** Returns a string representation of this object. */
public String toString() {
StringBuffer str = new StringBuffer();
str.append("name=\""+name+'"');
str.append(",ch="+ch);
str.append(",position="+position);
str.append(",count="+count);
return str.toString();
} // toString():String
} // class ScannedEntity
/**
* Implements the entity scanner methods.
*
* @author Andy Clark, IBM
*/
protected class EntityScanner
extends XMLEntityScanner {
//
// Constructors
//
/** Default constructor. */
public EntityScanner() {
} // <init>()
//
// XMLEntityScanner methods
//
/**
* Returns the base system identifier of the currently scanned
* entity, or null if none is available.
*/
public String getBaseSystemId() {
return (fCurrentEntity != null && fCurrentEntity.entityLocation != null) ? fCurrentEntity.entityLocation.getExpandedSystemId() : null;
} // getBaseSystemId():String
/**
* Sets the encoding of the scanner. This method is used by the
* scanners if the XMLDecl or TextDecl line contains an encoding
* pseudo-attribute.
* <p>
* <strong>Note:</strong> The underlying character reader on the
* current entity will be changed to accomodate the new encoding.
* However, the new encoding is ignored if the current reader was
* not constructed from an input stream (e.g. an external entity
* that is resolved directly to the appropriate java.io.Reader
* object).
*
* @param encoding The IANA encoding name of the new encoding.
*
* @throws IOException Thrown if the new encoding is not supported.
*
* @see org.apache.xerces.util.EncodingMap
*/
public void setEncoding(String encoding) throws IOException {
if (DEBUG_ENCODINGS) {
System.out.println("$$$ setEncoding: "+encoding);
}
if (fCurrentEntity.stream != null) {
// if the encoding is the same, don't change the reader and
// re-use the original reader used by the OneCharReader
// NOTE: Besides saving an object, this overcomes deficiencies
// in the UTF-16 reader supplied with the standard Java
// distribution (up to and including 1.3). The UTF-16
// decoder buffers 8K blocks even when only asked to read
// a single char! -Ac
if (fCurrentEntity.encoding == null ||
!fCurrentEntity.encoding.equals(encoding)) {
// UTF-16 is a bit of a special case. If the encoding is UTF-16,
// and we know the endian-ness, we shouldn't change readers.
// If it's ISO-10646-UCS-(2|4), then we'll have to deduce
// the endian-ness from the encoding we presently have.
if(fCurrentEntity.encoding != null && fCurrentEntity.encoding.startsWith("UTF-16")) {
String ENCODING = encoding.toUpperCase(Locale.ENGLISH);
if(ENCODING.equals("UTF-16")) return;
if(ENCODING.equals("ISO-10646-UCS-4")) {
if(fCurrentEntity.encoding.equals("UTF-16BE")) {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS4BE);
} else {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS4LE);
}
return;
}
if(ENCODING.equals("ISO-10646-UCS-2")) {
if(fCurrentEntity.encoding.equals("UTF-16BE")) {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS2BE);
} else {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS2LE);
}
return;
}
}
// wrap a new reader around the input stream, changing
// the encoding
if (DEBUG_ENCODINGS) {
System.out.println("$$$ creating new reader from stream: "+
fCurrentEntity.stream);
}
//fCurrentEntity.stream.reset();
fCurrentEntity.reader = createReader(fCurrentEntity.stream, encoding, null);
} else {
if (DEBUG_ENCODINGS)
System.out.println("$$$ reusing old reader on stream");
}
}
} // setEncoding(String)
/** Returns true if the current entity being scanned is external. */
public boolean isExternal() {
return fCurrentEntity.isExternal();
} // isExternal():boolean
/**
* Returns the next character on the input.
* <p>
* <strong>Note:</strong> The character is <em>not</em> consumed.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int peekChar() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(peekChar: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// peek at character
int c = fCurrentEntity.ch[fCurrentEntity.position];
// return peeked character
if (DEBUG_BUFFER) {
System.out.print(")peekChar: ");
print();
if (fCurrentEntity.isExternal()) {
System.out.println(" -> '"+(c!='\r'?(char)c:'\n')+"'");
}
else {
System.out.println(" -> '"+(char)c+"'");
}
}
if (fCurrentEntity.isExternal()) {
return c != '\r' ? c : '\n';
}
else {
return c;
}
} // peekChar():int
/**
* Returns the next character on the input.
* <p>
* <strong>Note:</strong> The character is consumed.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int scanChar() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanChar: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan character
int c = fCurrentEntity.ch[fCurrentEntity.position++];
boolean external = false;
if (c == '\n' ||
(c == '\r' && (external = fCurrentEntity.isExternal()))) {
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = (char)c;
load(1, false);
}
if (c == '\r' && external) {
if (fCurrentEntity.ch[fCurrentEntity.position++] != '\n') {
fCurrentEntity.position--;
}
c = '\n';
}
}
// return character that was scanned
if (DEBUG_BUFFER) {
System.out.print(")scanChar: ");
print();
System.out.println(" -> '"+(char)c+"'");
}
fCurrentEntity.columnNumber++;
return c;
} // scanChar():int
/**
* Returns a string matching the NMTOKEN production appearing immediately
* on the input as a symbol, or null if NMTOKEN Name string is present.
* <p>
* <strong>Note:</strong> The NMTOKEN characters are consumed.
* <p>
* <strong>Note:</strong> The string returned must be a symbol. The
* SymbolTable can be used for this purpose.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.SymbolTable
* @see org.apache.xerces.util.XMLChar#isName
*/
public String scanNmtoken() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanNmtoken: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan nmtoken
int offset = fCurrentEntity.position;
while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
int length = fCurrentEntity.position - offset;
if (length == fBufferSize) {
// bad luck we have to resize our buffer
char[] tmp = new char[fBufferSize * 2];
System.arraycopy(fCurrentEntity.ch, offset,
tmp, 0, length);
fCurrentEntity.ch = tmp;
fBufferSize *= 2;
}
else {
System.arraycopy(fCurrentEntity.ch, offset,
fCurrentEntity.ch, 0, length);
}
offset = 0;
if (load(length, false)) {
break;
}
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length;
// return nmtoken
String symbol = null;
if (length > 0) {
symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length);
}
if (DEBUG_BUFFER) {
System.out.print(")scanNmtoken: ");
print();
System.out.println(" -> "+String.valueOf(symbol));
}
return symbol;
} // scanNmtoken():String
/**
* Returns a string matching the Name production appearing immediately
* on the input as a symbol, or null if no Name string is present.
* <p>
* <strong>Note:</strong> The Name characters are consumed.
* <p>
* <strong>Note:</strong> The string returned must be a symbol. The
* SymbolTable can be used for this purpose.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.SymbolTable
* @see org.apache.xerces.util.XMLChar#isName
* @see org.apache.xerces.util.XMLChar#isNameStart
*/
public String scanName() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanName: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan name
int offset = fCurrentEntity.position;
if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[offset];
offset = 0;
if (load(1, false)) {
fCurrentEntity.columnNumber++;
String symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 1);
if (DEBUG_BUFFER) {
System.out.print(")scanName: ");
print();
System.out.println(" -> "+String.valueOf(symbol));
}
return symbol;
}
}
while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
int length = fCurrentEntity.position - offset;
if (length == fBufferSize) {
// bad luck we have to resize our buffer
char[] tmp = new char[fBufferSize * 2];
System.arraycopy(fCurrentEntity.ch, offset,
tmp, 0, length);
fCurrentEntity.ch = tmp;
fBufferSize *= 2;
}
else {
System.arraycopy(fCurrentEntity.ch, offset,
fCurrentEntity.ch, 0, length);
}
offset = 0;
if (load(length, false)) {
break;
}
}
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length;
// return name
String symbol = null;
if (length > 0) {
symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length);
}
if (DEBUG_BUFFER) {
System.out.print(")scanName: ");
print();
System.out.println(" -> "+String.valueOf(symbol));
}
return symbol;
} // scanName():String
/**
* Scans a qualified name from the input, setting the fields of the
* QName structure appropriately.
* <p>
* <strong>Note:</strong> The qualified name characters are consumed.
* <p>
* <strong>Note:</strong> The strings used to set the values of the
* QName structure must be symbols. The SymbolTable can be used for
* this purpose.
*
* @param qname The qualified name structure to fill.
*
* @return Returns true if a qualified name appeared immediately on
* the input and was scanned, false otherwise.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.SymbolTable
* @see org.apache.xerces.util.XMLChar#isName
* @see org.apache.xerces.util.XMLChar#isNameStart
*/
public boolean scanQName(QName qname) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanQName, "+qname+": ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan qualified name
int offset = fCurrentEntity.position;
if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[offset];
offset = 0;
if (load(1, false)) {
fCurrentEntity.columnNumber++;
String name =
fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 1);
qname.setValues(null, name, name, null);
if (DEBUG_BUFFER) {
System.out.print(")scanQName, "+qname+": ");
print();
System.out.println(" -> true");
}
return true;
}
}
int index = -1;
while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) {
char c = fCurrentEntity.ch[fCurrentEntity.position];
if (c == ':') {
if (index != -1) {
break;
}
index = fCurrentEntity.position;
}
if (++fCurrentEntity.position == fCurrentEntity.count) {
int length = fCurrentEntity.position - offset;
if (length == fBufferSize) {
// bad luck we have to resize our buffer
char[] tmp = new char[fBufferSize * 2];
System.arraycopy(fCurrentEntity.ch, offset,
tmp, 0, length);
fCurrentEntity.ch = tmp;
fBufferSize *= 2;
}
else {
System.arraycopy(fCurrentEntity.ch, offset,
fCurrentEntity.ch, 0, length);
}
if (index != -1) {
index = index - offset;
}
offset = 0;
if (load(length, false)) {
break;
}
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length;
if (length > 0) {
String prefix = null;
String localpart = null;
String rawname = fSymbolTable.addSymbol(fCurrentEntity.ch,
offset, length);
if (index != -1) {
int prefixLength = index - offset;
prefix = fSymbolTable.addSymbol(fCurrentEntity.ch,
offset, prefixLength);
int len = length - prefixLength - 1;
localpart = fSymbolTable.addSymbol(fCurrentEntity.ch,
index + 1, len);
}
else {
localpart = rawname;
}
qname.setValues(prefix, localpart, rawname, null);
if (DEBUG_BUFFER) {
System.out.print(")scanQName, "+qname+": ");
print();
System.out.println(" -> true");
}
return true;
}
}
// no qualified name found
if (DEBUG_BUFFER) {
System.out.print(")scanQName, "+qname+": ");
print();
System.out.println(" -> false");
}
return false;
} // scanQName(QName):boolean
/**
* Scans a range of parsed character data, setting the fields of the
* XMLString structure, appropriately.
* <p>
* <strong>Note:</strong> The characters are consumed.
* <p>
* <strong>Note:</strong> This method does not guarantee to return
* the longest run of parsed character data. This method may return
* before markup due to reaching the end of the input buffer or any
* other reason.
* <p>
* <strong>Note:</strong> The fields contained in the XMLString
* structure are not guaranteed to remain valid upon subsequent calls
* to the entity scanner. Therefore, the caller is responsible for
* immediately using the returned character data or making a copy of
* the character data.
*
* @param content The content structure to fill.
*
* @return Returns the next character on the input, if known. This
* value may be -1 but this does <em>note</em> designate
* end of file.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int scanContent(XMLString content) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanContent: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
load(1, false);
fCurrentEntity.position = 0;
}
// normalize newlines
int offset = fCurrentEntity.position;
int c = fCurrentEntity.ch[offset];
int newlines = 0;
boolean external = fCurrentEntity.isExternal();
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
}
else {
fCurrentEntity.position--;
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
content.setValues(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
return -1;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
}
// inner loop, scanning for content
while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (!XMLChar.isContent(c)) {
fCurrentEntity.position--;
break;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
content.setValues(fCurrentEntity.ch, offset, length);
// return next character
if (fCurrentEntity.position != fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position];
// REVISIT: Does this need to be updated to fix the
// #x0D ^#x0A newline normalization problem? -Ac
if (c == '\r' && external) {
c = '\n';
}
}
else {
c = -1;
}
if (DEBUG_BUFFER) {
System.out.print(")scanContent: ");
print();
System.out.println(" -> '"+(char)c+"'");
}
return c;
} // scanContent(XMLString):int
/**
* Scans a range of attribute value data, setting the fields of the
* XMLString structure, appropriately.
* <p>
* <strong>Note:</strong> The characters are consumed.
* <p>
* <strong>Note:</strong> This method does not guarantee to return
* the longest run of attribute value data. This method may return
* before the quote character due to reaching the end of the input
* buffer or any other reason.
* <p>
* <strong>Note:</strong> The fields contained in the XMLString
* structure are not guaranteed to remain valid upon subsequent calls
* to the entity scanner. Therefore, the caller is responsible for
* immediately using the returned character data or making a copy of
* the character data.
*
* @param quote The quote character that signifies the end of the
* attribute value data.
* @param content The content structure to fill.
*
* @return Returns the next character on the input, if known. This
* value may be -1 but this does <em>note</em> designate
* end of file.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int scanLiteral(int quote, XMLString content)
throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanLiteral, '"+(char)quote+"': ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
load(1, false);
fCurrentEntity.position = 0;
}
// normalize newlines
int offset = fCurrentEntity.position;
int c = fCurrentEntity.ch[offset];
int newlines = 0;
boolean external = fCurrentEntity.isExternal();
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
/***/
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
/*** NEWLINE NORMALIZATION ***
if (fCurrentEntity.ch[fCurrentEntity.position] == '\r'
&& external) {
fCurrentEntity.position++;
offset++;
}
/***/
}
else {
fCurrentEntity.position--;
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
content.setValues(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
return -1;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
}
// scan literal value
while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if ((c == quote &&
(!fCurrentEntity.literal || external))
|| c == '%' || !XMLChar.isContent(c)) {
fCurrentEntity.position--;
break;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
content.setValues(fCurrentEntity.ch, offset, length);
// return next character
if (fCurrentEntity.position != fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position];
// NOTE: We don't want to accidentally signal the
// end of the literal if we're expanding an
// entity appearing in the literal. -Ac
if (c == quote && fCurrentEntity.literal) {
c = -1;
}
}
else {
c = -1;
}
if (DEBUG_BUFFER) {
System.out.print(")scanLiteral, '"+(char)quote+"': ");
print();
System.out.println(" -> '"+(char)c+"'");
}
return c;
} // scanLiteral(int,XMLString):int
/**
* Scans a range of character data up to the specified delimiter,
* setting the fields of the XMLString structure, appropriately.
* <p>
* <strong>Note:</strong> The characters are consumed.
* <p>
* <strong>Note:</strong> This assumes that the internal buffer is
* at least the same size, or bigger, than the length of the delimiter
* and that the delimiter contains at least one character.
* <p>
* <strong>Note:</strong> This method does not guarantee to return
* the longest run of character data. This method may return before
* the delimiter due to reaching the end of the input buffer or any
* other reason.
* <p>
* <strong>Note:</strong> The fields contained in the XMLString
* structure are not guaranteed to remain valid upon subsequent calls
* to the entity scanner. Therefore, the caller is responsible for
* immediately using the returned character data or making a copy of
* the character data.
*
* @param delimiter The string that signifies the end of the character
* data to be scanned.
* @param data The data structure to fill.
*
* @return Returns true if there is more data to scan, false otherwise.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public boolean scanData(String delimiter, XMLStringBuffer buffer)
throws IOException {
boolean done = false;
int delimLen = delimiter.length();
char charAt0 = delimiter.charAt(0);
- int offset = fCurrentEntity.position;
- int c = fCurrentEntity.ch[offset];
+ int offset = 0;
+ int c = -1;
int newlines = 0;
boolean external = fCurrentEntity.isExternal();
do {
if (DEBUG_BUFFER) {
System.out.print("(scanData: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
else if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.position,
fCurrentEntity.ch, 0, fCurrentEntity.count - fCurrentEntity.position);
load(fCurrentEntity.count - fCurrentEntity.position, false);
fCurrentEntity.position = 0;
}
if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
// something must be wrong with the input: e.g., file ends an unterminated comment
int length = fCurrentEntity.count - fCurrentEntity.position;
buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length);
fCurrentEntity.columnNumber += fCurrentEntity.count;
fCurrentEntity.position = fCurrentEntity.count;
load(0,true);
return false;
}
// normalize newlines
offset = fCurrentEntity.position;
c = fCurrentEntity.ch[offset];
newlines = 0;
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
fCurrentEntity.count = newlines;
if (load(newlines, false)) {
break;
}
}
}
else {
fCurrentEntity.position--;
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
buffer.append(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
return true;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
}
// iterate over buffer looking for delimiter
OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == charAt0) {
// looks like we just hit the delimiter
int delimOffset = fCurrentEntity.position - 1;
for (int i = 1; i < delimLen; i++) {
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.position -= i;
break OUTER;
}
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (delimiter.charAt(i) != c) {
fCurrentEntity.position--;
break;
}
}
if (fCurrentEntity.position == delimOffset + delimLen) {
done = true;
break;
}
}
else if (c == '\n' || (external && c == '\r')) {
fCurrentEntity.position--;
break;
}
else if (XMLChar.isInvalid(c)) {
fCurrentEntity.position--;
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
buffer.append(fCurrentEntity.ch, offset, length);
return true;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
if (done) {
length -= delimLen;
}
buffer.append (fCurrentEntity.ch, offset, length);
// return true if string was skipped
if (DEBUG_BUFFER) {
System.out.print(")scanData: ");
print();
System.out.println(" -> " + done);
}
} while (!done);
return !done;
} // scanData(String,XMLString)
/**
* Skips a character appearing immediately on the input.
* <p>
* <strong>Note:</strong> The character is consumed only if it matches
* the specified character.
*
* @param c The character to skip.
*
* @return Returns true if the character was skipped.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public boolean skipChar(int c) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(skipChar, '"+(char)c+"': ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip character
int cc = fCurrentEntity.ch[fCurrentEntity.position];
if (cc == c) {
fCurrentEntity.position++;
if (c == '\n') {
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
}
else {
fCurrentEntity.columnNumber++;
}
if (DEBUG_BUFFER) {
System.out.print(")skipChar, '"+(char)c+"': ");
print();
System.out.println(" -> true");
}
return true;
}
else if (c == '\n' && cc == '\r' && fCurrentEntity.isExternal()) {
// handle newlines
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = (char)cc;
load(1, false);
}
fCurrentEntity.position++;
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
}
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (DEBUG_BUFFER) {
System.out.print(")skipChar, '"+(char)c+"': ");
print();
System.out.println(" -> true");
}
return true;
}
// character was not skipped
if (DEBUG_BUFFER) {
System.out.print(")skipChar, '"+(char)c+"': ");
print();
System.out.println(" -> false");
}
return false;
} // skipChar(int):boolean
/**
* Skips space characters appearing immediately on the input.
* <p>
* <strong>Note:</strong> The characters are consumed only if they are
* space characters.
*
* @return Returns true if at least one space character was skipped.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.XMLChar#isSpace
*/
public boolean skipSpaces() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(skipSpaces: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip spaces
int c = fCurrentEntity.ch[fCurrentEntity.position];
if (XMLChar.isSpace(c)) {
boolean external = fCurrentEntity.isExternal();
do {
boolean entityChanged = false;
// handle newlines
if (c == '\n' || (external && c == '\r')) {
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
fCurrentEntity.ch[0] = (char)c;
entityChanged = load(1, true);
if (!entityChanged)
// the load change the position to be 1,
// need to restore it when entity not changed
fCurrentEntity.position = 0;
}
if (c == '\r' && external) {
// REVISIT: Does this need to be updated to fix the
// #x0D ^#x0A newline normalization problem? -Ac
if (fCurrentEntity.ch[++fCurrentEntity.position] != '\n') {
fCurrentEntity.position--;
}
}
/*** NEWLINE NORMALIZATION ***
else {
if (fCurrentEntity.ch[fCurrentEntity.position + 1] == '\r'
&& external) {
fCurrentEntity.position++;
}
}
/***/
}
else {
fCurrentEntity.columnNumber++;
}
// load more characters, if needed
if (!entityChanged)
fCurrentEntity.position++;
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
} while (XMLChar.isSpace(c = fCurrentEntity.ch[fCurrentEntity.position]));
if (DEBUG_BUFFER) {
System.out.print(")skipSpaces: ");
print();
System.out.println(" -> true");
}
return true;
}
// no spaces were found
if (DEBUG_BUFFER) {
System.out.print(")skipSpaces: ");
print();
System.out.println(" -> false");
}
return false;
} // skipSpaces():boolean
/**
* Skips the specified string appearing immediately on the input.
* <p>
* <strong>Note:</strong> The characters are consumed only if they are
* space characters.
*
* @param s The string to skip.
*
* @return Returns true if the string was skipped.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public boolean skipString(String s) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(skipString, \""+s+"\": ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip string
final int length = s.length();
for (int i = 0; i < length; i++) {
char c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c != s.charAt(i)) {
fCurrentEntity.position -= i + 1;
if (DEBUG_BUFFER) {
System.out.print(")skipString, \""+s+"\": ");
print();
System.out.println(" -> false");
}
return false;
}
if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1);
// REVISIT: Can a string to be skipped cross an
// entity boundary? -Ac
if (load(i + 1, false)) {
fCurrentEntity.position -= i + 1;
if (DEBUG_BUFFER) {
System.out.print(")skipString, \""+s+"\": ");
print();
System.out.println(" -> false");
}
return false;
}
}
}
if (DEBUG_BUFFER) {
System.out.print(")skipString, \""+s+"\": ");
print();
System.out.println(" -> true");
}
fCurrentEntity.columnNumber += length;
return true;
} // skipString(String):boolean
//
// Locator methods
//
/**
* Return the public identifier for the current document event.
* <p>
* The return value is the public identifier of the document
* entity or of the external parsed entity in which the markup
* triggering the event appears.
*
* @return A string containing the public identifier, or
* null if none is available.
*/
public String getPublicId() {
return (fCurrentEntity != null && fCurrentEntity.entityLocation != null) ? fCurrentEntity.entityLocation.getPublicId() : null;
} // getPublicId():String
/**
* Return the expanded system identifier for the current document event.
* <p>
* The return value is the expanded system identifier of the document
* entity or of the external parsed entity in which the markup
* triggering the event appears.
* <p>
* If the system identifier is a URL, the parser must resolve it
* fully before passing it to the application.
*
* @return A string containing the expanded system identifier, or null
* if none is available.
*/
public String getExpandedSystemId() {
if (fCurrentEntity != null) {
if (fCurrentEntity.entityLocation != null &&
fCurrentEntity.entityLocation.getExpandedSystemId() != null ) {
return fCurrentEntity.entityLocation.getExpandedSystemId();
}
else {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i = size - 1; i >= 0 ; i--) {
ScannedEntity externalEntity =
(ScannedEntity)fEntityStack.elementAt(i);
if (externalEntity.entityLocation != null &&
externalEntity.entityLocation.getExpandedSystemId() != null) {
return externalEntity.entityLocation.getExpandedSystemId();
}
}
}
}
return null;
} // getExpandedSystemId():String
/**
* Return the literal system identifier for the current document event.
* <p>
* The return value is the literal system identifier of the document
* entity or of the external parsed entity in which the markup
* triggering the event appears.
* <p>
* @return A string containing the literal system identifier, or null
* if none is available.
*/
public String getLiteralSystemId() {
if (fCurrentEntity != null) {
if (fCurrentEntity.entityLocation != null &&
fCurrentEntity.entityLocation.getLiteralSystemId() != null ) {
return fCurrentEntity.entityLocation.getLiteralSystemId();
}
else {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i = size - 1; i >= 0 ; i--) {
ScannedEntity externalEntity =
(ScannedEntity)fEntityStack.elementAt(i);
if (externalEntity.entityLocation != null &&
externalEntity.entityLocation.getLiteralSystemId() != null) {
return externalEntity.entityLocation.getLiteralSystemId();
}
}
}
}
return null;
} // getLiteralSystemId():String
/**
* Return the line number where the current document event ends.
* <p>
* <strong>Warning:</strong> The return value from the method
* is intended only as an approximation for the sake of error
* reporting; it is not intended to provide sufficient information
* to edit the character content of the original XML document.
* <p>
* The return value is an approximation of the line number
* in the document entity or external parsed entity where the
* markup triggering the event appears.
* <p>
* If possible, the SAX driver should provide the line position
* of the first character after the text associated with the document
* event. The first line in the document is line 1.
*
* @return The line number, or -1 if none is available.
*/
public int getLineNumber() {
if (fCurrentEntity != null) {
if (fCurrentEntity.isExternal()) {
return fCurrentEntity.lineNumber;
}
else {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i=size-1; i>0 ; i--) {
ScannedEntity firstExternalEntity = (ScannedEntity)fEntityStack.elementAt(i);
if (firstExternalEntity.isExternal()) {
return firstExternalEntity.lineNumber;
}
}
}
}
return -1;
} // getLineNumber():int
/**
* Return the column number where the current document event ends.
* <p>
* <strong>Warning:</strong> The return value from the method
* is intended only as an approximation for the sake of error
* reporting; it is not intended to provide sufficient information
* to edit the character content of the original XML document.
* <p>
* The return value is an approximation of the column number
* in the document entity or external parsed entity where the
* markup triggering the event appears.
* <p>
* If possible, the SAX driver should provide the line position
* of the first character after the text associated with the document
* event.
* <p>
* If possible, the SAX driver should provide the line position
* of the first character after the text associated with the document
* event. The first column in each line is column 1.
*
* @return The column number, or -1 if none is available.
*/
public int getColumnNumber() {
if (fCurrentEntity != null) {
if (fCurrentEntity.isExternal()) {
return fCurrentEntity.columnNumber;
}
else {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i=size-1; i>0 ; i--) {
ScannedEntity firstExternalEntity = (ScannedEntity)fEntityStack.elementAt(i);
if (firstExternalEntity.isExternal()) {
return firstExternalEntity.columnNumber;
}
}
}
}
return -1;
} // getColumnNumber():int
//
// Private methods
//
/**
* Loads a chunk of text.
*
* @param offset The offset into the character buffer to
* read the next batch of characters.
* @param changeEntity True if the load should change entities
* at the end of the entity, otherwise leave
* the current entity in place and the entity
* boundary will be signaled by the return
* value.
*
* @returns Returns true if the entity changed as a result of this
* load operation.
*/
final boolean load(int offset, boolean changeEntity)
throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(load, "+offset+": ");
print();
System.out.println();
}
// read characters
int length = fCurrentEntity.mayReadChunks?
(fCurrentEntity.ch.length - offset):
(DEFAULT_XMLDECL_BUFFER_SIZE);
if (DEBUG_BUFFER) System.out.println(" length to try to read: "+length);
int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) System.out.println(" length actually read: "+count);
// reset count and position
boolean entityChanged = false;
if (count != -1) {
if (count != 0) {
fCurrentEntity.count = count + offset;
fCurrentEntity.position = offset;
}
}
// end of this entity
else {
fCurrentEntity.count = offset;
fCurrentEntity.position = offset;
entityChanged = true;
if (changeEntity) {
endEntity();
if (fCurrentEntity == null) {
throw new EOFException();
}
// handle the trailing edges
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
}
}
if (DEBUG_BUFFER) {
System.out.print(")load, "+offset+": ");
print();
System.out.println();
}
return entityChanged;
} // load(int, boolean):boolean
} // class EntityScanner
// This class wraps the byte inputstreams we're presented with.
// We need it because java.io.InputStreams don't provide
// functionality to reread processed bytes, and they have a habit
// of reading more than one character when you call their read()
// methods. This means that, once we discover the true (declared)
// encoding of a document, we can neither backtrack to read the
// whole doc again nor start reading where we are with a new
// reader.
//
// This class allows rewinding an inputStream by allowing a mark
// to be set, and the stream reset to that position. <strong>The
// class assumes that it needs to read one character per
// invocation when it's read() method is inovked, but uses the
// underlying InputStream's read(char[], offset length) method--it
// won't buffer data read this way!</strong>
//
// @author Neil Graham, IBM
// @author Glenn Marcy, IBM
protected final class RewindableInputStream extends InputStream {
private InputStream fInputStream;
private byte[] fData;
private int fStartOffset;
private int fEndOffset;
private int fOffset;
private int fLength;
private int fMark;
public RewindableInputStream(InputStream is) {
fData = new byte[DEFAULT_XMLDECL_BUFFER_SIZE];
fInputStream = is;
fStartOffset = 0;
fEndOffset = -1;
fOffset = 0;
fLength = 0;
fMark = 0;
}
public void setStartOffset(int offset) {
fStartOffset = offset;
}
public void rewind() {
fOffset = fStartOffset;
}
public int read() throws IOException {
int b = 0;
if (fOffset < fLength) {
return fData[fOffset++] & 0xff;
}
if (fOffset == fEndOffset) {
return -1;
}
if (fOffset == fData.length) {
byte[] newData = new byte[fOffset << 1];
System.arraycopy(fData, 0, newData, 0, fOffset);
fData = newData;
}
b = fInputStream.read();
if (b == -1) {
fEndOffset = fOffset;
return -1;
}
fData[fLength++] = (byte)b;
fOffset++;
return b & 0xff;
}
public int read(byte[] b, int off, int len) throws IOException {
int bytesLeft = fLength - fOffset;
if (bytesLeft == 0) {
if (fOffset == fEndOffset) {
return -1;
}
// better get some more for the voracious reader...
if(fCurrentEntity.mayReadChunks) {
return fInputStream.read(b, off, len);
}
int returnedVal = read();
if(returnedVal == -1) {
fEndOffset = fOffset;
return -1;
}
b[off] = (byte)returnedVal;
return 1;
}
if (len < bytesLeft) {
if (len <= 0) {
return 0;
}
}
else {
len = bytesLeft;
}
if (b != null) {
System.arraycopy(fData, fOffset, b, off, len);
}
fOffset += len;
return len;
}
public long skip(long n)
throws IOException
{
int bytesLeft;
if (n <= 0) {
return 0;
}
bytesLeft = fLength - fOffset;
if (bytesLeft == 0) {
if (fOffset == fEndOffset) {
return 0;
}
return fInputStream.skip(n);
}
if (n <= bytesLeft) {
fOffset += n;
return n;
}
fOffset += bytesLeft;
if (fOffset == fEndOffset) {
return bytesLeft;
}
n -= bytesLeft;
/*
* In a manner of speaking, when this class isn't permitting more
* than one byte at a time to be read, it is "blocking". The
* available() method should indicate how much can be read without
* blocking, so while we're in this mode, it should only indicate
* that bytes in its buffer are available; otherwise, the result of
* available() on the underlying InputStream is appropriate.
*/
return fInputStream.skip(n) + bytesLeft;
}
public int available() throws IOException {
int bytesLeft = fLength - fOffset;
if (bytesLeft == 0) {
if (fOffset == fEndOffset) {
return -1;
}
return fCurrentEntity.mayReadChunks ? fInputStream.available()
: 0;
}
return bytesLeft;
}
public void mark(int howMuch) {
fMark = fOffset;
}
public void reset() {
fOffset = fMark;
}
public boolean markSupported() {
return true;
}
public void close() throws IOException {
if (fInputStream != null) {
fInputStream.close();
fInputStream = null;
}
}
} // end of RewindableInputStream class
} // class XMLEntityManager
| true | true | public boolean scanData(String delimiter, XMLStringBuffer buffer)
throws IOException {
boolean done = false;
int delimLen = delimiter.length();
char charAt0 = delimiter.charAt(0);
int offset = fCurrentEntity.position;
int c = fCurrentEntity.ch[offset];
int newlines = 0;
boolean external = fCurrentEntity.isExternal();
do {
if (DEBUG_BUFFER) {
System.out.print("(scanData: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
else if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.position,
fCurrentEntity.ch, 0, fCurrentEntity.count - fCurrentEntity.position);
load(fCurrentEntity.count - fCurrentEntity.position, false);
fCurrentEntity.position = 0;
}
if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
// something must be wrong with the input: e.g., file ends an unterminated comment
int length = fCurrentEntity.count - fCurrentEntity.position;
buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length);
fCurrentEntity.columnNumber += fCurrentEntity.count;
fCurrentEntity.position = fCurrentEntity.count;
load(0,true);
return false;
}
// normalize newlines
offset = fCurrentEntity.position;
c = fCurrentEntity.ch[offset];
newlines = 0;
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
fCurrentEntity.count = newlines;
if (load(newlines, false)) {
break;
}
}
}
else {
fCurrentEntity.position--;
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
buffer.append(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
return true;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
}
// iterate over buffer looking for delimiter
OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == charAt0) {
// looks like we just hit the delimiter
int delimOffset = fCurrentEntity.position - 1;
for (int i = 1; i < delimLen; i++) {
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.position -= i;
break OUTER;
}
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (delimiter.charAt(i) != c) {
fCurrentEntity.position--;
break;
}
}
if (fCurrentEntity.position == delimOffset + delimLen) {
done = true;
break;
}
}
else if (c == '\n' || (external && c == '\r')) {
fCurrentEntity.position--;
break;
}
else if (XMLChar.isInvalid(c)) {
fCurrentEntity.position--;
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
buffer.append(fCurrentEntity.ch, offset, length);
return true;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
if (done) {
length -= delimLen;
}
buffer.append (fCurrentEntity.ch, offset, length);
// return true if string was skipped
if (DEBUG_BUFFER) {
System.out.print(")scanData: ");
print();
System.out.println(" -> " + done);
}
} while (!done);
return !done;
} // scanData(String,XMLString)
| public boolean scanData(String delimiter, XMLStringBuffer buffer)
throws IOException {
boolean done = false;
int delimLen = delimiter.length();
char charAt0 = delimiter.charAt(0);
int offset = 0;
int c = -1;
int newlines = 0;
boolean external = fCurrentEntity.isExternal();
do {
if (DEBUG_BUFFER) {
System.out.print("(scanData: ");
print();
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
else if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.position,
fCurrentEntity.ch, 0, fCurrentEntity.count - fCurrentEntity.position);
load(fCurrentEntity.count - fCurrentEntity.position, false);
fCurrentEntity.position = 0;
}
if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
// something must be wrong with the input: e.g., file ends an unterminated comment
int length = fCurrentEntity.count - fCurrentEntity.position;
buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length);
fCurrentEntity.columnNumber += fCurrentEntity.count;
fCurrentEntity.position = fCurrentEntity.count;
load(0,true);
return false;
}
// normalize newlines
offset = fCurrentEntity.position;
c = fCurrentEntity.ch[offset];
newlines = 0;
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
fCurrentEntity.count = newlines;
if (load(newlines, false)) {
break;
}
}
}
else {
fCurrentEntity.position--;
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
buffer.append(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
return true;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
print();
System.out.println();
}
}
// iterate over buffer looking for delimiter
OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == charAt0) {
// looks like we just hit the delimiter
int delimOffset = fCurrentEntity.position - 1;
for (int i = 1; i < delimLen; i++) {
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.position -= i;
break OUTER;
}
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (delimiter.charAt(i) != c) {
fCurrentEntity.position--;
break;
}
}
if (fCurrentEntity.position == delimOffset + delimLen) {
done = true;
break;
}
}
else if (c == '\n' || (external && c == '\r')) {
fCurrentEntity.position--;
break;
}
else if (XMLChar.isInvalid(c)) {
fCurrentEntity.position--;
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
buffer.append(fCurrentEntity.ch, offset, length);
return true;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
if (done) {
length -= delimLen;
}
buffer.append (fCurrentEntity.ch, offset, length);
// return true if string was skipped
if (DEBUG_BUFFER) {
System.out.print(")scanData: ");
print();
System.out.println(" -> " + done);
}
} while (!done);
return !done;
} // scanData(String,XMLString)
|
diff --git a/works.editor.antlr4/src/org/antlr/works/editor/antlr4/navigation/ParseTreeNode.java b/works.editor.antlr4/src/org/antlr/works/editor/antlr4/navigation/ParseTreeNode.java
index 521f99c..b6f88ab 100644
--- a/works.editor.antlr4/src/org/antlr/works/editor/antlr4/navigation/ParseTreeNode.java
+++ b/works.editor.antlr4/src/org/antlr/works/editor/antlr4/navigation/ParseTreeNode.java
@@ -1,200 +1,200 @@
/*
* Copyright (c) 2012 Sam Harwell, Tunnel Vision Laboratories LLC
* All rights reserved.
*
* The source code of this document is proprietary work, and is not licensed for
* distribution. For information about licensing, contact Sam Harwell at:
* [email protected]
*/
package org.antlr.works.editor.antlr4.navigation;
import java.awt.Image;
import java.util.List;
import java.util.concurrent.Callable;
import org.antlr.netbeans.editor.text.OffsetRegion;
import org.antlr.v4.runtime.InterpreterRuleContext;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.antlr.works.editor.antlr4.parsing.ParseTrees;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.annotations.common.NullAllowed;
import org.netbeans.api.annotations.common.StaticResource;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.ImageUtilities;
/**
*
* @author Sam Harwell
*/
public class ParseTreeNode extends AbstractNode implements OffsetProvider {
@StaticResource
private static final String RULE_IMAGE_PATH = "org/antlr/works/editor/antlr4/navigation/ui/rule.png";
public static final Image RULE_IMAGE = ImageUtilities.loadImage(RULE_IMAGE_PATH);
@StaticResource
private static final String TERMINAL_IMAGE_PATH = "org/antlr/works/editor/antlr4/navigation/ui/terminal.png";
public static final Image TERMINAL_IMAGE = ImageUtilities.loadImage(TERMINAL_IMAGE_PATH);
@StaticResource
private static final String ERROR_IMAGE_PATH = "org/antlr/works/editor/antlr4/navigation/ui/error.png";
public static final Image ERROR_IMAGE = ImageUtilities.loadImage(ERROR_IMAGE_PATH);
@NonNull
private final ParseTree _tree;
@NullAllowed
private final List<String> _ruleNames;
@Deprecated
public ParseTreeNode(@NonNull ParseTree tree) {
this(tree, null);
}
public ParseTreeNode(@NonNull ParseTree tree, @NullAllowed List<String> ruleNames) {
super(Children.LEAF);
_tree = tree;
_ruleNames = ruleNames;
if (tree.getChildCount() > 0) {
setChildren(Children.createLazy(new ChildrenOfParseTreeNodeCreator()));
}
if (tree instanceof RuleNode) {
RuleNode ruleNode = (RuleNode)tree;
RuleContext ruleContext = ruleNode.getRuleContext();
if (ruleContext instanceof ParserRuleContext && ruleContext.getClass() != ParserRuleContext.class && ruleContext.getClass() != InterpreterRuleContext.class) {
String contextName = ruleContext.getClass().getSimpleName();
if (!"Context".equals(contextName) && contextName.endsWith("Context")) {
contextName = contextName.substring(0, contextName.length() - "Context".length());
}
contextName = Character.toLowerCase(contextName.charAt(0)) + contextName.substring(1);
setDisplayName(contextName);
} else {
String displayName = null;
- if (ruleNames != null && ruleContext.getRuleIndex() > 0 && ruleContext.getRuleIndex() < ruleNames.size()) {
+ if (ruleNames != null && ruleContext.getRuleIndex() >= 0 && ruleContext.getRuleIndex() < ruleNames.size()) {
displayName = ruleNames.get(ruleContext.getRuleIndex());
}
if (displayName == null || displayName.isEmpty()) {
displayName = "Rule Node";
}
setDisplayName(displayName);
}
} else if (tree instanceof ErrorNode) {
setDisplayName("Error Node");
} else if (tree instanceof TerminalNode) {
String nodeText = tree.getText();
if (nodeText != null && !nodeText.isEmpty()) {
nodeText = nodeText.substring(0, Math.min(nodeText.length(), 100));
nodeText = nodeText.replace("\\", "\\\\");
nodeText = nodeText.replace("\r", "\\r");
nodeText = nodeText.replace("\n", "\\n");
nodeText = nodeText.replace("\t", "\\t");
nodeText = nodeText.replace("'", "\\'");
setDisplayName("'" + nodeText + "'");
} else {
setDisplayName("Terminal Node");
}
}
}
@NonNull
public ParseTree getTree() {
return _tree;
}
@CheckForNull
public List<String> getRuleNames() {
return _ruleNames;
}
@Override
public Image getIcon(int type) {
if (_tree instanceof RuleNode) {
return RULE_IMAGE;
} else if (_tree instanceof ErrorNode) {
return ERROR_IMAGE;
} else if (_tree instanceof TerminalNode) {
return TERMINAL_IMAGE;
}
return super.getIcon(type);
}
@Override
public Image getOpenedIcon(int type) {
return getIcon(type);
}
@Override
public OffsetRegion getSpan() {
TerminalNode startNode = ParseTrees.getStartNode(_tree);
if (startNode == null) {
return null;
}
TerminalNode stopNode = ParseTrees.getStopNode(_tree);
if (stopNode == null) {
// rule matched epsilon
return new OffsetRegion(startNode.getSymbol().getStartIndex(), 0);
}
return OffsetRegion.fromBounds(startNode.getSymbol().getStartIndex(), stopNode.getSymbol().getStopIndex() + 1);
}
@Override
public OffsetRegion getSeek() {
OffsetRegion span = getSpan();
if (span == null) {
return null;
}
return new OffsetRegion(span.getStart(), 0);
}
@Override
public OffsetRegion getEmphasis() {
return null;
}
protected ParseTreeNode createChildNode(ParseTree tree) {
return new ParseTreeNode(tree, _ruleNames);
}
private final class ChildrenOfParseTreeNodeCreator implements Callable<Children> {
@Override
public Children call() throws Exception {
Node[] childrenNodes = new Node[_tree.getChildCount()];
for (int i = 0; i < childrenNodes.length; i++) {
childrenNodes[i] = createChildNode(_tree.getChild(i));
}
return new NodeChildren(childrenNodes);
}
}
private static final class NodeChildren extends Children.Keys<Node> {
public NodeChildren(Node[] nodes) {
setKeys(nodes);
}
@Override
protected Node[] createNodes(Node key) {
return new Node[] { key };
}
}
}
| true | true | public ParseTreeNode(@NonNull ParseTree tree, @NullAllowed List<String> ruleNames) {
super(Children.LEAF);
_tree = tree;
_ruleNames = ruleNames;
if (tree.getChildCount() > 0) {
setChildren(Children.createLazy(new ChildrenOfParseTreeNodeCreator()));
}
if (tree instanceof RuleNode) {
RuleNode ruleNode = (RuleNode)tree;
RuleContext ruleContext = ruleNode.getRuleContext();
if (ruleContext instanceof ParserRuleContext && ruleContext.getClass() != ParserRuleContext.class && ruleContext.getClass() != InterpreterRuleContext.class) {
String contextName = ruleContext.getClass().getSimpleName();
if (!"Context".equals(contextName) && contextName.endsWith("Context")) {
contextName = contextName.substring(0, contextName.length() - "Context".length());
}
contextName = Character.toLowerCase(contextName.charAt(0)) + contextName.substring(1);
setDisplayName(contextName);
} else {
String displayName = null;
if (ruleNames != null && ruleContext.getRuleIndex() > 0 && ruleContext.getRuleIndex() < ruleNames.size()) {
displayName = ruleNames.get(ruleContext.getRuleIndex());
}
if (displayName == null || displayName.isEmpty()) {
displayName = "Rule Node";
}
setDisplayName(displayName);
}
} else if (tree instanceof ErrorNode) {
setDisplayName("Error Node");
} else if (tree instanceof TerminalNode) {
String nodeText = tree.getText();
if (nodeText != null && !nodeText.isEmpty()) {
nodeText = nodeText.substring(0, Math.min(nodeText.length(), 100));
nodeText = nodeText.replace("\\", "\\\\");
nodeText = nodeText.replace("\r", "\\r");
nodeText = nodeText.replace("\n", "\\n");
nodeText = nodeText.replace("\t", "\\t");
nodeText = nodeText.replace("'", "\\'");
setDisplayName("'" + nodeText + "'");
} else {
setDisplayName("Terminal Node");
}
}
}
| public ParseTreeNode(@NonNull ParseTree tree, @NullAllowed List<String> ruleNames) {
super(Children.LEAF);
_tree = tree;
_ruleNames = ruleNames;
if (tree.getChildCount() > 0) {
setChildren(Children.createLazy(new ChildrenOfParseTreeNodeCreator()));
}
if (tree instanceof RuleNode) {
RuleNode ruleNode = (RuleNode)tree;
RuleContext ruleContext = ruleNode.getRuleContext();
if (ruleContext instanceof ParserRuleContext && ruleContext.getClass() != ParserRuleContext.class && ruleContext.getClass() != InterpreterRuleContext.class) {
String contextName = ruleContext.getClass().getSimpleName();
if (!"Context".equals(contextName) && contextName.endsWith("Context")) {
contextName = contextName.substring(0, contextName.length() - "Context".length());
}
contextName = Character.toLowerCase(contextName.charAt(0)) + contextName.substring(1);
setDisplayName(contextName);
} else {
String displayName = null;
if (ruleNames != null && ruleContext.getRuleIndex() >= 0 && ruleContext.getRuleIndex() < ruleNames.size()) {
displayName = ruleNames.get(ruleContext.getRuleIndex());
}
if (displayName == null || displayName.isEmpty()) {
displayName = "Rule Node";
}
setDisplayName(displayName);
}
} else if (tree instanceof ErrorNode) {
setDisplayName("Error Node");
} else if (tree instanceof TerminalNode) {
String nodeText = tree.getText();
if (nodeText != null && !nodeText.isEmpty()) {
nodeText = nodeText.substring(0, Math.min(nodeText.length(), 100));
nodeText = nodeText.replace("\\", "\\\\");
nodeText = nodeText.replace("\r", "\\r");
nodeText = nodeText.replace("\n", "\\n");
nodeText = nodeText.replace("\t", "\\t");
nodeText = nodeText.replace("'", "\\'");
setDisplayName("'" + nodeText + "'");
} else {
setDisplayName("Terminal Node");
}
}
}
|
diff --git a/api/src/test/java/org/openmrs/OpenmrsTestsTest.java b/api/src/test/java/org/openmrs/OpenmrsTestsTest.java
index e6b272e9..3960806a 100644
--- a/api/src/test/java/org/openmrs/OpenmrsTestsTest.java
+++ b/api/src/test/java/org/openmrs/OpenmrsTestsTest.java
@@ -1,219 +1,219 @@
/**
* 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;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.openmrs.util.OpenmrsUtil;
/**
* Runs tests on the openmrs junit tests TODO: add unit test to make sure all tests have a call to
* assert* in them. This would help prevent people from making tests that just print results to the
* screen
*/
@SuppressWarnings("unchecked")
public class OpenmrsTestsTest {
private ClassLoader classLoader = this.getClass().getClassLoader();
private List<Class> testClasses = null;
/**
* Make sure there is at least one _other_ test case out there
*
* @throws Exception
*/
@Test
public void shouldHaveAtLeastOneTest() throws Exception {
List<Class> classes = getTestClasses();
assertTrue("There should be more than one class but there was only " + classes.size(), classes.size() > 1);
}
/**
* Makes sure all test methods in org.openmrs start with the word "should"
*
* @throws Exception
*/
@Test
public void shouldStartWithShould() throws Exception {
List<Class> classes = getTestClasses();
for (Class<TestCase> currentClass : classes) {
for (Method method : currentClass.getMethods()) {
// make sure every "test" method (determined by having
// the @Test annotation) starts with "testShould"
if (method.getAnnotation(Test.class) != null) {
String methodName = method.getName();
boolean passes = methodName.startsWith("should") || methodName.contains("_should");
assertTrue(currentClass.getName() + "#" + methodName
+ " is supposed to either 1) start with 'should' or 2) contain '_should' but it doesn't", passes);
}
}
}
}
/**
* Makes sure all "should___" methods in org.openmrs have an "@Test" annotation on it. This is
* to help prevent devs from forgetting to put the annotation and then seeing all tests pass
* because the new test wasn't actually ran
*
* @throws Exception
*/
@Test
public void shouldHaveTestAnnotationWhenStartingWithShould() throws Exception {
// loop over all methods in all test classes
for (Class<TestCase> currentClass : getTestClasses()) {
for (Method method : currentClass.getMethods()) {
String methodName = method.getName();
// make sure every should___ method has an @Test annotation
if (methodName.startsWith("should") || methodName.contains("_should")) {
assertTrue(currentClass.getName() + "#" + methodName
+ " does not have the @Test annotation on it even though the method name starts with 'should'",
method.getAnnotation(Test.class) != null);
}
}
}
}
/**
* Checks that a user hasn't accidentally created a test class that doesn't end with "Test". (If
* it doesn't, it isn't picked up by the test aggregator Ant target: junit-report) <br/>
* <br/>
* This class looks at all classes in the org.openmrs package. If a class contains an "@Test"
* annotated method but its class name does not end with Test, it fails.
*
* @throws Exception
*/
@Test
public void shouldHaveClassNameEndWithTestIfContainsMethodTestAnnotations() throws Exception {
// loop over all methods that _don't_ end in Test.class
for (Class<?> currentClass : getClasses("^.*(?<!Test)\\.class$")) {
// skip over classes that are @Ignore'd
if (currentClass.getAnnotation(Ignore.class) == null) {
boolean foundATestMethod = false;
for (Method method : currentClass.getMethods()) {
if (method.getAnnotation(Test.class) != null) {
foundATestMethod = true;
}
}
Assert.assertFalse(
currentClass.getName() + " does not end with 'Test' but contains @Test annotated methods",
foundATestMethod);
}
}
}
/**
* Get all classes ending in "Test.class".
*
* @return list of classes whose name ends with Test.class
*/
private List<Class> getTestClasses() {
return getClasses(".*Test\\.class$");
}
/**
* Get all classes in the org.openmrs.test package
*
* @return list of TestCase classes in org.openmrs.test
*/
private List<Class> getClasses(String classNameRegex) {
if (testClasses != null)
return testClasses;
Pattern pattern = Pattern.compile(classNameRegex);
URL url = classLoader.getResource("org/openmrs");
File directory = OpenmrsUtil.url2file(url);
// make sure we get a directory back
assertTrue("org.openmrs.test should be a directory", directory.isDirectory());
testClasses = getClassesInDirectory(directory, pattern);
// check to see if the web layer is also included. Skip it if its not there
url = classLoader.getResource("org/openmrs/web");
if (url != null) {
directory = OpenmrsUtil.url2file(url);
// make sure we get a directory back
assertTrue("org.openmrs.web.test should be a directory", directory.isDirectory());
testClasses.addAll(getClassesInDirectory(directory, pattern));
}
return testClasses;
}
/**
* Recurses into the given directory checking that all test methods start with "testShould"
*
* @param directory to loop through the files of
*/
private List<Class> getClassesInDirectory(File directory, Pattern pattern) {
List<Class> currentDirTestClasses = new ArrayList<Class>();
for (File currentFile : directory.listFiles()) {
// if looking at a folder, recurse into it
if (currentFile.isDirectory()) {
currentDirTestClasses.addAll(getClassesInDirectory(currentFile, pattern));
}
// if the user only wants classes ending in Test or they want all of them
if (pattern.matcher(currentFile.getName()).matches()) {
// strip off the extension
String className = currentFile.getAbsolutePath().replace(".class", "");
// switch to dot separation
className = className.replace(File.separator, ".");
// strip out the beginning (/home/ben/workspace...) up to org.openmrs.
- className = className.substring(className.indexOf("org.openmrs."));
+ className = className.substring(className.lastIndexOf("org.openmrs."));
try {
Class<?> currentClass = classLoader.loadClass(className);
currentDirTestClasses.add(currentClass);
}
catch (ClassNotFoundException e) {
System.out.println("Unable to load class: " + className + " error: " + e.getMessage());
}
}
}
return currentDirTestClasses;
}
}
| true | true | private List<Class> getClassesInDirectory(File directory, Pattern pattern) {
List<Class> currentDirTestClasses = new ArrayList<Class>();
for (File currentFile : directory.listFiles()) {
// if looking at a folder, recurse into it
if (currentFile.isDirectory()) {
currentDirTestClasses.addAll(getClassesInDirectory(currentFile, pattern));
}
// if the user only wants classes ending in Test or they want all of them
if (pattern.matcher(currentFile.getName()).matches()) {
// strip off the extension
String className = currentFile.getAbsolutePath().replace(".class", "");
// switch to dot separation
className = className.replace(File.separator, ".");
// strip out the beginning (/home/ben/workspace...) up to org.openmrs.
className = className.substring(className.indexOf("org.openmrs."));
try {
Class<?> currentClass = classLoader.loadClass(className);
currentDirTestClasses.add(currentClass);
}
catch (ClassNotFoundException e) {
System.out.println("Unable to load class: " + className + " error: " + e.getMessage());
}
}
}
return currentDirTestClasses;
}
| private List<Class> getClassesInDirectory(File directory, Pattern pattern) {
List<Class> currentDirTestClasses = new ArrayList<Class>();
for (File currentFile : directory.listFiles()) {
// if looking at a folder, recurse into it
if (currentFile.isDirectory()) {
currentDirTestClasses.addAll(getClassesInDirectory(currentFile, pattern));
}
// if the user only wants classes ending in Test or they want all of them
if (pattern.matcher(currentFile.getName()).matches()) {
// strip off the extension
String className = currentFile.getAbsolutePath().replace(".class", "");
// switch to dot separation
className = className.replace(File.separator, ".");
// strip out the beginning (/home/ben/workspace...) up to org.openmrs.
className = className.substring(className.lastIndexOf("org.openmrs."));
try {
Class<?> currentClass = classLoader.loadClass(className);
currentDirTestClasses.add(currentClass);
}
catch (ClassNotFoundException e) {
System.out.println("Unable to load class: " + className + " error: " + e.getMessage());
}
}
}
return currentDirTestClasses;
}
|
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/wizards/UserInteractionsComponent.java b/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/wizards/UserInteractionsComponent.java
index 4f8f7b61..b13aebcc 100644
--- a/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/wizards/UserInteractionsComponent.java
+++ b/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/wizards/UserInteractionsComponent.java
@@ -1,465 +1,465 @@
/*
* Created on 28.may.2005
*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*
*/
package org.cubictest.ui.gef.wizards;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.cubictest.model.AbstractPage;
import org.cubictest.model.ActionType;
import org.cubictest.model.Common;
import org.cubictest.model.CommonTransition;
import org.cubictest.model.IActionElement;
import org.cubictest.model.Page;
import org.cubictest.model.PageElement;
import org.cubictest.model.Test;
import org.cubictest.model.UserInteraction;
import org.cubictest.model.UserInteractionsTransition;
import org.cubictest.model.WebBrowser;
import org.cubictest.model.context.IContext;
import org.cubictest.model.formElement.AbstractTextInput;
import org.cubictest.model.parameterization.ParameterList;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
/**
* Component view (GUI) nfor creating new user interaction input.
* Both used in dialog box for new user interaction and for properties view.
*
* @author SK Skytteren
* @author chr_schwarz
*/
public class UserInteractionsComponent {
private static final String CHOOSE = "--Choose--";
private TableViewer viewer;
private Table table;
private static final String ELEMENT = "element";
private static final String ACTION = "action";
private static final String INPUT = "input";
private CellEditor[] cellEditors;
private String[] columnNames = new String[] {ELEMENT, ACTION, INPUT};
private String[] elementNames;
private UserInteractionsTransition transition;
private List<IActionElement> allActionElements = new ArrayList<IActionElement>();
private Test test;
private String[] currentActions;
private UserInteraction activeAction;
public UserInteractionsComponent(UserInteractionsTransition transition, Test test) {
this.test = test;
this.transition = transition;
List<PageElement> elementsTree = new ArrayList<PageElement>();
AbstractPage start = (AbstractPage)transition.getStart();
if(start instanceof Page) { // process commonTrasitions for pages
elementsTree.addAll(start.getElements());
List<CommonTransition> commonTransitions = ((Page)start).getCommonTransitions();
for (CommonTransition at : commonTransitions)
elementsTree.addAll(((Common)(at).getStart()).getElements());
}
allActionElements.addAll(getFlattenedPageElements(elementsTree));
allActionElements.add(new WebBrowser());
transition.setPage((AbstractPage)transition.getStart());
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public Composite createControl(Composite parent) {
Composite content = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout(2, false);
layout.verticalSpacing = 4;
content.setLayout(layout);
Label fill = new Label(content, SWT.NULL);
fill.setText("User interaction input");
Button button = new Button(content, SWT.PUSH);
button.setText("Add New User Input");
button.pack();
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
List<UserInteraction> currentInputs = transition.getUserInteractions();
UserInteraction newInput = new UserInteraction();
transition.addUserInteraction(newInput);
viewer.setInput(currentInputs);
}
});
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = false;
gd.horizontalSpan = 2;
gd.verticalIndent = 7;
createTable(content);
createTableViewer();
//populate viewer with initial user interactions:
List<UserInteraction> initialUserInteractions = transition.getUserInteractions();
if (initialUserInteractions == null || initialUserInteractions.size() == 0) {
initialUserInteractions.add(new UserInteraction());
}
viewer.setInput(initialUserInteractions);
transition.setUserInteractions(initialUserInteractions);
return content;
}
private void createTable(Composite parent) {
int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL |
SWT.FULL_SELECTION | SWT.HIDE_SELECTION;
table = new Table(parent, style);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.horizontalSpan = 2;
table.setLayoutData(gd);
table.setLinesVisible(true);
table.setHeaderVisible(true);
TableColumn tc1 = new TableColumn(table, SWT.LEFT, 0);
tc1.setText(ELEMENT);
tc1.setWidth(120);
tc1.setResizable(true);
TableColumn tc2 = new TableColumn(table, SWT.LEFT, 1);
tc2.setText(ACTION);
tc2.setWidth(120);
tc2.setResizable(true);
TableColumn tc3 = new TableColumn(table, SWT.LEFT, 2);
tc3.setText(INPUT);
tc3.setWidth(160);
tc3.setResizable(true);
}
private void createTableViewer() {
viewer = new TableViewer(table);
viewer.setUseHashlookup(true);
viewer.setColumnProperties(columnNames);
cellEditors = new CellEditor[3];
elementNames = new String[allActionElements.size() + 2];
elementNames[0] = CHOOSE;
int a = 1;
for (IActionElement element: allActionElements) {
if (element.getActionTypes().size() > 0) {
elementNames[a++] = element.getType() + ": " + element.getDescription();
}
}
elementNames[a] = "";
cellEditors[0] = new ActionElementComboBoxCellEditor(table, elementNames, SWT.READ_ONLY);
cellEditors[1] = new ComboBoxCellEditor(table, new String[]{""}, SWT.READ_ONLY);
cellEditors[2] = new TextCellEditor(table);
viewer.setCellEditors(cellEditors);
viewer.setContentProvider(new ActionContentProvider());
viewer.setLabelProvider(new ActionLabelProvider());
viewer.setCellModifier(new ActionInputCellModifier());
}
class ActionElementComboBoxCellEditor extends ComboBoxCellEditor {
public ActionElementComboBoxCellEditor(Table table, String[] elementNames, int read_only) {
super(table,elementNames, read_only);
}
@Override
protected Control createControl(Composite parent) {
CCombo comboBox = (CCombo) super.createControl(parent);
comboBox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
Integer selectedIndex = (Integer) doGetValue();
String elementName = elementNames[selectedIndex.intValue()];
for (IActionElement iae : allActionElements){
if ( (iae.getType() + ": " + iae.getDescription()).equals(elementName)){
activeAction.setElement(iae);
break;
}
}
IActionElement pe = ((UserInteraction)activeAction).getElement();
if(pe != null){
List<String> actionList = new ArrayList<String>();
for(ActionType action : pe.getActionTypes()){
if(ActionType.ENTER_PARAMETER_TEXT.equals(action)
&& test.getParamList() == null) {
continue;
}
actionList.add(action.getText());
}
String[] actions = actionList.toArray(new String[0]);
if (!ArrayUtils.isEquals(actions, currentActions)) {
cellEditors[1] = new ComboBoxCellEditor(table,actions, SWT.READ_ONLY);
currentActions = actions;
}
}
deactivate();
}
});
return comboBox;
}
}
class ActionInputCellModifier implements ICellModifier{
public boolean canModify(Object element, String property) {
activeAction = (UserInteraction) element;
if (property.equals(INPUT)){
if (((UserInteraction)element).getElement() instanceof AbstractTextInput){
UserInteraction input = (UserInteraction)element;
if(input.useParam()){
ParameterList list = test.getParamList();
String[] keys = list.getHeaders().toArray();
cellEditors[2] = new ComboBoxCellEditor(table,keys,SWT.READ_ONLY);
return true;
}else{
cellEditors[2] = new TextCellEditor(table);
}
}
if (((UserInteraction) element).getActionType().acceptsInput()) {
cellEditors[2] = new TextCellEditor(table);
}
else {
cellEditors[2] = new TextCellEditor(table, SWT.READ_ONLY);
((UserInteraction) element).setTextualInput("");
return false;
}
} else if(property.equals(ACTION)){
IActionElement pe = ((UserInteraction)element).getElement();
if(pe != null){
List<String> actionList = new ArrayList<String>();
for(ActionType action : pe.getActionTypes()){
if(ActionType.ENTER_PARAMETER_TEXT.equals(action)
&& test.getParamList() == null) {
continue;
}
actionList.add(action.getText());
}
String[] actions = actionList.toArray(new String[0]);
if (!ArrayUtils.isEquals(actions, currentActions)) {
cellEditors[1] = new ComboBoxCellEditor(table,actions, SWT.READ_ONLY);
currentActions = actions;
}
}
}
return true;
}
public Object getValue(Object element, String property) {
UserInteraction fInput = (UserInteraction) element;
int columnIndex = Arrays.asList(columnNames).indexOf(property);
Object result = null;
switch(columnIndex){
case 0:
IActionElement p = fInput.getElement();
String elementName = CHOOSE;
if (p != null)
elementName = p.getType() + ": " + p.getDescription();
for (int i = 0; i < elementNames.length; i++) {
if (elementName.equals(elementNames[i]))
return i;
}
case 1:
ActionType action = fInput.getActionType();
int j = 0;
if(fInput.getElement() == null)
break;
result = action;
for(ActionType actionType : fInput.getElement().getActionTypes()){
if(action.equals(actionType))
return j;
if(ActionType.ENTER_PARAMETER_TEXT.equals(action)
&& test.getParamList() == null) {
continue;
}
j++;
}
break;
case 2:
if(ActionType.ENTER_PARAMETER_TEXT.equals(fInput.getActionType())){
String key = fInput.getParamKey();
if(key == null || "".equals(key))
return 0;
return test.getParamList().getHeaders().indexOf(key);
}
return fInput.getTextualInput();
}
return result;
}
public void modify(Object element, String property, Object value) {
int columnIndex = java.util.Arrays.asList(columnNames).indexOf(property);
if (element instanceof TableItem) {
UserInteraction rowItem = (UserInteraction) ((TableItem) element).getData();
switch (columnIndex) {
case 0:
String name = elementNames[((Integer) value).intValue()];
- for (IActionElement iae : allActionElements){
+ for (int i = 0; i < allActionElements.size(); i++){
if (name.equals(CHOOSE) || name.equals("")) {
rowItem.setElement(null);
rowItem.setActionType(ActionType.NO_ACTION);
}
}
break;
case 1:
if(rowItem.getElement() == null)
break;
int i = 0;
for(ActionType action :rowItem.getElement().getActionTypes()){
if(i == (Integer) value){
rowItem.setActionType(action);
rowItem.setUseI18n(ActionType.ENTER_PARAMETER_TEXT.equals(action));
break;
}
if(ActionType.ENTER_PARAMETER_TEXT.equals(action)
&& test.getParamList() == null) {
continue;
}
i++;
}
break;
case 2:
if(ActionType.ENTER_PARAMETER_TEXT.equals(rowItem.getActionType())){
rowItem.setParamKey(test.getParamList().getHeaders().get((Integer)value));
test.getParamList().getParameters().get((Integer) value).addObserver(rowItem);
test.updateObservers();
}
else
rowItem.setTextualInput((String)value);
break;
}
viewer.update(rowItem, null);
}
}
}
class ActionContentProvider implements IStructuredContentProvider {
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public Object[] getElements(Object inputElement) {
List inputs = (List) inputElement;
return inputs.toArray();
}
}
class ActionLabelProvider extends LabelProvider implements ITableLabelProvider {
public ActionLabelProvider() {
}
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
UserInteraction fInput = (UserInteraction) element;
String result = "";
switch (columnIndex) {
case 0:
IActionElement p = fInput.getElement();
if (p!=null)
return p.getType() + ": " + p.getDescription();
else
return elementNames[0];
case 1:
return fInput.getActionType().getText();
case 2:
if (fInput.useParam())
return fInput.getParamKey();
if (fInput.getActionType().acceptsInput()) {
return fInput.getTextualInput();
}
default:
break;
}
return result;
}
public void dispose() {
}
}
private List<PageElement> getFlattenedPageElements(List<PageElement> elements) {
List<PageElement> flattenedElements = new ArrayList<PageElement>();
for (PageElement element: elements){
if(element.getActionTypes().size() == 0) {
continue;
}
if(element instanceof IContext){
getFlattenedPageElements(((IContext) element).getElements());
flattenedElements.add(element);
}
else {
flattenedElements.add(element);
}
}
return flattenedElements;
}
}
| true | true | public void modify(Object element, String property, Object value) {
int columnIndex = java.util.Arrays.asList(columnNames).indexOf(property);
if (element instanceof TableItem) {
UserInteraction rowItem = (UserInteraction) ((TableItem) element).getData();
switch (columnIndex) {
case 0:
String name = elementNames[((Integer) value).intValue()];
for (IActionElement iae : allActionElements){
if (name.equals(CHOOSE) || name.equals("")) {
rowItem.setElement(null);
rowItem.setActionType(ActionType.NO_ACTION);
}
}
break;
case 1:
if(rowItem.getElement() == null)
break;
int i = 0;
for(ActionType action :rowItem.getElement().getActionTypes()){
if(i == (Integer) value){
rowItem.setActionType(action);
rowItem.setUseI18n(ActionType.ENTER_PARAMETER_TEXT.equals(action));
break;
}
if(ActionType.ENTER_PARAMETER_TEXT.equals(action)
&& test.getParamList() == null) {
continue;
}
i++;
}
break;
case 2:
if(ActionType.ENTER_PARAMETER_TEXT.equals(rowItem.getActionType())){
rowItem.setParamKey(test.getParamList().getHeaders().get((Integer)value));
test.getParamList().getParameters().get((Integer) value).addObserver(rowItem);
test.updateObservers();
}
else
rowItem.setTextualInput((String)value);
break;
}
viewer.update(rowItem, null);
}
}
| public void modify(Object element, String property, Object value) {
int columnIndex = java.util.Arrays.asList(columnNames).indexOf(property);
if (element instanceof TableItem) {
UserInteraction rowItem = (UserInteraction) ((TableItem) element).getData();
switch (columnIndex) {
case 0:
String name = elementNames[((Integer) value).intValue()];
for (int i = 0; i < allActionElements.size(); i++){
if (name.equals(CHOOSE) || name.equals("")) {
rowItem.setElement(null);
rowItem.setActionType(ActionType.NO_ACTION);
}
}
break;
case 1:
if(rowItem.getElement() == null)
break;
int i = 0;
for(ActionType action :rowItem.getElement().getActionTypes()){
if(i == (Integer) value){
rowItem.setActionType(action);
rowItem.setUseI18n(ActionType.ENTER_PARAMETER_TEXT.equals(action));
break;
}
if(ActionType.ENTER_PARAMETER_TEXT.equals(action)
&& test.getParamList() == null) {
continue;
}
i++;
}
break;
case 2:
if(ActionType.ENTER_PARAMETER_TEXT.equals(rowItem.getActionType())){
rowItem.setParamKey(test.getParamList().getHeaders().get((Integer)value));
test.getParamList().getParameters().get((Integer) value).addObserver(rowItem);
test.updateObservers();
}
else
rowItem.setTextualInput((String)value);
break;
}
viewer.update(rowItem, null);
}
}
|
diff --git a/src/test/java/org/elasticsearch/river/rabbitmq/RabbitMQTestRunner.java b/src/test/java/org/elasticsearch/river/rabbitmq/RabbitMQTestRunner.java
index 2e8bcd2..9e71271 100644
--- a/src/test/java/org/elasticsearch/river/rabbitmq/RabbitMQTestRunner.java
+++ b/src/test/java/org/elasticsearch/river/rabbitmq/RabbitMQTestRunner.java
@@ -1,181 +1,181 @@
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.river.rabbitmq;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.indices.IndexMissingException;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.ConnectException;
/**
*
*/
public abstract class RabbitMQTestRunner {
protected ESLogger logger = ESLoggerFactory.getLogger(RabbitMQTestRunner.class.getName());
private static String INDEX = "test";
protected Node node;
protected abstract void pushMessages(Channel ch) throws IOException;
protected abstract XContentBuilder river() throws IOException;
protected abstract long expectedDocuments();
/**
* We don't want to run test more than needed. In
* case of timeout, test should fail as it means we did not
* consume all the queue
* @return Timeout for test (default to 10s)
*/
protected int timeout() {
return 10;
}
/**
* Helper method to inject x messages containing y index requests
* @param ch RabbitMQ channel
* @param nbMessages number of messages to inject (x)
* @param nbDocs number of docs per message to inject (y)
* @throws IOException
*/
protected static void pushMessages(Channel ch, int nbMessages, int nbDocs) throws IOException {
for (int i = 0; i < nbMessages; i++) {
StringBuffer message = new StringBuffer();
for (int j = 0; j < nbDocs; j++) {
message.append("{ \"index\" : { \"_index\" : \""+INDEX+"\", \"_type\" : \"typex\", \"_id\" : \""+ i + "_" + j +"\" } }\n");
message.append("{ \"typex\" : { \"field\" : \"" + i + "_" + j + "\" } }\n");
}
ch.basicPublish("elasticsearch", "elasticsearch", null, message.toString().getBytes());
}
}
/**
* If you need to run specific tests, just override this method.
* By default, we check the number of expected documents
* @param node Elasticsearch current node
*/
protected void postInjectionTests(Node node) {
CountResponse response = node.client().prepareCount("test").execute().actionGet();
// We have consumed all messages. We can now check expected number of documents
Assert.assertEquals("Wrong number of documents found", expectedDocuments(), response.getCount());
}
/**
* Override if you need to add specific settings for your node
* @return
*/
protected Settings nodeSettings() {
return ImmutableSettings.settingsBuilder().build();
}
@Test
public void test_all_messages_are_consumed() throws Exception {
// We try to connect to RabbitMQ.
// If it's not launched, we don't fail the test but only log it
try {
ConnectionFactory cfconn = new ConnectionFactory();
cfconn.setHost("localhost");
cfconn.setPort(AMQP.PROTOCOL.PORT);
Connection conn = cfconn.newConnection();
Channel ch = conn.createChannel();
ch.exchangeDeclare("elasticsearch", "direct", true);
AMQP.Queue.DeclareOk queue = ch.queueDeclare("elasticsearch", true, false, false, null);
// We purge the queue in case of something is remaining there
ch.queuePurge("elasticsearch");
pushMessages(ch);
// We can now create our node and our river
Settings settings = ImmutableSettings.settingsBuilder()
.put("gateway.type", "none")
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
.put(nodeSettings())
.build();
- node = NodeBuilder.nodeBuilder().settings(settings).node();
+ node = NodeBuilder.nodeBuilder().local(true).settings(settings).node();
// We first remove existing index if any
try {
node.client().admin().indices().prepareDelete(INDEX).execute().actionGet();
} catch (IndexMissingException e) {
// Index is missing? It's perfectly fine!
}
// Let's create an index for our docs and we will disable refresh
node.client().admin().indices().prepareCreate(INDEX).execute().actionGet();
node.client().prepareIndex("_river", "test", "_meta").setSource(river()).execute().actionGet();
// We need at some point to check if we have consumed the river
int steps = timeout();
long count = 0;
while (true) {
// We wait for one second
Thread.sleep(1000);
CountResponse response = node.client().prepareCount("test").execute().actionGet();
count = response.getCount();
steps--;
if (steps < 0 || count == expectedDocuments()) {
break;
}
}
ch.close();
conn.close();
postInjectionTests(node);
} catch (ConnectException e) {
logger.warn("RabbitMQ service is not launched on localhost:{}. Can not start Integration test. " +
"Launch `rabbitmq-server`.", AMQP.PROTOCOL.PORT);
}
}
@After
public void tearDown() {
// After each test, we kill the node
if (node != null) {
node.close();
}
node = null;
}
}
| true | true | public void test_all_messages_are_consumed() throws Exception {
// We try to connect to RabbitMQ.
// If it's not launched, we don't fail the test but only log it
try {
ConnectionFactory cfconn = new ConnectionFactory();
cfconn.setHost("localhost");
cfconn.setPort(AMQP.PROTOCOL.PORT);
Connection conn = cfconn.newConnection();
Channel ch = conn.createChannel();
ch.exchangeDeclare("elasticsearch", "direct", true);
AMQP.Queue.DeclareOk queue = ch.queueDeclare("elasticsearch", true, false, false, null);
// We purge the queue in case of something is remaining there
ch.queuePurge("elasticsearch");
pushMessages(ch);
// We can now create our node and our river
Settings settings = ImmutableSettings.settingsBuilder()
.put("gateway.type", "none")
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
.put(nodeSettings())
.build();
node = NodeBuilder.nodeBuilder().settings(settings).node();
// We first remove existing index if any
try {
node.client().admin().indices().prepareDelete(INDEX).execute().actionGet();
} catch (IndexMissingException e) {
// Index is missing? It's perfectly fine!
}
// Let's create an index for our docs and we will disable refresh
node.client().admin().indices().prepareCreate(INDEX).execute().actionGet();
node.client().prepareIndex("_river", "test", "_meta").setSource(river()).execute().actionGet();
// We need at some point to check if we have consumed the river
int steps = timeout();
long count = 0;
while (true) {
// We wait for one second
Thread.sleep(1000);
CountResponse response = node.client().prepareCount("test").execute().actionGet();
count = response.getCount();
steps--;
if (steps < 0 || count == expectedDocuments()) {
break;
}
}
ch.close();
conn.close();
postInjectionTests(node);
} catch (ConnectException e) {
logger.warn("RabbitMQ service is not launched on localhost:{}. Can not start Integration test. " +
"Launch `rabbitmq-server`.", AMQP.PROTOCOL.PORT);
}
}
| public void test_all_messages_are_consumed() throws Exception {
// We try to connect to RabbitMQ.
// If it's not launched, we don't fail the test but only log it
try {
ConnectionFactory cfconn = new ConnectionFactory();
cfconn.setHost("localhost");
cfconn.setPort(AMQP.PROTOCOL.PORT);
Connection conn = cfconn.newConnection();
Channel ch = conn.createChannel();
ch.exchangeDeclare("elasticsearch", "direct", true);
AMQP.Queue.DeclareOk queue = ch.queueDeclare("elasticsearch", true, false, false, null);
// We purge the queue in case of something is remaining there
ch.queuePurge("elasticsearch");
pushMessages(ch);
// We can now create our node and our river
Settings settings = ImmutableSettings.settingsBuilder()
.put("gateway.type", "none")
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
.put(nodeSettings())
.build();
node = NodeBuilder.nodeBuilder().local(true).settings(settings).node();
// We first remove existing index if any
try {
node.client().admin().indices().prepareDelete(INDEX).execute().actionGet();
} catch (IndexMissingException e) {
// Index is missing? It's perfectly fine!
}
// Let's create an index for our docs and we will disable refresh
node.client().admin().indices().prepareCreate(INDEX).execute().actionGet();
node.client().prepareIndex("_river", "test", "_meta").setSource(river()).execute().actionGet();
// We need at some point to check if we have consumed the river
int steps = timeout();
long count = 0;
while (true) {
// We wait for one second
Thread.sleep(1000);
CountResponse response = node.client().prepareCount("test").execute().actionGet();
count = response.getCount();
steps--;
if (steps < 0 || count == expectedDocuments()) {
break;
}
}
ch.close();
conn.close();
postInjectionTests(node);
} catch (ConnectException e) {
logger.warn("RabbitMQ service is not launched on localhost:{}. Can not start Integration test. " +
"Launch `rabbitmq-server`.", AMQP.PROTOCOL.PORT);
}
}
|
diff --git a/src/tsa/actors/BagScan.java b/src/tsa/actors/BagScan.java
index 7cb3633..983358e 100644
--- a/src/tsa/actors/BagScan.java
+++ b/src/tsa/actors/BagScan.java
@@ -1,84 +1,85 @@
// BagScan
package tsa.actors;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import tsa.messages.ScanBag;
import tsa.messages.ScanBagResults;
import tsa.messages.TimeBagMessage;
import akka.actor.ActorRef;
import akka.actor.Actors;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import tsa.messages.ActorTerminate;
public class BagScan extends UntypedActor {
private final int number;
private final ActorRef security;
private final ActorRef bagTimer;
private Queue<ActorRef> passengerBags = new LinkedList<ActorRef>();
public BagScan(int number, ActorRef security) {
bagTimer = Actors.actorOf(BagTimer.class);
bagTimer.start();
this.number = number;
this.security = security;
this.getContext().setId("BagScan-" + Integer.toString(this.number));
System.out.println(this.getContext().getId() + ": Scanner turned on for the day.");
}
@Override
public void onReceive(Object message) {
if (message instanceof ScanBag) {
// Baggage randomly fails inspection with a probability of 20%.
ActorRef passenger = ((ScanBag) message).passenger;
passengerBags.add(passenger);
// Bag processing takes a random amount of time, between 200 and 300 millis.
Random rand = new Random();
long whenToWakeUp = System.currentTimeMillis() + 200 + rand.nextInt(100);
// Tell BagTimer actor.
bagTimer.tell(new TimeBagMessage(whenToWakeUp, this.getContext()));
}
if(message instanceof String && ((String) message).equals("finished")){
ActorRef passenger = passengerBags.remove();
boolean passed = (Math.random() < 0.8);
if (passed) {
System.out.println(passenger.getId() + ": Passed BagScan-" + number);
} else {
System.out.println(passenger.getId() + ": Failed BagScan-" + number);
}
ScanBagResults resultsMessage =
new ScanBagResults(passenger, passed);
security.tell(resultsMessage);
}
//Message to terminate and actor terminates itself.
if (message instanceof ActorTerminate) {
if(passengerBags.isEmpty()){ // Can we terminate?
System.out.println(this.getContext().getId() + ": Scanner shut down for the day.");
//Try and tell the security to die. If already dead then it will
//throw an exception because it can't tell it to die. Catch the exception
//and print info message.
try {
security.tell(message);
} catch (Exception excep) {
System.out.println("Security Actor already terminated OR there is another error.");
}
+ bagTimer.tell(Actors.poisonPill());
this.getContext().tell(Actors.poisonPill());
} else { // Try again.
this.getContext().tell(message);
}
}
}
}
| true | true | public void onReceive(Object message) {
if (message instanceof ScanBag) {
// Baggage randomly fails inspection with a probability of 20%.
ActorRef passenger = ((ScanBag) message).passenger;
passengerBags.add(passenger);
// Bag processing takes a random amount of time, between 200 and 300 millis.
Random rand = new Random();
long whenToWakeUp = System.currentTimeMillis() + 200 + rand.nextInt(100);
// Tell BagTimer actor.
bagTimer.tell(new TimeBagMessage(whenToWakeUp, this.getContext()));
}
if(message instanceof String && ((String) message).equals("finished")){
ActorRef passenger = passengerBags.remove();
boolean passed = (Math.random() < 0.8);
if (passed) {
System.out.println(passenger.getId() + ": Passed BagScan-" + number);
} else {
System.out.println(passenger.getId() + ": Failed BagScan-" + number);
}
ScanBagResults resultsMessage =
new ScanBagResults(passenger, passed);
security.tell(resultsMessage);
}
//Message to terminate and actor terminates itself.
if (message instanceof ActorTerminate) {
if(passengerBags.isEmpty()){ // Can we terminate?
System.out.println(this.getContext().getId() + ": Scanner shut down for the day.");
//Try and tell the security to die. If already dead then it will
//throw an exception because it can't tell it to die. Catch the exception
//and print info message.
try {
security.tell(message);
} catch (Exception excep) {
System.out.println("Security Actor already terminated OR there is another error.");
}
this.getContext().tell(Actors.poisonPill());
} else { // Try again.
this.getContext().tell(message);
}
}
}
| public void onReceive(Object message) {
if (message instanceof ScanBag) {
// Baggage randomly fails inspection with a probability of 20%.
ActorRef passenger = ((ScanBag) message).passenger;
passengerBags.add(passenger);
// Bag processing takes a random amount of time, between 200 and 300 millis.
Random rand = new Random();
long whenToWakeUp = System.currentTimeMillis() + 200 + rand.nextInt(100);
// Tell BagTimer actor.
bagTimer.tell(new TimeBagMessage(whenToWakeUp, this.getContext()));
}
if(message instanceof String && ((String) message).equals("finished")){
ActorRef passenger = passengerBags.remove();
boolean passed = (Math.random() < 0.8);
if (passed) {
System.out.println(passenger.getId() + ": Passed BagScan-" + number);
} else {
System.out.println(passenger.getId() + ": Failed BagScan-" + number);
}
ScanBagResults resultsMessage =
new ScanBagResults(passenger, passed);
security.tell(resultsMessage);
}
//Message to terminate and actor terminates itself.
if (message instanceof ActorTerminate) {
if(passengerBags.isEmpty()){ // Can we terminate?
System.out.println(this.getContext().getId() + ": Scanner shut down for the day.");
//Try and tell the security to die. If already dead then it will
//throw an exception because it can't tell it to die. Catch the exception
//and print info message.
try {
security.tell(message);
} catch (Exception excep) {
System.out.println("Security Actor already terminated OR there is another error.");
}
bagTimer.tell(Actors.poisonPill());
this.getContext().tell(Actors.poisonPill());
} else { // Try again.
this.getContext().tell(message);
}
}
}
|
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/JobInformations.java b/javamelody-core/src/main/java/net/bull/javamelody/JobInformations.java
index cb75a18e..b6da3f2e 100644
--- a/javamelody-core/src/main/java/net/bull/javamelody/JobInformations.java
+++ b/javamelody-core/src/main/java/net/bull/javamelody/JobInformations.java
@@ -1,235 +1,235 @@
/*
* Copyright 2008-2010 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody 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.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.impl.SchedulerRepository;
/**
* Informations sur un job.
* L'état d'une instance est initialisé à son instanciation et non mutable;
* il est donc de fait thread-safe.
* Cet état est celui d'un job à un instant t.
* Les instances sont sérialisables pour pouvoir être transmises au serveur de collecte.
* Pour l'instant seul quartz est géré.
* @author Emeric Vernat
*/
class JobInformations implements Serializable {
static final boolean QUARTZ_AVAILABLE = isQuartzAvailable();
private static final long serialVersionUID = -2826168112578815952L;
private final String group;
private final String name;
private final String description;
private final String jobClassName;
private final Date previousFireTime;
private final Date nextFireTime;
private final long elapsedTime;
private final long repeatInterval;
private final String cronExpression;
private final boolean paused;
private final String globalJobId;
JobInformations(JobDetail jobDetail, JobExecutionContext jobExecutionContext,
Scheduler scheduler) throws SchedulerException {
// pas throws SchedulerException ici sinon NoClassDefFoundError
super();
assert jobDetail != null;
assert scheduler != null;
// rq: jobExecutionContext est non null si le job est en cours d'exécution ou null sinon
this.group = jobDetail.getGroup();
this.name = jobDetail.getName();
this.description = jobDetail.getDescription();
this.jobClassName = jobDetail.getJobClass().getName();
if (jobExecutionContext == null) {
elapsedTime = -1;
} else {
elapsedTime = System.currentTimeMillis() - jobExecutionContext.getFireTime().getTime();
}
final Trigger[] triggers = scheduler.getTriggersOfJob(name, group);
this.nextFireTime = getNextFireTime(triggers);
this.previousFireTime = getPreviousFireTime(triggers);
String cronTriggerExpression = null;
long simpleTriggerRepeatInterval = -1;
boolean jobPaused = true;
for (final Trigger trigger : triggers) {
if (trigger instanceof CronTrigger) {
// getCronExpression gives a PMD false+
cronTriggerExpression = ((CronTrigger) trigger).getCronExpression(); // NOPMD
} else if (trigger instanceof SimpleTrigger) {
simpleTriggerRepeatInterval = ((SimpleTrigger) trigger).getRepeatInterval(); // NOPMD
}
jobPaused = jobPaused
- && scheduler.getTriggerState(trigger.getName(), trigger.getGroup()) != Trigger.STATE_PAUSED;
+ && scheduler.getTriggerState(trigger.getName(), trigger.getGroup()) == Trigger.STATE_PAUSED;
}
this.repeatInterval = simpleTriggerRepeatInterval;
this.cronExpression = cronTriggerExpression;
this.paused = jobPaused;
this.globalJobId = buildGlobalJobId(jobDetail);
}
private static boolean isQuartzAvailable() {
try {
Class.forName("org.quartz.Job");
return true;
} catch (final ClassNotFoundException e) {
return false;
}
}
@SuppressWarnings("unchecked")
static List<JobInformations> buildJobInformationsList() {
if (!QUARTZ_AVAILABLE) {
return Collections.emptyList();
}
final List<JobInformations> result = new ArrayList<JobInformations>();
try {
for (final Scheduler scheduler : getAllSchedulers()) {
final Map<String, JobExecutionContext> currentlyExecutingJobsByFullName = new LinkedHashMap<String, JobExecutionContext>();
for (final JobExecutionContext currentlyExecutingJob : (List<JobExecutionContext>) scheduler
.getCurrentlyExecutingJobs()) {
currentlyExecutingJobsByFullName.put(currentlyExecutingJob.getJobDetail()
.getFullName(), currentlyExecutingJob);
}
for (final JobDetail jobDetail : getAllJobsOfScheduler(scheduler)) {
final JobExecutionContext jobExecutionContext = currentlyExecutingJobsByFullName
.get(jobDetail.getFullName());
result.add(new JobInformations(jobDetail, jobExecutionContext, scheduler));
}
}
} catch (final Exception e) {
throw new IllegalStateException(e);
}
return result;
}
@SuppressWarnings("unchecked")
static List<Scheduler> getAllSchedulers() {
return new ArrayList<Scheduler>(SchedulerRepository.getInstance().lookupAll());
}
static List<JobDetail> getAllJobsOfScheduler(Scheduler scheduler) throws SchedulerException {
final List<JobDetail> result = new ArrayList<JobDetail>();
for (final String jobGroupName : scheduler.getJobGroupNames()) {
for (final String jobName : scheduler.getJobNames(jobGroupName)) {
final JobDetail jobDetail = scheduler.getJobDetail(jobName, jobGroupName);
// le job peut être terminé et supprimé depuis la ligne ci-dessus
if (jobDetail != null) {
result.add(jobDetail);
}
}
}
return result;
}
private static Date getPreviousFireTime(Trigger[] triggers) {
Date triggerPreviousFireTime = null;
for (final Trigger trigger : triggers) {
if (triggerPreviousFireTime == null || trigger.getPreviousFireTime() != null
&& triggerPreviousFireTime.before(trigger.getPreviousFireTime())) {
triggerPreviousFireTime = trigger.getPreviousFireTime();
}
}
return triggerPreviousFireTime;
}
private static Date getNextFireTime(Trigger[] triggers) {
Date triggerNextFireTime = null;
for (final Trigger trigger : triggers) {
if (triggerNextFireTime == null || trigger.getNextFireTime() != null
&& triggerNextFireTime.after(trigger.getNextFireTime())) {
triggerNextFireTime = trigger.getNextFireTime();
}
}
return triggerNextFireTime;
}
String getGlobalJobId() {
return globalJobId;
}
String getName() {
return name;
}
String getGroup() {
return group;
}
String getDescription() {
return description;
}
String getJobClassName() {
return jobClassName;
}
long getElapsedTime() {
return elapsedTime;
}
boolean isCurrentlyExecuting() {
return elapsedTime >= 0;
}
Date getNextFireTime() {
return nextFireTime;
}
Date getPreviousFireTime() {
return previousFireTime;
}
long getRepeatInterval() {
return repeatInterval;
}
String getCronExpression() {
return cronExpression;
}
boolean isPaused() {
return paused;
}
private static String buildGlobalJobId(JobDetail jobDetail) {
return PID.getPID() + '_' + Parameters.getHostAddress() + '_'
+ jobDetail.getFullName().hashCode();
}
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + getName() + ", group=" + getGroup() + ']';
}
}
| true | true | JobInformations(JobDetail jobDetail, JobExecutionContext jobExecutionContext,
Scheduler scheduler) throws SchedulerException {
// pas throws SchedulerException ici sinon NoClassDefFoundError
super();
assert jobDetail != null;
assert scheduler != null;
// rq: jobExecutionContext est non null si le job est en cours d'exécution ou null sinon
this.group = jobDetail.getGroup();
this.name = jobDetail.getName();
this.description = jobDetail.getDescription();
this.jobClassName = jobDetail.getJobClass().getName();
if (jobExecutionContext == null) {
elapsedTime = -1;
} else {
elapsedTime = System.currentTimeMillis() - jobExecutionContext.getFireTime().getTime();
}
final Trigger[] triggers = scheduler.getTriggersOfJob(name, group);
this.nextFireTime = getNextFireTime(triggers);
this.previousFireTime = getPreviousFireTime(triggers);
String cronTriggerExpression = null;
long simpleTriggerRepeatInterval = -1;
boolean jobPaused = true;
for (final Trigger trigger : triggers) {
if (trigger instanceof CronTrigger) {
// getCronExpression gives a PMD false+
cronTriggerExpression = ((CronTrigger) trigger).getCronExpression(); // NOPMD
} else if (trigger instanceof SimpleTrigger) {
simpleTriggerRepeatInterval = ((SimpleTrigger) trigger).getRepeatInterval(); // NOPMD
}
jobPaused = jobPaused
&& scheduler.getTriggerState(trigger.getName(), trigger.getGroup()) != Trigger.STATE_PAUSED;
}
this.repeatInterval = simpleTriggerRepeatInterval;
this.cronExpression = cronTriggerExpression;
this.paused = jobPaused;
this.globalJobId = buildGlobalJobId(jobDetail);
}
| JobInformations(JobDetail jobDetail, JobExecutionContext jobExecutionContext,
Scheduler scheduler) throws SchedulerException {
// pas throws SchedulerException ici sinon NoClassDefFoundError
super();
assert jobDetail != null;
assert scheduler != null;
// rq: jobExecutionContext est non null si le job est en cours d'exécution ou null sinon
this.group = jobDetail.getGroup();
this.name = jobDetail.getName();
this.description = jobDetail.getDescription();
this.jobClassName = jobDetail.getJobClass().getName();
if (jobExecutionContext == null) {
elapsedTime = -1;
} else {
elapsedTime = System.currentTimeMillis() - jobExecutionContext.getFireTime().getTime();
}
final Trigger[] triggers = scheduler.getTriggersOfJob(name, group);
this.nextFireTime = getNextFireTime(triggers);
this.previousFireTime = getPreviousFireTime(triggers);
String cronTriggerExpression = null;
long simpleTriggerRepeatInterval = -1;
boolean jobPaused = true;
for (final Trigger trigger : triggers) {
if (trigger instanceof CronTrigger) {
// getCronExpression gives a PMD false+
cronTriggerExpression = ((CronTrigger) trigger).getCronExpression(); // NOPMD
} else if (trigger instanceof SimpleTrigger) {
simpleTriggerRepeatInterval = ((SimpleTrigger) trigger).getRepeatInterval(); // NOPMD
}
jobPaused = jobPaused
&& scheduler.getTriggerState(trigger.getName(), trigger.getGroup()) == Trigger.STATE_PAUSED;
}
this.repeatInterval = simpleTriggerRepeatInterval;
this.cronExpression = cronTriggerExpression;
this.paused = jobPaused;
this.globalJobId = buildGlobalJobId(jobDetail);
}
|
diff --git a/core-integ/src/test/java/org/apache/directory/server/core/operations/lookup/LookupIT.java b/core-integ/src/test/java/org/apache/directory/server/core/operations/lookup/LookupIT.java
index d627ea4696..ce09c76fc7 100644
--- a/core-integ/src/test/java/org/apache/directory/server/core/operations/lookup/LookupIT.java
+++ b/core-integ/src/test/java/org/apache/directory/server/core/operations/lookup/LookupIT.java
@@ -1,149 +1,149 @@
/*
* 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.directory.server.core.operations.lookup;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.integ.CiRunner;
import org.apache.directory.server.core.integ.Level;
import org.apache.directory.server.core.integ.annotations.ApplyLdifs;
import org.apache.directory.server.core.integ.annotations.CleanupLevel;
import org.apache.directory.shared.ldap.entry.Entry;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test the lookup operation
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$
*/
@RunWith ( CiRunner.class )
@CleanupLevel ( Level.CLASS )
@ApplyLdifs( {
// Entry # 1
"dn: cn=test,ou=system\n" +
"objectClass: person\n" +
"cn: test\n" +
"sn: sn_test\n"
})
public class LookupIT
{
/** The directory service */
public static DirectoryService service;
/**
* Test a lookup( DN, "*") operation
*/
@Test
public void testLookupStar() throws Exception
{
LdapDN dn = new LdapDN( "cn=test,ou=system" );
Entry entry = service.getAdminSession().lookup( dn, new String[]{ "*" } );
assertNotNull( entry );
// Check that we don't have any operational attributes :
// We should have only 3 attributes : objectClass, cn and sn
assertEquals( 3, entry.size() );
// Check that all the user attributes are present
assertEquals( "test", entry.get( "cn" ).getString() );
assertEquals( "sn_test", entry.get( "sn" ).getString() );
assertTrue( entry.contains( "objectClass", "top", "person" ) );
}
/**
* Test a lookup( DN, "+") operation
*/
@Test
public void testLookupPlus() throws Exception
{
service.setDenormalizeOpAttrsEnabled( true );
LdapDN dn = new LdapDN( "cn=test,ou=system" );
Entry entry = service.getAdminSession().lookup( dn, new String[]{ "+" } );
assertNotNull( entry );
// We should have 5 attributes
- assertEquals( 5, entry.size() );
+ assertEquals( 7, entry.size() );
// Check that all the user attributes are present
assertEquals( "test", entry.get( "cn" ).getString() );
assertEquals( "sn_test", entry.get( "sn" ).getString() );
assertTrue( entry.contains( "objectClass", "top", "person" ) );
// Check that we have all the operational attributes :
// We should have 3 users attributes : objectClass, cn and sn
// and 2 operational attributes : createTime and createUser
assertNotNull( entry.get( "createTimestamp" ).getString() );
assertEquals( "uid=admin,ou=system", entry.get( "creatorsName" ).getString() );
}
/**
* Test a lookup( DN, []) operation
*/
@Test
public void testLookupEmptyAtrid() throws Exception
{
LdapDN dn = new LdapDN( "cn=test,ou=system" );
Entry entry = service.getAdminSession().lookup( dn, new String[]{} );
assertNotNull( entry );
// We should have 3 attributes
assertEquals( 3, entry.size() );
// Check that all the user attributes are present
assertEquals( "test", entry.get( "cn" ).getString() );
assertEquals( "sn_test", entry.get( "sn" ).getString() );
assertTrue( entry.contains( "objectClass", "top", "person" ) );
}
/**
* Test a lookup( DN ) operation
*/
@Test
public void testLookup() throws Exception
{
LdapDN dn = new LdapDN( "cn=test,ou=system" );
Entry entry = service.getAdminSession().lookup( dn );
assertNotNull( entry );
// We should have 3 attributes
assertEquals( 3, entry.size() );
// Check that all the user attributes are present
assertEquals( "test", entry.get( "cn" ).getString() );
assertEquals( "sn_test", entry.get( "sn" ).getString() );
assertTrue( entry.contains( "objectClass", "top", "person" ) );
}
}
| true | true | public void testLookupPlus() throws Exception
{
service.setDenormalizeOpAttrsEnabled( true );
LdapDN dn = new LdapDN( "cn=test,ou=system" );
Entry entry = service.getAdminSession().lookup( dn, new String[]{ "+" } );
assertNotNull( entry );
// We should have 5 attributes
assertEquals( 5, entry.size() );
// Check that all the user attributes are present
assertEquals( "test", entry.get( "cn" ).getString() );
assertEquals( "sn_test", entry.get( "sn" ).getString() );
assertTrue( entry.contains( "objectClass", "top", "person" ) );
// Check that we have all the operational attributes :
// We should have 3 users attributes : objectClass, cn and sn
// and 2 operational attributes : createTime and createUser
assertNotNull( entry.get( "createTimestamp" ).getString() );
assertEquals( "uid=admin,ou=system", entry.get( "creatorsName" ).getString() );
}
| public void testLookupPlus() throws Exception
{
service.setDenormalizeOpAttrsEnabled( true );
LdapDN dn = new LdapDN( "cn=test,ou=system" );
Entry entry = service.getAdminSession().lookup( dn, new String[]{ "+" } );
assertNotNull( entry );
// We should have 5 attributes
assertEquals( 7, entry.size() );
// Check that all the user attributes are present
assertEquals( "test", entry.get( "cn" ).getString() );
assertEquals( "sn_test", entry.get( "sn" ).getString() );
assertTrue( entry.contains( "objectClass", "top", "person" ) );
// Check that we have all the operational attributes :
// We should have 3 users attributes : objectClass, cn and sn
// and 2 operational attributes : createTime and createUser
assertNotNull( entry.get( "createTimestamp" ).getString() );
assertEquals( "uid=admin,ou=system", entry.get( "creatorsName" ).getString() );
}
|
diff --git a/src/com/nullprogram/chess/Chess.java b/src/com/nullprogram/chess/Chess.java
index 986edc4..21ff5cd 100644
--- a/src/com/nullprogram/chess/Chess.java
+++ b/src/com/nullprogram/chess/Chess.java
@@ -1,60 +1,61 @@
package com.nullprogram.chess;
import com.nullprogram.chess.gui.ChessFrame;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import javax.swing.UIManager;
/**
* Main class for the Chess game application.
*/
public final class Chess {
/** This class's Logger. */
private static final Logger LOG =
Logger.getLogger("com.nullprogram.chess.Chess");
/** The program's running title, prefix only. */
private static final String TITLE_PREFIX = "October Chess";
/**
* Hidden constructor.
*/
protected Chess() {
}
/**
* The main method of the Chess game application.
*
* @param args command line arguments
*/
public static void main(final String[] args) {
try {
String lnf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lnf);
} catch (Exception e) {
LOG.warning("Failed to set 'Look and Feel'");
}
ChessFrame frame = new ChessFrame();
}
/**
* Returns the full title for the program, including version number.
*
* @return the title of the program
*/
public static String getTitle() {
String version = "";
try {
InputStream s = Chess.class.getResourceAsStream("/version.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(s));
version = in.readLine();
+ in.close();
} catch (java.io.IOException e) {
LOG.warning("failed to read version info");
version = "";
}
return TITLE_PREFIX + " " + version;
}
}
| true | true | public static String getTitle() {
String version = "";
try {
InputStream s = Chess.class.getResourceAsStream("/version.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(s));
version = in.readLine();
} catch (java.io.IOException e) {
LOG.warning("failed to read version info");
version = "";
}
return TITLE_PREFIX + " " + version;
}
| public static String getTitle() {
String version = "";
try {
InputStream s = Chess.class.getResourceAsStream("/version.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(s));
version = in.readLine();
in.close();
} catch (java.io.IOException e) {
LOG.warning("failed to read version info");
version = "";
}
return TITLE_PREFIX + " " + version;
}
|
diff --git a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java
index 9809b0ff..14f3ca7b 100644
--- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java
+++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java
@@ -1,127 +1,127 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.nuget.tests.integration;
import com.intellij.execution.configurations.GeneralCommandLine;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.SimpleCommandLineProcessRunner;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.nuget.agent.parameters.NuGetPublishParameters;
import jetbrains.buildServer.nuget.agent.runner.publish.PackagesPublishRunner;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
/**
* Created by Eugene Petrenko ([email protected])
* Date: 22.07.11 1:25
*/
public class PackagesPublishIntegrationTest extends IntegrationTestBase {
protected NuGetPublishParameters myPublishParameters;
@BeforeMethod
@Override
protected void setUp() throws Exception {
super.setUp();
myPublishParameters = m.mock(NuGetPublishParameters.class);
m.checking(new Expectations(){{
allowing(myLogger).activityStarted(with(equal("push")), with(any(String.class)), with(any(String.class)));
allowing(myLogger).activityFinished(with(equal("push")), with(any(String.class)));
}});
}
@Test(dataProvider = NUGET_VERSIONS)
public void test_publish_packages(@NotNull final NuGet nuget) throws IOException, RunBuildException {
final File pkg = preparePackage(nuget);
callPublishRunner(nuget, pkg);
Assert.assertTrue(getCommandsOutput().contains("Your package was uploaded"));
}
@Test(dataProvider = NUGET_VERSIONS)
public void test_create_mock_package(@NotNull final NuGet nuget) throws IOException {
final File file = preparePackage(nuget);
System.out.println(file);
}
private File preparePackage(@NotNull final NuGet nuget) throws IOException {
@NotNull final File root = createTempDir();
final File spec = new File(root, "SamplePackage.nuspec");
FileUtil.copy(getTestDataPath("SamplePackage.nuspec"), spec);
GeneralCommandLine cmd = new GeneralCommandLine();
cmd.setExePath(nuget.getPath().getPath());
cmd.setWorkingDirectory(root);
cmd.addParameter("pack");
cmd.addParameter(spec.getPath());
cmd.addParameter("-Version");
long time = System.currentTimeMillis();
final long max = 65536;
String build = "";
for(int i = 0; i <4; i++) {
build = (Math.max(1, time % max)) + (build.length() == 0 ? "" : "." + build);
time /= max;
}
cmd.addParameter(build);
cmd.addParameter("-Verbose");
final ExecResult result = SimpleCommandLineProcessRunner.runCommand(cmd, new byte[0]);
System.out.println(result.getStdout());
System.out.println(result.getStderr());
Assert.assertEquals(0, result.getExitCode());
- File pkg = new File(root, "SamplePackage." + build + ".nupkg");
+ File pkg = new File(root, "jonnyzzz.nuget.teamcity.testPackage." + build + ".nupkg");
Assert.assertTrue(pkg.isFile());
return pkg;
}
private void callPublishRunner(@NotNull final NuGet nuget, @NotNull final File pkg) throws RunBuildException {
m.checking(new Expectations(){{
allowing(myPublishParameters).getFiles(); will(returnValue(Arrays.asList(pkg.getPath())));
allowing(myPublishParameters).getCreateOnly(); will(returnValue(true));
allowing(myPublishParameters).getNuGetExeFile(); will(returnValue(nuget.getPath()));
allowing(myPublishParameters).getPublishSource(); will(returnValue(null));
allowing(myPublishParameters).getApiKey(); will(returnValue(getQ()));
allowing(myParametersFactory).loadPublishParameters(myContext);will(returnValue(myPublishParameters));
}});
final PackagesPublishRunner runner = new PackagesPublishRunner(myActionFactory, myParametersFactory);
final BuildProcess proc = runner.createBuildProcess(myBuild, myContext);
assertRunSuccessfully(proc, BuildFinishedStatus.FINISHED_SUCCESS);
}
private String getQ() {
final int i1 = 88001628;
final int universe = 42;
final int num = 4015;
final String nuget = 91 + "be" + "-" + num + "cf638bcf";
return (i1 + "-" + "cb" + universe + "-" + 4 + "c") + 35 + "-" + nuget;
}
}
| true | true | private File preparePackage(@NotNull final NuGet nuget) throws IOException {
@NotNull final File root = createTempDir();
final File spec = new File(root, "SamplePackage.nuspec");
FileUtil.copy(getTestDataPath("SamplePackage.nuspec"), spec);
GeneralCommandLine cmd = new GeneralCommandLine();
cmd.setExePath(nuget.getPath().getPath());
cmd.setWorkingDirectory(root);
cmd.addParameter("pack");
cmd.addParameter(spec.getPath());
cmd.addParameter("-Version");
long time = System.currentTimeMillis();
final long max = 65536;
String build = "";
for(int i = 0; i <4; i++) {
build = (Math.max(1, time % max)) + (build.length() == 0 ? "" : "." + build);
time /= max;
}
cmd.addParameter(build);
cmd.addParameter("-Verbose");
final ExecResult result = SimpleCommandLineProcessRunner.runCommand(cmd, new byte[0]);
System.out.println(result.getStdout());
System.out.println(result.getStderr());
Assert.assertEquals(0, result.getExitCode());
File pkg = new File(root, "SamplePackage." + build + ".nupkg");
Assert.assertTrue(pkg.isFile());
return pkg;
}
| private File preparePackage(@NotNull final NuGet nuget) throws IOException {
@NotNull final File root = createTempDir();
final File spec = new File(root, "SamplePackage.nuspec");
FileUtil.copy(getTestDataPath("SamplePackage.nuspec"), spec);
GeneralCommandLine cmd = new GeneralCommandLine();
cmd.setExePath(nuget.getPath().getPath());
cmd.setWorkingDirectory(root);
cmd.addParameter("pack");
cmd.addParameter(spec.getPath());
cmd.addParameter("-Version");
long time = System.currentTimeMillis();
final long max = 65536;
String build = "";
for(int i = 0; i <4; i++) {
build = (Math.max(1, time % max)) + (build.length() == 0 ? "" : "." + build);
time /= max;
}
cmd.addParameter(build);
cmd.addParameter("-Verbose");
final ExecResult result = SimpleCommandLineProcessRunner.runCommand(cmd, new byte[0]);
System.out.println(result.getStdout());
System.out.println(result.getStderr());
Assert.assertEquals(0, result.getExitCode());
File pkg = new File(root, "jonnyzzz.nuget.teamcity.testPackage." + build + ".nupkg");
Assert.assertTrue(pkg.isFile());
return pkg;
}
|
diff --git a/test/test/ApplicationTest.java b/test/test/ApplicationTest.java
index 1e981d2..49dc2d5 100644
--- a/test/test/ApplicationTest.java
+++ b/test/test/ApplicationTest.java
@@ -1,36 +1,36 @@
package test;
import models.ContactDB;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
import play.mvc.Content;
import static play.test.Helpers.contentType;
import static play.test.Helpers.contentAsString;
/**
*
* Simple (JUnit) tests that can call all parts of a play app. If you are interested in mocking a whole application, see
* the wiki for more details.
*
*/
public class ApplicationTest {
/**
* Illustrates a simple test.
*/
@Test
public void simpleCheck() {
int a = 1 + 1;
assertThat(a).isEqualTo(2);
}
/**
* Illustrates how to render a template for testing.
*/
@Test
public void renderTemplate() {
- Content html = views.html.Index.render("test", null, null, ContactDB.getContacts());
+ Content html = views.html.Index.render("test", null, null, ContactDB.getContacts(null));
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(contentAsString(html)).contains("home page");
}
}
| true | true | public void renderTemplate() {
Content html = views.html.Index.render("test", null, null, ContactDB.getContacts());
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(contentAsString(html)).contains("home page");
}
| public void renderTemplate() {
Content html = views.html.Index.render("test", null, null, ContactDB.getContacts(null));
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(contentAsString(html)).contains("home page");
}
|
diff --git a/src/minecraft/org/spoutcraft/client/chunkcache/HeightMap.java b/src/minecraft/org/spoutcraft/client/chunkcache/HeightMap.java
index 6fb1d987..7835dc53 100644
--- a/src/minecraft/org/spoutcraft/client/chunkcache/HeightMap.java
+++ b/src/minecraft/org/spoutcraft/client/chunkcache/HeightMap.java
@@ -1,349 +1,350 @@
/*
* This file is part of Spoutcraft (http://www.spout.org/).
*
* Spoutcraft 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.
*
* Spoutcraft 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.spoutcraft.client.chunkcache;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import org.getspout.commons.util.map.TIntPairObjectHashMap;
import org.spoutcraft.client.chunkcache.HeightMap.HeightChunk;
import org.spoutcraft.client.io.FileUtil;
import org.spoutcraft.spoutcraftapi.packet.PacketUtil;
public class HeightMap {
private String worldName;
private final static int INITIAL_CAPACITY = 500;
private final TIntPairObjectHashMap<HeightChunk> cache = new TIntPairObjectHashMap<HeightChunk>(INITIAL_CAPACITY);
private static final HashMap<String, HeightMap> heightMaps = new HashMap<String, HeightMap>();
private static HeightMap lastMap = null; //Faster access to last height-map (which will be the case in most cases)
private int minX = 0, maxX = 0, minZ = 0, maxZ = 0;
private boolean initBounds = false;
private File file = null;
private HeightChunk lastChunk = null; //Faster access to last accessed chunk
public class HeightChunk {
public short heightmap[] = new short[16 * 16];
public final int x, z;
public byte[] idmap = new byte[16 * 16];
{
for(int i = 0; i < 256; i++) {
heightmap[i] = -1;
idmap[i] = -1;
}
}
public HeightChunk(int x, int z) {
this.x = x;
this.z = z;
}
public short getHeight(int x, int z) {
return heightmap[z << 4 | x];
}
public byte getBlockId(int x, int z) {
return idmap[z << 4 | x];
}
public void setHeight(int x, int z, short h) {
heightmap[z << 4 | x] = h;
}
public void setBlockId(int x, int z, byte id) {
idmap[z << 4 | x] = id;
}
}
public void clear() {
cache.clear();
initBounds = false;
}
public static HeightMap getHeightMap(String worldName) {
return getHeightMap(worldName, getFile(worldName));
}
public static HeightMap getHeightMap(String worldName, File file) {
if(lastMap != null && lastMap.getWorldName().equals(worldName)) {
lastMap.file = file;
return lastMap;
}
HeightMap ret = null;
if(heightMaps.containsKey(worldName)) {
ret = heightMaps.get(worldName);
ret.file = file;
} else {
HeightMap map = new HeightMap(worldName);
map.file = file;
heightMaps.put(worldName, map);
if(file.exists()) {
map.load();
}
ret = map;
}
lastMap = ret;
return ret;
}
private HeightMap(String worldName) {
this.worldName = worldName;
}
/*
* Format of the file is this:
* worldName:String
* minX:int
* maxX:int
* minZ:int
* maxZ:int
* height-map:short[], where map[0] is at minX, minZ and map[last] is at maxX, maxZ
*/
public void load() {
synchronized (cache) {
clear();
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
String name = PacketUtil.readString(in);
if(!name.equals(getWorldName())) {
System.out.println("World names do not match: "+name+" [file] != "+getWorldName()+" [game]. Compensating...");
//TODO compensate
}
minX = in.readInt();
maxX = in.readInt();
minZ = in.readInt();
maxZ = in.readInt();
initBounds = true;
int x = minX;
int z = minZ;
try {
while(true) {
x = in.readInt();
z = in.readInt();
HeightChunk chunk = new HeightChunk(x, z);
for(int i = 0; i < 256; i++) {
chunk.heightmap[i] = in.readShort();
chunk.idmap[i] = in.readByte();
}
addChunk(chunk);
}
} catch (EOFException e) {}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
cache.clear();
initBounds = false;
System.out.println("Error while loading persistent copy of the heightmap. Clearing the cache.");
}
File progress = new File(file.getAbsoluteFile() + ".inProgress");
if(progress.exists()) {
System.out.println("Found in-progress file!");
- HeightMap progressMap = getHeightMap(getWorldName(), progress);
+ HeightMap progressMap = new HeightMap(getWorldName());
+ progressMap.file = progress;
progressMap.load();
for(HeightChunk chunk:progressMap.cache.valueCollection()) {
if(chunk.getHeight(0, 0) != -1) {
addChunk(chunk);
}
}
heightMaps.remove(progressMap);
progress.delete();
}
}
}
private void addChunk(HeightChunk chunk) {
synchronized (cache) {
int x = chunk.x;
int z = chunk.z;
cache.put(x, z, chunk);
if(!initBounds) {
minX = x;
maxX = x;
minZ = z;
maxZ = z;
initBounds = true;
} else {
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minZ = Math.min(minZ, z);
maxZ = Math.max(maxZ, z);
}
}
}
public void save() {
synchronized (cache) {
try {
File progress = new File(file.getAbsoluteFile() + ".inProgress");
DataOutputStream out = new DataOutputStream(new FileOutputStream(progress));
PacketUtil.writeString(out, getWorldName());
out.writeInt(minX);
out.writeInt(maxX);
out.writeInt(minZ);
out.writeInt(maxZ);
for(HeightChunk chunk : cache.valueCollection()) {
if(chunk == null) {
continue;
} else {
out.writeInt(chunk.x);
out.writeInt(chunk.z);
for(int i = 0; i < 256; i++) {
out.writeShort(chunk.heightmap[i]);
out.writeByte(chunk.idmap[i]);
}
}
}
out.close();
//Make sure that we don't loose older stuff when someone quits.
File older = new File(file.getAbsoluteFile() + ".old");
file.renameTo(older);
progress.renameTo(file);
older.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static File getFile(String worldName) {
File folder = new File(FileUtil.getSpoutcraftDirectory(), "heightmap");
if(!folder.isDirectory()) {
folder.delete();
}
if(!folder.exists()){
folder.mkdirs();
}
return new File(FileUtil.getSpoutcraftDirectory(), "heightmap/"+worldName+".hma");
}
// public boolean hasHeight(int x, int z) {
// synchronized (cache) {
// return cache.containsKey(x, z);
// }
// }
public HeightChunk getChunk(int x, int z) {
return getChunk(x, z, false);
}
public HeightChunk getChunk(int x, int z, boolean force) {
if(lastChunk != null && lastChunk.x == x && lastChunk.z == z) {
return lastChunk;
} else {
synchronized (cache) {
lastChunk = cache.get(x, z);
if(lastChunk == null) {
lastChunk = new HeightChunk(x, z);
addChunk(lastChunk);
}
return lastChunk;
}
}
}
public short getHeight(int x, int z) {
int cX = (x >> 4);
int cZ = (z >> 4);
x &= 0xF;
z &= 0xF;
if(lastChunk != null && lastChunk.x == cX && lastChunk.z == cZ) {
return lastChunk.heightmap[z << 4 | x];
}
synchronized (cache) {
if(cache.containsKey(cX, cZ)) {
lastChunk = cache.get(cX, cZ);
return lastChunk.heightmap[z << 4 | x];
} else {
return -1;
}
}
}
public byte getBlockId(int x, int z) {
int cX = (x >> 4);
int cZ = (z >> 4);
x &= 0xF;
z &= 0xF;
if(lastChunk != null && lastChunk.x == cX && lastChunk.z == cZ) {
return lastChunk.idmap[z << 4 | x];
}
synchronized (cache) {
if(cache.containsKey(cX, cZ)) {
lastChunk = cache.get(cX, cZ);
return lastChunk.idmap[z << 4 | x];
} else {
return -1;
}
}
}
public void setHighestBlock(int x, int z, short height, byte id) {
int cX = (x >> 4);
int cZ = (z >> 4);
x &= 0xF;
z &= 0xF;
synchronized (cache) {
if(!(lastChunk != null && lastChunk.x == cX && lastChunk.z == cZ)) {
if(cache.containsKey(cX, cZ)) {
lastChunk = cache.get(cX, cZ);
} else {
HeightChunk chunk = new HeightChunk(cX, cZ);
chunk.heightmap[z << 4 | x] = height;
chunk.idmap [z << 4 | x] = id;
lastChunk = chunk;
addChunk(chunk);
return;
}
}
lastChunk.heightmap[z << 4 | x] = height;
lastChunk.idmap[z << 4 | x] = id;
}
}
public String getWorldName() {
return worldName;
}
public int getMinX() {
return minX;
}
public int getMaxX() {
return maxX;
}
public int getMinZ() {
return minZ;
}
public int getMaxZ() {
return maxZ;
}
}
| true | true | public void load() {
synchronized (cache) {
clear();
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
String name = PacketUtil.readString(in);
if(!name.equals(getWorldName())) {
System.out.println("World names do not match: "+name+" [file] != "+getWorldName()+" [game]. Compensating...");
//TODO compensate
}
minX = in.readInt();
maxX = in.readInt();
minZ = in.readInt();
maxZ = in.readInt();
initBounds = true;
int x = minX;
int z = minZ;
try {
while(true) {
x = in.readInt();
z = in.readInt();
HeightChunk chunk = new HeightChunk(x, z);
for(int i = 0; i < 256; i++) {
chunk.heightmap[i] = in.readShort();
chunk.idmap[i] = in.readByte();
}
addChunk(chunk);
}
} catch (EOFException e) {}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
cache.clear();
initBounds = false;
System.out.println("Error while loading persistent copy of the heightmap. Clearing the cache.");
}
File progress = new File(file.getAbsoluteFile() + ".inProgress");
if(progress.exists()) {
System.out.println("Found in-progress file!");
HeightMap progressMap = getHeightMap(getWorldName(), progress);
progressMap.load();
for(HeightChunk chunk:progressMap.cache.valueCollection()) {
if(chunk.getHeight(0, 0) != -1) {
addChunk(chunk);
}
}
heightMaps.remove(progressMap);
progress.delete();
}
}
}
| public void load() {
synchronized (cache) {
clear();
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
String name = PacketUtil.readString(in);
if(!name.equals(getWorldName())) {
System.out.println("World names do not match: "+name+" [file] != "+getWorldName()+" [game]. Compensating...");
//TODO compensate
}
minX = in.readInt();
maxX = in.readInt();
minZ = in.readInt();
maxZ = in.readInt();
initBounds = true;
int x = minX;
int z = minZ;
try {
while(true) {
x = in.readInt();
z = in.readInt();
HeightChunk chunk = new HeightChunk(x, z);
for(int i = 0; i < 256; i++) {
chunk.heightmap[i] = in.readShort();
chunk.idmap[i] = in.readByte();
}
addChunk(chunk);
}
} catch (EOFException e) {}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
cache.clear();
initBounds = false;
System.out.println("Error while loading persistent copy of the heightmap. Clearing the cache.");
}
File progress = new File(file.getAbsoluteFile() + ".inProgress");
if(progress.exists()) {
System.out.println("Found in-progress file!");
HeightMap progressMap = new HeightMap(getWorldName());
progressMap.file = progress;
progressMap.load();
for(HeightChunk chunk:progressMap.cache.valueCollection()) {
if(chunk.getHeight(0, 0) != -1) {
addChunk(chunk);
}
}
heightMaps.remove(progressMap);
progress.delete();
}
}
}
|
diff --git a/CPP/src/ic/doc/cpp/server/handler/student/LoginActionHandler.java b/CPP/src/ic/doc/cpp/server/handler/student/LoginActionHandler.java
index 5fb0e69..25231f3 100644
--- a/CPP/src/ic/doc/cpp/server/handler/student/LoginActionHandler.java
+++ b/CPP/src/ic/doc/cpp/server/handler/student/LoginActionHandler.java
@@ -1,84 +1,86 @@
package ic.doc.cpp.server.handler.student;
import ic.doc.cpp.server.dao.CompanyUserDao;
import ic.doc.cpp.server.dao.StudentUserDao;
import ic.doc.cpp.server.domain.CompanyUser;
import ic.doc.cpp.server.domain.StudentUser;
import ic.doc.cpp.server.util.Security;
import ic.doc.cpp.shared.action.student.Login;
import ic.doc.cpp.shared.action.student.LoginResult;
import ic.doc.cpp.shared.exception.LoginException;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.google.inject.Provider;
public class LoginActionHandler implements ActionHandler<Login, LoginResult> {
private final Provider<HttpServletRequest> requestProvider;
@Inject
public LoginActionHandler(final Provider<HttpServletRequest> requestProvider) {
this.requestProvider = requestProvider;
}
@Override
public LoginResult execute(Login action, ExecutionContext context)
throws ActionException {
LoginResult result = null;
if (action.getType().equals("student")) {
StudentUserDao userDao = new StudentUserDao();
try {
StudentUser user = userDao.retrieveUser(action.getLogin());
if (user != null && isValidLogin(action, user.getPassword(), user.getSalt())) {
HttpSession session = requestProvider.get().getSession();
session.setAttribute("login.authenticated", action.getLogin());
result = new LoginResult(session.getId());
} else {
throw new LoginException("Invalid user name or password.");
}
} catch (Exception e) {
throw new ActionException(e);
}
} else if (action.getType().equals("company")){
CompanyUserDao userDao = new CompanyUserDao();
try {
CompanyUser user = userDao.retrieveUser(action.getLogin());
if (user != null && isValidLogin(action, user.getPassword(), user.getSalt())) {
HttpSession session = requestProvider.get().getSession();
session.setAttribute("login.authenticated", action.getLogin());
result = new LoginResult(session.getId());
+ } else {
+ throw new LoginException("Invalid user name or password.");
}
} catch (Exception e) {
throw new ActionException(e);
}
} else {
throw new ActionException("Invalid type of user.");
}
return result;
}
private boolean isValidLogin(Login action, String password, String salt) {
String hash = Security.sha256(salt + action.getPassword());
return hash.equals(password);
}
@Override
public void undo(Login action, LoginResult result, ExecutionContext context)
throws ActionException {
}
@Override
public Class<Login> getActionType() {
return Login.class;
}
}
| true | true | public LoginResult execute(Login action, ExecutionContext context)
throws ActionException {
LoginResult result = null;
if (action.getType().equals("student")) {
StudentUserDao userDao = new StudentUserDao();
try {
StudentUser user = userDao.retrieveUser(action.getLogin());
if (user != null && isValidLogin(action, user.getPassword(), user.getSalt())) {
HttpSession session = requestProvider.get().getSession();
session.setAttribute("login.authenticated", action.getLogin());
result = new LoginResult(session.getId());
} else {
throw new LoginException("Invalid user name or password.");
}
} catch (Exception e) {
throw new ActionException(e);
}
} else if (action.getType().equals("company")){
CompanyUserDao userDao = new CompanyUserDao();
try {
CompanyUser user = userDao.retrieveUser(action.getLogin());
if (user != null && isValidLogin(action, user.getPassword(), user.getSalt())) {
HttpSession session = requestProvider.get().getSession();
session.setAttribute("login.authenticated", action.getLogin());
result = new LoginResult(session.getId());
}
} catch (Exception e) {
throw new ActionException(e);
}
} else {
throw new ActionException("Invalid type of user.");
}
return result;
}
| public LoginResult execute(Login action, ExecutionContext context)
throws ActionException {
LoginResult result = null;
if (action.getType().equals("student")) {
StudentUserDao userDao = new StudentUserDao();
try {
StudentUser user = userDao.retrieveUser(action.getLogin());
if (user != null && isValidLogin(action, user.getPassword(), user.getSalt())) {
HttpSession session = requestProvider.get().getSession();
session.setAttribute("login.authenticated", action.getLogin());
result = new LoginResult(session.getId());
} else {
throw new LoginException("Invalid user name or password.");
}
} catch (Exception e) {
throw new ActionException(e);
}
} else if (action.getType().equals("company")){
CompanyUserDao userDao = new CompanyUserDao();
try {
CompanyUser user = userDao.retrieveUser(action.getLogin());
if (user != null && isValidLogin(action, user.getPassword(), user.getSalt())) {
HttpSession session = requestProvider.get().getSession();
session.setAttribute("login.authenticated", action.getLogin());
result = new LoginResult(session.getId());
} else {
throw new LoginException("Invalid user name or password.");
}
} catch (Exception e) {
throw new ActionException(e);
}
} else {
throw new ActionException("Invalid type of user.");
}
return result;
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorNotesPart.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorNotesPart.java
index 368a43542..7aee8b6e3 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorNotesPart.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorNotesPart.java
@@ -1,135 +1,135 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies 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:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonTextSupport;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.internal.EditorAreaHelper;
import org.eclipse.ui.internal.WorkbenchPage;
/**
* @author Shawn Minto
* @author Steffen Pingel
*/
public class TaskEditorNotesPart extends AbstractTaskEditorPart {
private String value;
private AbstractTask task;
private SourceViewer noteEditor;
public TaskEditorNotesPart() {
setPartName(Messages.TaskPlanningEditor_Notes);
}
@Override
public void initialize(AbstractTaskEditorPage taskEditorPage) {
super.initialize(taskEditorPage);
task = (AbstractTask) taskEditorPage.getTask();
}
private boolean notesEqual() {
if (task.getNotes() == null && value == null) {
return true;
}
if (task.getNotes() != null && value != null) {
return task.getNotes().equals(value);
}
return false;
}
@Override
public void commit(boolean onSave) {
Assert.isNotNull(task);
if (!notesEqual()) {
task.setNotes(value);
// XXX REFRESH THE TASLKIST
}
super.commit(onSave);
}
@Override
public void createControl(Composite parent, FormToolkit toolkit) {
this.value = task.getNotes();
if (this.value == null) {
this.value = ""; //$NON-NLS-1$
}
Section section = createSection(parent, toolkit, this.value != null && this.value.length() > 0);
Composite composite = toolkit.createComposite(section);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
composite.setLayout(layout);
- noteEditor = new SourceViewer(parent, null, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
+ noteEditor = new SourceViewer(composite, null, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
noteEditor.configure(new RepositoryTextViewerConfiguration(getModel().getTaskRepository(), true));
CommonTextSupport textSupport = (CommonTextSupport) getTaskEditorPage().getAdapter(CommonTextSupport.class);
if (textSupport != null) {
textSupport.configure(noteEditor, new Document(this.value), true);
}
noteEditor.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
TaskEditorNotesPart.this.value = noteEditor.getTextWidget().getText();
markDirty();
}
});
final GridData gd = new GridData(GridData.FILL_BOTH);
int widthHint = 0;
if (getManagedForm() != null && getManagedForm().getForm() != null) {
widthHint = getManagedForm().getForm().getClientArea().width - 90;
}
if (widthHint <= 0 && getTaskEditorPage().getEditor().getEditorSite() != null
&& getTaskEditorPage().getEditor().getEditorSite().getPage() != null) {
EditorAreaHelper editorManager = ((WorkbenchPage) getTaskEditorPage().getEditor().getEditorSite().getPage()).getEditorPresentation();
if (editorManager != null && editorManager.getLayoutPart() != null) {
widthHint = editorManager.getLayoutPart().getControl().getBounds().width - 90;
}
}
if (widthHint <= 0) {
widthHint = 100;
}
gd.widthHint = widthHint;
gd.minimumHeight = 100;
gd.grabExcessHorizontalSpace = true;
noteEditor.getControl().setLayoutData(gd);
noteEditor.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
noteEditor.setEditable(true);
toolkit.paintBordersFor(composite);
section.setClient(composite);
setSection(toolkit, section);
}
}
| true | true | public void createControl(Composite parent, FormToolkit toolkit) {
this.value = task.getNotes();
if (this.value == null) {
this.value = ""; //$NON-NLS-1$
}
Section section = createSection(parent, toolkit, this.value != null && this.value.length() > 0);
Composite composite = toolkit.createComposite(section);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
composite.setLayout(layout);
noteEditor = new SourceViewer(parent, null, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
noteEditor.configure(new RepositoryTextViewerConfiguration(getModel().getTaskRepository(), true));
CommonTextSupport textSupport = (CommonTextSupport) getTaskEditorPage().getAdapter(CommonTextSupport.class);
if (textSupport != null) {
textSupport.configure(noteEditor, new Document(this.value), true);
}
noteEditor.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
TaskEditorNotesPart.this.value = noteEditor.getTextWidget().getText();
markDirty();
}
});
final GridData gd = new GridData(GridData.FILL_BOTH);
int widthHint = 0;
if (getManagedForm() != null && getManagedForm().getForm() != null) {
widthHint = getManagedForm().getForm().getClientArea().width - 90;
}
if (widthHint <= 0 && getTaskEditorPage().getEditor().getEditorSite() != null
&& getTaskEditorPage().getEditor().getEditorSite().getPage() != null) {
EditorAreaHelper editorManager = ((WorkbenchPage) getTaskEditorPage().getEditor().getEditorSite().getPage()).getEditorPresentation();
if (editorManager != null && editorManager.getLayoutPart() != null) {
widthHint = editorManager.getLayoutPart().getControl().getBounds().width - 90;
}
}
if (widthHint <= 0) {
widthHint = 100;
}
gd.widthHint = widthHint;
gd.minimumHeight = 100;
gd.grabExcessHorizontalSpace = true;
noteEditor.getControl().setLayoutData(gd);
noteEditor.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
noteEditor.setEditable(true);
toolkit.paintBordersFor(composite);
section.setClient(composite);
setSection(toolkit, section);
}
| public void createControl(Composite parent, FormToolkit toolkit) {
this.value = task.getNotes();
if (this.value == null) {
this.value = ""; //$NON-NLS-1$
}
Section section = createSection(parent, toolkit, this.value != null && this.value.length() > 0);
Composite composite = toolkit.createComposite(section);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
composite.setLayout(layout);
noteEditor = new SourceViewer(composite, null, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
noteEditor.configure(new RepositoryTextViewerConfiguration(getModel().getTaskRepository(), true));
CommonTextSupport textSupport = (CommonTextSupport) getTaskEditorPage().getAdapter(CommonTextSupport.class);
if (textSupport != null) {
textSupport.configure(noteEditor, new Document(this.value), true);
}
noteEditor.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
TaskEditorNotesPart.this.value = noteEditor.getTextWidget().getText();
markDirty();
}
});
final GridData gd = new GridData(GridData.FILL_BOTH);
int widthHint = 0;
if (getManagedForm() != null && getManagedForm().getForm() != null) {
widthHint = getManagedForm().getForm().getClientArea().width - 90;
}
if (widthHint <= 0 && getTaskEditorPage().getEditor().getEditorSite() != null
&& getTaskEditorPage().getEditor().getEditorSite().getPage() != null) {
EditorAreaHelper editorManager = ((WorkbenchPage) getTaskEditorPage().getEditor().getEditorSite().getPage()).getEditorPresentation();
if (editorManager != null && editorManager.getLayoutPart() != null) {
widthHint = editorManager.getLayoutPart().getControl().getBounds().width - 90;
}
}
if (widthHint <= 0) {
widthHint = 100;
}
gd.widthHint = widthHint;
gd.minimumHeight = 100;
gd.grabExcessHorizontalSpace = true;
noteEditor.getControl().setLayoutData(gd);
noteEditor.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
noteEditor.setEditable(true);
toolkit.paintBordersFor(composite);
section.setClient(composite);
setSection(toolkit, section);
}
|
diff --git a/signserver/modules/SignServer-ejb/src/java/org/signserver/web/SignServerHealthCheck.java b/signserver/modules/SignServer-ejb/src/java/org/signserver/web/SignServerHealthCheck.java
index da8a24e14..e1b75fc90 100644
--- a/signserver/modules/SignServer-ejb/src/java/org/signserver/web/SignServerHealthCheck.java
+++ b/signserver/modules/SignServer-ejb/src/java/org/signserver/web/SignServerHealthCheck.java
@@ -1,230 +1,231 @@
package org.signserver.web;
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software 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 any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.List;
import javax.ejb.EJB;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ejbca.ui.web.pub.cluster.IHealthCheck;
import org.signserver.common.GlobalConfiguration;
import org.signserver.common.InvalidWorkerIdException;
import org.signserver.common.ServiceLocator;
import org.signserver.common.WorkerStatus;
import org.signserver.ejb.interfaces.IGlobalConfigurationSession;
import org.signserver.ejb.interfaces.IWorkerSession;
import org.signserver.healthcheck.HealthCheckUtils;
/**
* SignServer Health Checker.
*
* Does the following system checks.
*
* Not about to run out if memory (configurable through web.xml with param "MinimumFreeMemory")
* Database connection can be established.
* All SignerTokens are active if not set as offline.
*
* If a maintenance file has been configured during build, it can be used to enable maintenance mode.
* When enabled, none of the about system checks are performed, instead a down-for-maintenance message is returned.
*
* @author Philip Vendil
* @version $Id$
*/
public class SignServerHealthCheck implements IHealthCheck {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
SignServerHealthCheck.class);
@EJB
private IGlobalConfigurationSession.IRemote globalConfigurationSession;
@EJB
private IWorkerSession.IRemote signserversession;
private int minfreememory;
private String checkDBString;
private String maintenanceFile;
private String maintenancePropertyName;
private IGlobalConfigurationSession.IRemote getGlobalConfigurationSession() {
if (globalConfigurationSession == null) {
try {
globalConfigurationSession = ServiceLocator.getInstance().lookupRemote(
IGlobalConfigurationSession.IRemote.class);
} catch (NamingException e) {
LOG.error(e);
}
}
return globalConfigurationSession;
}
private IWorkerSession.IRemote getWorkerSession() {
if (signserversession == null) {
try {
signserversession = ServiceLocator.getInstance().lookupRemote(IWorkerSession.IRemote.class);
} catch (NamingException e) {
LOG.error(e);
}
}
return signserversession;
}
public void init(ServletConfig config) {
minfreememory = Integer.parseInt(config.getInitParameter("MinimumFreeMemory")) * 1024 * 1024;
checkDBString = config.getInitParameter("checkDBString");
maintenanceFile = config.getInitParameter("MaintenanceFile");
maintenancePropertyName = config.getInitParameter("MaintenancePropertyName");
initMaintenanceFile();
}
public String checkHealth(HttpServletRequest request) {
LOG.debug("Starting HealthCheck health check requested by : " + request.getRemoteAddr());
StringBuilder sb = new StringBuilder();
checkMaintenance(sb);
if (sb.length() > 0) {
// if Down for maintenance do not perform more checks
return sb.toString();
}
String errormessage = "";
errormessage += HealthCheckUtils.checkDB(checkDBString);
if (errormessage.equals("")) {
errormessage += HealthCheckUtils.checkMemory(minfreememory);
errormessage += checkSigners();
}
if (errormessage.equals("")) {
// everything seems ok.
errormessage = null;
}
return errormessage;
}
private String checkSigners() {
final StringBuilder sb = new StringBuilder();
Iterator<Integer> iter = getWorkerSession().getWorkers(GlobalConfiguration.WORKERTYPE_PROCESSABLE).iterator();
while (iter.hasNext()) {
int processableId = ((Integer) iter.next()).intValue();
try {
WorkerStatus workerStatus = getWorkerSession().getStatus(processableId);
if (workerStatus.isDisabled()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Not checking worker " + processableId + " as it is disabled");
}
} else {
final List<String> fatalErrors = workerStatus.getFatalErrors();
if (!fatalErrors.isEmpty()) {
for (String error : fatalErrors) {
sb.append("Worker ")
.append(workerStatus.getWorkerId())
.append(": ")
.append(error)
.append("\n");
}
}
}
} catch (InvalidWorkerIdException e) {
LOG.error(e.getMessage(), e);
}
}
if (sb.length() > 0) {
LOG.error("Health check reports error:\n" + sb.toString());
}
return sb.toString();
}
private void checkMaintenance(final StringBuilder sb) {
if (StringUtils.isEmpty(maintenanceFile)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Maintenance file not specified, node will be monitored");
}
return;
}
File maintFile = new File(maintenanceFile);
InputStream in = null;
try {
in = new FileInputStream(maintFile);
final Properties maintenanceProperties = new Properties();
maintenanceProperties.load(in);
final String maintenancePropertyValue = maintenanceProperties.getProperty(maintenancePropertyName);
if (maintenancePropertyValue == null) {
LOG.info("Could not find property " + maintenancePropertyName + " in " + maintenanceFile +
", will continue to monitor this node");
} else if (Boolean.TRUE.toString().equalsIgnoreCase(maintenancePropertyValue)) {
sb.append("MAINT: ").append(maintenancePropertyName);
}
} catch (IOException e) {
+ sb.append("MAINT: maintenance property file could not be read");
if (LOG.isDebugEnabled()) {
LOG.debug("Could not read Maintenance File. Expected to find file at: " +
maintFile.getAbsolutePath());
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOG.error("Error closing file: ", e);
}
}
}
}
private void initMaintenanceFile() {
if (StringUtils.isEmpty(maintenanceFile)) {
LOG.debug("Maintenance file not specified, node will be monitored");
} else {
Properties maintenanceProperties = new Properties();
File maintFile = new File(maintenanceFile);
InputStream in = null;
try {
in = new FileInputStream(maintFile);
maintenanceProperties.load(in);
} catch (IOException e) {
LOG.debug("Could not read Maintenance File. Expected to find file at: " +
maintFile.getAbsolutePath());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOG.error("Error closing file: ", e);
}
}
}
}
}
}
| true | true | private void checkMaintenance(final StringBuilder sb) {
if (StringUtils.isEmpty(maintenanceFile)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Maintenance file not specified, node will be monitored");
}
return;
}
File maintFile = new File(maintenanceFile);
InputStream in = null;
try {
in = new FileInputStream(maintFile);
final Properties maintenanceProperties = new Properties();
maintenanceProperties.load(in);
final String maintenancePropertyValue = maintenanceProperties.getProperty(maintenancePropertyName);
if (maintenancePropertyValue == null) {
LOG.info("Could not find property " + maintenancePropertyName + " in " + maintenanceFile +
", will continue to monitor this node");
} else if (Boolean.TRUE.toString().equalsIgnoreCase(maintenancePropertyValue)) {
sb.append("MAINT: ").append(maintenancePropertyName);
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not read Maintenance File. Expected to find file at: " +
maintFile.getAbsolutePath());
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOG.error("Error closing file: ", e);
}
}
}
}
| private void checkMaintenance(final StringBuilder sb) {
if (StringUtils.isEmpty(maintenanceFile)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Maintenance file not specified, node will be monitored");
}
return;
}
File maintFile = new File(maintenanceFile);
InputStream in = null;
try {
in = new FileInputStream(maintFile);
final Properties maintenanceProperties = new Properties();
maintenanceProperties.load(in);
final String maintenancePropertyValue = maintenanceProperties.getProperty(maintenancePropertyName);
if (maintenancePropertyValue == null) {
LOG.info("Could not find property " + maintenancePropertyName + " in " + maintenanceFile +
", will continue to monitor this node");
} else if (Boolean.TRUE.toString().equalsIgnoreCase(maintenancePropertyValue)) {
sb.append("MAINT: ").append(maintenancePropertyName);
}
} catch (IOException e) {
sb.append("MAINT: maintenance property file could not be read");
if (LOG.isDebugEnabled()) {
LOG.debug("Could not read Maintenance File. Expected to find file at: " +
maintFile.getAbsolutePath());
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOG.error("Error closing file: ", e);
}
}
}
}
|
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java
index e5175e047..dc6f99466 100644
--- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java
+++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java
@@ -1,358 +1,358 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.tasks.core;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
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.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.mylar.context.core.MylarStatusHandler;
import org.eclipse.mylar.internal.tasks.core.TaskRepositoriesExternalizer;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class TaskRepositoryManager {
public static final String OLD_REPOSITORIES_FILE = "repositories.xml";
public static final String DEFAULT_REPOSITORIES_FILE = "repositories.xml.zip";
public static final String PREF_REPOSITORIES = "org.eclipse.mylar.tasklist.repositories.";
private Map<String, AbstractRepositoryConnector> repositoryConnectors = new HashMap<String, AbstractRepositoryConnector>();
private Map<String, Set<TaskRepository>> repositoryMap = new HashMap<String, Set<TaskRepository>>();
private Set<ITaskRepositoryListener> listeners = new HashSet<ITaskRepositoryListener>();
private Set<TaskRepository> orphanedRepositories = new HashSet<TaskRepository>();
public static final String MESSAGE_NO_REPOSITORY = "No repository available, please add one using the Task Repositories view.";
public static final String PREFIX_LOCAL = "local-";
private TaskRepositoriesExternalizer externalizer = new TaskRepositoriesExternalizer();
private TaskList taskList;
public TaskRepositoryManager(TaskList taskList) {
this.taskList = taskList;
}
public Collection<AbstractRepositoryConnector> getRepositoryConnectors() {
return Collections.unmodifiableCollection(repositoryConnectors.values());
}
public AbstractRepositoryConnector getRepositoryConnector(String kind) {
return repositoryConnectors.get(kind);
}
public AbstractRepositoryConnector getRepositoryConnector(AbstractRepositoryTask task) {
return getRepositoryConnector(task.getRepositoryKind());
}
public void addRepositoryConnector(AbstractRepositoryConnector repositoryConnector) {
if (!repositoryConnectors.values().contains(repositoryConnector)) {
repositoryConnector.init(taskList);
repositoryConnectors.put(repositoryConnector.getRepositoryType(), repositoryConnector);
}
}
public void addRepository(TaskRepository repository, String repositoryFilePath) {
Set<TaskRepository> repositories;
if (!repositoryMap.containsKey(repository.getKind())) {
repositories = new HashSet<TaskRepository>();
repositoryMap.put(repository.getKind(), repositories);
} else {
repositories = repositoryMap.get(repository.getKind());
}
repositories.add(repository);
saveRepositories(repositoryFilePath);
for (ITaskRepositoryListener listener : listeners) {
listener.repositoryAdded(repository);
}
}
public void removeRepository(TaskRepository repository, String repositoryFilePath) {
Set<TaskRepository> repositories = repositoryMap.get(repository.getKind());
if (repositories != null) {
repository.flushAuthenticationCredentials();
repositories.remove(repository);
}
saveRepositories(repositoryFilePath);
for (ITaskRepositoryListener listener : listeners) {
listener.repositoryRemoved(repository);
}
}
public void addListener(ITaskRepositoryListener listener) {
listeners.add(listener);
}
public void removeListener(ITaskRepositoryListener listener) {
listeners.remove(listener);
}
public TaskRepository getRepository(String kind, String urlString) {
if (repositoryMap.containsKey(kind)) {
for (TaskRepository repository : repositoryMap.get(kind)) {
if (repository.getUrl().equals(urlString)) {
return repository;
}
}
}
return null;
}
/**
* @return first repository that matches the given url
*/
public TaskRepository getRepository(String urlString) {
for (String kind : repositoryMap.keySet()) {
for (TaskRepository repository : repositoryMap.get(kind)) {
if (repository.getUrl().equals(urlString)) {
return repository;
}
}
}
return null;
}
/**
* @return the first connector to accept the URL
*/
public AbstractRepositoryConnector getConnectorForRepositoryTaskUrl(String url) {
for (AbstractRepositoryConnector connector : getRepositoryConnectors()) {
if (connector.getRepositoryUrlFromTaskUrl(url) != null) {
return connector;
}
}
return null;
}
public Set<TaskRepository> getRepositories(String kind) {
if (repositoryMap.containsKey(kind)) {
return repositoryMap.get(kind);
} else {
return Collections.emptySet();
}
}
public List<TaskRepository> getAllRepositories() {
List<TaskRepository> repositories = new ArrayList<TaskRepository>();
for (AbstractRepositoryConnector repositoryConnector : repositoryConnectors.values()) {
if (repositoryMap.containsKey(repositoryConnector.getRepositoryType())) {
repositories.addAll(repositoryMap.get(repositoryConnector.getRepositoryType()));
}
}
return repositories;
}
public TaskRepository getRepositoryForActiveTask(String repositoryKind, TaskList taskList) {
List<ITask> activeTasks = taskList.getActiveTasks();
if (activeTasks.size() == 1) {
ITask activeTask = activeTasks.get(0);
if (activeTask instanceof AbstractRepositoryTask) {
String repositoryUrl = AbstractRepositoryTask.getRepositoryUrl(activeTask.getHandleIdentifier());
for (TaskRepository repository : getRepositories(repositoryKind)) {
if (repository.getUrl().equals(repositoryUrl)) {
return repository;
}
}
}
}
return null;
}
/**
* TODO: implement default support, this just returns first found
*/
public TaskRepository getDefaultRepository(String kind) {
// HACK: returns first repository found
if (repositoryMap.containsKey(kind)) {
for (TaskRepository repository : repositoryMap.get(kind)) {
return repository;
}
} else {
Collection<Set<TaskRepository>> values = repositoryMap.values();
if (!values.isEmpty()) {
Set<TaskRepository> repoistorySet = values.iterator().next();
return repoistorySet.iterator().next();
}
}
return null;
}
public Map<String, Set<TaskRepository>> readRepositories(String repositoriesFilePath) {
repositoryMap.clear();
orphanedRepositories.clear();
loadRepositories(repositoriesFilePath);
for (ITaskRepositoryListener listener : listeners) {
listener.repositoriesRead();
}
return repositoryMap;
}
private void loadRepositories(String repositoriesFilePath) {
try {
// String dataDirectory =
// TasksUiPlugin.getDefault().getDataDirectory();
File repositoriesFile = new File(repositoriesFilePath);
// Will only load repositories for which a connector exists
for (AbstractRepositoryConnector repositoryConnector : repositoryConnectors.values()) {
repositoryMap.put(repositoryConnector.getRepositoryType(), new HashSet<TaskRepository>());
}
if (repositoriesFile.exists()) {
Set<TaskRepository> repositories = externalizer.readRepositoriesFromXML(repositoriesFile);
if (repositories != null && repositories.size() > 0) {
for (TaskRepository repository : repositories) {
if (repositoryMap.containsKey(repository.getKind())) {
repositoryMap.get(repository.getKind()).add(repository);
} else {
orphanedRepositories.add(repository);
}
}
}
}
} catch (Throwable t) {
MylarStatusHandler.fail(t, "could not load repositories", false);
}
}
/**
* for testing purposes
*/
public void setVersion(TaskRepository repository, String version, String repositoriesFilePath) {
repository.setVersion(version);
saveRepositories(repositoriesFilePath);
}
/**
* for testing purposes
*/
public void setEncoding(TaskRepository repository, String encoding, String repositoriesFilePath) {
repository.setCharacterEncoding(encoding);
saveRepositories(repositoriesFilePath);
}
/**
* for testing purposes
*/
public void setTimeZoneId(TaskRepository repository, String timeZoneId, String repositoriesFilePath) {
repository.setTimeZoneId(timeZoneId);
saveRepositories(repositoriesFilePath);
}
public void setSyncTime(TaskRepository repository, String syncTime, String repositoriesFilePath) {
repository.setSyncTimeStamp(syncTime);
saveRepositories(repositoriesFilePath);
// String prefIdSyncTime = repository.getUrl() + PROPERTY_DELIM +
// PROPERTY_SYNCTIMESTAMP;
// if (repository.getSyncTimeStamp() != null) {
// MylarTaskListPlugin.getMylarCorePrefs().setValue(prefIdSyncTime,
// repository.getSyncTimeStamp());
// }
}
- public boolean saveRepositories(String destinationPath) {
+ public synchronized boolean saveRepositories(String destinationPath) {
if (!Platform.isRunning()) {// || TasksUiPlugin.getDefault() == null) {
return false;
}
Set<TaskRepository> repositoriesToWrite = new HashSet<TaskRepository>(getAllRepositories());
// if for some reason a repository is added/changed to equal one in the
// orphaned set the orphan is discarded
for (TaskRepository repository : orphanedRepositories) {
if (!repositoriesToWrite.contains(repository)) {
repositoriesToWrite.add(repository);
}
}
try {
// String dataDirectory =
// TasksUiPlugin.getDefault().getDataDirectory();
// File repositoriesFile = new File(dataDirectory + File.separator +
// TasksUiPlugin.DEFAULT_REPOSITORIES_FILE);
File repositoriesFile = new File(destinationPath);
externalizer.writeRepositoriesToXML(repositoriesToWrite, repositoriesFile);
} catch (Throwable t) {
MylarStatusHandler.fail(t, "could not save repositories", false);
return false;
}
return true;
}
/**
* For testing.
*/
public void clearRepositories(String repositoriesFilePath) {
repositoryMap.clear();
orphanedRepositories.clear();
saveRepositories(repositoriesFilePath);
// for (AbstractRepositoryConnector repositoryConnector :
// repositoryConnectors.values()) {
// String prefId = PREF_REPOSITORIES +
// repositoryConnector.getRepositoryType();
// MylarTaskListPlugin.getMylarCorePrefs().setValue(prefId, "");
// }
}
public void notifyRepositorySettingsChagned(TaskRepository repository) {
for (ITaskRepositoryListener listener : listeners) {
listener.repositorySettingsChanged(repository);
}
}
// TODO: run with progress
public String getAttachmentContents(RepositoryAttachment attachment) {
StringBuffer contents = new StringBuffer();
try {
TaskRepository repository = getRepository(attachment.getRepositoryKind(), attachment.getRepositoryUrl());
AbstractRepositoryConnector connector = getRepositoryConnector(attachment.getRepositoryKind());
if (repository == null || connector == null) {
return "";
}
IAttachmentHandler handler = connector.getAttachmentHandler();
InputStream stream = new ByteArrayInputStream(handler.getAttachmentData(repository, attachment));
int c;
while ((c = stream.read()) != -1) {
/* TODO jpound - handle non-text */
contents.append((char) c);
}
stream.close();
} catch (CoreException e) {
MylarStatusHandler.fail(e.getStatus().getException(), "Retrieval of attachment data failed.", false);
return null;
} catch (IOException e) {
MylarStatusHandler.fail(e, "Retrieval of attachment data failed.", false);
return null;
}
return contents.toString();
}
}
| true | true | public boolean saveRepositories(String destinationPath) {
if (!Platform.isRunning()) {// || TasksUiPlugin.getDefault() == null) {
return false;
}
Set<TaskRepository> repositoriesToWrite = new HashSet<TaskRepository>(getAllRepositories());
// if for some reason a repository is added/changed to equal one in the
// orphaned set the orphan is discarded
for (TaskRepository repository : orphanedRepositories) {
if (!repositoriesToWrite.contains(repository)) {
repositoriesToWrite.add(repository);
}
}
try {
// String dataDirectory =
// TasksUiPlugin.getDefault().getDataDirectory();
// File repositoriesFile = new File(dataDirectory + File.separator +
// TasksUiPlugin.DEFAULT_REPOSITORIES_FILE);
File repositoriesFile = new File(destinationPath);
externalizer.writeRepositoriesToXML(repositoriesToWrite, repositoriesFile);
} catch (Throwable t) {
MylarStatusHandler.fail(t, "could not save repositories", false);
return false;
}
return true;
}
/**
* For testing.
*/
public void clearRepositories(String repositoriesFilePath) {
repositoryMap.clear();
orphanedRepositories.clear();
saveRepositories(repositoriesFilePath);
// for (AbstractRepositoryConnector repositoryConnector :
// repositoryConnectors.values()) {
// String prefId = PREF_REPOSITORIES +
// repositoryConnector.getRepositoryType();
// MylarTaskListPlugin.getMylarCorePrefs().setValue(prefId, "");
// }
}
public void notifyRepositorySettingsChagned(TaskRepository repository) {
for (ITaskRepositoryListener listener : listeners) {
listener.repositorySettingsChanged(repository);
}
}
// TODO: run with progress
public String getAttachmentContents(RepositoryAttachment attachment) {
StringBuffer contents = new StringBuffer();
try {
TaskRepository repository = getRepository(attachment.getRepositoryKind(), attachment.getRepositoryUrl());
AbstractRepositoryConnector connector = getRepositoryConnector(attachment.getRepositoryKind());
if (repository == null || connector == null) {
return "";
}
IAttachmentHandler handler = connector.getAttachmentHandler();
InputStream stream = new ByteArrayInputStream(handler.getAttachmentData(repository, attachment));
int c;
while ((c = stream.read()) != -1) {
/* TODO jpound - handle non-text */
contents.append((char) c);
}
stream.close();
} catch (CoreException e) {
MylarStatusHandler.fail(e.getStatus().getException(), "Retrieval of attachment data failed.", false);
return null;
} catch (IOException e) {
MylarStatusHandler.fail(e, "Retrieval of attachment data failed.", false);
return null;
}
return contents.toString();
}
}
| public synchronized boolean saveRepositories(String destinationPath) {
if (!Platform.isRunning()) {// || TasksUiPlugin.getDefault() == null) {
return false;
}
Set<TaskRepository> repositoriesToWrite = new HashSet<TaskRepository>(getAllRepositories());
// if for some reason a repository is added/changed to equal one in the
// orphaned set the orphan is discarded
for (TaskRepository repository : orphanedRepositories) {
if (!repositoriesToWrite.contains(repository)) {
repositoriesToWrite.add(repository);
}
}
try {
// String dataDirectory =
// TasksUiPlugin.getDefault().getDataDirectory();
// File repositoriesFile = new File(dataDirectory + File.separator +
// TasksUiPlugin.DEFAULT_REPOSITORIES_FILE);
File repositoriesFile = new File(destinationPath);
externalizer.writeRepositoriesToXML(repositoriesToWrite, repositoriesFile);
} catch (Throwable t) {
MylarStatusHandler.fail(t, "could not save repositories", false);
return false;
}
return true;
}
/**
* For testing.
*/
public void clearRepositories(String repositoriesFilePath) {
repositoryMap.clear();
orphanedRepositories.clear();
saveRepositories(repositoriesFilePath);
// for (AbstractRepositoryConnector repositoryConnector :
// repositoryConnectors.values()) {
// String prefId = PREF_REPOSITORIES +
// repositoryConnector.getRepositoryType();
// MylarTaskListPlugin.getMylarCorePrefs().setValue(prefId, "");
// }
}
public void notifyRepositorySettingsChagned(TaskRepository repository) {
for (ITaskRepositoryListener listener : listeners) {
listener.repositorySettingsChanged(repository);
}
}
// TODO: run with progress
public String getAttachmentContents(RepositoryAttachment attachment) {
StringBuffer contents = new StringBuffer();
try {
TaskRepository repository = getRepository(attachment.getRepositoryKind(), attachment.getRepositoryUrl());
AbstractRepositoryConnector connector = getRepositoryConnector(attachment.getRepositoryKind());
if (repository == null || connector == null) {
return "";
}
IAttachmentHandler handler = connector.getAttachmentHandler();
InputStream stream = new ByteArrayInputStream(handler.getAttachmentData(repository, attachment));
int c;
while ((c = stream.read()) != -1) {
/* TODO jpound - handle non-text */
contents.append((char) c);
}
stream.close();
} catch (CoreException e) {
MylarStatusHandler.fail(e.getStatus().getException(), "Retrieval of attachment data failed.", false);
return null;
} catch (IOException e) {
MylarStatusHandler.fail(e, "Retrieval of attachment data failed.", false);
return null;
}
return contents.toString();
}
}
|
diff --git a/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/PatientController.java b/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/PatientController.java
index 40f756a..d17404d 100644
--- a/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/PatientController.java
+++ b/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/PatientController.java
@@ -1,88 +1,90 @@
/**
* 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.iqchartimport.web.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.PatientProgram;
import org.openmrs.module.iqchartimport.Constants;
import org.openmrs.module.iqchartimport.EntityBuilder;
import org.openmrs.module.iqchartimport.IncompleteMappingException;
import org.openmrs.module.iqchartimport.MappingUtils;
import org.openmrs.module.iqchartimport.Utils;
import org.openmrs.module.iqchartimport.iq.IQChartDatabase;
import org.openmrs.module.iqchartimport.iq.IQChartSession;
import org.openmrs.module.iqchartimport.iq.code.ExitCode;
import org.openmrs.web.WebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Patients page controller
*/
@Controller("iqChartImportPatientController")
@RequestMapping("/module/iqchartimport/patient")
public class PatientController {
protected final Log log = LogFactory.getLog(getClass());
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.GET)
public String showPage(HttpServletRequest request, @RequestParam("tracnetID") Integer tracnetID, ModelMap model) throws IOException {
Utils.checkSuperUser();
IQChartDatabase database = IQChartDatabase.load(request.getSession(), Constants.SESSION_ATTR_DATABASE);
if (database == null)
return "redirect:upload.form";
model.put("database", database);
IQChartSession session = new IQChartSession(database);
try {
EntityBuilder builder = new EntityBuilder(session);
Patient patient = builder.getPatient(tracnetID);
List<PatientProgram> patientPrograms = builder.getPatientPrograms(tracnetID);
List<Encounter> encounters = builder.getPatientEncounters(patient, tracnetID);
- Obs patientExitObs = Utils.findObs(encounters, MappingUtils.getConcept(ExitCode.mappedQuestion)).get(0);
+ // Find exit reason obs
+ List<Obs> exitObss = Utils.findObs(encounters, MappingUtils.getConcept(ExitCode.mappedQuestion));
+ Obs patientExitObs = exitObss.size() > 0 ? exitObss.get(0) : null;
model.put("patient", patient);
model.put("patientPrograms", patientPrograms);
model.put("patientExitObs", patientExitObs);
model.put("encounters", encounters);
return "/module/iqchartimport/patient";
}
catch (IncompleteMappingException ex) {
String message = ex.getMessage() != null ? ex.getMessage() : "Incomplete entity mappings";
request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
return "redirect:mappings.form";
}
finally {
session.close();
}
}
}
| true | true | public String showPage(HttpServletRequest request, @RequestParam("tracnetID") Integer tracnetID, ModelMap model) throws IOException {
Utils.checkSuperUser();
IQChartDatabase database = IQChartDatabase.load(request.getSession(), Constants.SESSION_ATTR_DATABASE);
if (database == null)
return "redirect:upload.form";
model.put("database", database);
IQChartSession session = new IQChartSession(database);
try {
EntityBuilder builder = new EntityBuilder(session);
Patient patient = builder.getPatient(tracnetID);
List<PatientProgram> patientPrograms = builder.getPatientPrograms(tracnetID);
List<Encounter> encounters = builder.getPatientEncounters(patient, tracnetID);
Obs patientExitObs = Utils.findObs(encounters, MappingUtils.getConcept(ExitCode.mappedQuestion)).get(0);
model.put("patient", patient);
model.put("patientPrograms", patientPrograms);
model.put("patientExitObs", patientExitObs);
model.put("encounters", encounters);
return "/module/iqchartimport/patient";
}
catch (IncompleteMappingException ex) {
String message = ex.getMessage() != null ? ex.getMessage() : "Incomplete entity mappings";
request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
return "redirect:mappings.form";
}
finally {
session.close();
}
}
| public String showPage(HttpServletRequest request, @RequestParam("tracnetID") Integer tracnetID, ModelMap model) throws IOException {
Utils.checkSuperUser();
IQChartDatabase database = IQChartDatabase.load(request.getSession(), Constants.SESSION_ATTR_DATABASE);
if (database == null)
return "redirect:upload.form";
model.put("database", database);
IQChartSession session = new IQChartSession(database);
try {
EntityBuilder builder = new EntityBuilder(session);
Patient patient = builder.getPatient(tracnetID);
List<PatientProgram> patientPrograms = builder.getPatientPrograms(tracnetID);
List<Encounter> encounters = builder.getPatientEncounters(patient, tracnetID);
// Find exit reason obs
List<Obs> exitObss = Utils.findObs(encounters, MappingUtils.getConcept(ExitCode.mappedQuestion));
Obs patientExitObs = exitObss.size() > 0 ? exitObss.get(0) : null;
model.put("patient", patient);
model.put("patientPrograms", patientPrograms);
model.put("patientExitObs", patientExitObs);
model.put("encounters", encounters);
return "/module/iqchartimport/patient";
}
catch (IncompleteMappingException ex) {
String message = ex.getMessage() != null ? ex.getMessage() : "Incomplete entity mappings";
request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
return "redirect:mappings.form";
}
finally {
session.close();
}
}
|
diff --git a/src/main/java/edu/msergey/jalg/exercises/ch3/ex40/DoubleLinkedList.java b/src/main/java/edu/msergey/jalg/exercises/ch3/ex40/DoubleLinkedList.java
index ce6204a..6b1975c 100644
--- a/src/main/java/edu/msergey/jalg/exercises/ch3/ex40/DoubleLinkedList.java
+++ b/src/main/java/edu/msergey/jalg/exercises/ch3/ex40/DoubleLinkedList.java
@@ -1,61 +1,61 @@
package edu.msergey.jalg.exercises.ch3.ex40;
public class DoubleLinkedList<E extends Comparable<E>> {
private Node<E> head;
private Node<E> tail;
public Node<E> getHead() {
return head;
}
public Node<E> getTail() {
return tail;
}
public DoubleLinkedList(Node<E> node) {
head = node;
tail = node;
head.prev = null;
tail.next = null;
}
public void addTail(Node<E> node) {
tail.next = node;
node.prev = tail;
node.next = null;
tail = node;
}
- public void remove(IRemoveChecker removeChecker) {
+ public void remove(IRemoveChecker<E> removeChecker) {
if (head != tail) {
for (Node<E> current = head.next; current != tail; current = current.next) {
if (removeChecker.needToRemove(current)) {
current.prev.next = current.next;
current.next.prev = current.prev;
Node<E> prevCurrent = current.prev;
current.next = null;
current.prev = null;
current = prevCurrent;
}
}
}
if (removeChecker.needToRemove(head)) {
Node<E> nextHead = head.next;
head.next = null;
head = nextHead;
if (head == null) return;
head.prev = null;
}
if (removeChecker.needToRemove(tail)) {
Node<E> prevTail = tail.prev;
tail.prev = null;
tail = prevTail;
if (tail == null) return;
tail.next = null;
}
}
}
| true | true | public void remove(IRemoveChecker removeChecker) {
if (head != tail) {
for (Node<E> current = head.next; current != tail; current = current.next) {
if (removeChecker.needToRemove(current)) {
current.prev.next = current.next;
current.next.prev = current.prev;
Node<E> prevCurrent = current.prev;
current.next = null;
current.prev = null;
current = prevCurrent;
}
}
}
if (removeChecker.needToRemove(head)) {
Node<E> nextHead = head.next;
head.next = null;
head = nextHead;
if (head == null) return;
head.prev = null;
}
if (removeChecker.needToRemove(tail)) {
Node<E> prevTail = tail.prev;
tail.prev = null;
tail = prevTail;
if (tail == null) return;
tail.next = null;
}
}
| public void remove(IRemoveChecker<E> removeChecker) {
if (head != tail) {
for (Node<E> current = head.next; current != tail; current = current.next) {
if (removeChecker.needToRemove(current)) {
current.prev.next = current.next;
current.next.prev = current.prev;
Node<E> prevCurrent = current.prev;
current.next = null;
current.prev = null;
current = prevCurrent;
}
}
}
if (removeChecker.needToRemove(head)) {
Node<E> nextHead = head.next;
head.next = null;
head = nextHead;
if (head == null) return;
head.prev = null;
}
if (removeChecker.needToRemove(tail)) {
Node<E> prevTail = tail.prev;
tail.prev = null;
tail = prevTail;
if (tail == null) return;
tail.next = null;
}
}
|
diff --git a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
index 70fc96ea..061729df 100644
--- a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
+++ b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
@@ -1,180 +1,180 @@
/*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*/
package org.cubictest.recorder.ui;
import org.cubictest.common.utils.ErrorHandler;
import org.cubictest.common.utils.UserInfo;
import org.cubictest.export.exceptions.ExporterException;
import org.cubictest.export.utils.exported.ExportUtils;
import org.cubictest.exporters.selenium.ui.RunSeleniumRunnerAction;
import org.cubictest.model.ExtensionPoint;
import org.cubictest.model.ExtensionStartPoint;
import org.cubictest.model.ExtensionTransition;
import org.cubictest.model.Page;
import org.cubictest.model.SubTest;
import org.cubictest.model.Test;
import org.cubictest.model.Transition;
import org.cubictest.model.UrlStartPoint;
import org.cubictest.recorder.CubicRecorder;
import org.cubictest.recorder.GUIAwareRecorder;
import org.cubictest.recorder.IRecorder;
import org.cubictest.recorder.selenium.SeleniumRecorder;
import org.cubictest.ui.gef.interfaces.exported.IDisposeListener;
import org.cubictest.ui.gef.interfaces.exported.ITestEditor;
import org.cubictest.ui.gef.layout.AutoLayout;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
/**
* Action for starting / stopping the CubicRecorder.
*
*/
public class RecordEditorAction implements IEditorActionDelegate {
IResource currentFile;
private boolean running;
private SeleniumRecorder seleniumRecorder;
private ITestEditor testEditor;
public RecordEditorAction() {
super();
}
/**
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
- ErrorHandler.showErrorDialog("The test must be empty to use the recorder.");
+ UserInfo.showErrorDialog("The test must be empty to use the recorder.");
return;
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (35 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
}
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
private void stopSelenium(AutoLayout autoLayout) {
try {
setRunning(false);
if (seleniumRecorder != null) {
seleniumRecorder.stop();
}
if (autoLayout != null) {
autoLayout.setPageSelected(null);
}
}
catch(Exception e) {
ErrorHandler.logAndRethrow(e);
}
}
/**
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {}
public void setActiveEditor(IAction action, IEditorPart targetEditor) {
this.testEditor = (ITestEditor) targetEditor;
}
private void setRunning(boolean run) {
running = run;
}
/**
* Get the initial URL start point of the test (expands subtests).
*/
private UrlStartPoint getInitialUrlStartPoint(Test test) {
if (test.getStartPoint() instanceof UrlStartPoint) {
return (UrlStartPoint) test.getStartPoint();
}
else {
//ExtensionStartPoint, get url start point recursively:
return getInitialUrlStartPoint(((ExtensionStartPoint) test.getStartPoint()).getTest(true));
}
}
public boolean firstPageIsEmpty(Test test) {
for(Transition t : test.getStartPoint().getOutTransitions()) {
if(t.getEnd() instanceof Page && ((Page)t.getEnd()).getElements().size() == 0) {
return true;
}
}
return false;
}
}
| true | true | public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
ErrorHandler.showErrorDialog("The test must be empty to use the recorder.");
return;
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (35 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
}
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
| public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
UserInfo.showErrorDialog("The test must be empty to use the recorder.");
return;
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (35 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
}
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
|
diff --git a/core/src/visad/trunk/util/SelectRangeWidget.java b/core/src/visad/trunk/util/SelectRangeWidget.java
index 66759d413..2f3d3b89c 100644
--- a/core/src/visad/trunk/util/SelectRangeWidget.java
+++ b/core/src/visad/trunk/util/SelectRangeWidget.java
@@ -1,337 +1,342 @@
/*
VisAD Utility Library: Widgets for use in building applications with
the VisAD interactive analysis and visualization library
Copyright (C) 1998 Nick Rasmussen
VisAD is Copyright (C) 1996 - 1998 Bill Hibbard, Curtis Rueden, Tom
Rink and Dave Glowacki.
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 1, 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 in file NOTICE 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package visad.util;
/* AWT packages */
import java.awt.*;
import java.awt.event.*;
/* RMI classes */
import java.rmi.RemoteException;
/* VisAD packages */
import visad.*;
/** A slider widget that allows users to select a lower and upper bound.<P> */
public class SelectRangeWidget extends Canvas implements MouseListener,
MouseMotionListener,
ScalarMapListener {
/** Percent through scale of min gripper. */
private float minPercent = 0;
/** Percent through scale of max gripper. */
private float maxPercent = 100;
/** Minimum slider value. */
private float minVal;
/** Maximum slider value. */
private float maxVal;
/** Location of min gripper. */
private int minGrip;
/** Location of max gripper. */
private int maxGrip;
/** Flag whether mouse is currently affecting min gripper. */
private boolean minSlide = false;
/** Flag whether mouse is currently affecting max gripper. */
private boolean maxSlide = false;
/** This SelectRangeWidget's associated Control. */
private RangeControl rangeControl;
/** construct a SelectRangeWidget linked to the Control
in the map (which must be to Display.SelectRange), with
auto-scaling range values. */
public SelectRangeWidget(ScalarMap smap) throws VisADException,
RemoteException {
this(smap, smap.getRange());
}
/** construct a SelectRangeWidget linked to the Control
in the map (which must be to Display.SelectRange), with
range of values (min, max) */
public SelectRangeWidget(ScalarMap smap, float min, float max)
throws VisADException, RemoteException {
this(smap, new double[] {min, max});
smap.setRange((double) min, (double) max);
}
private SelectRangeWidget(ScalarMap smap, double[] range)
throws VisADException, RemoteException {
minVal = (float) range[0];
maxVal = (float) range[1];
if (minVal != minVal || maxVal != maxVal) {
// fake min and max
minVal = 0.0f;
maxVal = 1.0f;
// listen for real min and max
smap.addScalarMapListener(this);
}
rangeControl = (RangeControl) smap.getControl();
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
minVal = (float) range[0];
maxVal = (float) range[1];
try {
rangeControl.setRange(new float[] {minVal, maxVal});
}
catch (VisADException exc) { }
catch (RemoteException exc) { }
}
/** ScalarMapListener method used with delayed auto-scaling. */
public void mapChanged(ScalarMapEvent e) {
ScalarMap s = e.getScalarMap();
double[] range = s.getRange();
minVal = (float) range[0];
maxVal = (float) range[1];
try {
rangeControl.setRange(new float[] {minVal, maxVal});
}
catch (VisADException exc) { }
catch (RemoteException exc) { }
}
/** MouseListener method for moving slider. */
public void mousePressed(MouseEvent e) {
int w = getSize().width;
int x = e.getX();
int y = e.getY();
oldX = x;
Rectangle min = new Rectangle(minGrip-8, 4, 9, 17);
Rectangle max = new Rectangle(maxGrip, 4, 9, 17);
Rectangle between = new Rectangle(minGrip, 1, maxGrip-minGrip, 22);
Rectangle left = new Rectangle(9, 1, minGrip-18, 22);
Rectangle right = new Rectangle(maxGrip+8, 1, w-maxGrip-18, 22);
if (min.contains(x, y)) minSlide = true;
else if (max.contains(x, y)) maxSlide = true;
else if (between.contains(x, y)) {
minSlide = true;
maxSlide = true;
}
else if (left.contains(x, y)) {
minGrip = x;
minSlide = true;
percPaint();
}
else if (right.contains(x, y)) {
maxGrip = x;
maxSlide = true;
percPaint();
}
}
/** MouseListener method for moving slider. */
public void mouseReleased(MouseEvent e) {
minSlide = false;
maxSlide = false;
Graphics g = getGraphics();
if (g != null) drawLabels(g);
}
// unneeded MouseListener methods
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
/** Previous mouse X position. */
private int oldX;
/** MouseMotionListener method for moving slider. */
public void mouseDragged(MouseEvent e) {
int w = getSize().width;
int x = e.getX();
int y = e.getY();
// move entire range
if (minSlide && maxSlide) {
int change = x - oldX;
if (minGrip+change < 9) change = 9-minGrip;
else if (maxGrip+change > w-9) change = w-9-maxGrip;
if (change != 0) {
minGrip += change;
maxGrip += change;
percPaint();
}
}
// move min gripper if it is held
else if (minSlide) {
if (x < 9) minGrip = 9;
else if (x >= maxGrip) minGrip = maxGrip-1;
else minGrip = x;
percPaint();
}
// move max gripper if it is held
else if (maxSlide) {
if (x > w-9) maxGrip = w-9;
else if (x <= minGrip) maxGrip = minGrip+1;
else maxGrip = x;
percPaint();
}
oldX = x;
}
// unneeded MouseMotionListener methods
public void mouseMoved(MouseEvent e) { }
// size methods for widget
public Dimension getMinimumSize() {
return new Dimension(0, 42);
}
public Dimension getPreferredSize() {
return new Dimension(200, 42);
}
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, 42);
}
/** Recomputes percent variables, updates control, then paints. */
private void percPaint() {
int w = getSize().width;
minPercent = 100*((float) (minGrip-9))/((float) (w-18));
maxPercent = 100*((float) (maxGrip-9))/((float) (w-18));
float min = 0.01f*minPercent*(maxVal-minVal)+minVal;
float max = 0.01f*maxPercent*(maxVal-minVal)+minVal;
try {
rangeControl.setRange(new float[] {min, max});
}
catch (VisADException exc) { }
catch (RemoteException exc ) { }
Graphics g = getGraphics();
if (g != null) paint(g);
}
private int lastW = 0;
private float lastMin = 0.0f;
private float lastMax = 0.0f;
private String lastCurStr = "";
/** Draws the slider. */
public void paint(Graphics g) {
int w = getSize().width;
// compute minGrip and maxGrip
if (lastW != w) {
minGrip = (int) (0.01*minPercent*(w-18)+9);
maxGrip = (int) (0.01*maxPercent*(w-18)+9);
}
// draw slider lines
g.setColor(Color.white);
g.drawLine(0, 12, w-1, 12);
g.drawLine(0, 0, 0, 23);
g.drawLine(0, 0, 2, 0);
g.drawLine(0, 23, 2, 23);
g.drawLine(w-1, 0, w-1, 23);
g.drawLine(w-1, 0, w-3, 0);
g.drawLine(w-1, 23, w-3, 23);
// draw labels
if (!minSlide && !maxSlide) drawLabels(g);
// erase old slider junk
g.setColor(Color.black);
g.fillRect(1, 4, w-2, 8);
g.fillRect(1, 13, w-2, 8);
// draw grippers
g.setColor(Color.yellow);
int[] xpts = {minGrip-8, minGrip, minGrip};
int[] ypts = {12, 4, 21};
g.fillPolygon(xpts, ypts, 3);
// Note: these coordinates are shifted up and left
// by one, to work around a misalignment bug
xpts = new int[] {maxGrip+7, maxGrip-1, maxGrip-1};
ypts = new int[] {13, 5, 20};
g.fillPolygon(xpts, ypts, 3);
g.setColor(Color.pink);
g.fillRect(minGrip, 11, maxGrip-minGrip-1, 3);
lastW = w;
}
/** Updates the labels at the bottom of the widget. */
private void drawLabels(Graphics g) {
int w = getSize().width;
FontMetrics fm = g.getFontMetrics();
if (lastMin != minVal || lastW != w) {
// minimum bound text string
g.setColor(Color.black);
int sw = fm.stringWidth(""+lastMin);
g.fillRect(1, 27, sw, 15);
lastMin = minVal;
}
if (lastMax != maxVal || lastW != w) {
// maximum bound text string
g.setColor(Color.black);
int sw = fm.stringWidth(""+lastMax);
g.fillRect(lastW - 4 - sw, 27, sw, 15);
lastMax = maxVal;
}
- String minS = ""+Math.round(minPercent*(maxVal-minVal)+minVal);
- String maxS = ""+Math.round(maxPercent*(maxVal-minVal)+minVal);
+ String minS = ""+Math.round(minPercent*(maxVal-minVal)+100*minVal);
+ String maxS = ""+Math.round(maxPercent*(maxVal-minVal)+100*minVal);
+ System.out.println("Minval: "+minVal+" Maxval: "+maxVal); /* CTR: TEMP */
+ System.out.println("Min: "+minS+" Max: "+maxS); /* CTR: TEMP */
if (minS.charAt(0) != '0') {
if (minS.endsWith("00")) minS = minS.substring(0, minS.length()-2);
else {
+ if (minS.length() == 1) minS = "0"+minS;
minS = minS.substring(0, minS.length()-2)+"."
+minS.substring(minS.length()-2);
if (minS.endsWith("0")) minS = minS.substring(0, minS.length()-1);
}
}
if (maxS.charAt(0) != '0') {
if (maxS.endsWith("00")) maxS = maxS.substring(0, maxS.length()-2);
else {
+ if (maxS.length() == 1) maxS = "0"+maxS;
maxS = maxS.substring(0, maxS.length()-2)+"."
+maxS.substring(maxS.length()-2);
if (maxS.endsWith("0")) maxS = maxS.substring(0, maxS.length()-1);
}
}
String curStr = "("+minS+", "+maxS+")";
+ System.out.println(curStr); /* CTR: TEMP */
if (!curStr.equals(lastCurStr) || lastW != w) {
g.setColor(Color.black);
int sw = fm.stringWidth(lastCurStr);
g.fillRect((lastW - sw)/2, 27, sw, 15);
lastCurStr = curStr;
}
g.setColor(Color.white);
g.drawString(""+minVal, 1, 40);
String maxStr = ""+maxVal;
g.drawString(maxStr, w - 4 - fm.stringWidth(maxStr), 40);
g.drawString(curStr, (w - fm.stringWidth(curStr))/2, 40);
}
}
| false | true | private void drawLabels(Graphics g) {
int w = getSize().width;
FontMetrics fm = g.getFontMetrics();
if (lastMin != minVal || lastW != w) {
// minimum bound text string
g.setColor(Color.black);
int sw = fm.stringWidth(""+lastMin);
g.fillRect(1, 27, sw, 15);
lastMin = minVal;
}
if (lastMax != maxVal || lastW != w) {
// maximum bound text string
g.setColor(Color.black);
int sw = fm.stringWidth(""+lastMax);
g.fillRect(lastW - 4 - sw, 27, sw, 15);
lastMax = maxVal;
}
String minS = ""+Math.round(minPercent*(maxVal-minVal)+minVal);
String maxS = ""+Math.round(maxPercent*(maxVal-minVal)+minVal);
if (minS.charAt(0) != '0') {
if (minS.endsWith("00")) minS = minS.substring(0, minS.length()-2);
else {
minS = minS.substring(0, minS.length()-2)+"."
+minS.substring(minS.length()-2);
if (minS.endsWith("0")) minS = minS.substring(0, minS.length()-1);
}
}
if (maxS.charAt(0) != '0') {
if (maxS.endsWith("00")) maxS = maxS.substring(0, maxS.length()-2);
else {
maxS = maxS.substring(0, maxS.length()-2)+"."
+maxS.substring(maxS.length()-2);
if (maxS.endsWith("0")) maxS = maxS.substring(0, maxS.length()-1);
}
}
String curStr = "("+minS+", "+maxS+")";
if (!curStr.equals(lastCurStr) || lastW != w) {
g.setColor(Color.black);
int sw = fm.stringWidth(lastCurStr);
g.fillRect((lastW - sw)/2, 27, sw, 15);
lastCurStr = curStr;
}
g.setColor(Color.white);
g.drawString(""+minVal, 1, 40);
String maxStr = ""+maxVal;
g.drawString(maxStr, w - 4 - fm.stringWidth(maxStr), 40);
g.drawString(curStr, (w - fm.stringWidth(curStr))/2, 40);
}
| private void drawLabels(Graphics g) {
int w = getSize().width;
FontMetrics fm = g.getFontMetrics();
if (lastMin != minVal || lastW != w) {
// minimum bound text string
g.setColor(Color.black);
int sw = fm.stringWidth(""+lastMin);
g.fillRect(1, 27, sw, 15);
lastMin = minVal;
}
if (lastMax != maxVal || lastW != w) {
// maximum bound text string
g.setColor(Color.black);
int sw = fm.stringWidth(""+lastMax);
g.fillRect(lastW - 4 - sw, 27, sw, 15);
lastMax = maxVal;
}
String minS = ""+Math.round(minPercent*(maxVal-minVal)+100*minVal);
String maxS = ""+Math.round(maxPercent*(maxVal-minVal)+100*minVal);
System.out.println("Minval: "+minVal+" Maxval: "+maxVal); /* CTR: TEMP */
System.out.println("Min: "+minS+" Max: "+maxS); /* CTR: TEMP */
if (minS.charAt(0) != '0') {
if (minS.endsWith("00")) minS = minS.substring(0, minS.length()-2);
else {
if (minS.length() == 1) minS = "0"+minS;
minS = minS.substring(0, minS.length()-2)+"."
+minS.substring(minS.length()-2);
if (minS.endsWith("0")) minS = minS.substring(0, minS.length()-1);
}
}
if (maxS.charAt(0) != '0') {
if (maxS.endsWith("00")) maxS = maxS.substring(0, maxS.length()-2);
else {
if (maxS.length() == 1) maxS = "0"+maxS;
maxS = maxS.substring(0, maxS.length()-2)+"."
+maxS.substring(maxS.length()-2);
if (maxS.endsWith("0")) maxS = maxS.substring(0, maxS.length()-1);
}
}
String curStr = "("+minS+", "+maxS+")";
System.out.println(curStr); /* CTR: TEMP */
if (!curStr.equals(lastCurStr) || lastW != w) {
g.setColor(Color.black);
int sw = fm.stringWidth(lastCurStr);
g.fillRect((lastW - sw)/2, 27, sw, 15);
lastCurStr = curStr;
}
g.setColor(Color.white);
g.drawString(""+minVal, 1, 40);
String maxStr = ""+maxVal;
g.drawString(maxStr, w - 4 - fm.stringWidth(maxStr), 40);
g.drawString(curStr, (w - fm.stringWidth(curStr))/2, 40);
}
|
diff --git a/hidapi/src/com/codeminders/hidapi/HIDAPITest.java b/hidapi/src/com/codeminders/hidapi/HIDAPITest.java
index b9c21a8..20a1853 100644
--- a/hidapi/src/com/codeminders/hidapi/HIDAPITest.java
+++ b/hidapi/src/com/codeminders/hidapi/HIDAPITest.java
@@ -1,93 +1,94 @@
package com.codeminders.hidapi;
import java.io.IOException;
public class HIDAPITest
{
private static final long READ_UPDATE_DELAY_MS = 50L;
static
{
System.loadLibrary("hidapi-jni");
}
// "Afterglow" controller for PS3
static final int VENDOR_ID = 3695;
static final int PRODUCT_ID = 25346;
private static final int BUFSIZE = 2048;
/**
* @param args
*/
public static void main(String[] args)
{
listDevices();
readDevice();
}
private static void readDevice()
{
HIDDevice dev;
try
{
dev = HIDManager.openById(VENDOR_ID, PRODUCT_ID, null);
+ //dev.close();
try
{
byte[] buf = new byte[BUFSIZE];
dev.enableBlocking();
while(true)
{
int n = dev.read(buf);
System.err.print(""+n+" bytes read:\n\t");
for(int i=0; i<n; i++)
{
int v = buf[i];
if (v<0) v = n+256;
String hs = Integer.toHexString(v);
if (v<16)
System.err.print("0");
System.err.print(hs + " ");
}
System.err.println("");
try
{
Thread.sleep(READ_UPDATE_DELAY_MS);
} catch(InterruptedException e)
{
//Ignore
}
}
} finally
{
dev.close();
}
} catch(IOException e)
{
e.printStackTrace();
}
}
private static void listDevices()
{
String property = System.getProperty("java.library.path");
System.err.println(property);
try
{
HIDDeviceInfo[] devs = HIDManager.listDevices();
System.err.println("Devices:\n\n");
for(int i=0;i<devs.length;i++)
{
System.err.println(""+i+".\t"+devs[i]);
System.err.println("---------------------------------------------\n");
}
}
catch(IOException e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
| true | true | private static void readDevice()
{
HIDDevice dev;
try
{
dev = HIDManager.openById(VENDOR_ID, PRODUCT_ID, null);
try
{
byte[] buf = new byte[BUFSIZE];
dev.enableBlocking();
while(true)
{
int n = dev.read(buf);
System.err.print(""+n+" bytes read:\n\t");
for(int i=0; i<n; i++)
{
int v = buf[i];
if (v<0) v = n+256;
String hs = Integer.toHexString(v);
if (v<16)
System.err.print("0");
System.err.print(hs + " ");
}
System.err.println("");
try
{
Thread.sleep(READ_UPDATE_DELAY_MS);
} catch(InterruptedException e)
{
//Ignore
}
}
} finally
{
dev.close();
}
} catch(IOException e)
{
e.printStackTrace();
}
}
| private static void readDevice()
{
HIDDevice dev;
try
{
dev = HIDManager.openById(VENDOR_ID, PRODUCT_ID, null);
//dev.close();
try
{
byte[] buf = new byte[BUFSIZE];
dev.enableBlocking();
while(true)
{
int n = dev.read(buf);
System.err.print(""+n+" bytes read:\n\t");
for(int i=0; i<n; i++)
{
int v = buf[i];
if (v<0) v = n+256;
String hs = Integer.toHexString(v);
if (v<16)
System.err.print("0");
System.err.print(hs + " ");
}
System.err.println("");
try
{
Thread.sleep(READ_UPDATE_DELAY_MS);
} catch(InterruptedException e)
{
//Ignore
}
}
} finally
{
dev.close();
}
} catch(IOException e)
{
e.printStackTrace();
}
}
|
diff --git a/src/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java b/src/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java
index 49e57cc..e4a5fb9 100644
--- a/src/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java
+++ b/src/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java
@@ -1,136 +1,136 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import java.util.Random;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import org.bukkit.entity.Horse.Color;
import org.bukkit.entity.Horse.Style;
public class HorseWatcher extends AgeableWatcher {
public HorseWatcher(Disguise disguise) {
super(disguise);
setColorId(new Random().nextInt(Color.values().length));
}
public Color getColor() {
return Color.values()[((Integer) getValue(20, 0) & 0xFF)];
}
public String getOwnerName() {
return (String) getValue(21, "");
}
public Style getStyle() {
return Style.values()[((Integer) getValue(20, 0) >>> 8)];
}
public boolean hasChest() {
return isTrue(8);
}
@Deprecated
public boolean isBredable() {
return isTrue(16);
}
public boolean isBreedable() {
return isTrue(16);
}
public boolean isGrazing() {
return isTrue(32);
}
public boolean isMouthOpen() {
return isTrue(128);
}
public boolean isRearing() {
return isTrue(64);
}
public boolean isSaddled() {
return isTrue(4);
}
public boolean isTamed() {
return isTrue(2);
}
private boolean isTrue(int i) {
return ((Integer) getValue(16, (byte) 0) & i) != 0;
}
@Deprecated
public void setCanBred(boolean breed) {
setFlag(16, breed);
}
public void setCanBreed(boolean breed) {
setFlag(16, breed);
}
public void setCarryingChest(boolean chest) {
setFlag(8, true);
}
public void setColor(Color color) {
setValue(20, color.ordinal() & 0xFF | getStyle().ordinal() << 8);
sendData(20);
}
@Deprecated
public void setColorId(int color) {
setValue(20, (color % Color.values().length) & 0xFF | getStyle().ordinal() << 8);
sendData(20);
}
private void setFlag(int i, boolean flag) {
- int j = (Integer) getValue(16, (byte) 0);
+ int j = (Byte) getValue(16, (byte) 0);
if (flag) {
setValue(16, j | i);
} else {
setValue(16, j & ~i);
}
sendData(16);
}
public void setGrazing(boolean grazing) {
setFlag(32, grazing);
}
public void setMouthOpen(boolean mouthOpen) {
setFlag(128, mouthOpen);
}
public void setOwnerName(String name) {
setValue(21, name);
sendData(21);
}
public void setRearing(boolean rear) {
setFlag(64, true);
}
public void setSaddled(boolean saddled) {
setFlag(4, saddled);
}
public void setStyle(Style style) {
setValue(20, getColor().ordinal() & 0xFF | style.ordinal() << 8);
sendData(20);
}
@Deprecated
public void setStyleId(int style) {
setValue(20, getColor().ordinal() & 0xFF | (style % Style.values().length) << 8);
sendData(20);
}
public void setTamed(boolean tamed) {
setFlag(2, tamed);
}
}
| true | true | private void setFlag(int i, boolean flag) {
int j = (Integer) getValue(16, (byte) 0);
if (flag) {
setValue(16, j | i);
} else {
setValue(16, j & ~i);
}
sendData(16);
}
| private void setFlag(int i, boolean flag) {
int j = (Byte) getValue(16, (byte) 0);
if (flag) {
setValue(16, j | i);
} else {
setValue(16, j & ~i);
}
sendData(16);
}
|
diff --git a/jython/org/python/core/Options.java b/jython/org/python/core/Options.java
index b6f0b1d3..02bfef63 100644
--- a/jython/org/python/core/Options.java
+++ b/jython/org/python/core/Options.java
@@ -1,162 +1,162 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.core;
/**
* A class with static fields for each of the settable options.
* The options from registry and command line is copied into
* the fields here and the rest of Jyhton checks these fields.
*/
public class Options
{
// JPython options. Some of these can be set from the command line
// options, but all can be controlled through the JPython registry
/**
* when an exception occurs in Java code, and it is not caught, should
* the interpreter print out the Java exception in the traceback?
*/
public static boolean showJavaExceptions = false;
/**
* When true, python exception raised in overriden methods will
* be shown on stderr. This option is remarkable usefull when
* python is used for implementing CORBA server. Some CORBA
* servers will turn python exception (say a NameError) into an
* anonymous user exception without any stacktrace. Setting this
* option will show the stacktrace.
*/
public static boolean showPythonProxyExceptions = false;
/**
* To force JIT compilation of Jython code -- should be unnecessary
* Setting this to true will cause jdk1.2rc1 to core dump on Windows
*/
public static boolean skipCompile = true;
/**
* Setting this to true will cause the console to poll standard in.
* This might be helpful on systems without system-level threads.
*/
public static boolean pollStandardIn = false;
/**
* If true, JPython respects Java the accessibility flag for fields,
* methods, and constructors. This means you can only access public
* members. Set this to false to access all members by toggling the
* accessible flag on the member.
*/
public static boolean respectJavaAccessibility = true;
/**
* When false the <code>site.py</code> will not be imported.
* This is only honored by the command line main class.
*/
public static boolean importSite = true;
/**
* Set verbosity to Py.ERROR, Py.WARNING, Py.MESSAGE, Py.COMMENT,
* or Py.DEBUG for varying levels of informative messages from
* Jython. Normally this option is set from the command line.
*/
public static int verbose = Py.MESSAGE;
/**
* Setting this to true will support old 1.0 style keyword+"_" names.
* This isn't needed any more due to improvements in the parser
*/
public static boolean deprecatedKeywordMangling = true;
/**
* A directory where the dynamicly generated classes are written.
* Nothing is ever read from here, it is only for debugging
* purposes.
*/
public static String proxyDebugDirectory = null;
/**
* If true, Jython will use the first module found on sys.path
* where java File.isFile() returns true. Setting this to true
* have no effect on unix-type filesystems. On Windows/HPS+
* systems setting it to true will enable Jython-2.0 behaviour.
*/
public static boolean caseok = false;
//
// ####### END OF OPTIONS
//
private Options() { ; }
private static boolean getBooleanOption(String name, boolean defaultValue)
{
String prop = PySystemState.registry.getProperty("python."+name);
if (prop == null)
return defaultValue;
return prop.equalsIgnoreCase("true") || prop.equalsIgnoreCase("yes");
}
private static String getStringOption(String name, String defaultValue) {
String prop = PySystemState.registry.getProperty("python."+name);
if (prop == null)
return defaultValue;
return prop;
}
/**
* Initialize the static fields from the registry options.
*/
public static void setFromRegistry() {
// Set the more unusual options
Options.showJavaExceptions =
getBooleanOption("options.showJavaExceptions",
Options.showJavaExceptions);
Options.showPythonProxyExceptions =
getBooleanOption("options.showPythonProxyExceptions",
Options.showPythonProxyExceptions);
Options.skipCompile =
getBooleanOption("options.skipCompile", Options.skipCompile);
Options.deprecatedKeywordMangling =
getBooleanOption("deprecated.keywordMangling",
Options.deprecatedKeywordMangling);
Options.pollStandardIn =
getBooleanOption("console.poll", Options.pollStandardIn);
Options.respectJavaAccessibility =
getBooleanOption("security.respectJavaAccessibility",
Options.respectJavaAccessibility);
Options.proxyDebugDirectory =
getStringOption("options.proxyDebugDirectory",
Options.proxyDebugDirectory);
// verbosity is more complicated:
String prop = PySystemState.registry.getProperty("python.verbose");
if (prop != null) {
if (prop.equalsIgnoreCase("error"))
Options.verbose = Py.ERROR;
else if (prop.equalsIgnoreCase("warning"))
Options.verbose = Py.WARNING;
else if (prop.equalsIgnoreCase("message"))
Options.verbose = Py.MESSAGE;
else if (prop.equalsIgnoreCase("comment"))
Options.verbose = Py.COMMENT;
else if (prop.equalsIgnoreCase("debug"))
Options.verbose = Py.DEBUG;
else
throw Py.ValueError("Illegal verbose option setting: '"+
prop+"'");
}
Options.caseok =
- getBooleanOption("options.caseok", Options.pollStandardIn);
+ getBooleanOption("options.caseok", Options.caseok);
// additional initializations which must happen after the registry
// is guaranteed to be initialized.
JavaAccessibility.initialize();
}
}
| true | true | */
public static void setFromRegistry() {
// Set the more unusual options
Options.showJavaExceptions =
getBooleanOption("options.showJavaExceptions",
Options.showJavaExceptions);
Options.showPythonProxyExceptions =
getBooleanOption("options.showPythonProxyExceptions",
Options.showPythonProxyExceptions);
Options.skipCompile =
getBooleanOption("options.skipCompile", Options.skipCompile);
Options.deprecatedKeywordMangling =
getBooleanOption("deprecated.keywordMangling",
Options.deprecatedKeywordMangling);
Options.pollStandardIn =
getBooleanOption("console.poll", Options.pollStandardIn);
Options.respectJavaAccessibility =
getBooleanOption("security.respectJavaAccessibility",
Options.respectJavaAccessibility);
Options.proxyDebugDirectory =
getStringOption("options.proxyDebugDirectory",
Options.proxyDebugDirectory);
// verbosity is more complicated:
String prop = PySystemState.registry.getProperty("python.verbose");
if (prop != null) {
if (prop.equalsIgnoreCase("error"))
Options.verbose = Py.ERROR;
else if (prop.equalsIgnoreCase("warning"))
Options.verbose = Py.WARNING;
else if (prop.equalsIgnoreCase("message"))
Options.verbose = Py.MESSAGE;
else if (prop.equalsIgnoreCase("comment"))
Options.verbose = Py.COMMENT;
else if (prop.equalsIgnoreCase("debug"))
Options.verbose = Py.DEBUG;
else
throw Py.ValueError("Illegal verbose option setting: '"+
prop+"'");
}
Options.caseok =
getBooleanOption("options.caseok", Options.pollStandardIn);
// additional initializations which must happen after the registry
// is guaranteed to be initialized.
JavaAccessibility.initialize();
}
| */
public static void setFromRegistry() {
// Set the more unusual options
Options.showJavaExceptions =
getBooleanOption("options.showJavaExceptions",
Options.showJavaExceptions);
Options.showPythonProxyExceptions =
getBooleanOption("options.showPythonProxyExceptions",
Options.showPythonProxyExceptions);
Options.skipCompile =
getBooleanOption("options.skipCompile", Options.skipCompile);
Options.deprecatedKeywordMangling =
getBooleanOption("deprecated.keywordMangling",
Options.deprecatedKeywordMangling);
Options.pollStandardIn =
getBooleanOption("console.poll", Options.pollStandardIn);
Options.respectJavaAccessibility =
getBooleanOption("security.respectJavaAccessibility",
Options.respectJavaAccessibility);
Options.proxyDebugDirectory =
getStringOption("options.proxyDebugDirectory",
Options.proxyDebugDirectory);
// verbosity is more complicated:
String prop = PySystemState.registry.getProperty("python.verbose");
if (prop != null) {
if (prop.equalsIgnoreCase("error"))
Options.verbose = Py.ERROR;
else if (prop.equalsIgnoreCase("warning"))
Options.verbose = Py.WARNING;
else if (prop.equalsIgnoreCase("message"))
Options.verbose = Py.MESSAGE;
else if (prop.equalsIgnoreCase("comment"))
Options.verbose = Py.COMMENT;
else if (prop.equalsIgnoreCase("debug"))
Options.verbose = Py.DEBUG;
else
throw Py.ValueError("Illegal verbose option setting: '"+
prop+"'");
}
Options.caseok =
getBooleanOption("options.caseok", Options.caseok);
// additional initializations which must happen after the registry
// is guaranteed to be initialized.
JavaAccessibility.initialize();
}
|
diff --git a/farrago/src/net/sf/farrago/namespace/jdbc/ResultSetToFarragoIteratorConverter.java b/farrago/src/net/sf/farrago/namespace/jdbc/ResultSetToFarragoIteratorConverter.java
index cb4a15fd1..2a5d597d7 100644
--- a/farrago/src/net/sf/farrago/namespace/jdbc/ResultSetToFarragoIteratorConverter.java
+++ b/farrago/src/net/sf/farrago/namespace/jdbc/ResultSetToFarragoIteratorConverter.java
@@ -1,199 +1,203 @@
/*
// $Id$
// Farrago is an extensible data management system.
// Copyright (C) 2005-2005 The Eigenbase Project
// Copyright (C) 2005-2005 Disruptive Tech
// Copyright (C) 2005-2005 LucidEra, Inc.
// 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 net.sf.farrago.namespace.jdbc;
import net.sf.farrago.query.*;
import net.sf.farrago.type.*;
import openjava.mop.*;
import openjava.ptree.*;
import org.eigenbase.oj.rel.JavaRel;
import org.eigenbase.oj.rel.JavaRelImplementor;
import org.eigenbase.oj.rel.ResultSetRel;
import org.eigenbase.oj.util.*;
import org.eigenbase.oj.rex.RexToOJTranslator;
import org.eigenbase.rel.*;
import org.eigenbase.rel.convert.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.rex.*;
import org.eigenbase.runtime.*;
import org.eigenbase.util.*;
import org.eigenbase.sql.type.*;
/**
* ResultSetToFarragoIteratorConverter is a ConverterRel from the RESULT_SET
* CallingConvention to the ITERATOR CallingConvention which ensures that
* the objects returned by the iterator are understood by the rest
* of Farrago.
*
* @author John V. Sichi
* @version $Id$
*/
class ResultSetToFarragoIteratorConverter extends ConverterRel
implements JavaRel
{
//~ Constructors ----------------------------------------------------------
/**
* Creates a new ResultSetToFarragoIteratorConverter object.
*
* @param cluster RelOptCluster for this rel
* @param child input rel producing rows in ResultSet
* representation
*/
public ResultSetToFarragoIteratorConverter(
RelOptCluster cluster,
RelNode child)
{
super(
cluster, CallingConventionTraitDef.instance,
new RelTraitSet(CallingConvention.ITERATOR), child);
}
//~ Methods ---------------------------------------------------------------
// implement RelNode
public Object clone()
{
ResultSetToFarragoIteratorConverter clone =
new ResultSetToFarragoIteratorConverter(getCluster(), getChild());
clone.inheritTraitsFrom(this);
return clone;
}
// implement RelNode
public ParseTree implement(JavaRelImplementor implementor)
{
FarragoRelImplementor farragoImplementor =
(FarragoRelImplementor) implementor;
Expression childObj =
implementor.visitJavaChild(this, 0, (ResultSetRel) getChild());
StatementList methodBody = new StatementList();
// variable for synthetic object instance
Variable varTuple = implementor.newVariable();
// variable for source ResultSet
Variable varResultSet = new Variable("resultSet");
// This is a little silly. Have to put in a dummy cast
// so that type inference will stop early (otherwise it
// fails to find variable reference).
Expression castResultSet =
new CastExpression(
TypeName.forOJClass(OJUtil.clazzResultSet),
varResultSet);
RelDataType rowType = getRowType();
FarragoTypeFactory factory =
farragoImplementor.getPreparingStmt().getFarragoTypeFactory();
OJClass rowClass = OJUtil.typeToOJClass(rowType,factory);
JavaRexBuilder javaRexBuilder =
(JavaRexBuilder) getCluster().getRexBuilder();
MemberDeclarationList memberList = new MemberDeclarationList();
RelDataTypeField [] fields = rowType.getFields();
for (int i = 0; i < fields.length; ++i) {
RelDataTypeField field = fields[i];
RelDataType type = field.getType();
ExpressionList colPosExpList =
new ExpressionList(Literal.makeLiteral(i + 1));
Expression rhsExp;
if ((SqlTypeUtil.isJavaPrimitive(type)) && !type.isNullable()) {
// TODO: make this official: java.sql and java.nio
- // use the same accessor names, happily
+ // use the same accessor names, happily,
+ // (except for boolean, sadly)
String methodName =
ReflectUtil.getByteBufferReadMethod(
factory.getClassForPrimitive(type)).getName();
+ if (type.getSqlTypeName() == SqlTypeName.Boolean) {
+ methodName = "getBoolean";
+ }
rhsExp =
new MethodCall(castResultSet, methodName, colPosExpList);
} else if (SqlTypeUtil.inCharFamily(type)) {
rhsExp =
new MethodCall(castResultSet, "getString", colPosExpList);
} else {
rhsExp =
new MethodCall(castResultSet, "getObject", colPosExpList);
}
RexNode rhs = javaRexBuilder.makeJava(
getCluster().getEnv(), rhsExp);
rhs = javaRexBuilder.makeAbstractCast(
field.getType(),
rhs);
final RexToOJTranslator translator =
farragoImplementor.newStmtTranslator(
this,
methodBody,
memberList);
translator.translateAssignment(
field,
new FieldAccess(
varTuple,
Util.toJavaId(
field.getName(),
i)),
rhs);
}
methodBody.add(new ReturnStatement(varTuple));
// allocate synthetic object as class data member
memberList.add(
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(rowClass),
varTuple.toString(),
new AllocationExpression(
rowClass,
new ExpressionList())));
// add method as implementation for super.makeRow
memberList.add(
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
TypeName.forOJClass(OJUtil.clazzObject),
"makeRow",
new ParameterList(),
new TypeName [] {
TypeName.forOJClass(OJUtil.clazzSQLException)
},
methodBody));
return new AllocationExpression(
TypeName.forOJClass(OJClass.forClass(ResultSetIterator.class)),
new ExpressionList(
new CastExpression(
TypeName.forOJClass(OJUtil.clazzResultSet),
childObj)),
memberList);
}
}
// End ResultSetToFarragoIteratorConverter.java
| false | true | public ParseTree implement(JavaRelImplementor implementor)
{
FarragoRelImplementor farragoImplementor =
(FarragoRelImplementor) implementor;
Expression childObj =
implementor.visitJavaChild(this, 0, (ResultSetRel) getChild());
StatementList methodBody = new StatementList();
// variable for synthetic object instance
Variable varTuple = implementor.newVariable();
// variable for source ResultSet
Variable varResultSet = new Variable("resultSet");
// This is a little silly. Have to put in a dummy cast
// so that type inference will stop early (otherwise it
// fails to find variable reference).
Expression castResultSet =
new CastExpression(
TypeName.forOJClass(OJUtil.clazzResultSet),
varResultSet);
RelDataType rowType = getRowType();
FarragoTypeFactory factory =
farragoImplementor.getPreparingStmt().getFarragoTypeFactory();
OJClass rowClass = OJUtil.typeToOJClass(rowType,factory);
JavaRexBuilder javaRexBuilder =
(JavaRexBuilder) getCluster().getRexBuilder();
MemberDeclarationList memberList = new MemberDeclarationList();
RelDataTypeField [] fields = rowType.getFields();
for (int i = 0; i < fields.length; ++i) {
RelDataTypeField field = fields[i];
RelDataType type = field.getType();
ExpressionList colPosExpList =
new ExpressionList(Literal.makeLiteral(i + 1));
Expression rhsExp;
if ((SqlTypeUtil.isJavaPrimitive(type)) && !type.isNullable()) {
// TODO: make this official: java.sql and java.nio
// use the same accessor names, happily
String methodName =
ReflectUtil.getByteBufferReadMethod(
factory.getClassForPrimitive(type)).getName();
rhsExp =
new MethodCall(castResultSet, methodName, colPosExpList);
} else if (SqlTypeUtil.inCharFamily(type)) {
rhsExp =
new MethodCall(castResultSet, "getString", colPosExpList);
} else {
rhsExp =
new MethodCall(castResultSet, "getObject", colPosExpList);
}
RexNode rhs = javaRexBuilder.makeJava(
getCluster().getEnv(), rhsExp);
rhs = javaRexBuilder.makeAbstractCast(
field.getType(),
rhs);
final RexToOJTranslator translator =
farragoImplementor.newStmtTranslator(
this,
methodBody,
memberList);
translator.translateAssignment(
field,
new FieldAccess(
varTuple,
Util.toJavaId(
field.getName(),
i)),
rhs);
}
methodBody.add(new ReturnStatement(varTuple));
// allocate synthetic object as class data member
memberList.add(
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(rowClass),
varTuple.toString(),
new AllocationExpression(
rowClass,
new ExpressionList())));
// add method as implementation for super.makeRow
memberList.add(
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
TypeName.forOJClass(OJUtil.clazzObject),
"makeRow",
new ParameterList(),
new TypeName [] {
TypeName.forOJClass(OJUtil.clazzSQLException)
},
methodBody));
return new AllocationExpression(
TypeName.forOJClass(OJClass.forClass(ResultSetIterator.class)),
new ExpressionList(
new CastExpression(
TypeName.forOJClass(OJUtil.clazzResultSet),
childObj)),
memberList);
}
| public ParseTree implement(JavaRelImplementor implementor)
{
FarragoRelImplementor farragoImplementor =
(FarragoRelImplementor) implementor;
Expression childObj =
implementor.visitJavaChild(this, 0, (ResultSetRel) getChild());
StatementList methodBody = new StatementList();
// variable for synthetic object instance
Variable varTuple = implementor.newVariable();
// variable for source ResultSet
Variable varResultSet = new Variable("resultSet");
// This is a little silly. Have to put in a dummy cast
// so that type inference will stop early (otherwise it
// fails to find variable reference).
Expression castResultSet =
new CastExpression(
TypeName.forOJClass(OJUtil.clazzResultSet),
varResultSet);
RelDataType rowType = getRowType();
FarragoTypeFactory factory =
farragoImplementor.getPreparingStmt().getFarragoTypeFactory();
OJClass rowClass = OJUtil.typeToOJClass(rowType,factory);
JavaRexBuilder javaRexBuilder =
(JavaRexBuilder) getCluster().getRexBuilder();
MemberDeclarationList memberList = new MemberDeclarationList();
RelDataTypeField [] fields = rowType.getFields();
for (int i = 0; i < fields.length; ++i) {
RelDataTypeField field = fields[i];
RelDataType type = field.getType();
ExpressionList colPosExpList =
new ExpressionList(Literal.makeLiteral(i + 1));
Expression rhsExp;
if ((SqlTypeUtil.isJavaPrimitive(type)) && !type.isNullable()) {
// TODO: make this official: java.sql and java.nio
// use the same accessor names, happily,
// (except for boolean, sadly)
String methodName =
ReflectUtil.getByteBufferReadMethod(
factory.getClassForPrimitive(type)).getName();
if (type.getSqlTypeName() == SqlTypeName.Boolean) {
methodName = "getBoolean";
}
rhsExp =
new MethodCall(castResultSet, methodName, colPosExpList);
} else if (SqlTypeUtil.inCharFamily(type)) {
rhsExp =
new MethodCall(castResultSet, "getString", colPosExpList);
} else {
rhsExp =
new MethodCall(castResultSet, "getObject", colPosExpList);
}
RexNode rhs = javaRexBuilder.makeJava(
getCluster().getEnv(), rhsExp);
rhs = javaRexBuilder.makeAbstractCast(
field.getType(),
rhs);
final RexToOJTranslator translator =
farragoImplementor.newStmtTranslator(
this,
methodBody,
memberList);
translator.translateAssignment(
field,
new FieldAccess(
varTuple,
Util.toJavaId(
field.getName(),
i)),
rhs);
}
methodBody.add(new ReturnStatement(varTuple));
// allocate synthetic object as class data member
memberList.add(
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(rowClass),
varTuple.toString(),
new AllocationExpression(
rowClass,
new ExpressionList())));
// add method as implementation for super.makeRow
memberList.add(
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
TypeName.forOJClass(OJUtil.clazzObject),
"makeRow",
new ParameterList(),
new TypeName [] {
TypeName.forOJClass(OJUtil.clazzSQLException)
},
methodBody));
return new AllocationExpression(
TypeName.forOJClass(OJClass.forClass(ResultSetIterator.class)),
new ExpressionList(
new CastExpression(
TypeName.forOJClass(OJUtil.clazzResultSet),
childObj)),
memberList);
}
|
diff --git a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitRemoteHandlerV1.java b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitRemoteHandlerV1.java
index a1e73902..2e398cf6 100644
--- a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitRemoteHandlerV1.java
+++ b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitRemoteHandlerV1.java
@@ -1,319 +1,319 @@
/*******************************************************************************
* Copyright (c) 2011 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.orion.server.git.servlets;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.core.runtime.*;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.storage.file.FileRepository;
import org.eclipse.jgit.transport.*;
import org.eclipse.orion.internal.server.servlets.ProtocolConstants;
import org.eclipse.orion.internal.server.servlets.ServletResourceHandler;
import org.eclipse.orion.server.core.ServerStatus;
import org.eclipse.orion.server.core.tasks.TaskInfo;
import org.eclipse.orion.server.git.*;
import org.eclipse.orion.server.servlets.OrionServlet;
import org.eclipse.osgi.util.NLS;
import org.json.*;
public class GitRemoteHandlerV1 extends ServletResourceHandler<String> {
private ServletResourceHandler<IStatus> statusHandler;
GitRemoteHandlerV1(ServletResourceHandler<IStatus> statusHandler) {
this.statusHandler = statusHandler;
}
@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException {
try {
switch (getMethod(request)) {
case GET :
return handleGet(request, response, path);
// case PUT :
// return handlePut(request, response, path);
case POST :
return handlePost(request, response, path);
case DELETE :
return handleDelete(request, response, path);
}
} catch (Exception e) {
String msg = NLS.bind("Failed to handle /git/remote request for {0}", path); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
}
return false;
}
private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
Path p = new Path(path);
// FIXME: what if a remote or branch is named "file"?
if (p.segment(0).equals("file")) { //$NON-NLS-1$
// /git/remote/file/{path}
File gitDir = GitUtils.getGitDir(p);
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
JSONArray children = new JSONArray();
URI baseLocation = getURI(request);
for (String configName : configNames) {
JSONObject o = new JSONObject();
o.put(ProtocolConstants.KEY_NAME, configName);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2.baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
} else if (p.segment(1).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
result.put(ProtocolConstants.KEY_NAME, configName);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$
JSONArray children = new JSONArray();
List<Ref> refs = new ArrayList<Ref>();
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
if (!refEntry.getValue().isSymbolic()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
name = Repository.shortenRefName(name).substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
if (db.getBranch().equals(name)) {
refs.add(0, ref);
} else {
refs.add(ref);
}
}
}
for (Ref ref : refs) {
JSONObject o = new JSONObject();
String name = ref.getName();
o.put(ProtocolConstants.KEY_NAME, name);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation, BaseToBranchConverter.REMOTE));
o.put(GitConstants.KEY_INDEX, BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
} else if (p.segment(2).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/{branch}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES).entrySet()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
if (!ref.isSymbolic() && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
JSONObject result = new JSONObject();
result.put(ProtocolConstants.KEY_NAME, name);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
}
- return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No remote branch found: " + p.uptoSegment(2).removeTrailingSeparator(), null));
}
+ return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No remote branch found: " + p.uptoSegment(2).removeTrailingSeparator(), null));
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}
// remove remote
private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String path) throws CoreException, IOException, URISyntaxException {
Path p = new Path(path);
if (p.segment(1).equals("file")) { //$NON-NLS-1$
// expected path: /git/remote/{remote}/file/{path}
String remoteName = p.segment(0);
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
Repository db = new FileRepository(gitDir);
StoredConfig config = db.getConfig();
config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName);
config.save();
//TODO: handle result
return true;
}
return false;
}
private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
Path p = new Path(path);
if (p.segment(0).equals("file")) { //$NON-NLS-1$
// handle adding new remote
// expected path: /git/remote/file/{path}
return addRemote(request, response, path);
} else {
JSONObject requestObject = OrionServlet.readJSONRequest(request);
boolean fetch = Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_FETCH, null));
String srcRef = requestObject.optString(GitConstants.KEY_PUSH_SRC_REF, null);
boolean tags = requestObject.optBoolean(GitConstants.KEY_PUSH_TAGS, false);
// prepare creds
String username = requestObject.optString(GitConstants.KEY_USERNAME, null);
char[] password = requestObject.optString(GitConstants.KEY_PASSWORD, "").toCharArray(); //$NON-NLS-1$
String knownHosts = requestObject.optString(GitConstants.KEY_KNOWN_HOSTS, null);
byte[] privateKey = requestObject.optString(GitConstants.KEY_PRIVATE_KEY, "").getBytes(); //$NON-NLS-1$
byte[] publicKey = requestObject.optString(GitConstants.KEY_PUBLIC_KEY, "").getBytes(); //$NON-NLS-1$
byte[] passphrase = requestObject.optString(GitConstants.KEY_PASSPHRASE, "").getBytes(); //$NON-NLS-1$
GitCredentialsProvider cp = new GitCredentialsProvider(null, username, password, knownHosts);
cp.setPrivateKey(privateKey);
cp.setPublicKey(publicKey);
cp.setPassphrase(passphrase);
// if all went well, continue with fetch or push
if (fetch) {
return fetch(request, response, cp, path);
} else if (srcRef != null) {
if (srcRef.equals("")) { //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Pushing with an empty source ref is not allowed. Did you mean DELETE?", null));
}
return push(request, response, path, cp, srcRef, tags);
} else {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Only Fetch:true is currently supported.", null));
}
}
}
// add new remote
private boolean addRemote(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, CoreException, URISyntaxException {
// expected path: /git/remote/file/{path}
Path p = new Path(path);
JSONObject toPut = OrionServlet.readJSONRequest(request);
String remoteName = toPut.optString(GitConstants.KEY_REMOTE_NAME, null);
// remoteName is required
if (remoteName == null || remoteName.isEmpty()) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Remote name must be provided", null));
}
String remoteURI = toPut.optString(GitConstants.KEY_REMOTE_URI, null);
// remoteURI is required
if (remoteURI == null || remoteURI.isEmpty()) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Remote URI must be provided", null));
}
String fetchRefSpec = toPut.optString(GitConstants.KEY_REMOTE_FETCH_REF, null);
String remotePushURI = toPut.optString(GitConstants.KEY_REMOTE_PUSH_URI, null);
String pushRefSpec = toPut.optString(GitConstants.KEY_REMOTE_PUSH_REF, null);
File gitDir = GitUtils.getGitDir(p);
Repository db = new FileRepository(gitDir);
StoredConfig config = db.getConfig();
RemoteConfig rc = new RemoteConfig(config, remoteName);
rc.addURI(new URIish(remoteURI));
// FetchRefSpec is required, but default version can be generated
// if it isn't provided
if (fetchRefSpec == null || fetchRefSpec.isEmpty()) {
fetchRefSpec = String.format("+refs/heads/*:refs/remotes/%s/*", remoteName); //$NON-NLS-1$
}
rc.addFetchRefSpec(new RefSpec(fetchRefSpec));
// pushURI is optional
if (remotePushURI != null && !remotePushURI.isEmpty())
rc.addPushURI(new URIish(remotePushURI));
// PushRefSpec is optional
if (pushRefSpec != null && !pushRefSpec.isEmpty())
rc.addPushRefSpec(new RefSpec(pushRefSpec));
rc.update(config);
config.save();
URI baseLocation = getURI(request);
JSONObject result = toJSON(remoteName, baseLocation);
OrionServlet.writeJSONResponse(request, response, result);
response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION));
response.setStatus(HttpServletResponse.SC_CREATED);
return true;
}
private boolean fetch(HttpServletRequest request, HttpServletResponse response, GitCredentialsProvider cp, String path) throws URISyntaxException, JSONException, IOException {
// {remote}/{branch}/{file}/{path}
Path p = new Path(path);
FetchJob job = new FetchJob(cp, p);
job.schedule();
TaskInfo task = job.getTask();
JSONObject result = task.toJSON();
URI taskLocation = createTaskLocation(OrionServlet.getURI(request), task.getTaskId());
result.put(ProtocolConstants.KEY_LOCATION, taskLocation);
response.setHeader(ProtocolConstants.HEADER_LOCATION, taskLocation.toString());
OrionServlet.writeJSONResponse(request, response, result);
response.setStatus(HttpServletResponse.SC_ACCEPTED);
return true;
}
private boolean push(HttpServletRequest request, HttpServletResponse response, String path, GitCredentialsProvider cp, String srcRef, boolean tags) throws ServletException, CoreException, IOException, JSONException, URISyntaxException {
Path p = new Path(path);
// FIXME: what if a remote or branch is named "file"?
if (p.segment(2).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/{branch}/file/{path}
PushJob job = new PushJob(cp, p, srcRef, tags);
job.schedule();
TaskInfo task = job.getTask();
JSONObject result = task.toJSON();
URI taskLocation = createTaskLocation(OrionServlet.getURI(request), task.getTaskId());
result.put(ProtocolConstants.KEY_LOCATION, taskLocation);
response.setHeader(ProtocolConstants.HEADER_LOCATION, taskLocation.toString());
OrionServlet.writeJSONResponse(request, response, result);
response.setStatus(HttpServletResponse.SC_ACCEPTED);
return true;
}
return false;
}
private URI createTaskLocation(URI baseLocation, String taskId) throws URISyntaxException {
return new URI(baseLocation.getScheme(), baseLocation.getAuthority(), "/task/id/" + taskId, null, null); //$NON-NLS-1$
}
private JSONObject toJSON(String remoteName, URI baseLocation) throws JSONException, URISyntaxException {
JSONObject result = new JSONObject();
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2.baseToRemoteLocation(baseLocation, Repository.shortenRefName(remoteName), ""));
return result;
}
}
| false | true | private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
Path p = new Path(path);
// FIXME: what if a remote or branch is named "file"?
if (p.segment(0).equals("file")) { //$NON-NLS-1$
// /git/remote/file/{path}
File gitDir = GitUtils.getGitDir(p);
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
JSONArray children = new JSONArray();
URI baseLocation = getURI(request);
for (String configName : configNames) {
JSONObject o = new JSONObject();
o.put(ProtocolConstants.KEY_NAME, configName);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2.baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
} else if (p.segment(1).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
result.put(ProtocolConstants.KEY_NAME, configName);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$
JSONArray children = new JSONArray();
List<Ref> refs = new ArrayList<Ref>();
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
if (!refEntry.getValue().isSymbolic()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
name = Repository.shortenRefName(name).substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
if (db.getBranch().equals(name)) {
refs.add(0, ref);
} else {
refs.add(ref);
}
}
}
for (Ref ref : refs) {
JSONObject o = new JSONObject();
String name = ref.getName();
o.put(ProtocolConstants.KEY_NAME, name);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation, BaseToBranchConverter.REMOTE));
o.put(GitConstants.KEY_INDEX, BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
} else if (p.segment(2).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/{branch}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES).entrySet()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
if (!ref.isSymbolic() && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
JSONObject result = new JSONObject();
result.put(ProtocolConstants.KEY_NAME, name);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No remote branch found: " + p.uptoSegment(2).removeTrailingSeparator(), null));
}
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}
| private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
Path p = new Path(path);
// FIXME: what if a remote or branch is named "file"?
if (p.segment(0).equals("file")) { //$NON-NLS-1$
// /git/remote/file/{path}
File gitDir = GitUtils.getGitDir(p);
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
JSONArray children = new JSONArray();
URI baseLocation = getURI(request);
for (String configName : configNames) {
JSONObject o = new JSONObject();
o.put(ProtocolConstants.KEY_NAME, configName);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2.baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
} else if (p.segment(1).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
result.put(ProtocolConstants.KEY_NAME, configName);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$
JSONArray children = new JSONArray();
List<Ref> refs = new ArrayList<Ref>();
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
if (!refEntry.getValue().isSymbolic()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
name = Repository.shortenRefName(name).substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
if (db.getBranch().equals(name)) {
refs.add(0, ref);
} else {
refs.add(ref);
}
}
}
for (Ref ref : refs) {
JSONObject o = new JSONObject();
String name = ref.getName();
o.put(ProtocolConstants.KEY_NAME, name);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation, BaseToBranchConverter.REMOTE));
o.put(GitConstants.KEY_INDEX, BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
} else if (p.segment(2).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/{branch}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES).entrySet()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
if (!ref.isSymbolic() && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
JSONObject result = new JSONObject();
result.put(ProtocolConstants.KEY_NAME, name);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
}
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No remote branch found: " + p.uptoSegment(2).removeTrailingSeparator(), null));
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}
|
diff --git a/src/main/java/org/apache/log4j/chainsaw/TableColorizingRenderer.java b/src/main/java/org/apache/log4j/chainsaw/TableColorizingRenderer.java
index 1cef2ed..eb6d656 100644
--- a/src/main/java/org/apache/log4j/chainsaw/TableColorizingRenderer.java
+++ b/src/main/java/org/apache/log4j/chainsaw/TableColorizingRenderer.java
@@ -1,402 +1,402 @@
/*
* 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.log4j.chainsaw;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import org.apache.log4j.chainsaw.color.RuleColorizer;
import org.apache.log4j.chainsaw.icons.LevelIconFactory;
import org.apache.log4j.helpers.Constants;
import org.apache.log4j.rule.Rule;
/**
* A specific TableCellRenderer that colourizes a particular cell based on
* some ColourFilters that have been stored according to the value for the row
*
* @author Claude Duguay
* @author Scott Deboy <[email protected]>
* @author Paul Smith <[email protected]>
*
*/
public class TableColorizingRenderer extends DefaultTableCellRenderer {
private static final DateFormat DATE_FORMATTER = new SimpleDateFormat(Constants.SIMPLE_TIME_PATTERN);
private static final Map iconMap = LevelIconFactory.getInstance().getLevelToIconMap();
private RuleColorizer colorizer;
private boolean levelUseIcons = false;
private boolean wrapMsg = false;
private DateFormat dateFormatInUse = DATE_FORMATTER;
private int loggerPrecision = 0;
private boolean toolTipsVisible;
private String dateFormatTZ;
private boolean useRelativeTimes = false;
private long relativeTimestampBase;
private static int borderWidth = 2;
private static Color borderColor = (Color)UIManager.get("Table.selectionBackground");
private static final Border LEFT_BORDER = BorderFactory.createMatteBorder(borderWidth, borderWidth, borderWidth, 0, borderColor);
private static final Border MIDDLE_BORDER = BorderFactory.createMatteBorder(borderWidth, 0, borderWidth, 0, borderColor);
private static final Border RIGHT_BORDER = BorderFactory.createMatteBorder(borderWidth, 0, borderWidth, borderWidth, borderColor);
private static final Border LEFT_EMPTY_BORDER = BorderFactory.createEmptyBorder(borderWidth, borderWidth, borderWidth, 0);
private static final Border MIDDLE_EMPTY_BORDER = BorderFactory.createEmptyBorder(borderWidth, 0, borderWidth, 0);
private static final Border RIGHT_EMPTY_BORDER = BorderFactory.createEmptyBorder(borderWidth, 0, borderWidth, borderWidth);
private final JTextArea msgTextArea = new JTextArea();
private final JLabel levelLabel = new JLabel();
private final JLabel generalLabel = new JLabel();
private final JPanel msgPanel = new JPanel();
private final JPanel generalPanel = new JPanel();
private final JPanel levelPanel = new JPanel();
/**
* Creates a new TableColorizingRenderer object.
*/
public TableColorizingRenderer(RuleColorizer colorizer) {
msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.Y_AXIS));
generalPanel.setLayout(new BoxLayout(generalPanel, BoxLayout.Y_AXIS));
levelPanel.setLayout(new BoxLayout(levelPanel, BoxLayout.Y_AXIS));
msgPanel.setAlignmentX(TOP_ALIGNMENT);
generalPanel.setAlignmentX(TOP_ALIGNMENT);
levelPanel.setAlignmentX(TOP_ALIGNMENT);
generalLabel.setVerticalAlignment(SwingConstants.TOP);
levelLabel.setVerticalAlignment(SwingConstants.TOP);
levelLabel.setOpaque(true);
levelLabel.setText("");
msgTextArea.setMargin(null);
msgTextArea.setEditable(false);
msgPanel.add(msgTextArea);
generalPanel.add(generalLabel);
levelPanel.add(levelLabel);
this.colorizer = colorizer;
}
public void setToolTipsVisible(boolean toolTipsVisible) {
this.toolTipsVisible = toolTipsVisible;
}
public Component getTableCellRendererComponent(
final JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
value = formatField(value);
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
TableColumn tableColumn = table.getColumnModel().getColumn(col);
//chainsawcolumns uses one-based indexing
int colIndex = tableColumn.getModelIndex() + 1;
EventContainer container = (EventContainer) table.getModel();
ExtendedLoggingEvent loggingEvent = container.getRow(row);
//no event, use default renderer
if (loggingEvent == null) {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
}
JComponent component;
switch (colIndex) {
case ChainsawColumns.INDEX_THROWABLE_COL_NAME:
if (value instanceof String[] && ((String[])value).length > 0){
generalLabel.setText(((String[]) value)[0]);
} else {
generalLabel.setText("");
}
component = generalPanel;
break;
case ChainsawColumns.INDEX_LOGGER_COL_NAME:
String logger = value.toString();
int startPos = -1;
for (int i = 0; i < loggerPrecision; i++) {
startPos = logger.indexOf(".", startPos + 1);
if (startPos < 0) {
break;
}
}
generalLabel.setText(logger.substring(startPos + 1));
component = generalPanel;
break;
case ChainsawColumns.INDEX_ID_COL_NAME:
case ChainsawColumns.INDEX_LOG4J_MARKER_COL_NAME:
case ChainsawColumns.INDEX_CLASS_COL_NAME:
case ChainsawColumns.INDEX_FILE_COL_NAME:
case ChainsawColumns.INDEX_LINE_COL_NAME:
case ChainsawColumns.INDEX_NDC_COL_NAME:
case ChainsawColumns.INDEX_THREAD_COL_NAME:
case ChainsawColumns.INDEX_TIMESTAMP_COL_NAME:
case ChainsawColumns.INDEX_METHOD_COL_NAME:
generalLabel.setText(value.toString());
component = generalPanel;
break;
case ChainsawColumns.INDEX_MESSAGE_COL_NAME:
String string = value.toString().trim();
int width = tableColumn.getWidth();
msgTextArea.setLineWrap(wrapMsg);
msgTextArea.setWrapStyleWord(wrapMsg);
msgTextArea.setFont(label.getFont());
msgTextArea.setText(string);
int tableRowHeight = table.getRowHeight(row);
if (wrapMsg) {
Map paramMap = new HashMap();
paramMap.put(TextAttribute.FONT, msgTextArea.getFont());
int calculatedHeight = calculateHeight(string, width, paramMap);
msgTextArea.setSize(new Dimension(width, calculatedHeight));
int msgPanelPrefHeight = msgPanel.getPreferredSize().height;
if(tableRowHeight < msgPanelPrefHeight/* && calculatedHeight > tableRowHeight*/) {
table.setRowHeight(row, Math.max(ChainsawConstants.DEFAULT_ROW_HEIGHT, msgPanelPrefHeight));
}
}
component = msgPanel;
break;
case ChainsawColumns.INDEX_LEVEL_COL_NAME:
if (levelUseIcons) {
levelLabel.setIcon((Icon) iconMap.get(value.toString()));
if (levelLabel.getIcon() != null) {
levelLabel.setText("");
}
if (!toolTipsVisible) {
levelLabel.setToolTipText(value.toString());
}
} else {
levelLabel.setIcon(null);
levelLabel.setText(value.toString());
if (!toolTipsVisible) {
levelLabel.setToolTipText(null);
}
}
if (toolTipsVisible) {
levelLabel.setToolTipText(label.getToolTipText());
}
levelLabel.setForeground(label.getForeground());
levelLabel.setBackground(label.getBackground());
component = levelPanel;
break;
//remaining entries are properties
default:
Set propertySet = loggingEvent.getPropertyKeySet();
String headerName = tableColumn.getHeaderValue().toString().toLowerCase();
String thisProp = null;
//find the property in the property set...case-sensitive
for (Iterator iter = propertySet.iterator();iter.hasNext();) {
String entry = iter.next().toString();
if (entry.toLowerCase().equals(headerName)) {
thisProp = entry;
break;
}
}
if (thisProp != null) {
- generalLabel.setText(loggingEvent.getProperty(headerName));
+ generalLabel.setText(loggingEvent.getProperty(thisProp));
} else {
generalLabel.setText("");
}
component = generalPanel;
break;
}
Color background;
Color foreground;
Rule loggerRule = colorizer.getLoggerRule();
//use logger colors in table instead of event colors if event passes logger rule
if (loggerRule != null && loggerRule.evaluate(loggingEvent)) {
background = ChainsawConstants.FIND_LOGGER_BACKGROUND;
foreground = ChainsawConstants.FIND_LOGGER_FOREGROUND;
} else {
background = loggingEvent.getBackground();
foreground = loggingEvent.getForeground();
}
/**
* Colourize background based on row striping if the event still has a background color
*/
if (background.equals(ChainsawConstants.COLOR_DEFAULT_BACKGROUND)) {
if ((row % 2) != 0) {
background = ChainsawConstants.COLOR_ODD_ROW;
} else {
background = ChainsawConstants.COLOR_EVEN_ROW;
}
}
component.setBackground(background);
component.setForeground(foreground);
//set the colors of the components inside 'component'
msgTextArea.setBackground(background);
msgTextArea.setForeground(foreground);
levelLabel.setBackground(background);
levelLabel.setForeground(foreground);
generalLabel.setBackground(background);
generalLabel.setForeground(foreground);
if (isSelected) {
if (col == 0) {
component.setBorder(LEFT_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_BORDER);
} else {
component.setBorder(MIDDLE_BORDER);
}
} else {
if (col == 0) {
component.setBorder(LEFT_EMPTY_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_EMPTY_BORDER);
} else {
component.setBorder(MIDDLE_EMPTY_BORDER);
}
}
return component;
}
/**
* Changes the Date Formatting object to be used for rendering dates.
* @param formatter
*/
void setDateFormatter(DateFormat formatter) {
this.dateFormatInUse = formatter;
if (dateFormatInUse != null && dateFormatTZ != null && !("".equals(dateFormatTZ))) {
dateFormatInUse.setTimeZone(TimeZone.getTimeZone(dateFormatTZ));
} else {
dateFormatInUse.setTimeZone(TimeZone.getDefault());
}
}
/**
* Changes the Logger precision.
* @param loggerPrecisionText
*/
void setLoggerPrecision(String loggerPrecisionText) {
try {
loggerPrecision = Integer.parseInt(loggerPrecisionText);
} catch (NumberFormatException nfe) {
loggerPrecision = 0;
}
}
/**
*Format date field
*
* @param o object
*
* @return formatted object
*/
private Object formatField(Object o) {
if (!(o instanceof Date)) {
return (o == null ? "" : o);
}
//handle date field
if (useRelativeTimes)
{
return "" + (((Date)o).getTime() - relativeTimestampBase);
}
return dateFormatInUse.format((Date) o);
}
/**
* Sets the property which determines whether to wrap the message
* @param wrapMsg
*/
public void setWrapMessage(boolean wrapMsg) {
this.wrapMsg = wrapMsg;
}
/**
* Sets the property which determines whether to use Icons or text
* for the Level column
* @param levelUseIcons
*/
public void setLevelUseIcons(boolean levelUseIcons) {
this.levelUseIcons = levelUseIcons;
}
public void setTimeZone(String dateFormatTZ) {
this.dateFormatTZ = dateFormatTZ;
if (dateFormatInUse != null && dateFormatTZ != null && !("".equals(dateFormatTZ))) {
dateFormatInUse.setTimeZone(TimeZone.getTimeZone(dateFormatTZ));
} else {
dateFormatInUse.setTimeZone(TimeZone.getDefault());
}
}
public void setUseRelativeTimes(long timeStamp) {
useRelativeTimes = true;
relativeTimestampBase = timeStamp;
}
public void setUseNormalTimes() {
useRelativeTimes = false;
}
private int calculateHeight(String string, int width, Map paramMap) {
if (string.trim().length() == 0) {
return ChainsawConstants.DEFAULT_ROW_HEIGHT;
}
AttributedCharacterIterator paragraph = new AttributedString(string, paramMap).getIterator();
LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, new FontRenderContext(null, true, true));
float height = 0;
lineMeasurer.setPosition(paragraph.getBeginIndex());
TextLayout layout;
while (lineMeasurer.getPosition() < paragraph.getEndIndex()) {
layout = lineMeasurer.nextLayout(width);
float layoutHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();
height += layoutHeight;
}
return Math.max(ChainsawConstants.DEFAULT_ROW_HEIGHT, (int) height);
}
}
| true | true | public Component getTableCellRendererComponent(
final JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
value = formatField(value);
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
TableColumn tableColumn = table.getColumnModel().getColumn(col);
//chainsawcolumns uses one-based indexing
int colIndex = tableColumn.getModelIndex() + 1;
EventContainer container = (EventContainer) table.getModel();
ExtendedLoggingEvent loggingEvent = container.getRow(row);
//no event, use default renderer
if (loggingEvent == null) {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
}
JComponent component;
switch (colIndex) {
case ChainsawColumns.INDEX_THROWABLE_COL_NAME:
if (value instanceof String[] && ((String[])value).length > 0){
generalLabel.setText(((String[]) value)[0]);
} else {
generalLabel.setText("");
}
component = generalPanel;
break;
case ChainsawColumns.INDEX_LOGGER_COL_NAME:
String logger = value.toString();
int startPos = -1;
for (int i = 0; i < loggerPrecision; i++) {
startPos = logger.indexOf(".", startPos + 1);
if (startPos < 0) {
break;
}
}
generalLabel.setText(logger.substring(startPos + 1));
component = generalPanel;
break;
case ChainsawColumns.INDEX_ID_COL_NAME:
case ChainsawColumns.INDEX_LOG4J_MARKER_COL_NAME:
case ChainsawColumns.INDEX_CLASS_COL_NAME:
case ChainsawColumns.INDEX_FILE_COL_NAME:
case ChainsawColumns.INDEX_LINE_COL_NAME:
case ChainsawColumns.INDEX_NDC_COL_NAME:
case ChainsawColumns.INDEX_THREAD_COL_NAME:
case ChainsawColumns.INDEX_TIMESTAMP_COL_NAME:
case ChainsawColumns.INDEX_METHOD_COL_NAME:
generalLabel.setText(value.toString());
component = generalPanel;
break;
case ChainsawColumns.INDEX_MESSAGE_COL_NAME:
String string = value.toString().trim();
int width = tableColumn.getWidth();
msgTextArea.setLineWrap(wrapMsg);
msgTextArea.setWrapStyleWord(wrapMsg);
msgTextArea.setFont(label.getFont());
msgTextArea.setText(string);
int tableRowHeight = table.getRowHeight(row);
if (wrapMsg) {
Map paramMap = new HashMap();
paramMap.put(TextAttribute.FONT, msgTextArea.getFont());
int calculatedHeight = calculateHeight(string, width, paramMap);
msgTextArea.setSize(new Dimension(width, calculatedHeight));
int msgPanelPrefHeight = msgPanel.getPreferredSize().height;
if(tableRowHeight < msgPanelPrefHeight/* && calculatedHeight > tableRowHeight*/) {
table.setRowHeight(row, Math.max(ChainsawConstants.DEFAULT_ROW_HEIGHT, msgPanelPrefHeight));
}
}
component = msgPanel;
break;
case ChainsawColumns.INDEX_LEVEL_COL_NAME:
if (levelUseIcons) {
levelLabel.setIcon((Icon) iconMap.get(value.toString()));
if (levelLabel.getIcon() != null) {
levelLabel.setText("");
}
if (!toolTipsVisible) {
levelLabel.setToolTipText(value.toString());
}
} else {
levelLabel.setIcon(null);
levelLabel.setText(value.toString());
if (!toolTipsVisible) {
levelLabel.setToolTipText(null);
}
}
if (toolTipsVisible) {
levelLabel.setToolTipText(label.getToolTipText());
}
levelLabel.setForeground(label.getForeground());
levelLabel.setBackground(label.getBackground());
component = levelPanel;
break;
//remaining entries are properties
default:
Set propertySet = loggingEvent.getPropertyKeySet();
String headerName = tableColumn.getHeaderValue().toString().toLowerCase();
String thisProp = null;
//find the property in the property set...case-sensitive
for (Iterator iter = propertySet.iterator();iter.hasNext();) {
String entry = iter.next().toString();
if (entry.toLowerCase().equals(headerName)) {
thisProp = entry;
break;
}
}
if (thisProp != null) {
generalLabel.setText(loggingEvent.getProperty(headerName));
} else {
generalLabel.setText("");
}
component = generalPanel;
break;
}
Color background;
Color foreground;
Rule loggerRule = colorizer.getLoggerRule();
//use logger colors in table instead of event colors if event passes logger rule
if (loggerRule != null && loggerRule.evaluate(loggingEvent)) {
background = ChainsawConstants.FIND_LOGGER_BACKGROUND;
foreground = ChainsawConstants.FIND_LOGGER_FOREGROUND;
} else {
background = loggingEvent.getBackground();
foreground = loggingEvent.getForeground();
}
/**
* Colourize background based on row striping if the event still has a background color
*/
if (background.equals(ChainsawConstants.COLOR_DEFAULT_BACKGROUND)) {
if ((row % 2) != 0) {
background = ChainsawConstants.COLOR_ODD_ROW;
} else {
background = ChainsawConstants.COLOR_EVEN_ROW;
}
}
component.setBackground(background);
component.setForeground(foreground);
//set the colors of the components inside 'component'
msgTextArea.setBackground(background);
msgTextArea.setForeground(foreground);
levelLabel.setBackground(background);
levelLabel.setForeground(foreground);
generalLabel.setBackground(background);
generalLabel.setForeground(foreground);
if (isSelected) {
if (col == 0) {
component.setBorder(LEFT_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_BORDER);
} else {
component.setBorder(MIDDLE_BORDER);
}
} else {
if (col == 0) {
component.setBorder(LEFT_EMPTY_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_EMPTY_BORDER);
} else {
component.setBorder(MIDDLE_EMPTY_BORDER);
}
}
return component;
}
| public Component getTableCellRendererComponent(
final JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
value = formatField(value);
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
TableColumn tableColumn = table.getColumnModel().getColumn(col);
//chainsawcolumns uses one-based indexing
int colIndex = tableColumn.getModelIndex() + 1;
EventContainer container = (EventContainer) table.getModel();
ExtendedLoggingEvent loggingEvent = container.getRow(row);
//no event, use default renderer
if (loggingEvent == null) {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
}
JComponent component;
switch (colIndex) {
case ChainsawColumns.INDEX_THROWABLE_COL_NAME:
if (value instanceof String[] && ((String[])value).length > 0){
generalLabel.setText(((String[]) value)[0]);
} else {
generalLabel.setText("");
}
component = generalPanel;
break;
case ChainsawColumns.INDEX_LOGGER_COL_NAME:
String logger = value.toString();
int startPos = -1;
for (int i = 0; i < loggerPrecision; i++) {
startPos = logger.indexOf(".", startPos + 1);
if (startPos < 0) {
break;
}
}
generalLabel.setText(logger.substring(startPos + 1));
component = generalPanel;
break;
case ChainsawColumns.INDEX_ID_COL_NAME:
case ChainsawColumns.INDEX_LOG4J_MARKER_COL_NAME:
case ChainsawColumns.INDEX_CLASS_COL_NAME:
case ChainsawColumns.INDEX_FILE_COL_NAME:
case ChainsawColumns.INDEX_LINE_COL_NAME:
case ChainsawColumns.INDEX_NDC_COL_NAME:
case ChainsawColumns.INDEX_THREAD_COL_NAME:
case ChainsawColumns.INDEX_TIMESTAMP_COL_NAME:
case ChainsawColumns.INDEX_METHOD_COL_NAME:
generalLabel.setText(value.toString());
component = generalPanel;
break;
case ChainsawColumns.INDEX_MESSAGE_COL_NAME:
String string = value.toString().trim();
int width = tableColumn.getWidth();
msgTextArea.setLineWrap(wrapMsg);
msgTextArea.setWrapStyleWord(wrapMsg);
msgTextArea.setFont(label.getFont());
msgTextArea.setText(string);
int tableRowHeight = table.getRowHeight(row);
if (wrapMsg) {
Map paramMap = new HashMap();
paramMap.put(TextAttribute.FONT, msgTextArea.getFont());
int calculatedHeight = calculateHeight(string, width, paramMap);
msgTextArea.setSize(new Dimension(width, calculatedHeight));
int msgPanelPrefHeight = msgPanel.getPreferredSize().height;
if(tableRowHeight < msgPanelPrefHeight/* && calculatedHeight > tableRowHeight*/) {
table.setRowHeight(row, Math.max(ChainsawConstants.DEFAULT_ROW_HEIGHT, msgPanelPrefHeight));
}
}
component = msgPanel;
break;
case ChainsawColumns.INDEX_LEVEL_COL_NAME:
if (levelUseIcons) {
levelLabel.setIcon((Icon) iconMap.get(value.toString()));
if (levelLabel.getIcon() != null) {
levelLabel.setText("");
}
if (!toolTipsVisible) {
levelLabel.setToolTipText(value.toString());
}
} else {
levelLabel.setIcon(null);
levelLabel.setText(value.toString());
if (!toolTipsVisible) {
levelLabel.setToolTipText(null);
}
}
if (toolTipsVisible) {
levelLabel.setToolTipText(label.getToolTipText());
}
levelLabel.setForeground(label.getForeground());
levelLabel.setBackground(label.getBackground());
component = levelPanel;
break;
//remaining entries are properties
default:
Set propertySet = loggingEvent.getPropertyKeySet();
String headerName = tableColumn.getHeaderValue().toString().toLowerCase();
String thisProp = null;
//find the property in the property set...case-sensitive
for (Iterator iter = propertySet.iterator();iter.hasNext();) {
String entry = iter.next().toString();
if (entry.toLowerCase().equals(headerName)) {
thisProp = entry;
break;
}
}
if (thisProp != null) {
generalLabel.setText(loggingEvent.getProperty(thisProp));
} else {
generalLabel.setText("");
}
component = generalPanel;
break;
}
Color background;
Color foreground;
Rule loggerRule = colorizer.getLoggerRule();
//use logger colors in table instead of event colors if event passes logger rule
if (loggerRule != null && loggerRule.evaluate(loggingEvent)) {
background = ChainsawConstants.FIND_LOGGER_BACKGROUND;
foreground = ChainsawConstants.FIND_LOGGER_FOREGROUND;
} else {
background = loggingEvent.getBackground();
foreground = loggingEvent.getForeground();
}
/**
* Colourize background based on row striping if the event still has a background color
*/
if (background.equals(ChainsawConstants.COLOR_DEFAULT_BACKGROUND)) {
if ((row % 2) != 0) {
background = ChainsawConstants.COLOR_ODD_ROW;
} else {
background = ChainsawConstants.COLOR_EVEN_ROW;
}
}
component.setBackground(background);
component.setForeground(foreground);
//set the colors of the components inside 'component'
msgTextArea.setBackground(background);
msgTextArea.setForeground(foreground);
levelLabel.setBackground(background);
levelLabel.setForeground(foreground);
generalLabel.setBackground(background);
generalLabel.setForeground(foreground);
if (isSelected) {
if (col == 0) {
component.setBorder(LEFT_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_BORDER);
} else {
component.setBorder(MIDDLE_BORDER);
}
} else {
if (col == 0) {
component.setBorder(LEFT_EMPTY_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_EMPTY_BORDER);
} else {
component.setBorder(MIDDLE_EMPTY_BORDER);
}
}
return component;
}
|
diff --git a/src/com/android/camera/IconListPreference.java b/src/com/android/camera/IconListPreference.java
index fc23f6c3..de9cba1e 100644
--- a/src/com/android/camera/IconListPreference.java
+++ b/src/com/android/camera/IconListPreference.java
@@ -1,91 +1,94 @@
/*
* 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.camera;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import com.android.camera.R;
import java.util.List;
/** A {@code ListPreference} where each entry has a corresponding icon. */
public class IconListPreference extends ListPreference {
private int mIconIds[];
private int mLargeIconIds[];
public IconListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.IconListPreference, 0, 0);
Resources res = context.getResources();
mIconIds = getIconIds(res, a.getResourceId(
R.styleable.IconListPreference_icons, 0));
mLargeIconIds = getIconIds(res, a.getResourceId(
R.styleable.IconListPreference_largeIcons, 0));
a.recycle();
}
public int[] getLargeIconIds() {
return mLargeIconIds;
}
public int[] getIconIds() {
return mIconIds;
}
public void setLargeIconIds(int[] largeIconIds) {
mLargeIconIds = largeIconIds;
}
public void setIconIds(int[] iconIds) {
mIconIds = iconIds;
}
private int[] getIconIds(Resources res, int iconsRes) {
if (iconsRes == 0) return null;
TypedArray array = res.obtainTypedArray(iconsRes);
int n = array.length();
int ids[] = new int[n];
for (int i = 0; i < n; ++i) {
ids[i] = array.getResourceId(i, 0);
}
array.recycle();
return ids;
}
@Override
public void filterUnsupported(List<String> supported) {
CharSequence entryValues[] = getEntryValues();
IntArray iconIds = new IntArray();
IntArray largeIconIds = new IntArray();
+ // We allow mIconsIds to be null, but not mLargeIconIds. The reason is that if large icons
+ // are unspecified, the on screen icons will be blank which is a bug.
for (int i = 0, len = entryValues.length; i < len; i++) {
if (supported.indexOf(entryValues[i].toString()) >= 0) {
- iconIds.add(mIconIds[i]);
+ if (mIconIds != null) {
+ iconIds.add(mIconIds[i]);
+ }
largeIconIds.add(mLargeIconIds[i]);
}
}
- int size = iconIds.size();
- mIconIds = iconIds.toArray(new int[size]);
- mLargeIconIds = iconIds.toArray(new int[size]);
+ if (mIconIds != null) mIconIds = iconIds.toArray(new int[iconIds.size()]);
+ mLargeIconIds = largeIconIds.toArray(new int[largeIconIds.size()]);
super.filterUnsupported(supported);
}
}
| false | true | public void filterUnsupported(List<String> supported) {
CharSequence entryValues[] = getEntryValues();
IntArray iconIds = new IntArray();
IntArray largeIconIds = new IntArray();
for (int i = 0, len = entryValues.length; i < len; i++) {
if (supported.indexOf(entryValues[i].toString()) >= 0) {
iconIds.add(mIconIds[i]);
largeIconIds.add(mLargeIconIds[i]);
}
}
int size = iconIds.size();
mIconIds = iconIds.toArray(new int[size]);
mLargeIconIds = iconIds.toArray(new int[size]);
super.filterUnsupported(supported);
}
| public void filterUnsupported(List<String> supported) {
CharSequence entryValues[] = getEntryValues();
IntArray iconIds = new IntArray();
IntArray largeIconIds = new IntArray();
// We allow mIconsIds to be null, but not mLargeIconIds. The reason is that if large icons
// are unspecified, the on screen icons will be blank which is a bug.
for (int i = 0, len = entryValues.length; i < len; i++) {
if (supported.indexOf(entryValues[i].toString()) >= 0) {
if (mIconIds != null) {
iconIds.add(mIconIds[i]);
}
largeIconIds.add(mLargeIconIds[i]);
}
}
if (mIconIds != null) mIconIds = iconIds.toArray(new int[iconIds.size()]);
mLargeIconIds = largeIconIds.toArray(new int[largeIconIds.size()]);
super.filterUnsupported(supported);
}
|
diff --git a/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java b/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java
index 0b53645..dc6d0d6 100644
--- a/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java
+++ b/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java
@@ -1,733 +1,733 @@
/**
*
*/
package com.madhackerdesigns.neverbelate.ui;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.madhackerdesigns.neverbelate.R;
import com.madhackerdesigns.neverbelate.provider.AlertsContract;
import com.madhackerdesigns.neverbelate.provider.AlertsHelper;
import com.madhackerdesigns.neverbelate.service.NeverBeLateService;
import com.madhackerdesigns.neverbelate.service.ServiceCommander;
import com.madhackerdesigns.neverbelate.service.WakefulServiceReceiver;
import com.madhackerdesigns.neverbelate.settings.PreferenceHelper;
import com.madhackerdesigns.neverbelate.ui.UserLocationOverlay.OnLocationChangedListener;
import com.madhackerdesigns.neverbelate.util.AdHelper;
import com.madhackerdesigns.neverbelate.util.BuildMode;
import com.madhackerdesigns.neverbelate.util.Logger;
/**
* @author flintinatux
*
*/
public class WarningDialog extends MapActivity implements ServiceCommander {
// private static tokens
private static final int ALERT_TOKEN = 1;
private static final String LOG_TAG = "NeverBeLateWarning";
// static strings for intent stuff
private static final String PACKAGE_NAME = "com.madhackerdesigns.neverbelate";
private static final Uri APP_DETAILS_URI = Uri.parse("market://details?id=" + PACKAGE_NAME);
public static final String EXTRA_URI = PACKAGE_NAME + ".uri";
private static final String MAPS_URL = "http://maps.google.com/maps";
// static strings for view tags
private static final String TAG_ALERT_LIST = "alert_list";
private static final String TAG_TRAFFIC_VIEW = "traffic_view";
// Maps API keys
private static final String MAPS_API_DEBUG = "09UCTg-5fHNGM1co-a60SYy42aJanoXio4xB0oQ";
private static final String MAPS_API_PRODUCTION = "09UCTg-5fHNFjWw-FcMUvJPaLH_YTUiHB5gh1Kg";
// Dialog id's
private static final int DLG_NAV = 0;
private static final int DLG_RATE = 1;
// fields to hold shared preferences and ad stuff
private AdHelper mAdHelper;
// private IAdManager mAdManager;
private boolean mAdJustShown = false;
private PreferenceHelper mPrefs;
private static final String PREF_ALERT_STATS = "alert_stats";
private static final String KEY_ALERT_COUNT = "alert_stats.alert_count";
private static final String KEY_RATED_ALREADY = "alert_stats.rated_already";
private static final String KEY_ALERT_STEP = "alert_stats.alert_step";
// other fields
private AlertQueryHandler mHandler;
private Cursor mEventCursor;
private ArrayList<EventHolder> mEventHolders = new ArrayList<EventHolder>();
private List<String> mDestList = new ArrayList<String>();
private boolean mInsistentStopped = false;
private MapView mMapView;
private ViewSwitcher mSwitcher;
private UserLocationOverlay mUserLocationOverlay;
// fields for handling locations
private ArrayList<OverlayItem> mDest = new ArrayList<OverlayItem>();
private OnLocationChangedListener mListener;
private GeoPoint mOrig;
/* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.warning_dialog);
setTitle(R.string.advance_warning_title);
Logger.d(LOG_TAG, "Title is set.");
// Load the preferences and Pontiflex IAdManager
Context applicationContext = getApplicationContext();
mAdHelper = new AdHelper(applicationContext);
// mAdManager = AdManagerFactory.createInstance(getApplication());
mPrefs = new PreferenceHelper(applicationContext);
// Grab the view switcher, inflate and add the departure window and traffic views
ViewSwitcher switcher = (ViewSwitcher) findViewById(R.id.view_switcher);
View alertListView = View.inflate(this, R.layout.alert_list_view, null);
View trafficView = View.inflate(this, R.layout.traffic_view_layout, null);
alertListView.setTag(TAG_ALERT_LIST);
trafficView.setTag(TAG_TRAFFIC_VIEW);
switcher.addView(alertListView);
switcher.addView(trafficView);
mSwitcher = switcher;
Logger.d(LOG_TAG, "ViewSwitcher loaded.");
if (mMapView == null) {
// Inflate the MapView, and pass correct API key based on debug mode
LinearLayout layout = (LinearLayout) findViewById(R.id.mapview);
mMapView = new MapView(this, BuildMode.isDebug(applicationContext) ? MAPS_API_DEBUG : MAPS_API_PRODUCTION);
layout.addView(mMapView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mMapView.setClickable(true);
}
// Enable the user location to the map (early, to feed the location to the AdMob banner)
mUserLocationOverlay = new UserLocationOverlay(this, mMapView);
boolean providersEnabled = mUserLocationOverlay.enableMyLocation();
if (providersEnabled) {
Logger.d(LOG_TAG, "User location updates enabled.");
}
// Adjust the warning text to include early arrival if set
final Long earlyArrival = mPrefs.getEarlyArrival() / 60000;
if (!earlyArrival.equals(new Long(0))) {
final TextView tv_warningText = (TextView) findViewById(R.id.warning_text);
final Resources res = getResources();
String warningText = res.getString(R.string.warning_text);
String onTime = res.getString(R.string.on_time);
String minutesEarly = res.getString(R.string.minutes_early);
warningText = warningText.replaceFirst(onTime, earlyArrival + " " + minutesEarly);
tv_warningText.setText(warningText);
}
// Load up the list of alerts
loadAlertList();
// Set the "View Traffic" button action
Button trafficButton = (Button) findViewById(R.id.traffic_button);
trafficButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Switch to the traffic view and setup the MapView
Logger.d(LOG_TAG, "'View Traffic' button clicked, switching to traffic view...");
stopInsistentAlarm();
loadTrafficView();
}
});
Logger.d(LOG_TAG, "Traffic button added.");
// Load up an AdMob banner
if (! BuildMode.isDebug(applicationContext)) {
AdRequest request = new AdRequest();
if (providersEnabled) { request.setLocation(mUserLocationOverlay.getLastFix()); }
AdView adView = (AdView) findViewById(R.id.ad_view);
adView.loadAd(request);
Logger.d(LOG_TAG, "AdMob banner loaded.");
}
mUserLocationOverlay.disableMyLocation();
}
private void loadAlertList() {
// Query the AlertProvider for alerts that are fired, but not dismissed
ContentResolver cr = getContentResolver();
if (mHandler == null) { mHandler = new AlertQueryHandler(cr); }
Uri contentUri = AlertsContract.Alerts.CONTENT_URI;
String[] projection = AlertsHelper.ALERT_PROJECTION;
String selection =
AlertsContract.Alerts.FIRED + "=? AND " +
AlertsContract.Alerts.DISMISSED + "=?";
String[] selectionArgs = new String[] { "1", "0" };
mHandler.startQuery(ALERT_TOKEN, getApplicationContext(),
contentUri, projection, selection, selectionArgs, null);
Logger.d(LOG_TAG, "AlertProvider queried for alerts.");
}
private class AlertQueryHandler extends AsyncQueryHandler {
public AlertQueryHandler(ContentResolver cr) {
super(cr);
}
/* (non-Javadoc)
* @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
*/
@SuppressWarnings("deprecation")
@Override
protected void onQueryComplete(int token, Object context, Cursor cursor) {
// Let the activity manage the cursor life-cycle
startManagingCursor(cursor);
mEventCursor = cursor;
Logger.d(LOG_TAG, "Query returned...");
// Now fill in the content of the WarningDialog
switch (token) {
case ALERT_TOKEN:
if (cursor.moveToFirst()) {
do {
// Store away the event information
EventHolder eh = new EventHolder();
eh.json = cursor.getString(AlertsHelper.PROJ_JSON);
eh.title = cursor.getString(AlertsHelper.PROJ_TITLE);
eh.location = cursor.getString(AlertsHelper.PROJ_LOCATION);
mEventHolders.add(eh);
} while (cursor.moveToNext());
// Calculate the departure window. Note that first row in cursor should be
// the first upcoming event instance, since it is sorted by begin time, ascending.
cursor.moveToFirst();
long begin = cursor.getLong(AlertsHelper.PROJ_BEGIN);
long duration = cursor.getLong(AlertsHelper.PROJ_DURATION);
TextView departureWindow = (TextView) findViewById(R.id.departure_window);
- long departureTime = begin - duration;
+ long departureTime = begin - mPrefs.getEarlyArrival() - duration;
long now = new Date().getTime();
Resources res = getResources();
String unitMinutes = res.getString(R.string.unit_minutes);
String departureString;
if (departureTime > now) {
departureString = "in " + (int)((departureTime - now) / 60000 + 1)
+ " " + unitMinutes + "!";
} else {
departureString = "NOW!";
}
departureWindow.setText(departureString);
departureWindow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
// Load the copyrights
Set<String> copyrights = new HashSet<String>();
do {
copyrights.add(cursor.getString(AlertsHelper.PROJ_COPYRIGHTS));
} while (cursor.moveToNext());
String copyrightString = TextUtils.join(" | ", copyrights);
TextView copyrightText = (TextView) findViewById(R.id.copyright_text);
copyrightText.setText(copyrightString);
// Attach the cursor to the alert list view
cursor.moveToFirst();
EventListAdapter adapter = new EventListAdapter((Context) context,
R.layout.event_list_item, cursor, true);
ListView lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
}
}
// Set the "Snooze" button label
Resources res = getResources();
Button snoozeButton = (Button) findViewById(R.id.snooze_button);
int count = cursor.getCount();
if (count > 1) {
snoozeButton.setText(res.getString(R.string.snooze_all_button_text));
} else {
snoozeButton.setText(res.getString(R.string.snooze_button_text));
}
// Enable or disable snooze per user preference
- if (mPrefs.getEarlyArrival().equals(new Long(0))) {
+ if (mPrefs.getSnoozeDuration().equals(new Long(0))) {
snoozeButton.setVisibility(View.GONE);
Logger.d(LOG_TAG, "Snooze button disabled.");
} else {
snoozeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Snooze the alert, and finish the activity
snoozeAlert();
showRateDialogAndFinish();
}
});
Logger.d(LOG_TAG, "Snooze button added.");
}
// Set the "Dismiss" button action
Button dismissButton = (Button) findViewById(R.id.dismiss_button);
if (count > 1) {
dismissButton.setText(res.getString(R.string.dismiss_all_button_text));
} else {
dismissButton.setText(res.getString(R.string.dismiss_button_text));
}
dismissButton.setOnClickListener(new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
// For now, to dismiss, cancel notification and finish
dismissAlert();
showRateDialogAndFinish();
}
});
Logger.d(LOG_TAG, "Dismiss button loaded.");
}
}
/**
*
*/
private void snoozeAlert() {
// With respect to ads, consider a SNOOZE as a DISMISS
mAdHelper.setWarningDismissed(true);
// Set a new alarm to notify for this same event instance
Logger.d(LOG_TAG, "'Snooze' button clicked.");
long now = new Date().getTime();
long warnTime = now + mPrefs.getSnoozeDuration();
String warnTimeString = NeverBeLateService.FullDateTime(warnTime);
Logger.d(LOG_TAG, "Alarm will be set to warn user again at " + warnTimeString);
Context context = getApplicationContext();
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, WakefulServiceReceiver.class);
intent.putExtra(EXTRA_SERVICE_COMMAND, NOTIFY);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarm.set(AlarmManager.RTC_WAKEUP, warnTime, alarmIntent);
// Ask the Service to just SNOOZE the event, which just clears the notification
intent = new Intent(context, NeverBeLateService.class);
intent.putExtra(EXTRA_SERVICE_COMMAND, SNOOZE);
startService(intent);
}
/**
*
*/
private void dismissAlert() {
// Tell the AdHelper that this warning has been dismissed
mAdHelper.setWarningDismissed(true);
// Ask the Service to just DISMISS the alert.
Context context = getApplicationContext();
Intent cancelIntent = new Intent(context, NeverBeLateService.class);
cancelIntent.putExtra(EXTRA_SERVICE_COMMAND, DISMISS);
startService(cancelIntent);
}
@SuppressWarnings("deprecation")
private void showRateDialogAndFinish() {
SharedPreferences alertStats = getSharedPreferences(PREF_ALERT_STATS, Activity.MODE_PRIVATE);
if (! alertStats.getBoolean(KEY_RATED_ALREADY, false)) {
long count = alertStats.getLong(KEY_ALERT_COUNT, 1);
alertStats.edit().putLong(KEY_ALERT_COUNT, ++count).commit();
// Show rate dialog after first 4, then every 8 alerts shown
int step = alertStats.getInt(KEY_ALERT_STEP, 4);
if (count % step == 0) {
if (step == 4) { alertStats.edit().putInt(KEY_ALERT_STEP, 8).commit(); }
showDialog(DLG_RATE);
} else {
finish();
}
} else {
finish();
}
}
private void stopInsistentAlarm() {
Logger.d(LOG_TAG, "Stopping insistent alarm.");
if (mPrefs.isInsistent() && !mInsistentStopped) {
mInsistentStopped = true;
Context context = getApplicationContext();
Intent i = new Intent(context, NeverBeLateService.class);
i.putExtra(EXTRA_SERVICE_COMMAND, SILENCE);
startService(i);
}
}
private void switchToAlertListView() {
mSwitcher.showPrevious();
Logger.d(LOG_TAG, "Switched to alert list view.");
}
private void switchToTrafficView() {
mSwitcher.showNext();
Logger.d(LOG_TAG, "Switched to traffic view.");
}
/**
*
*/
private void loadTrafficView() {
// Log a little
Logger.d(LOG_TAG, "Loading traffic view.");
// Get mapview and add zoom controls
MapView mapView = mMapView;
if (mapView != null) { Logger.d(LOG_TAG, "MapView loaded."); }
mapView.setBuiltInZoomControls(true);
// Turn on the traffic (as early as possible)
mapView.setTraffic(true);
// Add the Back button action
Button backButton = (Button) findViewById(R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switchToAlertListView();
mUserLocationOverlay.disableMyLocation();
mUserLocationOverlay.disableCompass();
}
});
// Add the Navigate button
Button btnNav = (Button) findViewById(R.id.btn_nav);
btnNav.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
ArrayList<EventHolder> eventHolders = mEventHolders;
if (eventHolders.size() == 1) {
// If only one event location, immediately send intent
startNavigation(eventHolders.get(0).location);
} else if (eventHolders.size() >= 2) {
// If two or more locations, ask user to choose first
showDialog(DLG_NAV);
}
}
});
// Get the UserLocationOverlay to draw both flags and stay updated
UserLocationOverlay overlay = mUserLocationOverlay;
// Parse the json directions data
final Iterator<EventHolder> eventIterator = mEventHolders.iterator();
do {
try {
// Get the next EventHolder
EventHolder eh = eventIterator.next();
// Get the zoom span and zoom center from the route
JSONObject directions = new JSONObject(eh.json);
JSONObject route = directions.getJSONArray("routes").getJSONObject(0);
// If the origin is null, pull the origin coordinates
JSONObject leg = route.getJSONArray("legs").getJSONObject(0);
if (mOrig == null) {
int latOrigE6 = (int) (1.0E6 * leg.getJSONObject("start_location").getDouble("lat"));
int lonOrigE6 = (int) (1.0E6 * leg.getJSONObject("start_location").getDouble("lng"));
mOrig = new GeoPoint(latOrigE6, lonOrigE6);
}
// Get the destination coordinates from the leg
int latDestE6 = (int) (1.0E6 * leg.getJSONObject("end_location").getDouble("lat"));
int lonDestE6 = (int) (1.0E6 * leg.getJSONObject("end_location").getDouble("lng"));
// Create a GeoPoint for the destination and push onto MapOverlay
GeoPoint destPoint = new GeoPoint(latDestE6, lonDestE6);
mDest.add(new OverlayItem(destPoint, eh.title, eh.location));
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} while (eventIterator.hasNext());
// Create and store new OnLocationChangedListener
if (mListener == null) {
mListener = new UserLocationOverlay.OnLocationChangedListener() {
public void onLocationChanged(Location location) {
// If we are ready, then draw the locations
if (mDest.size() > 0 && mOrig != null) {
drawLocations(location);
}
}
};
}
// Set the listener and draw the initial locations
overlay.setOnLocationChangedListener(mListener);
mListener.onLocationChanged(null);
overlay.enableMyLocation();
overlay.enableCompass();
// // Load an interstitial ad if it's time
// AdHelper adHelper = mAdHelper;
// if (adHelper.isTimeToShowAd()) {
// adHelper.setAdShown(true);
// mAdJustShown = true;
//// mAdManager.showAd();
// mAdManager.startMultiOfferActivity();
// } else {
// Otherwise, switch to the traffic view
switchToTrafficView();
// }
}
public void drawLocations(Location current) {
final MapView mapView = mMapView;
// Use origin point if current is null
GeoPoint userLoc;
if (current != null) {
int lat = (int) (1.0E6 * current.getLatitude());
int lon = (int) (1.0E6 * current.getLongitude());
userLoc = new GeoPoint(lat, lon);
} else {
userLoc = mOrig;
}
// Add the user location to the map bounds
MapBounds bounds = new MapBounds();
bounds.addPoint(userLoc.getLatitudeE6(), userLoc.getLongitudeE6());
// Create an overlay with a blue flag for the user location
Drawable blueDrawable = getResources().getDrawable(R.drawable.flag_blue);
MapOverlay blueOverlay = new MapOverlay(this, blueDrawable);
blueOverlay.addOverlay(new OverlayItem(userLoc, null, null));
// Add the blue overlay
List<Overlay> mapOverlays = mapView.getOverlays();
mapOverlays.clear();
mapOverlays.add(blueOverlay);
// Always rebuild red overlay to get the bounds correct
Drawable redDrawable = getResources().getDrawable(R.drawable.flag_red);
MapOverlay redOverlay = new MapOverlay(this, redDrawable);
final Iterator<OverlayItem> destIterator = mDest.iterator();
do {
OverlayItem item = destIterator.next();
redOverlay.addOverlay(item);
GeoPoint dest = item.getPoint();
bounds.addPoint(dest.getLatitudeE6(), dest.getLongitudeE6());
} while (destIterator.hasNext());
mapOverlays.add(redOverlay);
// Get map controller, animate to zoom center, and set zoom span
final MapController mapController = mapView.getController();
GeoPoint zoomCenter = new GeoPoint(bounds.getLatCenterE6(), bounds.getLonCenterE6());
mapController.animateTo(zoomCenter);
mapController.zoomToSpan(bounds.getLatSpanE6(), bounds.getLonSpanE6());
}
private void startNavigation(String dest) {
Uri.Builder b = Uri.parse(MAPS_URL).buildUpon();
b.appendQueryParameter("daddr", dest);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, b.build());
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
}
/* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Context context = getApplicationContext();
switch (id) {
case DLG_NAV:
for (EventHolder eh : mEventHolders) {
mDestList.add(eh.location);
}
builder.setTitle(R.string.dlg_nav_title)
// .setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, mDestList),
.setAdapter(new EventListAdapter(context, R.layout.event_list_item, mEventCursor, true),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Pull out the selected destination and send nav intent
startNavigation(mDestList.get(which));
}
});
break;
case DLG_RATE:
// Build a "rate my app" dialog
builder.setTitle(R.string.dlg_rate_title)
.setMessage(R.string.dlg_rate_msg)
.setPositiveButton(R.string.rate_it, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Send user to app details page
SharedPreferences alertStats = getSharedPreferences(PREF_ALERT_STATS, Activity.MODE_PRIVATE);
alertStats.edit().putBoolean(KEY_RATED_ALREADY, true).commit();
startActivity(new Intent(Intent.ACTION_VIEW, APP_DETAILS_URI));
finish();
}
})
.setNegativeButton(R.string.decline_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
break;
}
return builder.create();
}
/* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
// Disable the user location
if (mUserLocationOverlay != null) {
mUserLocationOverlay.disableMyLocation();
mUserLocationOverlay.disableCompass();
}
}
/* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
// Re-enable the user location
if (mUserLocationOverlay != null &&
((String) mSwitcher.getCurrentView().getTag()).equals(TAG_TRAFFIC_VIEW)) {
mUserLocationOverlay.enableMyLocation();
mUserLocationOverlay.enableCompass();
}
// Switch to the traffic view if an ad was just shown
if (mAdJustShown) {
switchToTrafficView();
mAdJustShown = false;
}
}
@Override
protected boolean isRouteDisplayed() {
// No route will be displayed, since that would cover up the traffic
return false;
}
private class EventHolder {
String json;
String title;
String location;
}
private class MapBounds {
private int mLatMinE6 = 0;
private int mLatMaxE6 = 0;
private int mLonMinE6 = 0;
private int mLonMaxE6 = 0;
private static final double RATIO = 1.25;
protected MapBounds() {
super();
}
protected void addPoint(int latE6, int lonE6) {
// Check if this latitude is the minimum
if (mLatMinE6 == 0 || latE6 < mLatMinE6) { mLatMinE6 = latE6; }
// Check if this latitude is the maximum
if (mLatMaxE6 == 0 || latE6 > mLatMaxE6) { mLatMaxE6 = latE6; }
// Check if this longitude is the minimum
if (mLonMinE6 == 0 || lonE6 < mLonMinE6) { mLonMinE6 = lonE6; }
// Check if this longitude is the maximum
if (mLonMaxE6 == 0 || lonE6 > mLonMaxE6) { mLonMaxE6 = lonE6; }
}
protected int getLatSpanE6() {
return (int) Math.abs(RATIO * (mLatMaxE6 - mLatMinE6));
}
protected int getLonSpanE6() {
return (int) Math.abs(RATIO * (mLonMaxE6 - mLonMinE6));
}
protected int getLatCenterE6() {
return (int) (mLatMaxE6 + mLatMinE6)/2;
}
protected int getLonCenterE6() {
return (int) (mLonMaxE6 + mLonMinE6)/2;
}
}
}
| false | true | protected void onQueryComplete(int token, Object context, Cursor cursor) {
// Let the activity manage the cursor life-cycle
startManagingCursor(cursor);
mEventCursor = cursor;
Logger.d(LOG_TAG, "Query returned...");
// Now fill in the content of the WarningDialog
switch (token) {
case ALERT_TOKEN:
if (cursor.moveToFirst()) {
do {
// Store away the event information
EventHolder eh = new EventHolder();
eh.json = cursor.getString(AlertsHelper.PROJ_JSON);
eh.title = cursor.getString(AlertsHelper.PROJ_TITLE);
eh.location = cursor.getString(AlertsHelper.PROJ_LOCATION);
mEventHolders.add(eh);
} while (cursor.moveToNext());
// Calculate the departure window. Note that first row in cursor should be
// the first upcoming event instance, since it is sorted by begin time, ascending.
cursor.moveToFirst();
long begin = cursor.getLong(AlertsHelper.PROJ_BEGIN);
long duration = cursor.getLong(AlertsHelper.PROJ_DURATION);
TextView departureWindow = (TextView) findViewById(R.id.departure_window);
long departureTime = begin - duration;
long now = new Date().getTime();
Resources res = getResources();
String unitMinutes = res.getString(R.string.unit_minutes);
String departureString;
if (departureTime > now) {
departureString = "in " + (int)((departureTime - now) / 60000 + 1)
+ " " + unitMinutes + "!";
} else {
departureString = "NOW!";
}
departureWindow.setText(departureString);
departureWindow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
// Load the copyrights
Set<String> copyrights = new HashSet<String>();
do {
copyrights.add(cursor.getString(AlertsHelper.PROJ_COPYRIGHTS));
} while (cursor.moveToNext());
String copyrightString = TextUtils.join(" | ", copyrights);
TextView copyrightText = (TextView) findViewById(R.id.copyright_text);
copyrightText.setText(copyrightString);
// Attach the cursor to the alert list view
cursor.moveToFirst();
EventListAdapter adapter = new EventListAdapter((Context) context,
R.layout.event_list_item, cursor, true);
ListView lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
}
}
// Set the "Snooze" button label
Resources res = getResources();
Button snoozeButton = (Button) findViewById(R.id.snooze_button);
int count = cursor.getCount();
if (count > 1) {
snoozeButton.setText(res.getString(R.string.snooze_all_button_text));
} else {
snoozeButton.setText(res.getString(R.string.snooze_button_text));
}
// Enable or disable snooze per user preference
if (mPrefs.getEarlyArrival().equals(new Long(0))) {
snoozeButton.setVisibility(View.GONE);
Logger.d(LOG_TAG, "Snooze button disabled.");
} else {
snoozeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Snooze the alert, and finish the activity
snoozeAlert();
showRateDialogAndFinish();
}
});
Logger.d(LOG_TAG, "Snooze button added.");
}
// Set the "Dismiss" button action
Button dismissButton = (Button) findViewById(R.id.dismiss_button);
if (count > 1) {
dismissButton.setText(res.getString(R.string.dismiss_all_button_text));
} else {
dismissButton.setText(res.getString(R.string.dismiss_button_text));
}
dismissButton.setOnClickListener(new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
// For now, to dismiss, cancel notification and finish
dismissAlert();
showRateDialogAndFinish();
}
});
Logger.d(LOG_TAG, "Dismiss button loaded.");
}
| protected void onQueryComplete(int token, Object context, Cursor cursor) {
// Let the activity manage the cursor life-cycle
startManagingCursor(cursor);
mEventCursor = cursor;
Logger.d(LOG_TAG, "Query returned...");
// Now fill in the content of the WarningDialog
switch (token) {
case ALERT_TOKEN:
if (cursor.moveToFirst()) {
do {
// Store away the event information
EventHolder eh = new EventHolder();
eh.json = cursor.getString(AlertsHelper.PROJ_JSON);
eh.title = cursor.getString(AlertsHelper.PROJ_TITLE);
eh.location = cursor.getString(AlertsHelper.PROJ_LOCATION);
mEventHolders.add(eh);
} while (cursor.moveToNext());
// Calculate the departure window. Note that first row in cursor should be
// the first upcoming event instance, since it is sorted by begin time, ascending.
cursor.moveToFirst();
long begin = cursor.getLong(AlertsHelper.PROJ_BEGIN);
long duration = cursor.getLong(AlertsHelper.PROJ_DURATION);
TextView departureWindow = (TextView) findViewById(R.id.departure_window);
long departureTime = begin - mPrefs.getEarlyArrival() - duration;
long now = new Date().getTime();
Resources res = getResources();
String unitMinutes = res.getString(R.string.unit_minutes);
String departureString;
if (departureTime > now) {
departureString = "in " + (int)((departureTime - now) / 60000 + 1)
+ " " + unitMinutes + "!";
} else {
departureString = "NOW!";
}
departureWindow.setText(departureString);
departureWindow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
// Load the copyrights
Set<String> copyrights = new HashSet<String>();
do {
copyrights.add(cursor.getString(AlertsHelper.PROJ_COPYRIGHTS));
} while (cursor.moveToNext());
String copyrightString = TextUtils.join(" | ", copyrights);
TextView copyrightText = (TextView) findViewById(R.id.copyright_text);
copyrightText.setText(copyrightString);
// Attach the cursor to the alert list view
cursor.moveToFirst();
EventListAdapter adapter = new EventListAdapter((Context) context,
R.layout.event_list_item, cursor, true);
ListView lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
}
}
// Set the "Snooze" button label
Resources res = getResources();
Button snoozeButton = (Button) findViewById(R.id.snooze_button);
int count = cursor.getCount();
if (count > 1) {
snoozeButton.setText(res.getString(R.string.snooze_all_button_text));
} else {
snoozeButton.setText(res.getString(R.string.snooze_button_text));
}
// Enable or disable snooze per user preference
if (mPrefs.getSnoozeDuration().equals(new Long(0))) {
snoozeButton.setVisibility(View.GONE);
Logger.d(LOG_TAG, "Snooze button disabled.");
} else {
snoozeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Snooze the alert, and finish the activity
snoozeAlert();
showRateDialogAndFinish();
}
});
Logger.d(LOG_TAG, "Snooze button added.");
}
// Set the "Dismiss" button action
Button dismissButton = (Button) findViewById(R.id.dismiss_button);
if (count > 1) {
dismissButton.setText(res.getString(R.string.dismiss_all_button_text));
} else {
dismissButton.setText(res.getString(R.string.dismiss_button_text));
}
dismissButton.setOnClickListener(new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
// For now, to dismiss, cancel notification and finish
dismissAlert();
showRateDialogAndFinish();
}
});
Logger.d(LOG_TAG, "Dismiss button loaded.");
}
|
diff --git a/src/com/fsck/k9/activity/setup/AccountSettings.java b/src/com/fsck/k9/activity/setup/AccountSettings.java
index 7ea0df06..44e36cf4 100644
--- a/src/com/fsck/k9/activity/setup/AccountSettings.java
+++ b/src/com/fsck/k9/activity/setup/AccountSettings.java
@@ -1,954 +1,954 @@
package com.fsck.k9.activity.setup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.RingtonePreference;
import android.util.Log;
import android.view.KeyEvent;
import java.util.Map;
import java.util.LinkedList;
import java.util.List;
import com.fsck.k9.Account;
import com.fsck.k9.Account.FolderMode;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.ChooseIdentity;
import com.fsck.k9.activity.ColorPickerDialog;
import com.fsck.k9.activity.K9PreferenceActivity;
import com.fsck.k9.activity.ManageIdentities;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.crypto.Apg;
import com.fsck.k9.mail.Store;
import com.fsck.k9.service.MailService;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.StorageManager;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.mail.store.StorageManager.StorageProvider;
public class AccountSettings extends K9PreferenceActivity
{
private static final String EXTRA_ACCOUNT = "account";
private static final int SELECT_AUTO_EXPAND_FOLDER = 1;
private static final int ACTIVITY_MANAGE_IDENTITIES = 2;
private static final String PREFERENCE_DESCRIPTION = "account_description";
private static final String PREFERENCE_COMPOSITION = "composition";
private static final String PREFERENCE_MANAGE_IDENTITIES = "manage_identities";
private static final String PREFERENCE_FREQUENCY = "account_check_frequency";
private static final String PREFERENCE_DISPLAY_COUNT = "account_display_count";
private static final String PREFERENCE_DEFAULT = "account_default";
private static final String PREFERENCE_HIDE_BUTTONS = "hide_buttons_enum";
private static final String PREFERENCE_HIDE_MOVE_BUTTONS = "hide_move_buttons_enum";
private static final String PREFERENCE_SHOW_PICTURES = "show_pictures_enum";
private static final String PREFERENCE_ENABLE_MOVE_BUTTONS = "enable_move_buttons";
private static final String PREFERENCE_NOTIFY = "account_notify";
private static final String PREFERENCE_NOTIFY_SELF = "account_notify_self";
private static final String PREFERENCE_NOTIFY_SYNC = "account_notify_sync";
private static final String PREFERENCE_VIBRATE = "account_vibrate";
private static final String PREFERENCE_VIBRATE_PATTERN = "account_vibrate_pattern";
private static final String PREFERENCE_VIBRATE_TIMES = "account_vibrate_times";
private static final String PREFERENCE_RINGTONE = "account_ringtone";
private static final String PREFERENCE_NOTIFICATION_LED = "account_led";
private static final String PREFERENCE_INCOMING = "incoming";
private static final String PREFERENCE_OUTGOING = "outgoing";
private static final String PREFERENCE_DISPLAY_MODE = "folder_display_mode";
private static final String PREFERENCE_SYNC_MODE = "folder_sync_mode";
private static final String PREFERENCE_PUSH_MODE = "folder_push_mode";
private static final String PREFERENCE_PUSH_POLL_ON_CONNECT = "push_poll_on_connect";
private static final String PREFERENCE_MAX_PUSH_FOLDERS = "max_push_folders";
private static final String PREFERENCE_IDLE_REFRESH_PERIOD = "idle_refresh_period";
private static final String PREFERENCE_TARGET_MODE = "folder_target_mode";
private static final String PREFERENCE_DELETE_POLICY = "delete_policy";
private static final String PREFERENCE_EXPUNGE_POLICY = "expunge_policy";
private static final String PREFERENCE_AUTO_EXPAND_FOLDER = "account_setup_auto_expand_folder";
private static final String PREFERENCE_SEARCHABLE_FOLDERS = "searchable_folders";
private static final String PREFERENCE_CHIP_COLOR = "chip_color";
private static final String PREFERENCE_LED_COLOR = "led_color";
private static final String PREFERENCE_NOTIFICATION_OPENS_UNREAD = "notification_opens_unread";
private static final String PREFERENCE_MESSAGE_AGE = "account_message_age";
private static final String PREFERENCE_MESSAGE_SIZE = "account_autodownload_size";
private static final String PREFERENCE_SAVE_ALL_HEADERS = "account_save_all_headers";
private static final String PREFERENCE_QUOTE_PREFIX = "account_quote_prefix";
private static final String PREFERENCE_REPLY_AFTER_QUOTE = "reply_after_quote";
private static final String PREFERENCE_SYNC_REMOTE_DELETIONS = "account_sync_remote_deletetions";
private static final String PREFERENCE_CRYPTO_APP = "crypto_app";
private static final String PREFERENCE_CRYPTO_AUTO_SIGNATURE = "crypto_auto_signature";
private static final String PREFERENCE_LOCAL_STORAGE_PROVIDER = "local_storage_provider";
private static final String PREFERENCE_ARCHIVE_FOLDER = "archive_folder";
private static final String PREFERENCE_DRAFTS_FOLDER = "drafts_folder";
private static final String PREFERENCE_OUTBOX_FOLDER = "outbox_folder";
private static final String PREFERENCE_SENT_FOLDER = "sent_folder";
private static final String PREFERENCE_SPAM_FOLDER = "spam_folder";
private static final String PREFERENCE_TRASH_FOLDER = "trash_folder";
private Account mAccount;
private boolean mIsPushCapable = false;
private boolean mIsExpungeCapable = false;
private EditTextPreference mAccountDescription;
private ListPreference mCheckFrequency;
private ListPreference mDisplayCount;
private ListPreference mMessageAge;
private ListPreference mMessageSize;
private CheckBoxPreference mAccountDefault;
private CheckBoxPreference mAccountNotify;
private CheckBoxPreference mAccountNotifySelf;
private ListPreference mAccountHideButtons;
private ListPreference mAccountHideMoveButtons;
private ListPreference mAccountShowPictures;
private CheckBoxPreference mAccountEnableMoveButtons;
private CheckBoxPreference mAccountNotifySync;
private CheckBoxPreference mAccountVibrate;
private CheckBoxPreference mAccountLed;
private ListPreference mAccountVibratePattern;
private ListPreference mAccountVibrateTimes;
private RingtonePreference mAccountRingtone;
private ListPreference mDisplayMode;
private ListPreference mSyncMode;
private ListPreference mPushMode;
private ListPreference mTargetMode;
private ListPreference mDeletePolicy;
private ListPreference mExpungePolicy;
private ListPreference mSearchableFolders;
private ListPreference mAutoExpandFolder;
private Preference mChipColor;
private Preference mLedColor;
private boolean mIncomingChanged = false;
private CheckBoxPreference mNotificationOpensUnread;
private EditTextPreference mAccountQuotePrefix;
private CheckBoxPreference mReplyAfterQuote;
private CheckBoxPreference mSyncRemoteDeletions;
private CheckBoxPreference mSaveAllHeaders;
private CheckBoxPreference mPushPollOnConnect;
private ListPreference mIdleRefreshPeriod;
private ListPreference mMaxPushFolders;
private ListPreference mCryptoApp;
private CheckBoxPreference mCryptoAutoSignature;
private ListPreference mLocalStorageProvider;
private ListPreference mArchiveFolder;
private ListPreference mDraftsFolder;
private ListPreference mOutboxFolder;
private ListPreference mSentFolder;
private ListPreference mSpamFolder;
private ListPreference mTrashFolder;
public static void actionSettings(Context context, Account account)
{
Intent i = new Intent(context, AccountSettings.class);
i.putExtra(EXTRA_ACCOUNT, account.getUuid());
context.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try
{
final Store store = mAccount.getRemoteStore();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountQuotePrefix.setSummary(value);
mAccountQuotePrefix.setText(value);
return false;
}
});
mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
mDisplayMode.setSummary(mDisplayMode.getEntry());
mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayMode.findIndexOfValue(summary);
mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
mDisplayMode.setValue(summary);
return false;
}
});
mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
mSyncMode.setValue(mAccount.getFolderSyncMode().name());
mSyncMode.setSummary(mSyncMode.getEntry());
mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSyncMode.findIndexOfValue(summary);
mSyncMode.setSummary(mSyncMode.getEntries()[index]);
mSyncMode.setValue(summary);
return false;
}
});
mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
mPushMode.setEnabled(mIsPushCapable);
mPushMode.setValue(mAccount.getFolderPushMode().name());
mPushMode.setSummary(mPushMode.getEntry());
mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mPushMode.findIndexOfValue(summary);
mPushMode.setSummary(mPushMode.getEntries()[index]);
mPushMode.setValue(summary);
return false;
}
});
mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
mTargetMode.setValue(mAccount.getFolderTargetMode().name());
mTargetMode.setSummary(mTargetMode.getEntry());
mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mTargetMode.findIndexOfValue(summary);
mTargetMode.setSummary(mTargetMode.getEntries()[index]);
mTargetMode.setValue(summary);
return false;
}
});
mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
mDeletePolicy.setSummary(mDeletePolicy.getEntry());
mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDeletePolicy.findIndexOfValue(summary);
mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
mDeletePolicy.setValue(summary);
return false;
}
});
mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
mExpungePolicy.setEnabled(mIsExpungeCapable);
mExpungePolicy.setValue(mAccount.getExpungePolicy());
mExpungePolicy.setSummary(mExpungePolicy.getEntry());
mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mExpungePolicy.findIndexOfValue(summary);
mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
mExpungePolicy.setValue(summary);
return false;
}
});
mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
mSearchableFolders.setSummary(mSearchableFolders.getEntry());
mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSearchableFolders.findIndexOfValue(summary);
mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
mSearchableFolders.setValue(summary);
return false;
}
});
mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
mDisplayCount.setSummary(mDisplayCount.getEntry());
mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayCount.findIndexOfValue(summary);
mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
mDisplayCount.setValue(summary);
return false;
}
});
mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
mMessageAge.setSummary(mMessageAge.getEntry());
mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageAge.findIndexOfValue(summary);
mMessageAge.setSummary(mMessageAge.getEntries()[index]);
mMessageAge.setValue(summary);
return false;
}
});
mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
mMessageSize.setSummary(mMessageSize.getEntry());
mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageSize.findIndexOfValue(summary);
mMessageSize.setSummary(mMessageSize.getEntries()[index]);
mMessageSize.setValue(summary);
return false;
}
});
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
mAccountHideButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS);
mAccountHideButtons.setValue("" + mAccount.getHideMessageViewButtons());
mAccountHideButtons.setSummary(mAccountHideButtons.getEntry());
mAccountHideButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideButtons.findIndexOfValue(summary);
mAccountHideButtons.setSummary(mAccountHideButtons.getEntries()[index]);
mAccountHideButtons.setValue(summary);
return false;
}
});
mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
mAccountHideMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS);
mAccountHideMoveButtons.setValue("" + mAccount.getHideMessageViewMoveButtons());
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntry());
mAccountHideMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideMoveButtons.findIndexOfValue(summary);
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntries()[index]);
mAccountHideMoveButtons.setValue(summary);
return false;
}
});
mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
mAccountShowPictures.setValue("" + mAccount.getShowPictures());
mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountShowPictures.findIndexOfValue(summary);
mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
mAccountShowPictures.setValue(summary);
return false;
}
});
mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
{
final Map<String, String> providers;
providers = StorageManager.getInstance(K9.app).getAvailableProviders();
int i = 0;
final String[] providerLabels = new String[providers.size()];
final String[] providerIds = new String[providers.size()];
for (final Map.Entry<String, String> entry : providers.entrySet())
{
providerIds[i] = entry.getKey();
providerLabels[i] = entry.getValue();
i++;
}
mLocalStorageProvider.setEntryValues(providerIds);
mLocalStorageProvider.setEntries(providerLabels);
mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId());
mLocalStorageProvider.setSummary(providers.get((Object)mAccount.getLocalStorageProviderId()));
mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
mLocalStorageProvider.setSummary(providers.get(newValue));
return true;
}
});
}
// IMAP-specific preferences
mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (mIsPushCapable)
{
mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mIdleRefreshPeriod.findIndexOfValue(summary);
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
mIdleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
}
else
{
mPushPollOnConnect.setEnabled(false);
mMaxPushFolders.setEnabled(false);
mIdleRefreshPeriod.setEnabled(false);
}
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(mAccount.isNotifyNewMail());
mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
mAccountNotifySync.setChecked(mAccount.isShowOngoing());
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(mAccount.getNotificationSetting().isVibrate());
mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountVibratePattern.findIndexOfValue(summary);
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
mAccountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountVibrateTimes.setSummary(value);
mAccountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
List<? extends Folder> folders = new LinkedList<LocalFolder>();;
try
{
folders = mAccount.getLocalStore().getPersonalNamespaces(false);
}
catch (Exception e)
{
/// this can't be checked in
}
final String[] allFolderValues = new String[folders.size()+2];
final String[] allFolderLabels = new String[folders.size()+2];
- allFolderValues[0] = "";
+ allFolderValues[0] = K9.FOLDER_NONE;
allFolderLabels[0] = K9.FOLDER_NONE;
// There's a non-zero chance that "outbox" won't actually exist, so we force it into the list
allFolderValues[1] = mAccount.getOutboxFolderName();
allFolderLabels[1] = mAccount.getOutboxFolderName();
int i =2;
for (Folder folder : folders)
{
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels,allFolderValues);
mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER);
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels,allFolderValues);
mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels,allFolderValues);
mOutboxFolder = (ListPreference)findPreference(PREFERENCE_OUTBOX_FOLDER);
initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels,allFolderValues);
mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER);
initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels,allFolderValues);
mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER);
initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels,allFolderValues);
mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER);
initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels,allFolderValues);
mChipColor = (Preference)findPreference(PREFERENCE_CHIP_COLOR);
mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseChipColor();
return false;
}
});
mLedColor = (Preference)findPreference(PREFERENCE_LED_COLOR);
mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
mIncomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onOutgoingSettings();
return true;
}
});
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
if (!new Apg().isAvailable(this))
{
int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
if (apgIndex >= 0)
{
cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
mCryptoApp.setEntries(cryptoAppEntries);
}
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value))
{
Apg.createInstance(null).test(AccountSettings.this);
}
return false;
}
});
mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
handleCryptoAppDependencies();
}
private void handleCryptoAppDependencies()
{
if ("".equals(mCryptoApp.getValue()))
{
mCryptoAutoSignature.setEnabled(false);
}
else
{
mCryptoAutoSignature.setEnabled(true);
}
}
@Override
public void onResume()
{
super.onResume();
}
private void saveSettings()
{
if (mAccountDefault.isChecked())
{
Preferences.getPreferences(this).setDefaultAccount(mAccount);
}
mAccount.setDescription(mAccountDescription.getText());
mAccount.setNotifyNewMail(mAccountNotify.isChecked());
mAccount.setNotifySelfNewMail(mAccountNotifySelf.isChecked());
mAccount.setShowOngoing(mAccountNotifySync.isChecked());
mAccount.setDisplayCount(Integer.parseInt(mDisplayCount.getValue()));
mAccount.setMaximumPolledMessageAge(Integer.parseInt(mMessageAge.getValue()));
mAccount.setMaximumAutoDownloadMessageSize(Integer.parseInt(mMessageSize.getValue()));
mAccount.getNotificationSetting().setVibrate(mAccountVibrate.isChecked());
mAccount.getNotificationSetting().setVibratePattern(Integer.parseInt(mAccountVibratePattern.getValue()));
mAccount.getNotificationSetting().setVibrateTimes(Integer.parseInt(mAccountVibrateTimes.getValue()));
mAccount.getNotificationSetting().setLed(mAccountLed.isChecked());
mAccount.setGoToUnreadMessageSearch(mNotificationOpensUnread.isChecked());
mAccount.setFolderTargetMode(Account.FolderMode.valueOf(mTargetMode.getValue()));
mAccount.setDeletePolicy(Integer.parseInt(mDeletePolicy.getValue()));
mAccount.setExpungePolicy(mExpungePolicy.getValue());
mAccount.setSyncRemoteDeletions(mSyncRemoteDeletions.isChecked());
mAccount.setSaveAllHeaders(mSaveAllHeaders.isChecked());
mAccount.setSearchableFolders(Account.Searchable.valueOf(mSearchableFolders.getValue()));
mAccount.setQuotePrefix(mAccountQuotePrefix.getText());
mAccount.setReplyAfterQuote(mReplyAfterQuote.isChecked());
mAccount.setCryptoApp(mCryptoApp.getValue());
mAccount.setCryptoAutoSignature(mCryptoAutoSignature.isChecked());
mAccount.setLocalStorageProviderId(mLocalStorageProvider.getValue());
mAccount.setAutoExpandFolderName(reverseTranslateFolder(mAutoExpandFolder.getValue().toString()));
mAccount.setArchiveFolderName(mArchiveFolder.getValue().toString());
mAccount.setDraftsFolderName(mDraftsFolder.getValue().toString());
mAccount.setOutboxFolderName(mOutboxFolder.getValue().toString());
mAccount.setSentFolderName(mSentFolder.getValue().toString());
mAccount.setSpamFolderName(mSpamFolder.getValue().toString());
mAccount.setTrashFolderName(mTrashFolder.getValue().toString());
if (mIsPushCapable)
{
mAccount.setPushPollOnConnect(mPushPollOnConnect.isChecked());
mAccount.setIdleRefreshMinutes(Integer.parseInt(mIdleRefreshPeriod.getValue()));
mAccount.setMaxPushFolders(Integer.parseInt(mMaxPushFolders.getValue()));
}
boolean needsRefresh = mAccount.setAutomaticCheckIntervalMinutes(Integer.parseInt(mCheckFrequency.getValue()));
needsRefresh |= mAccount.setFolderSyncMode(Account.FolderMode.valueOf(mSyncMode.getValue()));
boolean needsPushRestart = mAccount.setFolderPushMode(Account.FolderMode.valueOf(mPushMode.getValue()));
boolean displayModeChanged = mAccount.setFolderDisplayMode(Account.FolderMode.valueOf(mDisplayMode.getValue()));
if (mAccount.getFolderPushMode() != FolderMode.NONE)
{
needsPushRestart |= displayModeChanged;
needsPushRestart |= mIncomingChanged;
}
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String newRingtone = prefs.getString(PREFERENCE_RINGTONE, null);
if (newRingtone != null)
{
mAccount.getNotificationSetting().setRing(true);
mAccount.getNotificationSetting().setRingtone(newRingtone);
}
else
{
if (mAccount.getNotificationSetting().shouldRing())
{
mAccount.getNotificationSetting().setRingtone(null);
}
}
mAccount.setHideMessageViewButtons(Account.HideButtons.valueOf(mAccountHideButtons.getValue()));
mAccount.setHideMessageViewMoveButtons(Account.HideButtons.valueOf(mAccountHideMoveButtons.getValue()));
mAccount.setShowPictures(Account.ShowPictures.valueOf(mAccountShowPictures.getValue()));
mAccount.setEnableMoveButtons(mAccountEnableMoveButtons.isChecked());
mAccount.save(Preferences.getPreferences(this));
if (needsRefresh && needsPushRestart)
{
MailService.actionReset(this, null);
}
else if (needsRefresh)
{
MailService.actionReschedulePoll(this, null);
}
else if (needsPushRestart)
{
MailService.actionRestartPushers(this, null);
}
// TODO: refresh folder list here
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case SELECT_AUTO_EXPAND_FOLDER:
mAutoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER)));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
saveSettings();
}
return super.onKeyDown(keyCode, event);
}
private void onCompositionSettings()
{
AccountSetupComposition.actionEditCompositionSettings(this, mAccount);
}
private void onManageIdentities()
{
Intent intent = new Intent(this, ManageIdentities.class);
intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid());
startActivityForResult(intent, ACTIVITY_MANAGE_IDENTITIES);
}
private void onIncomingSettings()
{
AccountSetupIncoming.actionEditIncomingSettings(this, mAccount);
}
private void onOutgoingSettings()
{
AccountSetupOutgoing.actionEditOutgoingSettings(this, mAccount);
}
public void onChooseChipColor()
{
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener()
{
public void colorChanged(int color)
{
mAccount.setChipColor(color);
}
},
mAccount.getChipColor()).show();
}
public void onChooseLedColor()
{
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener()
{
public void colorChanged(int color)
{
mAccount.getNotificationSetting().setLedColor(color);
}
},
mAccount.getNotificationSetting().getLedColor()).show();
}
public void onChooseAutoExpandFolder()
{
Intent selectIntent = new Intent(this, ChooseFolder.class);
selectIntent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
selectIntent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mAutoExpandFolder.getSummary());
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_FOLDER_NONE, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_DISPLAYABLE_ONLY, "yes");
startActivityForResult(selectIntent, SELECT_AUTO_EXPAND_FOLDER);
}
private String translateFolder(String in)
{
if (K9.INBOX.equalsIgnoreCase(in))
{
return getString(R.string.special_mailbox_name_inbox);
}
else
{
return in;
}
}
private String reverseTranslateFolder(String in)
{
if (getString(R.string.special_mailbox_name_inbox).equals(in))
{
return K9.INBOX;
}
else
{
return in;
}
}
private void doVibrateTest(Preference preference)
{
// Do the vibration to show the user what it's like.
Vibrator vibrate = (Vibrator)preference.getContext().getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = MessagingController.getVibratePattern(
Integer.parseInt(mAccountVibratePattern.getValue()),
Integer.parseInt(mAccountVibrateTimes.getValue()));
vibrate.vibrate(pattern, -1);
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try
{
final Store store = mAccount.getRemoteStore();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountQuotePrefix.setSummary(value);
mAccountQuotePrefix.setText(value);
return false;
}
});
mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
mDisplayMode.setSummary(mDisplayMode.getEntry());
mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayMode.findIndexOfValue(summary);
mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
mDisplayMode.setValue(summary);
return false;
}
});
mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
mSyncMode.setValue(mAccount.getFolderSyncMode().name());
mSyncMode.setSummary(mSyncMode.getEntry());
mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSyncMode.findIndexOfValue(summary);
mSyncMode.setSummary(mSyncMode.getEntries()[index]);
mSyncMode.setValue(summary);
return false;
}
});
mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
mPushMode.setEnabled(mIsPushCapable);
mPushMode.setValue(mAccount.getFolderPushMode().name());
mPushMode.setSummary(mPushMode.getEntry());
mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mPushMode.findIndexOfValue(summary);
mPushMode.setSummary(mPushMode.getEntries()[index]);
mPushMode.setValue(summary);
return false;
}
});
mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
mTargetMode.setValue(mAccount.getFolderTargetMode().name());
mTargetMode.setSummary(mTargetMode.getEntry());
mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mTargetMode.findIndexOfValue(summary);
mTargetMode.setSummary(mTargetMode.getEntries()[index]);
mTargetMode.setValue(summary);
return false;
}
});
mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
mDeletePolicy.setSummary(mDeletePolicy.getEntry());
mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDeletePolicy.findIndexOfValue(summary);
mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
mDeletePolicy.setValue(summary);
return false;
}
});
mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
mExpungePolicy.setEnabled(mIsExpungeCapable);
mExpungePolicy.setValue(mAccount.getExpungePolicy());
mExpungePolicy.setSummary(mExpungePolicy.getEntry());
mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mExpungePolicy.findIndexOfValue(summary);
mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
mExpungePolicy.setValue(summary);
return false;
}
});
mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
mSearchableFolders.setSummary(mSearchableFolders.getEntry());
mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSearchableFolders.findIndexOfValue(summary);
mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
mSearchableFolders.setValue(summary);
return false;
}
});
mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
mDisplayCount.setSummary(mDisplayCount.getEntry());
mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayCount.findIndexOfValue(summary);
mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
mDisplayCount.setValue(summary);
return false;
}
});
mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
mMessageAge.setSummary(mMessageAge.getEntry());
mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageAge.findIndexOfValue(summary);
mMessageAge.setSummary(mMessageAge.getEntries()[index]);
mMessageAge.setValue(summary);
return false;
}
});
mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
mMessageSize.setSummary(mMessageSize.getEntry());
mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageSize.findIndexOfValue(summary);
mMessageSize.setSummary(mMessageSize.getEntries()[index]);
mMessageSize.setValue(summary);
return false;
}
});
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
mAccountHideButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS);
mAccountHideButtons.setValue("" + mAccount.getHideMessageViewButtons());
mAccountHideButtons.setSummary(mAccountHideButtons.getEntry());
mAccountHideButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideButtons.findIndexOfValue(summary);
mAccountHideButtons.setSummary(mAccountHideButtons.getEntries()[index]);
mAccountHideButtons.setValue(summary);
return false;
}
});
mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
mAccountHideMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS);
mAccountHideMoveButtons.setValue("" + mAccount.getHideMessageViewMoveButtons());
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntry());
mAccountHideMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideMoveButtons.findIndexOfValue(summary);
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntries()[index]);
mAccountHideMoveButtons.setValue(summary);
return false;
}
});
mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
mAccountShowPictures.setValue("" + mAccount.getShowPictures());
mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountShowPictures.findIndexOfValue(summary);
mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
mAccountShowPictures.setValue(summary);
return false;
}
});
mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
{
final Map<String, String> providers;
providers = StorageManager.getInstance(K9.app).getAvailableProviders();
int i = 0;
final String[] providerLabels = new String[providers.size()];
final String[] providerIds = new String[providers.size()];
for (final Map.Entry<String, String> entry : providers.entrySet())
{
providerIds[i] = entry.getKey();
providerLabels[i] = entry.getValue();
i++;
}
mLocalStorageProvider.setEntryValues(providerIds);
mLocalStorageProvider.setEntries(providerLabels);
mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId());
mLocalStorageProvider.setSummary(providers.get((Object)mAccount.getLocalStorageProviderId()));
mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
mLocalStorageProvider.setSummary(providers.get(newValue));
return true;
}
});
}
// IMAP-specific preferences
mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (mIsPushCapable)
{
mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mIdleRefreshPeriod.findIndexOfValue(summary);
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
mIdleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
}
else
{
mPushPollOnConnect.setEnabled(false);
mMaxPushFolders.setEnabled(false);
mIdleRefreshPeriod.setEnabled(false);
}
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(mAccount.isNotifyNewMail());
mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
mAccountNotifySync.setChecked(mAccount.isShowOngoing());
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(mAccount.getNotificationSetting().isVibrate());
mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountVibratePattern.findIndexOfValue(summary);
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
mAccountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountVibrateTimes.setSummary(value);
mAccountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
List<? extends Folder> folders = new LinkedList<LocalFolder>();;
try
{
folders = mAccount.getLocalStore().getPersonalNamespaces(false);
}
catch (Exception e)
{
/// this can't be checked in
}
final String[] allFolderValues = new String[folders.size()+2];
final String[] allFolderLabels = new String[folders.size()+2];
allFolderValues[0] = "";
allFolderLabels[0] = K9.FOLDER_NONE;
// There's a non-zero chance that "outbox" won't actually exist, so we force it into the list
allFolderValues[1] = mAccount.getOutboxFolderName();
allFolderLabels[1] = mAccount.getOutboxFolderName();
int i =2;
for (Folder folder : folders)
{
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels,allFolderValues);
mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER);
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels,allFolderValues);
mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels,allFolderValues);
mOutboxFolder = (ListPreference)findPreference(PREFERENCE_OUTBOX_FOLDER);
initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels,allFolderValues);
mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER);
initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels,allFolderValues);
mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER);
initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels,allFolderValues);
mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER);
initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels,allFolderValues);
mChipColor = (Preference)findPreference(PREFERENCE_CHIP_COLOR);
mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseChipColor();
return false;
}
});
mLedColor = (Preference)findPreference(PREFERENCE_LED_COLOR);
mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
mIncomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onOutgoingSettings();
return true;
}
});
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
if (!new Apg().isAvailable(this))
{
int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
if (apgIndex >= 0)
{
cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
mCryptoApp.setEntries(cryptoAppEntries);
}
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value))
{
Apg.createInstance(null).test(AccountSettings.this);
}
return false;
}
});
mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
handleCryptoAppDependencies();
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try
{
final Store store = mAccount.getRemoteStore();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountQuotePrefix.setSummary(value);
mAccountQuotePrefix.setText(value);
return false;
}
});
mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
mDisplayMode.setSummary(mDisplayMode.getEntry());
mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayMode.findIndexOfValue(summary);
mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
mDisplayMode.setValue(summary);
return false;
}
});
mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
mSyncMode.setValue(mAccount.getFolderSyncMode().name());
mSyncMode.setSummary(mSyncMode.getEntry());
mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSyncMode.findIndexOfValue(summary);
mSyncMode.setSummary(mSyncMode.getEntries()[index]);
mSyncMode.setValue(summary);
return false;
}
});
mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
mPushMode.setEnabled(mIsPushCapable);
mPushMode.setValue(mAccount.getFolderPushMode().name());
mPushMode.setSummary(mPushMode.getEntry());
mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mPushMode.findIndexOfValue(summary);
mPushMode.setSummary(mPushMode.getEntries()[index]);
mPushMode.setValue(summary);
return false;
}
});
mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
mTargetMode.setValue(mAccount.getFolderTargetMode().name());
mTargetMode.setSummary(mTargetMode.getEntry());
mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mTargetMode.findIndexOfValue(summary);
mTargetMode.setSummary(mTargetMode.getEntries()[index]);
mTargetMode.setValue(summary);
return false;
}
});
mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
mDeletePolicy.setSummary(mDeletePolicy.getEntry());
mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDeletePolicy.findIndexOfValue(summary);
mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
mDeletePolicy.setValue(summary);
return false;
}
});
mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
mExpungePolicy.setEnabled(mIsExpungeCapable);
mExpungePolicy.setValue(mAccount.getExpungePolicy());
mExpungePolicy.setSummary(mExpungePolicy.getEntry());
mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mExpungePolicy.findIndexOfValue(summary);
mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
mExpungePolicy.setValue(summary);
return false;
}
});
mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
mSearchableFolders.setSummary(mSearchableFolders.getEntry());
mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSearchableFolders.findIndexOfValue(summary);
mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
mSearchableFolders.setValue(summary);
return false;
}
});
mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
mDisplayCount.setSummary(mDisplayCount.getEntry());
mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayCount.findIndexOfValue(summary);
mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
mDisplayCount.setValue(summary);
return false;
}
});
mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
mMessageAge.setSummary(mMessageAge.getEntry());
mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageAge.findIndexOfValue(summary);
mMessageAge.setSummary(mMessageAge.getEntries()[index]);
mMessageAge.setValue(summary);
return false;
}
});
mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
mMessageSize.setSummary(mMessageSize.getEntry());
mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageSize.findIndexOfValue(summary);
mMessageSize.setSummary(mMessageSize.getEntries()[index]);
mMessageSize.setValue(summary);
return false;
}
});
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
mAccountHideButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS);
mAccountHideButtons.setValue("" + mAccount.getHideMessageViewButtons());
mAccountHideButtons.setSummary(mAccountHideButtons.getEntry());
mAccountHideButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideButtons.findIndexOfValue(summary);
mAccountHideButtons.setSummary(mAccountHideButtons.getEntries()[index]);
mAccountHideButtons.setValue(summary);
return false;
}
});
mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
mAccountHideMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS);
mAccountHideMoveButtons.setValue("" + mAccount.getHideMessageViewMoveButtons());
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntry());
mAccountHideMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideMoveButtons.findIndexOfValue(summary);
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntries()[index]);
mAccountHideMoveButtons.setValue(summary);
return false;
}
});
mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
mAccountShowPictures.setValue("" + mAccount.getShowPictures());
mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountShowPictures.findIndexOfValue(summary);
mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
mAccountShowPictures.setValue(summary);
return false;
}
});
mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
{
final Map<String, String> providers;
providers = StorageManager.getInstance(K9.app).getAvailableProviders();
int i = 0;
final String[] providerLabels = new String[providers.size()];
final String[] providerIds = new String[providers.size()];
for (final Map.Entry<String, String> entry : providers.entrySet())
{
providerIds[i] = entry.getKey();
providerLabels[i] = entry.getValue();
i++;
}
mLocalStorageProvider.setEntryValues(providerIds);
mLocalStorageProvider.setEntries(providerLabels);
mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId());
mLocalStorageProvider.setSummary(providers.get((Object)mAccount.getLocalStorageProviderId()));
mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
mLocalStorageProvider.setSummary(providers.get(newValue));
return true;
}
});
}
// IMAP-specific preferences
mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (mIsPushCapable)
{
mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mIdleRefreshPeriod.findIndexOfValue(summary);
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
mIdleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
}
else
{
mPushPollOnConnect.setEnabled(false);
mMaxPushFolders.setEnabled(false);
mIdleRefreshPeriod.setEnabled(false);
}
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(mAccount.isNotifyNewMail());
mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
mAccountNotifySync.setChecked(mAccount.isShowOngoing());
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(mAccount.getNotificationSetting().isVibrate());
mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountVibratePattern.findIndexOfValue(summary);
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
mAccountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountVibrateTimes.setSummary(value);
mAccountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
List<? extends Folder> folders = new LinkedList<LocalFolder>();;
try
{
folders = mAccount.getLocalStore().getPersonalNamespaces(false);
}
catch (Exception e)
{
/// this can't be checked in
}
final String[] allFolderValues = new String[folders.size()+2];
final String[] allFolderLabels = new String[folders.size()+2];
allFolderValues[0] = K9.FOLDER_NONE;
allFolderLabels[0] = K9.FOLDER_NONE;
// There's a non-zero chance that "outbox" won't actually exist, so we force it into the list
allFolderValues[1] = mAccount.getOutboxFolderName();
allFolderLabels[1] = mAccount.getOutboxFolderName();
int i =2;
for (Folder folder : folders)
{
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels,allFolderValues);
mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER);
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels,allFolderValues);
mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels,allFolderValues);
mOutboxFolder = (ListPreference)findPreference(PREFERENCE_OUTBOX_FOLDER);
initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels,allFolderValues);
mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER);
initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels,allFolderValues);
mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER);
initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels,allFolderValues);
mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER);
initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels,allFolderValues);
mChipColor = (Preference)findPreference(PREFERENCE_CHIP_COLOR);
mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseChipColor();
return false;
}
});
mLedColor = (Preference)findPreference(PREFERENCE_LED_COLOR);
mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
mIncomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onOutgoingSettings();
return true;
}
});
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
if (!new Apg().isAvailable(this))
{
int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
if (apgIndex >= 0)
{
cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
mCryptoApp.setEntries(cryptoAppEntries);
}
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value))
{
Apg.createInstance(null).test(AccountSettings.this);
}
return false;
}
});
mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
handleCryptoAppDependencies();
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/net/RouteArc.java b/src/uk/me/parabola/imgfmt/app/net/RouteArc.java
index 271b9462..dca1f850 100644
--- a/src/uk/me/parabola/imgfmt/app/net/RouteArc.java
+++ b/src/uk/me/parabola/imgfmt/app/net/RouteArc.java
@@ -1,368 +1,364 @@
/*
* Copyright (C) 2008
*
* This program 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.
*
* 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.
*
* Create date: 07-Jul-2008
*/
package uk.me.parabola.imgfmt.app.net;
import uk.me.parabola.imgfmt.app.ImgFileWriter;
import uk.me.parabola.log.Logger;
/**
* An arc joins two nodes within a {@link RouteCenter}. This may be renamed
* to a Segment.
* The arc also references the road that it is a part of.
*
* There are also links between nodes in different centers.
*
* @author Steve Ratcliffe
*/
public class RouteArc {
private static final Logger log = Logger.getLogger(RouteArc.class);
// Flags A
private static final int FLAG_NEWDIR = 0x80;
private static final int FLAG_FORWARD = 0x40;
private static final int MASK_DESTCLASS = 0x7;
public static final int MASK_CURVE_LEN = 0x38;
// Flags B
private static final int FLAG_LAST_LINK = 0x80;
private static final int FLAG_EXTERNAL = 0x40;
private int offset;
private int initialHeading; // degrees
private final int finalHeading; // degrees
private final RoadDef roadDef;
// The nodes that this arc comes from and goes to
private final RouteNode source;
private final RouteNode dest;
// The index in Table A describing this arc.
private byte indexA;
// The index in Table B that this arc goes via, if external.
private byte indexB;
private byte flagA;
private byte flagB;
private boolean haveCurve;
private int length;
private final int pointsHash;
private final boolean curveEnabled;
/**
* Create a new arc.
*
* @param roadDef The road that this arc segment is part of.
* @param source The source node.
* @param dest The destination node.
* @param initialHeading The initial heading (signed degrees)
*/
public RouteArc(RoadDef roadDef,
RouteNode source, RouteNode dest,
int initialHeading, int finalHeading,
double length,
boolean curveEnabled,
int pointsHash) {
this.roadDef = roadDef;
this.source = source;
this.dest = dest;
this.initialHeading = initialHeading;
this.finalHeading = finalHeading;
this.length = convertMeters(length);
this.curveEnabled = curveEnabled;
this.pointsHash = pointsHash;
}
public int getInitialHeading() {
return initialHeading;
}
public void setInitialHeading(int ih) {
initialHeading = ih;
}
public int getFinalHeading() {
return finalHeading;
}
public RouteNode getSource() {
return source;
}
public RouteNode getDest() {
return dest;
}
public int getLength() {
return length;
}
public int getPointsHash() {
return pointsHash;
}
/**
* Provide an upper bound for the written size in bytes.
*/
public int boundSize() {
int[] lendat = encodeLength();
// 1 (flagA) + 1-2 (offset) + 1 (indexA) + 1 (initialHeading)
int size = 5 + lendat.length;
if(haveCurve)
size += encodeCurve().length;
return size;
}
/**
* Is this an arc within the RouteCenter?
*/
public boolean isInternal() {
// we might check that setInternal has been called before
return (flagB & FLAG_EXTERNAL) == 0;
}
public void setInternal(boolean internal) {
if (internal)
flagB &= ~FLAG_EXTERNAL;
else
flagB |= FLAG_EXTERNAL;
}
/**
* Set this arc's index into Table A.
*/
public void setIndexA(byte indexA) {
this.indexA = indexA;
}
/**
* Get this arc's index into Table A.
*
* Required for writing restrictions (Table C).
*/
public byte getIndexA() {
return indexA;
}
/**
* Set this arc's index into Table B. Applies to external arcs only.
*/
public void setIndexB(byte indexB) {
assert !isInternal() : "Trying to set index on internal arc.";
this.indexB = indexB;
}
/**
* Get this arc's index into Table B.
*
* Required for writing restrictions (Table C).
*/
public byte getIndexB() {
return indexB;
}
// units of 16 feet
final static double LENGTH_FACTOR = 3.2808 / 16;
private static int convertMeters(double l) {
return (int) (l * LENGTH_FACTOR);
}
public void write(ImgFileWriter writer) {
offset = writer.position();
if(log.isDebugEnabled())
log.debug("writing arc at", offset, ", flagA=", Integer.toHexString(flagA));
// fetch destination class -- will have been set correctly by now
setDestinationClass(dest.getNodeClass());
// determine how to write length and curve bit
int[] lendat = encodeLength();
writer.put(flagA);
if (isInternal()) {
// space for 14 bit node offset, written in writeSecond.
writer.put(flagB);
writer.put((byte) 0);
} else {
if(indexB >= 0x3f) {
writer.put((byte) (flagB | 0x3f));
writer.put(indexB);
}
else
writer.put((byte) (flagB | indexB));
}
writer.put(indexA);
if(log.isDebugEnabled())
log.debug("writing length", length);
for (int aLendat : lendat)
writer.put((byte) aLendat);
writer.put((byte)(256 * initialHeading / 360));
if (haveCurve) {
int[] curvedat = encodeCurve();
for (int aCurvedat : curvedat)
writer.put((byte) aCurvedat);
}
}
/**
* Second pass over the nodes in this RouteCenter.
* Node offsets are now all known, so we can write the pointers
* for internal arcs.
*/
public void writeSecond(ImgFileWriter writer) {
if (!isInternal())
return;
writer.position(offset + 1);
char val = (char) (flagB << 8);
int diff = dest.getOffsetNod1() - source.getOffsetNod1();
assert diff < 0x2000 && diff >= -0x2000
: "relative pointer too large for 14 bits (source offset = " + source.getOffsetNod1() + ", dest offset = " + dest.getOffsetNod1() + ")";
val |= diff & 0x3fff;
// We write this big endian
if(log.isDebugEnabled())
log.debug("val is", Integer.toHexString((int)val));
writer.put((byte) (val >> 8));
writer.put((byte) val);
}
/*
* length and curve flag are stored in a variety of ways, involving
* 1. flagA & 0x38 (3 bits)
* 2. 1-3 bytes following the possible Table A index
*
* There's even more different encodings supposedly.
*/
private int[] encodeLength() {
// update haveCurve
haveCurve = (curveEnabled && finalHeading != initialHeading);
- if (length >= (1 << 14)) {
- log.error("warning: Way " + roadDef.getName() + " (id " + roadDef.getId() + ") contains an arc whose length (" + length + " units) is too big to be encoded so the way will not be routable");
- //length = (1 << 14) - 1;
- }
if (length >= (1 << 22)) {
- log.error("Way " + roadDef.getName() + " (id " + roadDef.getId() + ") contains an arc whose length (" + length + " units) is too big to be encoded so the way will not be routable");
+ log.error("Way " + roadDef.getName() + " (id " + roadDef.getId() + ") contains an arc whose length (" + length + " units) is too big to be encoded so the way might not be routable");
length = (1 << 22) - 1;
}
// clear existing bits in case length or final heading have
// been changed
flagA &= ~0x38;
int[] lendat;
if(length < 0x200) {
// 9 bit length optional curve
if(haveCurve)
flagA |= 0x20;
flagA |= (length >> 5) & 0x08; // top bit of length
lendat = new int[1]; // one byte of data
lendat[0] = length; // bottom 8 bits of length
}
else if(length >= (1 << 14)) {
// 22 bit length with curve
flagA |= 0x38;
lendat = new int[3]; // three bytes of data
lendat[0] = 0xC0 | (length & 0x3f); // 0x80 set, 0x40 set, 6 low bits of length
lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
lendat[2] = (length >> 14) & 0xff; // 8 more bits of length
}
else if(haveCurve) {
// 15 bit length with curve
flagA |= 0x38; // all three bits set
lendat = new int[2]; // two bytes of data
lendat[0] = (length & 0x7f); // 0x80 not set, 7 low bits of length
lendat[1] = (length >> 7) & 0xff; // 8 more bits of length
}
else {
// 14 bit length no curve
flagA |= 0x38; // all three bits set
lendat = new int[2]; // two bytes of data
lendat[0] = 0x80 | (length & 0x3f); // 0x80 set, 0x40 not set, 6 low bits of length
lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
}
return lendat;
}
/**
* Encode the curve data into a sequence of bytes.
*
* 1 or 2 bytes show up in practice, but they're not at
* all well understood yet.
*/
private int[] encodeCurve() {
// most examples of curve data are a single byte that encodes
// the final heading of the arc. The bits appear to be
// reorganised into the order 21076543 (i.e. the top 5 bits
// are shifted down to the bottom). Unfortunately, it's not
// that simple because sometimes the curve is encoded using 2
// bytes. The presence of the 2nd byte is indicated by the top
// 3 bits of the first byte all being zero. As the encoding of
// the 2-byte variant is not yet understood, for the moment,
// if the resulting value would have the top 3 bits all zero,
// we set what we hope is the LSB so that it becomes valid
// 1-byte curve data
int heading = 256 * finalHeading / 360;
int encodedHeading = ((heading & 0xf8) >> 3) | ((heading & 0x07) << 5);
if((encodedHeading & 0xe0) == 0) {
// hack - set a bit (hopefully, the LSB) to force 1-byte
// encoding
encodedHeading |= 0x20;
}
int[] curveData = new int[1];
curveData[0] = encodedHeading;
return curveData;
}
public RoadDef getRoadDef() {
return roadDef;
}
public void setNewDir() {
flagA |= FLAG_NEWDIR;
}
public void setForward() {
flagA |= FLAG_FORWARD;
}
public boolean isForward() {
return (flagA & FLAG_FORWARD) != 0;
}
public void setLast() {
flagB |= FLAG_LAST_LINK;
}
protected void setDestinationClass(int destinationClass) {
if(log.isDebugEnabled())
log.debug("setting destination class", destinationClass);
flagA |= (destinationClass & MASK_DESTCLASS);
}
}
| false | true | private int[] encodeLength() {
// update haveCurve
haveCurve = (curveEnabled && finalHeading != initialHeading);
if (length >= (1 << 14)) {
log.error("warning: Way " + roadDef.getName() + " (id " + roadDef.getId() + ") contains an arc whose length (" + length + " units) is too big to be encoded so the way will not be routable");
//length = (1 << 14) - 1;
}
if (length >= (1 << 22)) {
log.error("Way " + roadDef.getName() + " (id " + roadDef.getId() + ") contains an arc whose length (" + length + " units) is too big to be encoded so the way will not be routable");
length = (1 << 22) - 1;
}
// clear existing bits in case length or final heading have
// been changed
flagA &= ~0x38;
int[] lendat;
if(length < 0x200) {
// 9 bit length optional curve
if(haveCurve)
flagA |= 0x20;
flagA |= (length >> 5) & 0x08; // top bit of length
lendat = new int[1]; // one byte of data
lendat[0] = length; // bottom 8 bits of length
}
else if(length >= (1 << 14)) {
// 22 bit length with curve
flagA |= 0x38;
lendat = new int[3]; // three bytes of data
lendat[0] = 0xC0 | (length & 0x3f); // 0x80 set, 0x40 set, 6 low bits of length
lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
lendat[2] = (length >> 14) & 0xff; // 8 more bits of length
}
else if(haveCurve) {
// 15 bit length with curve
flagA |= 0x38; // all three bits set
lendat = new int[2]; // two bytes of data
lendat[0] = (length & 0x7f); // 0x80 not set, 7 low bits of length
lendat[1] = (length >> 7) & 0xff; // 8 more bits of length
}
else {
// 14 bit length no curve
flagA |= 0x38; // all three bits set
lendat = new int[2]; // two bytes of data
lendat[0] = 0x80 | (length & 0x3f); // 0x80 set, 0x40 not set, 6 low bits of length
lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
}
return lendat;
}
| private int[] encodeLength() {
// update haveCurve
haveCurve = (curveEnabled && finalHeading != initialHeading);
if (length >= (1 << 22)) {
log.error("Way " + roadDef.getName() + " (id " + roadDef.getId() + ") contains an arc whose length (" + length + " units) is too big to be encoded so the way might not be routable");
length = (1 << 22) - 1;
}
// clear existing bits in case length or final heading have
// been changed
flagA &= ~0x38;
int[] lendat;
if(length < 0x200) {
// 9 bit length optional curve
if(haveCurve)
flagA |= 0x20;
flagA |= (length >> 5) & 0x08; // top bit of length
lendat = new int[1]; // one byte of data
lendat[0] = length; // bottom 8 bits of length
}
else if(length >= (1 << 14)) {
// 22 bit length with curve
flagA |= 0x38;
lendat = new int[3]; // three bytes of data
lendat[0] = 0xC0 | (length & 0x3f); // 0x80 set, 0x40 set, 6 low bits of length
lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
lendat[2] = (length >> 14) & 0xff; // 8 more bits of length
}
else if(haveCurve) {
// 15 bit length with curve
flagA |= 0x38; // all three bits set
lendat = new int[2]; // two bytes of data
lendat[0] = (length & 0x7f); // 0x80 not set, 7 low bits of length
lendat[1] = (length >> 7) & 0xff; // 8 more bits of length
}
else {
// 14 bit length no curve
flagA |= 0x38; // all three bits set
lendat = new int[2]; // two bytes of data
lendat[0] = 0x80 | (length & 0x3f); // 0x80 set, 0x40 not set, 6 low bits of length
lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
}
return lendat;
}
|
diff --git a/engine/src/bullet/com/jme3/bullet/control/KinematicRagdollControl.java b/engine/src/bullet/com/jme3/bullet/control/KinematicRagdollControl.java
index 08809f3a2..a7dd9dd19 100644
--- a/engine/src/bullet/com/jme3/bullet/control/KinematicRagdollControl.java
+++ b/engine/src/bullet/com/jme3/bullet/control/KinematicRagdollControl.java
@@ -1,875 +1,875 @@
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* 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 'jMonkeyEngine' 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 OWNER 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.jme3.bullet.control;
import com.jme3.bullet.control.ragdoll.RagdollPreset;
import com.jme3.bullet.control.ragdoll.HumanoidRagdollPreset;
import com.jme3.animation.AnimControl;
import com.jme3.animation.Bone;
import com.jme3.animation.Skeleton;
import com.jme3.animation.SkeletonControl;
import com.jme3.asset.AssetManager;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.RagdollCollisionListener;
import com.jme3.bullet.collision.shapes.BoxCollisionShape;
import com.jme3.bullet.collision.shapes.HullCollisionShape;
import com.jme3.bullet.control.ragdoll.RagdollUtils;
import com.jme3.bullet.joints.SixDofJoint;
import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**<strong>This control is still a WIP, use it at your own risk</strong><br>
* To use this control you need a model with an AnimControl and a SkeletonControl.<br>
* This should be the case if you imported an animated model from Ogre or blender.<br>
* Note enabling/disabling the control add/removes it from the physic space<br>
* <p>
* This control creates collision shapes for each bones of the skeleton when you call spatial.addControl(ragdollControl).
* <ul>
* <li>The shape is HullCollision shape based on the vertices associated with each bone and based on a tweakable weight threshold (see setWeightThreshold)</li>
* <li>If you don't want each bone to be a collision shape, you can specify what bone to use by using the addBoneName method<br>
* By using this method, bone that are not used to create a shape, are "merged" to their parent to create the collision shape.
* </li>
* </ul>
*</p>
*<p>
*There are 2 modes for this control :
* <ul>
* <li><strong>The kinematic modes :</strong><br>
* this is the default behavior, this means that the collision shapes of the body are able to interact with physics enabled objects.
* in this mode physic shapes follow the moovements of the animated skeleton (for example animated by a key framed animation)
* this mode is enabled by calling setKinematicMode();
* </li>
* <li><strong>The ragdoll modes :</strong><br>
* To enable this behavior, you need to call setRagdollMode() method.
* In this mode the charater is entirely controled by physics, so it will fall under the gravity and move if any force is applied to it.
* </li>
* </ul>
*</p>
*
* @author Normen Hansen and Rémy Bouquet (Nehon)
*/
public class KinematicRagdollControl implements PhysicsControl, PhysicsCollisionListener {
protected static final Logger logger = Logger.getLogger(KinematicRagdollControl.class.getName());
protected Map<String, PhysicsBoneLink> boneLinks = new HashMap<String, PhysicsBoneLink>();
protected Skeleton skeleton;
protected PhysicsSpace space;
protected boolean enabled = true;
protected boolean debug = false;
protected PhysicsRigidBody baseRigidBody;
protected float weightThreshold = -1.0f;
protected Spatial targetModel;
protected Vector3f initScale;
protected Mode mode = Mode.Kinetmatic;
protected boolean blendedControl = false;
protected float blendTime = 1.0f;
protected float blendStart = 0.0f;
protected List<RagdollCollisionListener> listeners;
protected float eventDispatchImpulseThreshold = 10;
protected RagdollPreset preset = new HumanoidRagdollPreset();
protected Set<String> boneList = new TreeSet<String>();
protected Vector3f modelPosition = new Vector3f();
protected Quaternion modelRotation = new Quaternion();
protected float rootMass = 15;
protected float totalMass = 0;
protected boolean added = false;
public static enum Mode {
Kinetmatic,
Ragdoll
}
protected class PhysicsBoneLink {
protected Bone bone;
protected Quaternion initalWorldRotation;
protected SixDofJoint joint;
protected PhysicsRigidBody rigidBody;
protected Quaternion startBlendingRot = new Quaternion();
protected Vector3f startBlendingPos = new Vector3f();
}
/**
* contruct a KinematicRagdollControl
*/
public KinematicRagdollControl() {
}
public KinematicRagdollControl(float weightThreshold) {
this.weightThreshold = weightThreshold;
}
public KinematicRagdollControl(RagdollPreset preset, float weightThreshold) {
this.preset = preset;
this.weightThreshold = weightThreshold;
}
public KinematicRagdollControl(RagdollPreset preset) {
this.preset = preset;
}
public void update(float tpf) {
if (!enabled) {
return;
}
TempVars vars = TempVars.get();
assert vars.lock();
Quaternion tmpRot1 = vars.quat1;
Quaternion tmpRot2 = vars.quat2;
//if the ragdoll has the control of the skeleton, we update each bone with its position in physic world space.
if (mode == mode.Ragdoll && targetModel.getLocalTranslation().equals(modelPosition)) {
for (PhysicsBoneLink link : boneLinks.values()) {
Vector3f position = vars.vect1;
//retrieving bone position in physic world space
Vector3f p = link.rigidBody.getMotionState().getWorldLocation();
//transforming this position with inverse transforms of the model
targetModel.getWorldTransform().transformInverseVector(p, position);
//retrieving bone rotation in physic world space
Quaternion q = link.rigidBody.getMotionState().getWorldRotationQuat();
//multiplying this rotation by the initialWorld rotation of the bone,
//then transforming it with the inverse world rotation of the model
tmpRot1.set(q).multLocal(link.initalWorldRotation);
tmpRot2.set(targetModel.getWorldRotation()).inverseLocal().mult(tmpRot1, tmpRot1);
tmpRot1.normalizeLocal();
//if the bone is the root bone, we apply the physic's transform to the model, so its position and rotation are correctly updated
if (link.bone.getParent() == null) {
//offsetting the physic's position/rotation by the root bone inverse model space position/rotaion
- modelPosition.set(p).subtractLocal(link.bone.getInitialPos());
+ modelPosition.set(p).subtractLocal(link.bone.getWorldBindPosition());
targetModel.getParent().getWorldTransform().transformInverseVector(modelPosition, modelPosition);
- modelRotation.set(q).multLocal(tmpRot2.set(link.bone.getInitialRot()).inverseLocal());
+ modelRotation.set(q).multLocal(tmpRot2.set(link.bone.getWorldBindRotation()).inverseLocal());
//applying transforms to the model
targetModel.setLocalTranslation(modelPosition);
targetModel.setLocalRotation(modelRotation);
//Applying computed transforms to the bone
link.bone.setUserTransformsWorld(position, tmpRot1);
} else {
//if boneList is empty, this means that every bone in the ragdoll has a collision shape,
//so we just update the bone position
if (boneList.isEmpty()) {
link.bone.setUserTransformsWorld(position, tmpRot1);
} else {
//boneList is not empty, this means some bones of the skeleton might not be associated with a collision shape.
//So we update them recusively
RagdollUtils.setTransform(link.bone, position, tmpRot1, false, boneList);
}
}
}
} else {
//the ragdoll does not have the controll, so the keyframed animation updates the physic position of the physic bonces
for (PhysicsBoneLink link : boneLinks.values()) {
Vector3f position = vars.vect1;
//if blended control this means, keyframed animation is updating the skeleton,
//but to allow smooth transition, we blend this transformation with the saved position of the ragdoll
if (blendedControl) {
Vector3f position2 = vars.vect2;
//initializing tmp vars with the start position/rotation of the ragdoll
position.set(link.startBlendingPos);
tmpRot1.set(link.startBlendingRot);
//interpolating between ragdoll position/rotation and keyframed position/rotation
tmpRot2.set(tmpRot1).nlerp(link.bone.getModelSpaceRotation(), blendStart / blendTime);
position2.set(position).interpolate(link.bone.getModelSpacePosition(), blendStart / blendTime);
tmpRot1.set(tmpRot2);
position.set(position2);
//updating bones transforms
if (boneList.isEmpty()) {
//we ensure we have the control to update the bone
link.bone.setUserControl(true);
link.bone.setUserTransformsWorld(position, tmpRot1);
//we give control back to the key framed animation.
link.bone.setUserControl(false);
} else {
RagdollUtils.setTransform(link.bone, position, tmpRot1, true, boneList);
}
}
//setting skeleton transforms to the ragdoll
matchPhysicObjectToBone(link, position, tmpRot1);
modelPosition.set(targetModel.getLocalTranslation());
}
//time control for blending
if (blendedControl) {
blendStart += tpf;
if (blendStart > blendTime) {
blendedControl = false;
}
}
}
assert vars.unlock();
}
/**
* Set the transforms of a rigidBody to match the transforms of a bone.
* this is used to make the ragdoll follow the skeleton motion while in Kinematic mode
* @param link the link containing the bone and the rigidBody
* @param position just a temp vector for position
* @param tmpRot1 just a temp quaternion for rotation
*/
private void matchPhysicObjectToBone(PhysicsBoneLink link, Vector3f position, Quaternion tmpRot1) {
//computing position from rotation and scale
targetModel.getWorldTransform().transformVector(link.bone.getModelSpacePosition(), position);
//computing rotation
tmpRot1.set(link.bone.getModelSpaceRotation()).multLocal(link.bone.getWorldBindInverseRotation());
targetModel.getWorldRotation().mult(tmpRot1, tmpRot1);
tmpRot1.normalizeLocal();
//updating physic location/rotation of the physic bone
link.rigidBody.setPhysicsLocation(position);
link.rigidBody.setPhysicsRotation(tmpRot1);
}
public Control cloneForSpatial(Spatial spatial) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* rebuild the ragdoll
* this is useful if you applied scale on the ragdoll after it's been initialized
*/
public void reBuild() {
setSpatial(targetModel);
addToPhysicsSpace();
}
public void setSpatial(Spatial model) {
if (model == null) {
removeFromPhysicsSpace();
clearData();
return;
}
targetModel = model;
Node parent = model.getParent();
Vector3f initPosition = model.getLocalTranslation().clone();
Quaternion initRotation = model.getLocalRotation().clone();
initScale = model.getLocalScale().clone();
model.removeFromParent();
model.setLocalTranslation(Vector3f.ZERO);
model.setLocalRotation(Quaternion.IDENTITY);
model.setLocalScale(1);
//HACK ALERT change this
//I remove the skeletonControl and readd it to the spatial to make sure it's after the ragdollControl in the stack
//Find a proper way to order the controls.
SkeletonControl sc = model.getControl(SkeletonControl.class);
model.removeControl(sc);
model.addControl(sc);
//----
removeFromPhysicsSpace();
clearData();
// put into bind pose and compute bone transforms in model space
// maybe dont reset to ragdoll out of animations?
scanSpatial(model);
if (parent != null) {
parent.attachChild(model);
}
model.setLocalTranslation(initPosition);
model.setLocalRotation(initRotation);
model.setLocalScale(initScale);
logger.log(Level.INFO, "Created physics ragdoll for skeleton {0}", skeleton);
}
/**
* Add a bone name to this control
* Using this method you can specify which bones of the skeleton will be used to build the collision shapes.
* @param name
*/
public void addBoneName(String name) {
boneList.add(name);
}
private void scanSpatial(Spatial model) {
AnimControl animControl = model.getControl(AnimControl.class);
Map<Integer, List<Float>> pointsMap = null;
if (weightThreshold == -1.0f) {
pointsMap = RagdollUtils.buildPointMap(model);
}
skeleton = animControl.getSkeleton();
skeleton.resetAndUpdate();
for (int i = 0; i < skeleton.getRoots().length; i++) {
Bone childBone = skeleton.getRoots()[i];
if (childBone.getParent() == null) {
logger.log(Level.INFO, "Found root bone in skeleton {0}", skeleton);
baseRigidBody = new PhysicsRigidBody(new BoxCollisionShape(Vector3f.UNIT_XYZ.mult(0.1f)), 1);
baseRigidBody.setKinematic(mode == Mode.Kinetmatic);
boneRecursion(model, childBone, baseRigidBody, 1, pointsMap);
}
}
}
private void boneRecursion(Spatial model, Bone bone, PhysicsRigidBody parent, int reccount, Map<Integer, List<Float>> pointsMap) {
PhysicsRigidBody parentShape = parent;
if (boneList.isEmpty() || boneList.contains(bone.getName())) {
PhysicsBoneLink link = new PhysicsBoneLink();
link.bone = bone;
//creating the collision shape
HullCollisionShape shape = null;
if (pointsMap != null) {
//build a shape for the bone, using the vertices that are most influenced by this bone
shape = RagdollUtils.makeShapeFromPointMap(pointsMap, RagdollUtils.getBoneIndices(link.bone, skeleton, boneList), initScale, link.bone.getModelSpacePosition());
} else {
//build a shape for the bone, using the vertices associated with this bone with a weight above the threshold
shape = RagdollUtils.makeShapeFromVerticeWeights(model, RagdollUtils.getBoneIndices(link.bone, skeleton, boneList), initScale, link.bone.getModelSpacePosition(), weightThreshold);
}
PhysicsRigidBody shapeNode = new PhysicsRigidBody(shape, rootMass / (float) reccount);
shapeNode.setKinematic(mode == Mode.Kinetmatic);
totalMass += rootMass / (float) reccount;
link.rigidBody = shapeNode;
link.initalWorldRotation = bone.getModelSpaceRotation().clone();
if (parent != null) {
//get joint position for parent
Vector3f posToParent = new Vector3f();
if (bone.getParent() != null) {
bone.getModelSpacePosition().subtract(bone.getParent().getModelSpacePosition(), posToParent).multLocal(initScale);
}
SixDofJoint joint = new SixDofJoint(parent, shapeNode, posToParent, new Vector3f(0, 0, 0f), true);
preset.setupJointForBone(bone.getName(), joint);
link.joint = joint;
joint.setCollisionBetweenLinkedBodys(false);
}
boneLinks.put(bone.getName(), link);
shapeNode.setUserObject(link);
parentShape = shapeNode;
}
for (Iterator<Bone> it = bone.getChildren().iterator(); it.hasNext();) {
Bone childBone = it.next();
boneRecursion(model, childBone, parentShape, reccount + 1, pointsMap);
}
}
/**
* Set the joint limits for the joint between the given bone and its parent.
* This method can't work before attaching the control to a spatial
* @param boneName the name of the bone
* @param maxX the maximum rotation on the x axis (in radians)
* @param minX the minimum rotation on the x axis (in radians)
* @param maxY the maximum rotation on the y axis (in radians)
* @param minY the minimum rotation on the z axis (in radians)
* @param maxZ the maximum rotation on the z axis (in radians)
* @param minZ the minimum rotation on the z axis (in radians)
*/
public void setJointLimit(String boneName, float maxX, float minX, float maxY, float minY, float maxZ, float minZ) {
PhysicsBoneLink link = boneLinks.get(boneName);
if (link != null) {
RagdollUtils.setJointLimit(link.joint, maxX, minX, maxY, minY, maxZ, minZ);
} else {
logger.log(Level.WARNING, "Not joint was found for bone {0}. make sure you call spatial.addControl(ragdoll) before setting joints limit", boneName);
}
}
/**
* Return the joint between the given bone and its parent.
* This return null if it's called before attaching the control to a spatial
* @param boneName the name of the bone
* @return the joint between the given bone and its parent
*/
public SixDofJoint getJoint(String boneName) {
PhysicsBoneLink link = boneLinks.get(boneName);
if (link != null) {
return link.joint;
} else {
logger.log(Level.WARNING, "Not joint was found for bone {0}. make sure you call spatial.addControl(ragdoll) before setting joints limit", boneName);
return null;
}
}
private void clearData() {
boneLinks.clear();
baseRigidBody = null;
}
private void addToPhysicsSpace() {
if (space == null) {
return;
}
if (baseRigidBody != null) {
space.add(baseRigidBody);
added = true;
}
for (Iterator<PhysicsBoneLink> it = boneLinks.values().iterator(); it.hasNext();) {
PhysicsBoneLink physicsBoneLink = it.next();
if (physicsBoneLink.rigidBody != null) {
space.add(physicsBoneLink.rigidBody);
if (physicsBoneLink.joint != null) {
space.add(physicsBoneLink.joint);
}
added = true;
}
}
}
protected void removeFromPhysicsSpace() {
if (space == null) {
return;
}
if (baseRigidBody != null) {
space.remove(baseRigidBody);
}
for (Iterator<PhysicsBoneLink> it = boneLinks.values().iterator(); it.hasNext();) {
PhysicsBoneLink physicsBoneLink = it.next();
if (physicsBoneLink.joint != null) {
space.remove(physicsBoneLink.joint);
if (physicsBoneLink.rigidBody != null) {
space.remove(physicsBoneLink.rigidBody);
}
}
}
added = false;
}
/**
* enable or disable the control
* note that if enabled is true and that the physic space has been set on the ragdoll, the ragdoll is added to the physic space
* if enabled is false the ragdoll is removed from physic space.
* @param enabled
*/
public void setEnabled(boolean enabled) {
if (this.enabled == enabled) {
return;
}
this.enabled = enabled;
if (!enabled && space != null) {
removeFromPhysicsSpace();
} else if (enabled && space != null) {
addToPhysicsSpace();
}
}
/**
* returns true if the control is enabled
* @return
*/
public boolean isEnabled() {
return enabled;
}
protected void attachDebugShape(AssetManager manager) {
for (Iterator<PhysicsBoneLink> it = boneLinks.values().iterator(); it.hasNext();) {
PhysicsBoneLink physicsBoneLink = it.next();
physicsBoneLink.rigidBody.createDebugShape(manager);
}
debug = true;
}
protected void detachDebugShape() {
for (Iterator<PhysicsBoneLink> it = boneLinks.values().iterator(); it.hasNext();) {
PhysicsBoneLink physicsBoneLink = it.next();
physicsBoneLink.rigidBody.detachDebugShape();
}
debug = false;
}
/**
* For internal use only
* specific render for the ragdoll(if debugging)
* @param rm
* @param vp
*/
public void render(RenderManager rm, ViewPort vp) {
if (enabled && space != null && space.getDebugManager() != null) {
if (!debug) {
attachDebugShape(space.getDebugManager());
}
for (Iterator<PhysicsBoneLink> it = boneLinks.values().iterator(); it.hasNext();) {
PhysicsBoneLink physicsBoneLink = it.next();
Spatial debugShape = physicsBoneLink.rigidBody.debugShape();
if (debugShape != null) {
debugShape.setLocalTranslation(physicsBoneLink.rigidBody.getMotionState().getWorldLocation());
debugShape.setLocalRotation(physicsBoneLink.rigidBody.getMotionState().getWorldRotationQuat());
debugShape.updateGeometricState();
rm.renderScene(debugShape, vp);
}
}
}
}
/**
* set the physic space to this ragdoll
* @param space
*/
public void setPhysicsSpace(PhysicsSpace space) {
if (space == null) {
removeFromPhysicsSpace();
this.space = space;
} else {
if (this.space == space) {
return;
}
this.space = space;
addToPhysicsSpace();
this.space.addCollisionListener(this);
}
}
/**
* returns the physic space
* @return
*/
public PhysicsSpace getPhysicsSpace() {
return space;
}
/**
* serialize this control
* @param ex
* @throws IOException
*/
public void write(JmeExporter ex) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* de-serialize this control
* @param im
* @throws IOException
*/
public void read(JmeImporter im) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* For internal use only
* callback for collisionevent
* @param event
*/
public void collision(PhysicsCollisionEvent event) {
PhysicsCollisionObject objA = event.getObjectA();
PhysicsCollisionObject objB = event.getObjectB();
//excluding collisions that involve 2 parts of the ragdoll
if (event.getNodeA() == null && event.getNodeB() == null) {
return;
}
//discarding low impulse collision
if (event.getAppliedImpulse() < eventDispatchImpulseThreshold) {
return;
}
boolean hit = false;
Bone hitBone = null;
PhysicsCollisionObject hitObject = null;
//Computing which bone has been hit
if (objA.getUserObject() instanceof PhysicsBoneLink) {
PhysicsBoneLink link = (PhysicsBoneLink) objA.getUserObject();
if (link != null) {
hit = true;
hitBone = link.bone;
hitObject = objB;
}
}
if (objB.getUserObject() instanceof PhysicsBoneLink) {
PhysicsBoneLink link = (PhysicsBoneLink) objB.getUserObject();
if (link != null) {
hit = true;
hitBone = link.bone;
hitObject = objA;
}
}
//dispatching the event if the ragdoll has been hit
if (hit) {
for (RagdollCollisionListener listener : listeners) {
listener.collide(hitBone, hitObject, event);
}
}
}
/**
* Enable or disable the ragdoll behaviour.
* if ragdollEnabled is true, the character motion will only be powerd by physics
* else, the characted will be animated by the keyframe animation,
* but will be able to physically interact with its physic environnement
* @param ragdollEnabled
*/
protected void setMode(Mode mode) {
this.mode = mode;
AnimControl animControl = targetModel.getControl(AnimControl.class);
animControl.setEnabled(mode == Mode.Kinetmatic);
baseRigidBody.setKinematic(mode == Mode.Kinetmatic);
TempVars vars = TempVars.get();
assert vars.lock();
for (PhysicsBoneLink link : boneLinks.values()) {
link.rigidBody.setKinematic(mode == Mode.Kinetmatic);
if (mode == Mode.Ragdoll) {
Quaternion tmpRot1 = vars.quat1;
Vector3f position = vars.vect1;
//making sure that the ragdoll is at the correct place.
matchPhysicObjectToBone(link, position, tmpRot1);
}
}
assert vars.unlock();
for (Bone bone : skeleton.getRoots()) {
RagdollUtils.setUserControl(bone, mode == Mode.Ragdoll);
}
}
/**
* Smoothly blend from Ragdoll mode to Kinematic mode
* This is useful to blend ragdoll actual position to a keyframe animation for example
* @param blendTime the blending time between ragdoll to anim.
*/
public void blendToKinematicMode(float blendTime) {
if (mode == Mode.Kinetmatic) {
return;
}
blendedControl = true;
this.blendTime = blendTime;
mode = Mode.Kinetmatic;
AnimControl animControl = targetModel.getControl(AnimControl.class);
animControl.setEnabled(true);
TempVars vars = TempVars.get();
assert vars.lock();
for (PhysicsBoneLink link : boneLinks.values()) {
Vector3f p = link.rigidBody.getMotionState().getWorldLocation();
Vector3f position = vars.vect1;
targetModel.getWorldTransform().transformInverseVector(p, position);
Quaternion q = link.rigidBody.getMotionState().getWorldRotationQuat();
Quaternion q2 = vars.quat1;
Quaternion q3 = vars.quat2;
q2.set(q).multLocal(link.initalWorldRotation).normalizeLocal();
q3.set(targetModel.getWorldRotation()).inverseLocal().mult(q2, q2);
q2.normalizeLocal();
link.startBlendingPos.set(position);
link.startBlendingRot.set(q2);
link.rigidBody.setKinematic(true);
}
assert vars.unlock();
for (Bone bone : skeleton.getRoots()) {
RagdollUtils.setUserControl(bone, false);
}
blendStart = 0;
}
/**
* Set the control into Kinematic mode
* In theis mode, the collision shapes follow the movements of the skeleton,
* and can interact with physical environement
*/
public void setKinematicMode() {
if (mode != Mode.Kinetmatic) {
setMode(Mode.Kinetmatic);
}
}
/**
* Sets the control into Ragdoll mode
* The skeleton is entirely controlled by physics.
*/
public void setRagdollMode() {
if (mode != Mode.Ragdoll) {
setMode(Mode.Ragdoll);
}
}
/**
* retruns the mode of this control
* @return
*/
public Mode getMode() {
return mode;
}
/**
* add a
* @param listener
*/
public void addCollisionListener(RagdollCollisionListener listener) {
if (listeners == null) {
listeners = new ArrayList<RagdollCollisionListener>();
}
listeners.add(listener);
}
public void setRootMass(float rootMass) {
this.rootMass = rootMass;
}
public float getTotalMass() {
return totalMass;
}
public float getWeightThreshold() {
return weightThreshold;
}
public void setWeightThreshold(float weightThreshold) {
this.weightThreshold = weightThreshold;
}
public float getEventDispatchImpulseThreshold() {
return eventDispatchImpulseThreshold;
}
public void setEventDispatchImpulseThreshold(float eventDispatchImpulseThreshold) {
this.eventDispatchImpulseThreshold = eventDispatchImpulseThreshold;
}
/**
* Set the CcdMotionThreshold of all the bone's rigidBodies of the ragdoll
* @see PhysicsRigidBody#setCcdMotionThreshold(float)
* @param value
*/
public void setCcdMotionThreshold(float value) {
for (PhysicsBoneLink link : boneLinks.values()) {
link.rigidBody.setCcdMotionThreshold(value);
}
}
/**
* Set the CcdSweptSphereRadius of all the bone's rigidBodies of the ragdoll
* @see PhysicsRigidBody#setCcdSweptSphereRadius(float)
* @param value
*/
public void setCcdSweptSphereRadius(float value) {
for (PhysicsBoneLink link : boneLinks.values()) {
link.rigidBody.setCcdSweptSphereRadius(value);
}
}
/**
* Set the CcdMotionThreshold of the given bone's rigidBodies of the ragdoll
* @see PhysicsRigidBody#setCcdMotionThreshold(float)
* @param value
* @deprecated use getBoneRigidBody(String BoneName).setCcdMotionThreshold(float) instead
*/
@Deprecated
public void setBoneCcdMotionThreshold(String boneName, float value) {
PhysicsBoneLink link = boneLinks.get(boneName);
if (link != null) {
link.rigidBody.setCcdMotionThreshold(value);
}
}
/**
* Set the CcdSweptSphereRadius of the given bone's rigidBodies of the ragdoll
* @see PhysicsRigidBody#setCcdSweptSphereRadius(float)
* @param value
* @deprecated use getBoneRigidBody(String BoneName).setCcdSweptSphereRadius(float) instead
*/
@Deprecated
public void setBoneCcdSweptSphereRadius(String boneName, float value) {
PhysicsBoneLink link = boneLinks.get(boneName);
if (link != null) {
link.rigidBody.setCcdSweptSphereRadius(value);
}
}
/**
* return the rigidBody associated to the given bone
* @param boneName the name of the bone
* @return the associated rigidBody.
*/
public PhysicsRigidBody getBoneRigidBody(String boneName) {
PhysicsBoneLink link = boneLinks.get(boneName);
if (link != null) {
return link.rigidBody;
}
return null;
}
}
| false | true | public void update(float tpf) {
if (!enabled) {
return;
}
TempVars vars = TempVars.get();
assert vars.lock();
Quaternion tmpRot1 = vars.quat1;
Quaternion tmpRot2 = vars.quat2;
//if the ragdoll has the control of the skeleton, we update each bone with its position in physic world space.
if (mode == mode.Ragdoll && targetModel.getLocalTranslation().equals(modelPosition)) {
for (PhysicsBoneLink link : boneLinks.values()) {
Vector3f position = vars.vect1;
//retrieving bone position in physic world space
Vector3f p = link.rigidBody.getMotionState().getWorldLocation();
//transforming this position with inverse transforms of the model
targetModel.getWorldTransform().transformInverseVector(p, position);
//retrieving bone rotation in physic world space
Quaternion q = link.rigidBody.getMotionState().getWorldRotationQuat();
//multiplying this rotation by the initialWorld rotation of the bone,
//then transforming it with the inverse world rotation of the model
tmpRot1.set(q).multLocal(link.initalWorldRotation);
tmpRot2.set(targetModel.getWorldRotation()).inverseLocal().mult(tmpRot1, tmpRot1);
tmpRot1.normalizeLocal();
//if the bone is the root bone, we apply the physic's transform to the model, so its position and rotation are correctly updated
if (link.bone.getParent() == null) {
//offsetting the physic's position/rotation by the root bone inverse model space position/rotaion
modelPosition.set(p).subtractLocal(link.bone.getInitialPos());
targetModel.getParent().getWorldTransform().transformInverseVector(modelPosition, modelPosition);
modelRotation.set(q).multLocal(tmpRot2.set(link.bone.getInitialRot()).inverseLocal());
//applying transforms to the model
targetModel.setLocalTranslation(modelPosition);
targetModel.setLocalRotation(modelRotation);
//Applying computed transforms to the bone
link.bone.setUserTransformsWorld(position, tmpRot1);
} else {
//if boneList is empty, this means that every bone in the ragdoll has a collision shape,
//so we just update the bone position
if (boneList.isEmpty()) {
link.bone.setUserTransformsWorld(position, tmpRot1);
} else {
//boneList is not empty, this means some bones of the skeleton might not be associated with a collision shape.
//So we update them recusively
RagdollUtils.setTransform(link.bone, position, tmpRot1, false, boneList);
}
}
}
} else {
//the ragdoll does not have the controll, so the keyframed animation updates the physic position of the physic bonces
for (PhysicsBoneLink link : boneLinks.values()) {
Vector3f position = vars.vect1;
//if blended control this means, keyframed animation is updating the skeleton,
//but to allow smooth transition, we blend this transformation with the saved position of the ragdoll
if (blendedControl) {
Vector3f position2 = vars.vect2;
//initializing tmp vars with the start position/rotation of the ragdoll
position.set(link.startBlendingPos);
tmpRot1.set(link.startBlendingRot);
//interpolating between ragdoll position/rotation and keyframed position/rotation
tmpRot2.set(tmpRot1).nlerp(link.bone.getModelSpaceRotation(), blendStart / blendTime);
position2.set(position).interpolate(link.bone.getModelSpacePosition(), blendStart / blendTime);
tmpRot1.set(tmpRot2);
position.set(position2);
//updating bones transforms
if (boneList.isEmpty()) {
//we ensure we have the control to update the bone
link.bone.setUserControl(true);
link.bone.setUserTransformsWorld(position, tmpRot1);
//we give control back to the key framed animation.
link.bone.setUserControl(false);
} else {
RagdollUtils.setTransform(link.bone, position, tmpRot1, true, boneList);
}
}
//setting skeleton transforms to the ragdoll
matchPhysicObjectToBone(link, position, tmpRot1);
modelPosition.set(targetModel.getLocalTranslation());
}
//time control for blending
if (blendedControl) {
blendStart += tpf;
if (blendStart > blendTime) {
blendedControl = false;
}
}
}
assert vars.unlock();
}
| public void update(float tpf) {
if (!enabled) {
return;
}
TempVars vars = TempVars.get();
assert vars.lock();
Quaternion tmpRot1 = vars.quat1;
Quaternion tmpRot2 = vars.quat2;
//if the ragdoll has the control of the skeleton, we update each bone with its position in physic world space.
if (mode == mode.Ragdoll && targetModel.getLocalTranslation().equals(modelPosition)) {
for (PhysicsBoneLink link : boneLinks.values()) {
Vector3f position = vars.vect1;
//retrieving bone position in physic world space
Vector3f p = link.rigidBody.getMotionState().getWorldLocation();
//transforming this position with inverse transforms of the model
targetModel.getWorldTransform().transformInverseVector(p, position);
//retrieving bone rotation in physic world space
Quaternion q = link.rigidBody.getMotionState().getWorldRotationQuat();
//multiplying this rotation by the initialWorld rotation of the bone,
//then transforming it with the inverse world rotation of the model
tmpRot1.set(q).multLocal(link.initalWorldRotation);
tmpRot2.set(targetModel.getWorldRotation()).inverseLocal().mult(tmpRot1, tmpRot1);
tmpRot1.normalizeLocal();
//if the bone is the root bone, we apply the physic's transform to the model, so its position and rotation are correctly updated
if (link.bone.getParent() == null) {
//offsetting the physic's position/rotation by the root bone inverse model space position/rotaion
modelPosition.set(p).subtractLocal(link.bone.getWorldBindPosition());
targetModel.getParent().getWorldTransform().transformInverseVector(modelPosition, modelPosition);
modelRotation.set(q).multLocal(tmpRot2.set(link.bone.getWorldBindRotation()).inverseLocal());
//applying transforms to the model
targetModel.setLocalTranslation(modelPosition);
targetModel.setLocalRotation(modelRotation);
//Applying computed transforms to the bone
link.bone.setUserTransformsWorld(position, tmpRot1);
} else {
//if boneList is empty, this means that every bone in the ragdoll has a collision shape,
//so we just update the bone position
if (boneList.isEmpty()) {
link.bone.setUserTransformsWorld(position, tmpRot1);
} else {
//boneList is not empty, this means some bones of the skeleton might not be associated with a collision shape.
//So we update them recusively
RagdollUtils.setTransform(link.bone, position, tmpRot1, false, boneList);
}
}
}
} else {
//the ragdoll does not have the controll, so the keyframed animation updates the physic position of the physic bonces
for (PhysicsBoneLink link : boneLinks.values()) {
Vector3f position = vars.vect1;
//if blended control this means, keyframed animation is updating the skeleton,
//but to allow smooth transition, we blend this transformation with the saved position of the ragdoll
if (blendedControl) {
Vector3f position2 = vars.vect2;
//initializing tmp vars with the start position/rotation of the ragdoll
position.set(link.startBlendingPos);
tmpRot1.set(link.startBlendingRot);
//interpolating between ragdoll position/rotation and keyframed position/rotation
tmpRot2.set(tmpRot1).nlerp(link.bone.getModelSpaceRotation(), blendStart / blendTime);
position2.set(position).interpolate(link.bone.getModelSpacePosition(), blendStart / blendTime);
tmpRot1.set(tmpRot2);
position.set(position2);
//updating bones transforms
if (boneList.isEmpty()) {
//we ensure we have the control to update the bone
link.bone.setUserControl(true);
link.bone.setUserTransformsWorld(position, tmpRot1);
//we give control back to the key framed animation.
link.bone.setUserControl(false);
} else {
RagdollUtils.setTransform(link.bone, position, tmpRot1, true, boneList);
}
}
//setting skeleton transforms to the ragdoll
matchPhysicObjectToBone(link, position, tmpRot1);
modelPosition.set(targetModel.getLocalTranslation());
}
//time control for blending
if (blendedControl) {
blendStart += tpf;
if (blendStart > blendTime) {
blendedControl = false;
}
}
}
assert vars.unlock();
}
|
diff --git a/src/net/milkbowl/vault/economy/plugins/Economy_iConomy6.java b/src/net/milkbowl/vault/economy/plugins/Economy_iConomy6.java
index c6e8757..f17db6e 100644
--- a/src/net/milkbowl/vault/economy/plugins/Economy_iConomy6.java
+++ b/src/net/milkbowl/vault/economy/plugins/Economy_iConomy6.java
@@ -1,236 +1,239 @@
/* This file is part of Vault.
Vault 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.
Vault 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 Vault. If not, see <http://www.gnu.org/licenses/>.
*/
package net.milkbowl.vault.economy.plugins;
import java.util.List;
import java.util.logging.Logger;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import net.milkbowl.vault.economy.EconomyResponse.ResponseType;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.iCo6.Constants;
import com.iCo6.iConomy;
import com.iCo6.system.Accounts;
import com.iCo6.system.Holdings;
public class Economy_iConomy6 implements Economy {
private static final Logger log = Logger.getLogger("Minecraft");
private final String name = "iConomy 6";
private JavaPlugin plugin = null;
protected iConomy economy = null;
private Accounts accounts;
public Economy_iConomy6(JavaPlugin plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new EconomyServerListener(this), plugin);
+ log.severe("iConomy6 - If you are using Flatfile storage be aware that iCo6 has a CRITICAL bug which can wipe ALL iconomy data.");
+ log.severe("if you're using Votifier, or any other plugin which handles economy data in a threaded manner your server is at risk!");
+ log.severe("it is highly suggested to use SQL with iCo6 or to use an alternative economy plugin!");
// Load Plugin in case it was loaded before
if (economy == null) {
Plugin ec = plugin.getServer().getPluginManager().getPlugin("iConomy");
if (ec != null && ec.isEnabled() && ec.getClass().getName().equals("com.iCo6.iConomy")) {
economy = (iConomy) ec;
accounts = new Accounts();
log.info(String.format("[%s][Economy] %s hooked.", plugin.getDescription().getName(), name));
}
}
}
public class EconomyServerListener implements Listener {
Economy_iConomy6 economy = null;
public EconomyServerListener(Economy_iConomy6 economy) {
this.economy = economy;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginEnable(PluginEnableEvent event) {
if (economy.economy == null) {
Plugin ec = plugin.getServer().getPluginManager().getPlugin("iConomy");
if (ec != null && ec.isEnabled() && ec.getClass().getName().equals("com.iCo6.iConomy")) {
economy.economy = (iConomy) ec;
accounts = new Accounts();
log.info(String.format("[%s][Economy] %s hooked.", plugin.getDescription().getName(), economy.name));
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginDisable(PluginDisableEvent event) {
if (economy.economy != null) {
if (event.getPlugin().getDescription().getName().equals("iConomy")) {
economy.economy = null;
log.info(String.format("[%s][Economy] %s unhooked.", plugin.getDescription().getName(), economy.name));
}
}
}
}
@Override
public boolean isEnabled() {
if (economy == null) {
return false;
} else {
return economy.isEnabled();
}
}
@Override
public String getName() {
return name;
}
@Override
public String format(double amount) {
return iConomy.format(amount);
}
@Override
public String currencyNameSingular() {
return Constants.Nodes.Major.getStringList().get(0);
}
@Override
public String currencyNamePlural() {
return Constants.Nodes.Major.getStringList().get(1);
}
@Override
public double getBalance(String playerName) {
if (accounts.exists(playerName)) {
return accounts.get(playerName).getHoldings().getBalance();
} else {
return 0;
}
}
@Override
public EconomyResponse withdrawPlayer(String playerName, double amount) {
Holdings holdings = accounts.get(playerName).getHoldings();
if (holdings.hasEnough(amount)) {
holdings.subtract(amount);
return new EconomyResponse(amount, holdings.getBalance(), ResponseType.SUCCESS, null);
} else {
return new EconomyResponse(0, holdings.getBalance(), ResponseType.FAILURE, "Insufficient funds");
}
}
@Override
public EconomyResponse depositPlayer(String playerName, double amount) {
Holdings holdings = accounts.get(playerName).getHoldings();
holdings.add(amount);
return new EconomyResponse(amount, holdings.getBalance(), ResponseType.SUCCESS, null);
}
@Override
public boolean has(String playerName, double amount) {
return getBalance(playerName) >= amount;
}
@Override
public EconomyResponse createBank(String name, String player) {
if (accounts.exists(name)) {
return new EconomyResponse(0, accounts.get(name).getHoldings().getBalance(), ResponseType.FAILURE, "That account already exists.");
}
boolean created = accounts.create(name);
if (created) {
return new EconomyResponse(0, 0, ResponseType.SUCCESS, "");
} else {
return new EconomyResponse(0, 0, ResponseType.FAILURE, "There was an error creating the account");
}
}
@Override
public EconomyResponse deleteBank(String name) {
if (accounts.exists(name)) {
accounts.remove(name);
return new EconomyResponse(0, 0, ResponseType.SUCCESS, "");
}
return new EconomyResponse(0, 0, ResponseType.FAILURE, "That bank account does not exist.");
}
@Override
public EconomyResponse bankHas(String name, double amount) {
if (has(name, amount)) {
return new EconomyResponse(0, amount, ResponseType.SUCCESS, "");
} else {
return new EconomyResponse(0, accounts.get(name).getHoldings().getBalance(), ResponseType.FAILURE, "The account does not have enough!");
}
}
@Override
public EconomyResponse bankWithdraw(String name, double amount) {
return withdrawPlayer(name, amount);
}
@Override
public EconomyResponse bankDeposit(String name, double amount) {
return depositPlayer(name, amount);
}
@Override
public EconomyResponse isBankOwner(String name, String playerName) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "iConomy 6 does not support Bank owners.");
}
@Override
public EconomyResponse isBankMember(String name, String playerName) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "iConomy 6 does not support Bank members.");
}
@Override
public EconomyResponse bankBalance(String name) {
if (!accounts.exists(name)) {
return new EconomyResponse(0, 0, ResponseType.FAILURE, "There is no bank account with that name");
} else {
return new EconomyResponse(0, accounts.get(name).getHoldings().getBalance(), ResponseType.SUCCESS, null);
}
}
@Override
public List<String> getBanks() {
throw new UnsupportedOperationException("iConomy does not support listing of bank accounts");
}
@Override
public boolean hasBankSupport() {
return true;
}
@Override
public boolean hasAccount(String playerName) {
return accounts.exists(playerName);
}
@Override
public boolean createPlayerAccount(String playerName) {
if (hasAccount(playerName)) {
return false;
}
return accounts.create(playerName);
}
}
| true | true | public Economy_iConomy6(JavaPlugin plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new EconomyServerListener(this), plugin);
// Load Plugin in case it was loaded before
if (economy == null) {
Plugin ec = plugin.getServer().getPluginManager().getPlugin("iConomy");
if (ec != null && ec.isEnabled() && ec.getClass().getName().equals("com.iCo6.iConomy")) {
economy = (iConomy) ec;
accounts = new Accounts();
log.info(String.format("[%s][Economy] %s hooked.", plugin.getDescription().getName(), name));
}
}
}
| public Economy_iConomy6(JavaPlugin plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new EconomyServerListener(this), plugin);
log.severe("iConomy6 - If you are using Flatfile storage be aware that iCo6 has a CRITICAL bug which can wipe ALL iconomy data.");
log.severe("if you're using Votifier, or any other plugin which handles economy data in a threaded manner your server is at risk!");
log.severe("it is highly suggested to use SQL with iCo6 or to use an alternative economy plugin!");
// Load Plugin in case it was loaded before
if (economy == null) {
Plugin ec = plugin.getServer().getPluginManager().getPlugin("iConomy");
if (ec != null && ec.isEnabled() && ec.getClass().getName().equals("com.iCo6.iConomy")) {
economy = (iConomy) ec;
accounts = new Accounts();
log.info(String.format("[%s][Economy] %s hooked.", plugin.getDescription().getName(), name));
}
}
}
|
diff --git a/src/net/reichholf/dreamdroid/activities/ServiceListActivity.java b/src/net/reichholf/dreamdroid/activities/ServiceListActivity.java
index f19b0b11..3b3d5224 100644
--- a/src/net/reichholf/dreamdroid/activities/ServiceListActivity.java
+++ b/src/net/reichholf/dreamdroid/activities/ServiceListActivity.java
@@ -1,552 +1,552 @@
/* © 2010 Stephan Reichholf <stephan at reichholf dot net>
*
* Licensed under the Create-Commons Attribution-Noncommercial-Share Alike 3.0 Unported
* http://creativecommons.org/licenses/by-nc-sa/3.0/
*/
package net.reichholf.dreamdroid.activities;
import java.util.ArrayList;
import net.reichholf.dreamdroid.DreamDroid;
import net.reichholf.dreamdroid.R;
import net.reichholf.dreamdroid.abstivities.AbstractHttpEventListActivity;
import net.reichholf.dreamdroid.helpers.ExtendedHashMap;
import net.reichholf.dreamdroid.helpers.enigma2.Event;
import net.reichholf.dreamdroid.helpers.enigma2.Service;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
/**
* Handles ServiceLists of (based on service references).
*
* If called with Intent.ACTION_PICK it can be used for selecting services (e.g.
* to set a timer).<br/>
* In Pick-Mode no EPG will be loaded/shown.<br/>
* For any other action it will be a full-featured ServiceList Browser capable
* of showing EPG of running events or calling a
* <code>ServiceEpgListActivity</code> to show the whole EPG of a service
*
* @author sreichholf
*
*/
public class ServiceListActivity extends AbstractHttpEventListActivity {
public static final int MENU_OVERVIEW = 1;
public static final int MENU_SET_AS_DEFAULT = 2;
public static final int MENU_RELOAD = 3;
private String mReference;
private String mName;
private boolean mIsBouquetList;
private ArrayList<ExtendedHashMap> mHistory;
private boolean mPickMode;
private GetServiceListTask mListTask;
/**
* @author sreichholf Fetches a service list async. Does all the
* error-handling, refreshing and title-setting
*/
private class GetServiceListTask extends AsyncListUpdateTask {
public GetServiceListTask() {
super(getString(R.string.services));
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Boolean doInBackground(ArrayList<NameValuePair>... params) {
mTaskList = new ArrayList<ExtendedHashMap>();
publishProgress(mBaseTitle + " - " + getText(R.string.fetching_data));
String xml;
if (!mIsBouquetList && !mPickMode) {
xml = Service.getEpgBouquetList(mShc, params);
} else {
xml = Service.getList(mShc, params);
}
if (xml != null) {
publishProgress(mBaseTitle + " - " + getText(R.string.parsing));
boolean result = false;
if (!mIsBouquetList && !mPickMode) {
result = Service.parseEpgBouquetList(xml, mTaskList);
} else {
result = Service.parseList(xml, mTaskList);
}
return result;
}
return false;
}
}
/*
* (non-Javadoc)
*
* @see
* net.reichholf.dreamdroid.activities.AbstractHttpListActivity#onCreate
* (android.os.Bundle)
*/
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String mode = getIntent().getAction();
if (mode.equals(Intent.ACTION_PICK)) {
mPickMode = true;
} else {
mPickMode = false;
}
String ref = DreamDroid.SP.getString(DreamDroid.PREFS_KEY_DEFAULT_BOUQUET_REF, "default");
String name = DreamDroid.SP.getString(DreamDroid.PREFS_KEY_DEFAULT_BOUQUET_NAME,
(String) getText(R.string.bouquet_overview));
mReference = getDataForKey(Event.SERVICE_REFERENCE, ref);
mName = getDataForKey(Event.SERVICE_NAME, name);
if (savedInstanceState != null) {
mIsBouquetList = savedInstanceState.getBoolean("isBouquetList", true);
mHistory = (ArrayList<ExtendedHashMap>) savedInstanceState.getSerializable("history");
} else {
mIsBouquetList = DreamDroid.SP.getBoolean(DreamDroid.PREFS_KEY_DEFAULT_BOUQUET_IS_LIST, true);
mHistory = new ArrayList<ExtendedHashMap>();
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, mReference);
map.put(Event.SERVICE_NAME, mName);
mHistory.add(map);
}
setAdapter();
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> a, View v, int position, long id) {
return onListItemLongClick(a, v, position, id);
}
});
reload();
}
/*
* (non-Javadoc)
*
* @see net.reichholf.dreamdroid.abstivities.AbstractHttpListActivity#
* onSaveInstanceState(android.os.Bundle)
*/
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("history", mHistory);
outState.putBoolean("isBouquetList", mIsBouquetList);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPause()
*/
@Override
public void onPause() {
if (mListTask != null) {
mListTask.cancel(true);
}
super.onPause();
}
/*
* (non-Javadoc)
*
* @see
* net.reichholf.dreamdroid.abstivities.AbstractHttpListActivity#generateTitle
* ()
*/
@Override
protected String genWindowTitle(String title) {
return title + " - " + mName;
}
/**
*
*/
private void setAdapter() {
mAdapter = new SimpleAdapter(this, mMapList, R.layout.service_list_item, new String[] { Event.SERVICE_NAME,
Event.EVENT_TITLE, Event.EVENT_START_TIME_READABLE, Event.EVENT_DURATION_READABLE }, new int[] {
R.id.service_name, R.id.event_title, R.id.event_start, R.id.event_duration });
setListAdapter(mAdapter);
}
/**
* @return
*/
private boolean isListTaskRunning() {
if (mListTask != null) {
if (mListTask.getStatus().equals(AsyncTask.Status.RUNNING)) {
return true;
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see
* net.reichholf.dreamdroid.activities.AbstractHttpListActivity#onKeyDown
* (int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// back to standard back-button-behaviour when we're already at root
// level
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (!"default".equals(mReference)) {
int idx = mHistory.size() - 1;
if (idx >= 0) {
ExtendedHashMap map = null;
try {
map = (mHistory.get(idx));
} catch (ClassCastException ex) {
return super.onKeyDown(keyCode, event);
}
if (map != null) {
String oldref = map.getString(Event.SERVICE_REFERENCE);
String oldname = map.getString(Event.SERVICE_NAME);
if (!mReference.equals(oldref) && oldref != null) {
// there is a download Task running, the list may
// have already been altered so we let that request finish
if (!isListTaskRunning()) {
mReference = oldref;
mName = oldname;
mHistory.remove(idx);
if (isBouquetReference(mReference)) {
mIsBouquetList = true;
}
reload();
} else {
showToast(getText(R.string.wait_request_finished));
}
return true;
}
}
}
}
}
return super.onKeyDown(keyCode, event);
}
/*
* (non-Javadoc)
*
* @see android.app.ListActivity#onListItemClick(android.widget.ListView,
* android.view.View, int, long)
*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
onListItemClick(v, position, id, false);
}
/**
* @param a
* @param v
* @param position
* @param id
* @return
*/
protected boolean onListItemLongClick(AdapterView<?> a, View v, int position, long id) {
onListItemClick(v, position, id, true);
return true;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_SET_AS_DEFAULT, 0, getText(R.string.set_default)).setIcon(android.R.drawable.ic_menu_set_as);
menu.add(0, MENU_RELOAD, 0, getText(R.string.reload)).setIcon(android.R.drawable.ic_menu_rotate);
menu.add(0, MENU_OVERVIEW, 0, getText(R.string.bouquet_overview)).setIcon(R.drawable.ic_menu_list_overview);
return true;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem overview = menu.getItem(2);
if (mReference.equals("default")) {
overview.setEnabled(false);
} else {
overview.setEnabled(true);
}
MenuItem reload = menu.getItem(1);
if (!mIsBouquetList && !mPickMode) {
reload.setEnabled(true);
} else {
reload.setEnabled(false);
}
return true;
}
/*
* (non-Javadoc)
*
* @see
* net.reichholf.dreamdroid.abstivities.AbstractHttpListActivity#onItemClicked
* (int)
*/
@Override
protected boolean onItemClicked(int id) {
switch (id) {
case MENU_OVERVIEW:
mReference = "default";
mName = (String) getText(R.string.bouquet_overview);
reload();
return true;
case MENU_SET_AS_DEFAULT:
Editor editor = DreamDroid.SP.edit();
editor.putString(DreamDroid.PREFS_KEY_DEFAULT_BOUQUET_REF, mReference);
editor.putString(DreamDroid.PREFS_KEY_DEFAULT_BOUQUET_NAME, mName);
editor.putBoolean(DreamDroid.PREFS_KEY_DEFAULT_BOUQUET_IS_LIST, mIsBouquetList);
if (editor.commit()) {
showToast(getText(R.string.default_bouquet_set_to) + " '" + mName + "'");
} else {
showToast(getText(R.string.default_bouquet_not_set));
}
return true;
case MENU_RELOAD:
reload();
return true;
default:
return super.onItemClicked(id);
}
}
/**
* @param ref
* @return
*/
private boolean isBouquetReference(String ref) {
if (ref.startsWith("1:7:")) {
return true;
}
return false;
}
/**
* @param ref
* The ServiceReference to catch the EPG for
* @param nam
* The name of the Service for the reference
*/
public void openEpg(String ref, String nam) {
Intent intent = new Intent(this, ServiceEpgListActivity.class);
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, ref);
map.put(Event.SERVICE_NAME, nam);
intent.putExtra(sData, map);
startActivity(intent);
}
/**
* @param ref
* A ServiceReference
*/
private void streamService(String ref) {
Intent intent = new Intent(Intent.ACTION_VIEW);
String uriString = "http://" + DreamDroid.PROFILE.getStreamHost().trim() + ":8001/" + ref;
Log.i(DreamDroid.LOG_TAG, "Streaming URL set to '" + uriString + "'");
intent.setDataAndType(Uri.parse(uriString), "video/*");
startActivity(intent);
}
private void onListItemClick(View v, int position, long id, boolean isLong) {
mCurrentItem = mMapList.get(position);
final String ref = mCurrentItem.getString(Event.SERVICE_REFERENCE);
final String nam = mCurrentItem.getString(Event.SERVICE_NAME);
if (isBouquetReference(ref)) {
if (!isListTaskRunning()) {
mIsBouquetList = true;
// Second hierarchy level -> we get a List of Services now
if (isBouquetReference(mReference)) {
mIsBouquetList = false;
}
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, String.valueOf(mReference));
map.put(Event.SERVICE_NAME, String.valueOf(mName));
mHistory.add(map);
mReference = ref;
mName = nam;
reload();
} else {
showToast(getText(R.string.wait_request_finished));
}
} else {
if (mPickMode) {
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, ref);
map.put(Event.SERVICE_NAME, nam);
Intent intent = new Intent();
intent.putExtra(sData, map);
setResult(RESULT_OK, intent);
finish();
} else {
boolean isInsta = DreamDroid.SP.getBoolean("instant_zap", false);
if ((isInsta && !isLong) || (!isInsta && isLong)) {
zapTo(ref);
} else {
CharSequence[] actions = {
getText(R.string.current_event),
getText(R.string.browse_epg),
getText(R.string.zap),
getText(R.string.stream) };
AlertDialog.Builder adBuilder = new AlertDialog.Builder(this);
adBuilder.setTitle(getText(R.string.pick_action));
adBuilder.setItems(actions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
removeDialog(DIALOG_EPG_ITEM_ID);
showDialog(DIALOG_EPG_ITEM_ID);
break;
case 1:
openEpg(ref, nam);
break;
case 2:
zapTo(ref);
break;
- case 4:
+ case 3:
streamService(ref);
break;
}
}
});
AlertDialog alert = adBuilder.create();
alert.show();
}
}
}
}
/**
*
*/
@SuppressWarnings("unchecked")
public void reload() {
if (mListTask != null) {
mListTask.cancel(true);
}
ExtendedHashMap data = new ExtendedHashMap();
data.put(Event.SERVICE_REFERENCE, String.valueOf(mReference));
data.put(Event.SERVICE_NAME, String.valueOf(mName));
mExtras.putSerializable(sData, data);
if (mReference.equals("default")) {
loadDefault();
return;
}
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
if (!mIsBouquetList && !mPickMode) {
params.add(new BasicNameValuePair("bRef", mReference));
} else {
params.add(new BasicNameValuePair("sRef", mReference));
}
mListTask = new GetServiceListTask();
mListTask.execute(params);
}
/**
*
*/
public void loadDefault() {
String title = getText(R.string.app_name) + "::" + getText(R.string.services);
setTitle(title);
mIsBouquetList = true;
mMapList.clear();
String[] servicelist = getResources().getStringArray(R.array.servicelist);
String[] servicerefs = getResources().getStringArray(R.array.servicerefs);
for (int i = 0; i < servicelist.length; i++) {
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_NAME, servicelist[i]);
map.put(Event.SERVICE_REFERENCE, servicerefs[i]);
mMapList.add(map);
}
mAdapter.notifyDataSetChanged();
}
}
| true | true | private void onListItemClick(View v, int position, long id, boolean isLong) {
mCurrentItem = mMapList.get(position);
final String ref = mCurrentItem.getString(Event.SERVICE_REFERENCE);
final String nam = mCurrentItem.getString(Event.SERVICE_NAME);
if (isBouquetReference(ref)) {
if (!isListTaskRunning()) {
mIsBouquetList = true;
// Second hierarchy level -> we get a List of Services now
if (isBouquetReference(mReference)) {
mIsBouquetList = false;
}
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, String.valueOf(mReference));
map.put(Event.SERVICE_NAME, String.valueOf(mName));
mHistory.add(map);
mReference = ref;
mName = nam;
reload();
} else {
showToast(getText(R.string.wait_request_finished));
}
} else {
if (mPickMode) {
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, ref);
map.put(Event.SERVICE_NAME, nam);
Intent intent = new Intent();
intent.putExtra(sData, map);
setResult(RESULT_OK, intent);
finish();
} else {
boolean isInsta = DreamDroid.SP.getBoolean("instant_zap", false);
if ((isInsta && !isLong) || (!isInsta && isLong)) {
zapTo(ref);
} else {
CharSequence[] actions = {
getText(R.string.current_event),
getText(R.string.browse_epg),
getText(R.string.zap),
getText(R.string.stream) };
AlertDialog.Builder adBuilder = new AlertDialog.Builder(this);
adBuilder.setTitle(getText(R.string.pick_action));
adBuilder.setItems(actions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
removeDialog(DIALOG_EPG_ITEM_ID);
showDialog(DIALOG_EPG_ITEM_ID);
break;
case 1:
openEpg(ref, nam);
break;
case 2:
zapTo(ref);
break;
case 4:
streamService(ref);
break;
}
}
});
AlertDialog alert = adBuilder.create();
alert.show();
}
}
}
}
| private void onListItemClick(View v, int position, long id, boolean isLong) {
mCurrentItem = mMapList.get(position);
final String ref = mCurrentItem.getString(Event.SERVICE_REFERENCE);
final String nam = mCurrentItem.getString(Event.SERVICE_NAME);
if (isBouquetReference(ref)) {
if (!isListTaskRunning()) {
mIsBouquetList = true;
// Second hierarchy level -> we get a List of Services now
if (isBouquetReference(mReference)) {
mIsBouquetList = false;
}
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, String.valueOf(mReference));
map.put(Event.SERVICE_NAME, String.valueOf(mName));
mHistory.add(map);
mReference = ref;
mName = nam;
reload();
} else {
showToast(getText(R.string.wait_request_finished));
}
} else {
if (mPickMode) {
ExtendedHashMap map = new ExtendedHashMap();
map.put(Event.SERVICE_REFERENCE, ref);
map.put(Event.SERVICE_NAME, nam);
Intent intent = new Intent();
intent.putExtra(sData, map);
setResult(RESULT_OK, intent);
finish();
} else {
boolean isInsta = DreamDroid.SP.getBoolean("instant_zap", false);
if ((isInsta && !isLong) || (!isInsta && isLong)) {
zapTo(ref);
} else {
CharSequence[] actions = {
getText(R.string.current_event),
getText(R.string.browse_epg),
getText(R.string.zap),
getText(R.string.stream) };
AlertDialog.Builder adBuilder = new AlertDialog.Builder(this);
adBuilder.setTitle(getText(R.string.pick_action));
adBuilder.setItems(actions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
removeDialog(DIALOG_EPG_ITEM_ID);
showDialog(DIALOG_EPG_ITEM_ID);
break;
case 1:
openEpg(ref, nam);
break;
case 2:
zapTo(ref);
break;
case 3:
streamService(ref);
break;
}
}
});
AlertDialog alert = adBuilder.create();
alert.show();
}
}
}
}
|
diff --git a/xjc/src/com/sun/tools/jxc/apt/SchemaGenerator.java b/xjc/src/com/sun/tools/jxc/apt/SchemaGenerator.java
index 90031ed5..d8ab202b 100644
--- a/xjc/src/com/sun/tools/jxc/apt/SchemaGenerator.java
+++ b/xjc/src/com/sun/tools/jxc/apt/SchemaGenerator.java
@@ -1,98 +1,100 @@
package com.sun.tools.jxc.apt;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.apt.AnnotationProcessorFactory;
import com.sun.mirror.apt.Filer;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;
import com.sun.tools.xjc.api.J2SJAXBModel;
import com.sun.tools.xjc.api.Reference;
import com.sun.tools.xjc.api.XJC;
import com.sun.xml.bind.api.SchemaOutputResolver;
/**
* {@link AnnotationProcessorFactory} that implements the schema generator
* command line tool.
*
* @author Kohsuke Kawaguchi
*/
public class SchemaGenerator implements AnnotationProcessorFactory {
/**
* User-specified schema locations, if any.
*/
private final Map<String,File> schemaLocations = new HashMap<String, File>();
public SchemaGenerator() {
}
public SchemaGenerator( Map<String,File> m ) {
schemaLocations.putAll(m);
}
public Collection<String> supportedOptions() {
return Collections.emptyList();
}
public Collection<String> supportedAnnotationTypes() {
return Arrays.asList("*");
}
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds, final AnnotationProcessorEnvironment env) {
return new AnnotationProcessor() {
final ErrorReceiverImpl errorListener = new ErrorReceiverImpl(env);
public void process() {
List<Reference> decls = new ArrayList<Reference>();
for(TypeDeclaration d : env.getTypeDeclarations())
decls.add(new Reference(d,env));
J2SJAXBModel model = XJC.createJavaCompiler().bind(decls,Collections.<QName,Reference>emptyMap(),null,env);
+ if(model==null)
+ return; // error
try {
model.generateSchema(
new SchemaOutputResolver() {
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
File file;
OutputStream out;
if(schemaLocations.containsKey(namespaceUri)) {
file = schemaLocations.get(namespaceUri);
if(file==null) return null; // don't generate
out = new FileOutputStream(file);
} else {
// use the default
file = new File(suggestedFileName);
out = env.getFiler().createBinaryFile(Filer.Location.CLASS_TREE,"",file);
}
StreamResult ss = new StreamResult(out);
env.getMessager().printNotice("Writing "+file);
ss.setSystemId(file.getPath());
return ss;
}
}, errorListener);
} catch (IOException e) {
errorListener.error(e.getMessage(),e);
}
}
};
}
}
| true | true | public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds, final AnnotationProcessorEnvironment env) {
return new AnnotationProcessor() {
final ErrorReceiverImpl errorListener = new ErrorReceiverImpl(env);
public void process() {
List<Reference> decls = new ArrayList<Reference>();
for(TypeDeclaration d : env.getTypeDeclarations())
decls.add(new Reference(d,env));
J2SJAXBModel model = XJC.createJavaCompiler().bind(decls,Collections.<QName,Reference>emptyMap(),null,env);
try {
model.generateSchema(
new SchemaOutputResolver() {
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
File file;
OutputStream out;
if(schemaLocations.containsKey(namespaceUri)) {
file = schemaLocations.get(namespaceUri);
if(file==null) return null; // don't generate
out = new FileOutputStream(file);
} else {
// use the default
file = new File(suggestedFileName);
out = env.getFiler().createBinaryFile(Filer.Location.CLASS_TREE,"",file);
}
StreamResult ss = new StreamResult(out);
env.getMessager().printNotice("Writing "+file);
ss.setSystemId(file.getPath());
return ss;
}
}, errorListener);
} catch (IOException e) {
errorListener.error(e.getMessage(),e);
}
}
};
}
| public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds, final AnnotationProcessorEnvironment env) {
return new AnnotationProcessor() {
final ErrorReceiverImpl errorListener = new ErrorReceiverImpl(env);
public void process() {
List<Reference> decls = new ArrayList<Reference>();
for(TypeDeclaration d : env.getTypeDeclarations())
decls.add(new Reference(d,env));
J2SJAXBModel model = XJC.createJavaCompiler().bind(decls,Collections.<QName,Reference>emptyMap(),null,env);
if(model==null)
return; // error
try {
model.generateSchema(
new SchemaOutputResolver() {
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
File file;
OutputStream out;
if(schemaLocations.containsKey(namespaceUri)) {
file = schemaLocations.get(namespaceUri);
if(file==null) return null; // don't generate
out = new FileOutputStream(file);
} else {
// use the default
file = new File(suggestedFileName);
out = env.getFiler().createBinaryFile(Filer.Location.CLASS_TREE,"",file);
}
StreamResult ss = new StreamResult(out);
env.getMessager().printNotice("Writing "+file);
ss.setSystemId(file.getPath());
return ss;
}
}, errorListener);
} catch (IOException e) {
errorListener.error(e.getMessage(),e);
}
}
};
}
|
diff --git a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java
index fcfe22164..6e8efcd81 100644
--- a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java
+++ b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java
@@ -1,236 +1,234 @@
/*
* Copyright 2002-2013 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.springframework.cache.ehcache;
import junit.framework.TestCase;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.constructs.blocking.BlockingCache;
import net.sf.ehcache.constructs.blocking.CacheEntryFactory;
import net.sf.ehcache.constructs.blocking.SelfPopulatingCache;
import net.sf.ehcache.constructs.blocking.UpdatingCacheEntryFactory;
import net.sf.ehcache.constructs.blocking.UpdatingSelfPopulatingCache;
import org.springframework.core.io.ClassPathResource;
/**
* @author Dmitriy Kopylenko
* @author Juergen Hoeller
* @since 27.09.2004
*/
public class EhCacheSupportTests extends TestCase {
public void testLoadingBlankCacheManager() throws Exception {
EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.setCacheManagerName("myCacheManager");
assertEquals(CacheManager.class, cacheManagerFb.getObjectType());
assertTrue("Singleton property", cacheManagerFb.isSingleton());
cacheManagerFb.afterPropertiesSet();
try {
CacheManager cm = cacheManagerFb.getObject();
assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0);
Cache myCache1 = cm.getCache("myCache1");
assertTrue("No myCache1 defined", myCache1 == null);
}
finally {
cacheManagerFb.destroy();
}
}
public void testLoadingCacheManagerFromConfigFile() throws Exception {
EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass()));
cacheManagerFb.setCacheManagerName("myCacheManager");
cacheManagerFb.afterPropertiesSet();
try {
CacheManager cm = cacheManagerFb.getObject();
assertTrue("Correct number of caches loaded", cm.getCacheNames().length == 1);
Cache myCache1 = cm.getCache("myCache1");
assertFalse("myCache1 is not eternal", myCache1.getCacheConfiguration().isEternal());
assertTrue("myCache1.maxElements == 300", myCache1.getCacheConfiguration().getMaxElementsInMemory() == 300);
}
finally {
cacheManagerFb.destroy();
}
}
public void testEhCacheFactoryBeanWithDefaultCacheManager() throws Exception {
doTestEhCacheFactoryBean(false);
}
public void testEhCacheFactoryBeanWithExplicitCacheManager() throws Exception {
doTestEhCacheFactoryBean(true);
}
private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exception {
Cache cache = null;
EhCacheManagerFactoryBean cacheManagerFb = null;
try {
EhCacheFactoryBean cacheFb = new EhCacheFactoryBean();
Class<? extends Ehcache> objectType = cacheFb.getObjectType();
assertTrue(Ehcache.class.isAssignableFrom(objectType));
assertTrue("Singleton property", cacheFb.isSingleton());
if (useCacheManagerFb) {
cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass()));
cacheManagerFb.afterPropertiesSet();
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setCacheName("myCache1");
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
Class<? extends Ehcache> objectType2 = cacheFb.getObjectType();
assertSame(objectType, objectType2);
CacheConfiguration config = cache.getCacheConfiguration();
assertEquals("myCache1", cache.getName());
if (useCacheManagerFb){
assertEquals("myCache1.maxElements", 300, config.getMaxElementsInMemory());
}
else {
assertEquals("myCache1.maxElements", 10000, config.getMaxElementsInMemory());
}
// Cache region is not defined. Should create one with default properties.
cacheFb = new EhCacheFactoryBean();
if (useCacheManagerFb) {
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setCacheName("undefinedCache");
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
config = cache.getCacheConfiguration();
assertEquals("undefinedCache", cache.getName());
assertTrue("default maxElements is correct", config.getMaxElementsInMemory() == 10000);
assertTrue("default overflowToDisk is correct", config.isOverflowToDisk());
assertFalse("default eternal is correct", config.isEternal());
assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 120);
assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 120);
assertTrue("default diskPersistent is correct", !config.isDiskPersistent());
assertTrue("default diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 120);
// overriding the default properties
cacheFb = new EhCacheFactoryBean();
if (useCacheManagerFb) {
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setBeanName("undefinedCache2");
cacheFb.setMaxElementsInMemory(5);
cacheFb.setOverflowToDisk(false);
- cacheFb.setEternal(true);
cacheFb.setTimeToLive(8);
cacheFb.setTimeToIdle(7);
cacheFb.setDiskPersistent(true);
cacheFb.setDiskExpiryThreadIntervalSeconds(10);
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
config = cache.getCacheConfiguration();
assertEquals("undefinedCache2", cache.getName());
assertTrue("overridden maxElements is correct", config.getMaxElementsInMemory() == 5);
assertFalse("overridden overflowToDisk is correct", config.isOverflowToDisk());
- assertTrue("overridden eternal is correct", config.isEternal());
assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 8);
assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 7);
assertTrue("overridden diskPersistent is correct", config.isDiskPersistent());
assertTrue("overridden diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 10);
}
finally {
if (useCacheManagerFb && cacheManagerFb != null) {
cacheManagerFb.destroy();
}
else {
CacheManager.getInstance().shutdown();
}
}
}
public void testEhCacheFactoryBeanWithBlockingCache() throws Exception {
EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.afterPropertiesSet();
try {
CacheManager cm = cacheManagerFb.getObject();
EhCacheFactoryBean cacheFb = new EhCacheFactoryBean();
cacheFb.setCacheManager(cm);
cacheFb.setCacheName("myCache1");
cacheFb.setBlocking(true);
assertEquals(cacheFb.getObjectType(), BlockingCache.class);
cacheFb.afterPropertiesSet();
Ehcache myCache1 = cm.getEhcache("myCache1");
assertTrue(myCache1 instanceof BlockingCache);
}
finally {
cacheManagerFb.destroy();
}
}
public void testEhCacheFactoryBeanWithSelfPopulatingCache() throws Exception {
EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.afterPropertiesSet();
try {
CacheManager cm = cacheManagerFb.getObject();
EhCacheFactoryBean cacheFb = new EhCacheFactoryBean();
cacheFb.setCacheManager(cm);
cacheFb.setCacheName("myCache1");
cacheFb.setCacheEntryFactory(new CacheEntryFactory() {
@Override
public Object createEntry(Object key) throws Exception {
return key;
}
});
assertEquals(cacheFb.getObjectType(), SelfPopulatingCache.class);
cacheFb.afterPropertiesSet();
Ehcache myCache1 = cm.getEhcache("myCache1");
assertTrue(myCache1 instanceof SelfPopulatingCache);
assertEquals("myKey1", myCache1.get("myKey1").getValue());
}
finally {
cacheManagerFb.destroy();
}
}
public void testEhCacheFactoryBeanWithUpdatingSelfPopulatingCache() throws Exception {
EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.afterPropertiesSet();
try {
CacheManager cm = cacheManagerFb.getObject();
EhCacheFactoryBean cacheFb = new EhCacheFactoryBean();
cacheFb.setCacheManager(cm);
cacheFb.setCacheName("myCache1");
cacheFb.setCacheEntryFactory(new UpdatingCacheEntryFactory() {
@Override
public Object createEntry(Object key) throws Exception {
return key;
}
@Override
public void updateEntryValue(Object key, Object value) throws Exception {
}
});
assertEquals(cacheFb.getObjectType(), UpdatingSelfPopulatingCache.class);
cacheFb.afterPropertiesSet();
Ehcache myCache1 = cm.getEhcache("myCache1");
assertTrue(myCache1 instanceof UpdatingSelfPopulatingCache);
assertEquals("myKey1", myCache1.get("myKey1").getValue());
}
finally {
cacheManagerFb.destroy();
}
}
}
| false | true | private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exception {
Cache cache = null;
EhCacheManagerFactoryBean cacheManagerFb = null;
try {
EhCacheFactoryBean cacheFb = new EhCacheFactoryBean();
Class<? extends Ehcache> objectType = cacheFb.getObjectType();
assertTrue(Ehcache.class.isAssignableFrom(objectType));
assertTrue("Singleton property", cacheFb.isSingleton());
if (useCacheManagerFb) {
cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass()));
cacheManagerFb.afterPropertiesSet();
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setCacheName("myCache1");
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
Class<? extends Ehcache> objectType2 = cacheFb.getObjectType();
assertSame(objectType, objectType2);
CacheConfiguration config = cache.getCacheConfiguration();
assertEquals("myCache1", cache.getName());
if (useCacheManagerFb){
assertEquals("myCache1.maxElements", 300, config.getMaxElementsInMemory());
}
else {
assertEquals("myCache1.maxElements", 10000, config.getMaxElementsInMemory());
}
// Cache region is not defined. Should create one with default properties.
cacheFb = new EhCacheFactoryBean();
if (useCacheManagerFb) {
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setCacheName("undefinedCache");
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
config = cache.getCacheConfiguration();
assertEquals("undefinedCache", cache.getName());
assertTrue("default maxElements is correct", config.getMaxElementsInMemory() == 10000);
assertTrue("default overflowToDisk is correct", config.isOverflowToDisk());
assertFalse("default eternal is correct", config.isEternal());
assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 120);
assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 120);
assertTrue("default diskPersistent is correct", !config.isDiskPersistent());
assertTrue("default diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 120);
// overriding the default properties
cacheFb = new EhCacheFactoryBean();
if (useCacheManagerFb) {
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setBeanName("undefinedCache2");
cacheFb.setMaxElementsInMemory(5);
cacheFb.setOverflowToDisk(false);
cacheFb.setEternal(true);
cacheFb.setTimeToLive(8);
cacheFb.setTimeToIdle(7);
cacheFb.setDiskPersistent(true);
cacheFb.setDiskExpiryThreadIntervalSeconds(10);
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
config = cache.getCacheConfiguration();
assertEquals("undefinedCache2", cache.getName());
assertTrue("overridden maxElements is correct", config.getMaxElementsInMemory() == 5);
assertFalse("overridden overflowToDisk is correct", config.isOverflowToDisk());
assertTrue("overridden eternal is correct", config.isEternal());
assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 8);
assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 7);
assertTrue("overridden diskPersistent is correct", config.isDiskPersistent());
assertTrue("overridden diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 10);
}
finally {
if (useCacheManagerFb && cacheManagerFb != null) {
cacheManagerFb.destroy();
}
else {
CacheManager.getInstance().shutdown();
}
}
}
| private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exception {
Cache cache = null;
EhCacheManagerFactoryBean cacheManagerFb = null;
try {
EhCacheFactoryBean cacheFb = new EhCacheFactoryBean();
Class<? extends Ehcache> objectType = cacheFb.getObjectType();
assertTrue(Ehcache.class.isAssignableFrom(objectType));
assertTrue("Singleton property", cacheFb.isSingleton());
if (useCacheManagerFb) {
cacheManagerFb = new EhCacheManagerFactoryBean();
cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass()));
cacheManagerFb.afterPropertiesSet();
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setCacheName("myCache1");
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
Class<? extends Ehcache> objectType2 = cacheFb.getObjectType();
assertSame(objectType, objectType2);
CacheConfiguration config = cache.getCacheConfiguration();
assertEquals("myCache1", cache.getName());
if (useCacheManagerFb){
assertEquals("myCache1.maxElements", 300, config.getMaxElementsInMemory());
}
else {
assertEquals("myCache1.maxElements", 10000, config.getMaxElementsInMemory());
}
// Cache region is not defined. Should create one with default properties.
cacheFb = new EhCacheFactoryBean();
if (useCacheManagerFb) {
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setCacheName("undefinedCache");
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
config = cache.getCacheConfiguration();
assertEquals("undefinedCache", cache.getName());
assertTrue("default maxElements is correct", config.getMaxElementsInMemory() == 10000);
assertTrue("default overflowToDisk is correct", config.isOverflowToDisk());
assertFalse("default eternal is correct", config.isEternal());
assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 120);
assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 120);
assertTrue("default diskPersistent is correct", !config.isDiskPersistent());
assertTrue("default diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 120);
// overriding the default properties
cacheFb = new EhCacheFactoryBean();
if (useCacheManagerFb) {
cacheFb.setCacheManager(cacheManagerFb.getObject());
}
cacheFb.setBeanName("undefinedCache2");
cacheFb.setMaxElementsInMemory(5);
cacheFb.setOverflowToDisk(false);
cacheFb.setTimeToLive(8);
cacheFb.setTimeToIdle(7);
cacheFb.setDiskPersistent(true);
cacheFb.setDiskExpiryThreadIntervalSeconds(10);
cacheFb.afterPropertiesSet();
cache = (Cache) cacheFb.getObject();
config = cache.getCacheConfiguration();
assertEquals("undefinedCache2", cache.getName());
assertTrue("overridden maxElements is correct", config.getMaxElementsInMemory() == 5);
assertFalse("overridden overflowToDisk is correct", config.isOverflowToDisk());
assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 8);
assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 7);
assertTrue("overridden diskPersistent is correct", config.isDiskPersistent());
assertTrue("overridden diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 10);
}
finally {
if (useCacheManagerFb && cacheManagerFb != null) {
cacheManagerFb.destroy();
}
else {
CacheManager.getInstance().shutdown();
}
}
}
|
diff --git a/src/states/ForestState.java b/src/states/ForestState.java
index 4b76664..e8b7f0b 100644
--- a/src/states/ForestState.java
+++ b/src/states/ForestState.java
@@ -1,110 +1,110 @@
package states;
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Music;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.tiled.TiledMap;
import core.MainGame;
import dudes.GoblinArcher;
import dudes.Knight;
import dudes.Monster;
public class ForestState extends AreaState {
public ForestState(int stateID) {
super(stateID);
}
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
super.init(container, game);
loop = new Music("Assets/Sound/Loops/ForestState.wav");
bgImage = new TiledMap("Assets/World/woodsmap1.tmx");
areaLength = 200;
// SpiderWeb sw1 = new SpiderWeb(new float[] {container.getWidth()-200f, container.getHeight()-200f});
// SpiderWeb sw2 = new SpiderWeb(new float[] {container.getWidth()-300f, container.getHeight()-150f});
//
// obstacles.add(sw1);
// obstacles.add(sw2);
ArrayList<Monster> group_1 = new ArrayList<Monster>();
GoblinArcher g1_knight1 = new GoblinArcher(container.getWidth(),
container.getHeight() - 80, 1, container);
GoblinArcher g1_knight2 = new GoblinArcher(container.getWidth(),
container.getHeight() - 160, 1, container);
//GoblinArcher g1_knight3 = new GoblinArcher(container.getWidth(),
// container.getHeight() - 240, 1);
g1_knight1.init();
g1_knight2.init();
//g1_knight3.init();
group_1.add(g1_knight1);
group_1.add(g1_knight2);
//group_1.add(g1_knight3);
ArrayList<Monster> group_2 = new ArrayList<Monster>();
Knight g2_knight1 = new Knight(container.getWidth(),
container.getHeight() - 80, 1, container);
Knight g2_knight2 = new Knight(container.getWidth(),
container.getHeight() - 160, 1, container);
Knight g2_knight3 = new Knight(container.getWidth(),
container.getHeight() - 240, 1, container);
g2_knight1.init();
g2_knight2.init();
g2_knight3.init();
group_2.add(g2_knight1);
group_2.add(g2_knight2);
group_2.add(g2_knight3);
ArrayList<Monster> group_3 = new ArrayList<Monster>();
Knight g3_knight1 = new Knight(0,
container.getHeight() - 80, 1, container);
GoblinArcher g3_knight2 = new GoblinArcher(0,
container.getHeight() - 160, 1, container);
Knight g3_knight3 = new Knight(container.getWidth(),
- container.getHeight() - 240, 1, container);
+ container.getHeight() - 200, 1, container);
GoblinArcher g3_knight4 = new GoblinArcher(container.getWidth(),
container.getHeight() - 240, 1, container);
g3_knight1.init();
g3_knight2.init();
g3_knight3.init();
g3_knight4.init();
group_3.add(g3_knight1);
group_3.add(g3_knight2);
group_3.add(g3_knight3);
group_3.add(g3_knight4);
monsters.add(group_1);
monsters.add(group_2);
monsters.add(group_3);
battleStops = new int[3];
battleStops[0] = 1000;
battleStops[1] = 2000;
battleStops[2] = 3000;
}
/*@Override
public ArrayList<Weapon> makeInitItems() throws SlickException {
ArrayList<Weapon> o = new ArrayList<Weapon>();
Weapon k1 = new Sword(1200f, MainGame.GAME_HEIGHT - 100);
Weapon k2 = new Bear(1300f, MainGame.GAME_HEIGHT - 100);
k1.createGroundSprite();
k2.createGroundSprite();
o.add(k1);
o.add(k2);
return o;
}*/
@Override
public int getID(){
return 3;
}
}
| true | true | public void init(GameContainer container, StateBasedGame game)
throws SlickException {
super.init(container, game);
loop = new Music("Assets/Sound/Loops/ForestState.wav");
bgImage = new TiledMap("Assets/World/woodsmap1.tmx");
areaLength = 200;
// SpiderWeb sw1 = new SpiderWeb(new float[] {container.getWidth()-200f, container.getHeight()-200f});
// SpiderWeb sw2 = new SpiderWeb(new float[] {container.getWidth()-300f, container.getHeight()-150f});
//
// obstacles.add(sw1);
// obstacles.add(sw2);
ArrayList<Monster> group_1 = new ArrayList<Monster>();
GoblinArcher g1_knight1 = new GoblinArcher(container.getWidth(),
container.getHeight() - 80, 1, container);
GoblinArcher g1_knight2 = new GoblinArcher(container.getWidth(),
container.getHeight() - 160, 1, container);
//GoblinArcher g1_knight3 = new GoblinArcher(container.getWidth(),
// container.getHeight() - 240, 1);
g1_knight1.init();
g1_knight2.init();
//g1_knight3.init();
group_1.add(g1_knight1);
group_1.add(g1_knight2);
//group_1.add(g1_knight3);
ArrayList<Monster> group_2 = new ArrayList<Monster>();
Knight g2_knight1 = new Knight(container.getWidth(),
container.getHeight() - 80, 1, container);
Knight g2_knight2 = new Knight(container.getWidth(),
container.getHeight() - 160, 1, container);
Knight g2_knight3 = new Knight(container.getWidth(),
container.getHeight() - 240, 1, container);
g2_knight1.init();
g2_knight2.init();
g2_knight3.init();
group_2.add(g2_knight1);
group_2.add(g2_knight2);
group_2.add(g2_knight3);
ArrayList<Monster> group_3 = new ArrayList<Monster>();
Knight g3_knight1 = new Knight(0,
container.getHeight() - 80, 1, container);
GoblinArcher g3_knight2 = new GoblinArcher(0,
container.getHeight() - 160, 1, container);
Knight g3_knight3 = new Knight(container.getWidth(),
container.getHeight() - 240, 1, container);
GoblinArcher g3_knight4 = new GoblinArcher(container.getWidth(),
container.getHeight() - 240, 1, container);
g3_knight1.init();
g3_knight2.init();
g3_knight3.init();
g3_knight4.init();
group_3.add(g3_knight1);
group_3.add(g3_knight2);
group_3.add(g3_knight3);
group_3.add(g3_knight4);
monsters.add(group_1);
monsters.add(group_2);
monsters.add(group_3);
battleStops = new int[3];
battleStops[0] = 1000;
battleStops[1] = 2000;
battleStops[2] = 3000;
}
| public void init(GameContainer container, StateBasedGame game)
throws SlickException {
super.init(container, game);
loop = new Music("Assets/Sound/Loops/ForestState.wav");
bgImage = new TiledMap("Assets/World/woodsmap1.tmx");
areaLength = 200;
// SpiderWeb sw1 = new SpiderWeb(new float[] {container.getWidth()-200f, container.getHeight()-200f});
// SpiderWeb sw2 = new SpiderWeb(new float[] {container.getWidth()-300f, container.getHeight()-150f});
//
// obstacles.add(sw1);
// obstacles.add(sw2);
ArrayList<Monster> group_1 = new ArrayList<Monster>();
GoblinArcher g1_knight1 = new GoblinArcher(container.getWidth(),
container.getHeight() - 80, 1, container);
GoblinArcher g1_knight2 = new GoblinArcher(container.getWidth(),
container.getHeight() - 160, 1, container);
//GoblinArcher g1_knight3 = new GoblinArcher(container.getWidth(),
// container.getHeight() - 240, 1);
g1_knight1.init();
g1_knight2.init();
//g1_knight3.init();
group_1.add(g1_knight1);
group_1.add(g1_knight2);
//group_1.add(g1_knight3);
ArrayList<Monster> group_2 = new ArrayList<Monster>();
Knight g2_knight1 = new Knight(container.getWidth(),
container.getHeight() - 80, 1, container);
Knight g2_knight2 = new Knight(container.getWidth(),
container.getHeight() - 160, 1, container);
Knight g2_knight3 = new Knight(container.getWidth(),
container.getHeight() - 240, 1, container);
g2_knight1.init();
g2_knight2.init();
g2_knight3.init();
group_2.add(g2_knight1);
group_2.add(g2_knight2);
group_2.add(g2_knight3);
ArrayList<Monster> group_3 = new ArrayList<Monster>();
Knight g3_knight1 = new Knight(0,
container.getHeight() - 80, 1, container);
GoblinArcher g3_knight2 = new GoblinArcher(0,
container.getHeight() - 160, 1, container);
Knight g3_knight3 = new Knight(container.getWidth(),
container.getHeight() - 200, 1, container);
GoblinArcher g3_knight4 = new GoblinArcher(container.getWidth(),
container.getHeight() - 240, 1, container);
g3_knight1.init();
g3_knight2.init();
g3_knight3.init();
g3_knight4.init();
group_3.add(g3_knight1);
group_3.add(g3_knight2);
group_3.add(g3_knight3);
group_3.add(g3_knight4);
monsters.add(group_1);
monsters.add(group_2);
monsters.add(group_3);
battleStops = new int[3];
battleStops[0] = 1000;
battleStops[1] = 2000;
battleStops[2] = 3000;
}
|
diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java
index f2df5638d..ddcd91920 100644
--- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java
+++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java
@@ -1,110 +1,112 @@
package org.apache.maven.project;
/*
* 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.util.ArrayList;
import java.util.List;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.model.building.ModelProblem;
/**
* Collects the output of the project builder.
*
* @author Benjamin Bentmann
*/
class DefaultProjectBuildingResult
implements ProjectBuildingResult
{
private String projectId;
private File pomFile;
private MavenProject project;
private List<ModelProblem> problems;
private ArtifactResolutionResult artifactResolutionResult;
/**
* Creates a new result with the specified contents.
*
* @param project The project that was built, may be {@code null}.
* @param problems The problems that were encouterned, may be {@code null}.
* @param dependencyResolutionResult The result of the artifact resolution for the project dependencies, may be
* {@code null}.
*/
public DefaultProjectBuildingResult( MavenProject project, List<ModelProblem> problems,
ArtifactResolutionResult dependencyResolutionResult )
{
- this.projectId = ( project != null ) ? project.getId() : "";
+ this.projectId =
+ ( project != null ) ? project.getGroupId() + ':' + project.getArtifactId() + ':' + project.getVersion()
+ : "";
this.pomFile = ( project != null ) ? project.getFile() : null;
this.project = project;
this.problems = problems;
this.artifactResolutionResult = dependencyResolutionResult;
}
/**
* Creates a new result with the specified contents.
*
* @param projectId The identifier of the project, may be {@code null}.
* @param pomFile The POM file from which the project was built, may be {@code null}.
* @param problems The problems that were encouterned, may be {@code null}.
*/
public DefaultProjectBuildingResult( String projectId, File pomFile, List<ModelProblem> problems )
{
this.projectId = ( projectId != null ) ? projectId : "";
this.pomFile = pomFile;
this.problems = problems;
}
public String getProjectId()
{
return projectId;
}
public File getPomFile()
{
return pomFile;
}
public MavenProject getProject()
{
return project;
}
public List<ModelProblem> getProblems()
{
if ( problems == null )
{
problems = new ArrayList<ModelProblem>();
}
return problems;
}
public ArtifactResolutionResult getArtifactResolutionResult()
{
return artifactResolutionResult;
}
}
| true | true | public DefaultProjectBuildingResult( MavenProject project, List<ModelProblem> problems,
ArtifactResolutionResult dependencyResolutionResult )
{
this.projectId = ( project != null ) ? project.getId() : "";
this.pomFile = ( project != null ) ? project.getFile() : null;
this.project = project;
this.problems = problems;
this.artifactResolutionResult = dependencyResolutionResult;
}
| public DefaultProjectBuildingResult( MavenProject project, List<ModelProblem> problems,
ArtifactResolutionResult dependencyResolutionResult )
{
this.projectId =
( project != null ) ? project.getGroupId() + ':' + project.getArtifactId() + ':' + project.getVersion()
: "";
this.pomFile = ( project != null ) ? project.getFile() : null;
this.project = project;
this.problems = problems;
this.artifactResolutionResult = dependencyResolutionResult;
}
|
diff --git a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/LinkEObjectFlatComboViewer.java b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/LinkEObjectFlatComboViewer.java
index 8146636f9..6acdbea61 100644
--- a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/LinkEObjectFlatComboViewer.java
+++ b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/LinkEObjectFlatComboViewer.java
@@ -1,148 +1,148 @@
/*******************************************************************************
* Copyright (c) 2008, 2013 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.emf.eef.runtime.ui.widgets;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Link;
/**
* AdvancedEObjectFlatComboViewer with a link to set the element properties.
*
* @author <a href="mailto:[email protected]">Nathalie L�pine</a>
*/
public class LinkEObjectFlatComboViewer extends AbstractAdvancedEObjectFlatComboViewer {
/** Associated link. */
protected Link valueLink;
/**
* Constructor from super class
*
* @param dialogTitle
* @param input Object
* @param filter ViewerFilter
* @param adapterFactory AdapterFactory
* @param callback EObjectFlatComboViewerListener
*/
public LinkEObjectFlatComboViewer(String dialogTitle, Object input,
ViewerFilter filter, AdapterFactory adapterFactory,
EObjectFlatComboViewerListener callback) {
super(dialogTitle, input, filter, adapterFactory, callback);
}
/** (non-Javadoc)
* @see org.eclipse.emf.eef.runtime.ui.widgets.AbstractAdvancedEObjectFlatComboViewer#createLabels(org.eclipse.swt.widgets.Composite)
*/
protected void createLabels(Composite parent) {
String value = UNDEFINED_VALUE;
if (selection != null) {
value = labelProvider.getText(selection);
}
this.valueLink = createLink(parent, value, SWT.NONE);
FormData data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(browseButton, 0);
- data.top = new FormAttachment(0, 1);
- valueLink.setLayoutData(data);
+ data.top = new FormAttachment(0, 4);
+ valueLink.setLayoutData(data);
valueLink.addSelectionListener(new SelectionAdapter() {
/** (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
EObject editedElement = getSelection();
handleEdit(editedElement);
}
});
}
/**
* @param parent Composite
* @param value String
* @param style
* @return the created Link
*/
private Link createLink(Composite parent, String value, int style) {
Link link = new Link(parent, style);
link.setText(value);
EditingUtils.setEEFtype(field, "eef::LinkEObjectFlatComboViewer::link");
return link;
}
/** (non-Javadoc)
* @see org.eclipse.emf.eef.runtime.ui.widgets.AbstractAdvancedEObjectFlatComboViewer#setSelection(org.eclipse.jface.viewers.ISelection)
*/
public void setSelection(ISelection selection) {
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
if (!structuredSelection.isEmpty()
&& !"".equals(structuredSelection.getFirstElement())) {
setSelection((EObject) structuredSelection.getFirstElement());
} else {
this.valueLink.setText(UNDEFINED_VALUE);
}
}
}
/** (non-Javadoc)
* @see org.eclipse.emf.eef.runtime.ui.widgets.AbstractAdvancedEObjectFlatComboViewer#setSelection(org.eclipse.emf.ecore.EObject)
*/
public void setSelection(EObject selection) {
this.selection = selection;
String text = labelProvider.getText(selection);
if ("".equals(text)) //$NON-NLS-1$
this.valueLink.setText(UNDEFINED_VALUE);
else
this.valueLink.setText("<a>" + text + "</a>");
}
/** (non-Javadoc)
* @see org.eclipse.emf.eef.runtime.ui.widgets.AbstractAdvancedEObjectFlatComboViewer#setID(java.lang.Object)
*/
public void setID(Object id) {
super.setID(id);
EditingUtils.setID(valueLink, id);
}
/** (non-Javadoc)
* @see org.eclipse.emf.eef.runtime.ui.widgets.AbstractAdvancedEObjectFlatComboViewer#setEnabled(boolean)
*/
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
valueLink.setEnabled(enabled);
}
/** (non-Javadoc)
* @see org.eclipse.emf.eef.runtime.ui.widgets.AbstractAdvancedEObjectFlatComboViewer#isEnabled()
*/
public boolean isEnabled() {
return super.isEnabled() && valueLink.isEnabled();
}
/** (non-Javadoc)
* @see org.eclipse.emf.eef.runtime.ui.widgets.AbstractAdvancedEObjectFlatComboViewer#setToolTipText(java.lang.String)
*/
public void setToolTipText(String tooltip) {
super.setToolTipText(tooltip);
valueLink.setToolTipText(tooltip);
}
}
| true | true | protected void createLabels(Composite parent) {
String value = UNDEFINED_VALUE;
if (selection != null) {
value = labelProvider.getText(selection);
}
this.valueLink = createLink(parent, value, SWT.NONE);
FormData data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(browseButton, 0);
data.top = new FormAttachment(0, 1);
valueLink.setLayoutData(data);
valueLink.addSelectionListener(new SelectionAdapter() {
/** (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
EObject editedElement = getSelection();
handleEdit(editedElement);
}
});
}
| protected void createLabels(Composite parent) {
String value = UNDEFINED_VALUE;
if (selection != null) {
value = labelProvider.getText(selection);
}
this.valueLink = createLink(parent, value, SWT.NONE);
FormData data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(browseButton, 0);
data.top = new FormAttachment(0, 4);
valueLink.setLayoutData(data);
valueLink.addSelectionListener(new SelectionAdapter() {
/** (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
EObject editedElement = getSelection();
handleEdit(editedElement);
}
});
}
|
diff --git a/src/haven/Listbox.java b/src/haven/Listbox.java
index b6516fd6..0999ece7 100644
--- a/src/haven/Listbox.java
+++ b/src/haven/Listbox.java
@@ -1,94 +1,94 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* 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.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.awt.Color;
public abstract class Listbox<T> extends ListWidget<T> {
public final int h;
public final Scrollbar sb;
public Listbox(Coord c, Widget parent, int w, int h, int itemh) {
super(c, new Coord(w, h * itemh), parent, itemh);
this.h = h;
this.sb = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 0);
}
protected void drawsel(GOut g) {
g.chcolor(255, 255, 0, 128);
g.frect(Coord.z, g.sz);
g.chcolor();
}
public void draw(GOut g) {
sb.max = listitems() - h;
g.chcolor(Color.BLACK);
g.frect(Coord.z, sz);
g.chcolor();
int n = listitems();
for(int i = 0; i < h; i++) {
int idx = i + sb.val;
if(idx >= n)
break;
T item = listitem(idx);
int w = sz.x - (sb.vis()?sb.sz.x:0);
- GOut ig = g.reclip(new Coord(0, i * itemh), new Coord(sz.x, itemh));
+ GOut ig = g.reclip(new Coord(0, i * itemh), new Coord(w, itemh));
if(item == sel)
drawsel(ig);
drawitem(ig, item);
}
super.draw(g);
}
public boolean mousewheel(Coord c, int amount) {
sb.ch(amount);
return(true);
}
protected void itemclick(T item, int button) {
if(button == 1)
change(item);
}
public T itemat(Coord c) {
int idx = (c.y / itemh) + sb.val;
if(idx >= listitems())
return(null);
return(listitem(idx));
}
public boolean mousedown(Coord c, int button) {
if(super.mousedown(c, button))
return(true);
T item = itemat(c);
if((item == null) && (button == 1))
change(null);
else if(item != null)
itemclick(item, button);
return(true);
}
}
| true | true | public void draw(GOut g) {
sb.max = listitems() - h;
g.chcolor(Color.BLACK);
g.frect(Coord.z, sz);
g.chcolor();
int n = listitems();
for(int i = 0; i < h; i++) {
int idx = i + sb.val;
if(idx >= n)
break;
T item = listitem(idx);
int w = sz.x - (sb.vis()?sb.sz.x:0);
GOut ig = g.reclip(new Coord(0, i * itemh), new Coord(sz.x, itemh));
if(item == sel)
drawsel(ig);
drawitem(ig, item);
}
super.draw(g);
}
| public void draw(GOut g) {
sb.max = listitems() - h;
g.chcolor(Color.BLACK);
g.frect(Coord.z, sz);
g.chcolor();
int n = listitems();
for(int i = 0; i < h; i++) {
int idx = i + sb.val;
if(idx >= n)
break;
T item = listitem(idx);
int w = sz.x - (sb.vis()?sb.sz.x:0);
GOut ig = g.reclip(new Coord(0, i * itemh), new Coord(w, itemh));
if(item == sel)
drawsel(ig);
drawitem(ig, item);
}
super.draw(g);
}
|
diff --git a/rest/src/main/java/org/dbpedia/spotlight/web/rest/Server.java b/rest/src/main/java/org/dbpedia/spotlight/web/rest/Server.java
index 8c125c2f..c4285ae2 100644
--- a/rest/src/main/java/org/dbpedia/spotlight/web/rest/Server.java
+++ b/rest/src/main/java/org/dbpedia/spotlight/web/rest/Server.java
@@ -1,272 +1,273 @@
/*
* Copyright 2011 DBpedia Spotlight Development Team
*
* 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.
*
* Check our project website for information on how to acknowledge the authors and how to contribute to the project: http://spotlight.dbpedia.org
*/
package org.dbpedia.spotlight.web.rest;
import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbpedia.spotlight.db.SpotlightModel;
import org.dbpedia.spotlight.db.model.Tokenizer;
import org.dbpedia.spotlight.disambiguate.ParagraphDisambiguatorJ;
import org.dbpedia.spotlight.exceptions.InitializationException;
import org.dbpedia.spotlight.exceptions.InputException;
import org.dbpedia.spotlight.filter.annotations.CombineAllAnnotationFilters;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.SpotlightConfiguration;
import org.dbpedia.spotlight.model.SpotlightFactory;
import org.dbpedia.spotlight.model.SpotterConfiguration;
import org.dbpedia.spotlight.spot.Spotter;
import org.dbpedia.spotlight.model.SpotterConfiguration.SpotterPolicy;
import org.dbpedia.spotlight.model.SpotlightConfiguration.DisambiguationPolicy;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
/**
* Instantiates Web Service that will execute annotation and disambiguation tasks.
*
* @author maxjakob
* @author pablomendes - added WADL generator config, changed to Grizzly
*/
public class Server {
static Log LOG = LogFactory.getLog(Server.class);
public static final String APPLICATION_PATH = "http://spotlight.dbpedia.org/rest";
// Server reads configuration parameters into this static configuration object that will be used by other classes downstream
protected static SpotlightConfiguration configuration;
// Server will hold a few spotters that can be chosen from URL parameters
protected static Map<SpotterPolicy,Spotter> spotters = new HashMap<SpotterConfiguration.SpotterPolicy,Spotter>();
// Server will hold a few disambiguators that can be chosen from URL parameters
protected static Map<DisambiguationPolicy,ParagraphDisambiguatorJ> disambiguators = new HashMap<SpotlightConfiguration.DisambiguationPolicy,ParagraphDisambiguatorJ>();
private static volatile Boolean running = true;
static String usage = "usage: java -jar dbpedia-spotlight.jar org.dbpedia.spotlight.web.rest.Server [config file]"
+ " or: mvn scala:run \"-DaddArgs=[config file]\"";
//This is currently only used in the DB-based version.
private static Tokenizer tokenizer;
protected static CombineAllAnnotationFilters combinedFilters = null;
private static String namespacePrefix = SpotlightConfiguration.DEFAULT_NAMESPACE;
public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException, ClassNotFoundException, InitializationException {
URI serverURI = null;
if(args[0].endsWith(".properties")) {
//We are using the old-style configuration file:
//Initialization, check values
try {
String configFileName = args[0];
configuration = new SpotlightConfiguration(configFileName);
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n"+usage);
System.exit(1);
}
serverURI = new URI(configuration.getServerURI());
// Set static annotator that will be used by Annotate and Disambiguate
final SpotlightFactory factory = new SpotlightFactory(configuration);
setDisambiguators(factory.disambiguators());
setSpotters(factory.spotters());
+ setNamespacePrefix(configuration.getDbpediaResource());
setCombinedFilters(new CombineAllAnnotationFilters(Server.getConfiguration()));
} else {
//We are using a model folder:
serverURI = new URI(args[1]);
File modelFolder = null;
try {
modelFolder = new File(args[0]);
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n"+usage);
System.exit(1);
}
SpotlightModel db = SpotlightModel.fromFolder(modelFolder);
setNamespacePrefix(db.properties().getProperty("namespace"));
setTokenizer(db.tokenizer());
setSpotters(db.spotters());
setDisambiguators(db.disambiguators());
}
//ExternalUriWadlGeneratorConfig.setUri(configuration.getServerURI()); //TODO get another parameter, maybe getExternalServerURI since Grizzly will use this in order to find out to which port to bind
LOG.info(String.format("Initiated %d disambiguators.",disambiguators.size()));
LOG.info(String.format("Initiated %d spotters.",spotters.size()));
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
initParams.put("com.sun.jersey.config.property.packages", "org.dbpedia.spotlight.web.rest.resources");
initParams.put("com.sun.jersey.config.property.WadlGeneratorConfig", "org.dbpedia.spotlight.web.rest.wadl.ExternalUriWadlGeneratorConfig");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(serverURI, initParams);
threadSelector.start();
System.err.println("Server started in " + System.getProperty("user.dir") + " listening on " + serverURI);
//Open browser
try {
String example1 = "annotate?text=At%20a%20private%20dinner%20on%20Friday%20at%20the%20Canadian%20Embassy,%20finance%20officials%20from%20seven%20world%20economic%20powers%20focused%20on%20the%20most%20vexing%20international%20economic%20problem%20facing%20the%20Obama%20administration.%20Over%20seared%20scallops%20and%20beef%20tenderloin,%20Treasury%20Secretary%20Timothy%20F.%20Geithner%20urged%20his%20counterparts%20from%20Europe,%20Canada%20and%20Japan%20to%20help%20persuade%20China%20to%20let%20its%20currency,%20the%20renminbi,%20rise%20in%20value%20a%20crucial%20element%20in%20redressing%20the%20trade%20imbalances%20that%20are%20threatening%20recovery%20around%20the%20world.%20But%20the%20next%20afternoon,%20the%20annual%20meetings%20of%20the%20International%20Monetary%20Fund%20ended%20with%20a%20tepid%20statement%20that%20made%20only%20fleeting%20and%20indirect%20references%20to%20the%20simmering%20currency%20tensions&confidence=0.2&support=20";
String example2 = "annotate?text=Brazilian%20oil%20giant%20Petrobras%20and%20U.S.%20oilfield%20service%20company%20Halliburton%20have%20signed%20a%20technological%20cooperation%20agreement,%20Petrobras%20announced%20Monday.%20%20%20%20The%20two%20companies%20agreed%20on%20three%20projects:%20studies%20on%20contamination%20of%20fluids%20in%20oil%20wells,%20laboratory%20simulation%20of%20well%20production,%20and%20research%20on%20solidification%20of%20salt%20and%20carbon%20dioxide%20formations,%20said%20Petrobras.%20Twelve%20other%20projects%20are%20still%20under%20negotiation.&confidence=0.0&support=0";
URI example = new URI(serverURI.toString() + example2);
java.awt.Desktop.getDesktop().browse(example);
}
catch (Exception e) {
System.err.println("Could not open browser. " + e);
}
Thread warmUp = new Thread() {
public void run() {
//factory.searcher().warmUp((int) (configuration.getMaxCacheSize() * 0.7));
}
};
warmUp.start();
while(running) {
Thread.sleep(100);
}
//Stop the HTTP server
//server.stop(0);
threadSelector.stopEndpoint();
System.exit(0);
}
private static void setSpotters(Map<SpotterPolicy,Spotter> s) throws InitializationException {
if (spotters.size() == 0)
spotters = s;
else
throw new InitializationException("Trying to overwrite singleton Server.spotters. Something fishy happened!");
}
private static void setDisambiguators(Map<SpotlightConfiguration.DisambiguationPolicy,ParagraphDisambiguatorJ> s) throws InitializationException {
if (disambiguators.size() == 0)
disambiguators = s;
else
throw new InitializationException("Trying to overwrite singleton Server.disambiguators. Something fishy happened!");
}
public static Spotter getSpotter(String name) throws InputException {
SpotterPolicy policy = SpotterPolicy.Default;
try {
policy = SpotterPolicy.valueOf(name);
} catch (IllegalArgumentException e) {
throw new InputException(String.format("Specified parameter spotter=%s is invalid. Use one of %s.",name,SpotterPolicy.values()));
}
if (spotters.size() == 0)
throw new InputException(String.format("No spotters were loaded. Please add one of %s.",spotters.keySet()));
Spotter spotter = spotters.get(policy);
if (spotter==null) {
throw new InputException(String.format("Specified spotter=%s has not been loaded. Use one of %s.",name,spotters.keySet()));
}
return spotter;
}
public static ParagraphDisambiguatorJ getDisambiguator(String name) throws InputException {
DisambiguationPolicy policy = DisambiguationPolicy.Default;
try {
policy = DisambiguationPolicy.valueOf(name);
} catch (IllegalArgumentException e) {
throw new InputException(String.format("Specified parameter disambiguator=%s is invalid. Use one of %s.",name,DisambiguationPolicy.values()));
}
if (disambiguators.size() == 0)
throw new InputException(String.format("No disambiguators were loaded. Please add one of %s.",disambiguators.keySet()));
ParagraphDisambiguatorJ disambiguator = disambiguators.get(policy);
if (disambiguator == null)
throw new InputException(String.format("Specified disambiguator=%s has not been loaded. Use one of %s.",name,disambiguators.keySet()));
return disambiguator;
}
// public static Spotter getSpotter(SpotterPolicy policy) throws InputException {
// Spotter spotter = spotters.get(policy);
// if (spotters.size()==0 || spotter==null) {
// throw new InputException(String.format("Specified spotter=%s has not been loaded. Use one of %s.",policy,spotters.keySet()));
// }
// return spotter;
// }
//
// public static ParagraphDisambiguatorJ getDisambiguator(DisambiguationPolicy policy) throws InputException {
// ParagraphDisambiguatorJ disambiguator = disambiguators.get(policy);
// if (disambiguators.size() == 0 || disambiguators == null)
// throw new InputException(String.format("Specified disambiguator=%s has not been loaded. Use one of %s.",policy,disambiguators.keySet()));
// return disambiguator;
// }
public static SpotlightConfiguration getConfiguration() {
return configuration;
}
public static Tokenizer getTokenizer() {
return tokenizer;
}
public static void setTokenizer(Tokenizer tokenizer) {
Server.tokenizer = tokenizer;
}
public static CombineAllAnnotationFilters getCombinedFilters() {
return combinedFilters;
}
public static void setCombinedFilters(CombineAllAnnotationFilters combinedFilters) {
Server.combinedFilters = combinedFilters;
}
public static String getPrefixedDBpediaURL(DBpediaResource resource) {
return namespacePrefix + resource.uri();
}
public static void setNamespacePrefix(String namespacePrefix) {
Server.namespacePrefix = namespacePrefix;
}
}
| true | true | public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException, ClassNotFoundException, InitializationException {
URI serverURI = null;
if(args[0].endsWith(".properties")) {
//We are using the old-style configuration file:
//Initialization, check values
try {
String configFileName = args[0];
configuration = new SpotlightConfiguration(configFileName);
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n"+usage);
System.exit(1);
}
serverURI = new URI(configuration.getServerURI());
// Set static annotator that will be used by Annotate and Disambiguate
final SpotlightFactory factory = new SpotlightFactory(configuration);
setDisambiguators(factory.disambiguators());
setSpotters(factory.spotters());
setCombinedFilters(new CombineAllAnnotationFilters(Server.getConfiguration()));
} else {
//We are using a model folder:
serverURI = new URI(args[1]);
File modelFolder = null;
try {
modelFolder = new File(args[0]);
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n"+usage);
System.exit(1);
}
SpotlightModel db = SpotlightModel.fromFolder(modelFolder);
setNamespacePrefix(db.properties().getProperty("namespace"));
setTokenizer(db.tokenizer());
setSpotters(db.spotters());
setDisambiguators(db.disambiguators());
}
//ExternalUriWadlGeneratorConfig.setUri(configuration.getServerURI()); //TODO get another parameter, maybe getExternalServerURI since Grizzly will use this in order to find out to which port to bind
LOG.info(String.format("Initiated %d disambiguators.",disambiguators.size()));
LOG.info(String.format("Initiated %d spotters.",spotters.size()));
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
initParams.put("com.sun.jersey.config.property.packages", "org.dbpedia.spotlight.web.rest.resources");
initParams.put("com.sun.jersey.config.property.WadlGeneratorConfig", "org.dbpedia.spotlight.web.rest.wadl.ExternalUriWadlGeneratorConfig");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(serverURI, initParams);
threadSelector.start();
System.err.println("Server started in " + System.getProperty("user.dir") + " listening on " + serverURI);
//Open browser
try {
String example1 = "annotate?text=At%20a%20private%20dinner%20on%20Friday%20at%20the%20Canadian%20Embassy,%20finance%20officials%20from%20seven%20world%20economic%20powers%20focused%20on%20the%20most%20vexing%20international%20economic%20problem%20facing%20the%20Obama%20administration.%20Over%20seared%20scallops%20and%20beef%20tenderloin,%20Treasury%20Secretary%20Timothy%20F.%20Geithner%20urged%20his%20counterparts%20from%20Europe,%20Canada%20and%20Japan%20to%20help%20persuade%20China%20to%20let%20its%20currency,%20the%20renminbi,%20rise%20in%20value%20a%20crucial%20element%20in%20redressing%20the%20trade%20imbalances%20that%20are%20threatening%20recovery%20around%20the%20world.%20But%20the%20next%20afternoon,%20the%20annual%20meetings%20of%20the%20International%20Monetary%20Fund%20ended%20with%20a%20tepid%20statement%20that%20made%20only%20fleeting%20and%20indirect%20references%20to%20the%20simmering%20currency%20tensions&confidence=0.2&support=20";
String example2 = "annotate?text=Brazilian%20oil%20giant%20Petrobras%20and%20U.S.%20oilfield%20service%20company%20Halliburton%20have%20signed%20a%20technological%20cooperation%20agreement,%20Petrobras%20announced%20Monday.%20%20%20%20The%20two%20companies%20agreed%20on%20three%20projects:%20studies%20on%20contamination%20of%20fluids%20in%20oil%20wells,%20laboratory%20simulation%20of%20well%20production,%20and%20research%20on%20solidification%20of%20salt%20and%20carbon%20dioxide%20formations,%20said%20Petrobras.%20Twelve%20other%20projects%20are%20still%20under%20negotiation.&confidence=0.0&support=0";
URI example = new URI(serverURI.toString() + example2);
java.awt.Desktop.getDesktop().browse(example);
}
catch (Exception e) {
System.err.println("Could not open browser. " + e);
}
Thread warmUp = new Thread() {
public void run() {
//factory.searcher().warmUp((int) (configuration.getMaxCacheSize() * 0.7));
}
};
warmUp.start();
while(running) {
Thread.sleep(100);
}
//Stop the HTTP server
//server.stop(0);
threadSelector.stopEndpoint();
System.exit(0);
}
| public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException, ClassNotFoundException, InitializationException {
URI serverURI = null;
if(args[0].endsWith(".properties")) {
//We are using the old-style configuration file:
//Initialization, check values
try {
String configFileName = args[0];
configuration = new SpotlightConfiguration(configFileName);
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n"+usage);
System.exit(1);
}
serverURI = new URI(configuration.getServerURI());
// Set static annotator that will be used by Annotate and Disambiguate
final SpotlightFactory factory = new SpotlightFactory(configuration);
setDisambiguators(factory.disambiguators());
setSpotters(factory.spotters());
setNamespacePrefix(configuration.getDbpediaResource());
setCombinedFilters(new CombineAllAnnotationFilters(Server.getConfiguration()));
} else {
//We are using a model folder:
serverURI = new URI(args[1]);
File modelFolder = null;
try {
modelFolder = new File(args[0]);
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n"+usage);
System.exit(1);
}
SpotlightModel db = SpotlightModel.fromFolder(modelFolder);
setNamespacePrefix(db.properties().getProperty("namespace"));
setTokenizer(db.tokenizer());
setSpotters(db.spotters());
setDisambiguators(db.disambiguators());
}
//ExternalUriWadlGeneratorConfig.setUri(configuration.getServerURI()); //TODO get another parameter, maybe getExternalServerURI since Grizzly will use this in order to find out to which port to bind
LOG.info(String.format("Initiated %d disambiguators.",disambiguators.size()));
LOG.info(String.format("Initiated %d spotters.",spotters.size()));
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
initParams.put("com.sun.jersey.config.property.packages", "org.dbpedia.spotlight.web.rest.resources");
initParams.put("com.sun.jersey.config.property.WadlGeneratorConfig", "org.dbpedia.spotlight.web.rest.wadl.ExternalUriWadlGeneratorConfig");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(serverURI, initParams);
threadSelector.start();
System.err.println("Server started in " + System.getProperty("user.dir") + " listening on " + serverURI);
//Open browser
try {
String example1 = "annotate?text=At%20a%20private%20dinner%20on%20Friday%20at%20the%20Canadian%20Embassy,%20finance%20officials%20from%20seven%20world%20economic%20powers%20focused%20on%20the%20most%20vexing%20international%20economic%20problem%20facing%20the%20Obama%20administration.%20Over%20seared%20scallops%20and%20beef%20tenderloin,%20Treasury%20Secretary%20Timothy%20F.%20Geithner%20urged%20his%20counterparts%20from%20Europe,%20Canada%20and%20Japan%20to%20help%20persuade%20China%20to%20let%20its%20currency,%20the%20renminbi,%20rise%20in%20value%20a%20crucial%20element%20in%20redressing%20the%20trade%20imbalances%20that%20are%20threatening%20recovery%20around%20the%20world.%20But%20the%20next%20afternoon,%20the%20annual%20meetings%20of%20the%20International%20Monetary%20Fund%20ended%20with%20a%20tepid%20statement%20that%20made%20only%20fleeting%20and%20indirect%20references%20to%20the%20simmering%20currency%20tensions&confidence=0.2&support=20";
String example2 = "annotate?text=Brazilian%20oil%20giant%20Petrobras%20and%20U.S.%20oilfield%20service%20company%20Halliburton%20have%20signed%20a%20technological%20cooperation%20agreement,%20Petrobras%20announced%20Monday.%20%20%20%20The%20two%20companies%20agreed%20on%20three%20projects:%20studies%20on%20contamination%20of%20fluids%20in%20oil%20wells,%20laboratory%20simulation%20of%20well%20production,%20and%20research%20on%20solidification%20of%20salt%20and%20carbon%20dioxide%20formations,%20said%20Petrobras.%20Twelve%20other%20projects%20are%20still%20under%20negotiation.&confidence=0.0&support=0";
URI example = new URI(serverURI.toString() + example2);
java.awt.Desktop.getDesktop().browse(example);
}
catch (Exception e) {
System.err.println("Could not open browser. " + e);
}
Thread warmUp = new Thread() {
public void run() {
//factory.searcher().warmUp((int) (configuration.getMaxCacheSize() * 0.7));
}
};
warmUp.start();
while(running) {
Thread.sleep(100);
}
//Stop the HTTP server
//server.stop(0);
threadSelector.stopEndpoint();
System.exit(0);
}
|
diff --git a/spi/src/main/java/org/qi4j/spi/service/importer/ServiceSelectorImporter.java b/spi/src/main/java/org/qi4j/spi/service/importer/ServiceSelectorImporter.java
index 48c075384..80c9d9ee4 100644
--- a/spi/src/main/java/org/qi4j/spi/service/importer/ServiceSelectorImporter.java
+++ b/spi/src/main/java/org/qi4j/spi/service/importer/ServiceSelectorImporter.java
@@ -1,73 +1,73 @@
/*
* Copyright (c) 2008, Rickard Öberg. All Rights Reserved.
*
* 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.qi4j.spi.service.importer;
import java.util.ArrayList;
import java.util.List;
import org.qi4j.api.injection.scope.Structure;
import org.qi4j.api.service.Availability;
import org.qi4j.api.service.ImportedServiceDescriptor;
import org.qi4j.api.service.ServiceFinder;
import org.qi4j.api.service.ServiceImporter;
import org.qi4j.api.service.ServiceImporterException;
import org.qi4j.api.service.ServiceReference;
import org.qi4j.api.service.qualifier.ServiceQualifier;
import org.qi4j.api.specification.Specification;
/**
* If several services are available with a given type, and you want to constrain
* the current module to use a specific one, then use this importer. Specify a
* Specification<ServiceReference<T>> criteria as meta-info for the service, which will be applied
* to the list of available services, and the first match will be chosen.
*
* This importer will avoid selecting itself, as could be possible if the ServiceQualifier.first()
* filter is used.
*/
public final class ServiceSelectorImporter<T>
implements ServiceImporter<T>
{
@Structure
private ServiceFinder locator;
public T importService( ImportedServiceDescriptor serviceDescriptor )
throws ServiceImporterException
{
Specification<ServiceReference<?>> selector = serviceDescriptor.metaInfo( Specification.class );
Class serviceType = serviceDescriptor.type();
Iterable<ServiceReference<T>> services = locator.findServices( serviceType );
List<ServiceReference<T>> filteredServices = new ArrayList<ServiceReference<T>>();
for( ServiceReference<T> service : services )
{
- ServiceQualifier selector1 = service.metaInfo( ServiceQualifier.class );
+ Specification selector1 = service.metaInfo( Specification.class );
if( selector1 != null && selector1 == selector )
{
continue;
}
filteredServices.add( service );
}
return ServiceQualifier.firstService( selector, filteredServices );
}
public boolean isActive( T instance )
{
return true;
}
public boolean isAvailable( T instance )
{
return !( instance instanceof Availability ) || ( (Availability) instance ).isAvailable();
}
}
| true | true | public T importService( ImportedServiceDescriptor serviceDescriptor )
throws ServiceImporterException
{
Specification<ServiceReference<?>> selector = serviceDescriptor.metaInfo( Specification.class );
Class serviceType = serviceDescriptor.type();
Iterable<ServiceReference<T>> services = locator.findServices( serviceType );
List<ServiceReference<T>> filteredServices = new ArrayList<ServiceReference<T>>();
for( ServiceReference<T> service : services )
{
ServiceQualifier selector1 = service.metaInfo( ServiceQualifier.class );
if( selector1 != null && selector1 == selector )
{
continue;
}
filteredServices.add( service );
}
return ServiceQualifier.firstService( selector, filteredServices );
}
| public T importService( ImportedServiceDescriptor serviceDescriptor )
throws ServiceImporterException
{
Specification<ServiceReference<?>> selector = serviceDescriptor.metaInfo( Specification.class );
Class serviceType = serviceDescriptor.type();
Iterable<ServiceReference<T>> services = locator.findServices( serviceType );
List<ServiceReference<T>> filteredServices = new ArrayList<ServiceReference<T>>();
for( ServiceReference<T> service : services )
{
Specification selector1 = service.metaInfo( Specification.class );
if( selector1 != null && selector1 == selector )
{
continue;
}
filteredServices.add( service );
}
return ServiceQualifier.firstService( selector, filteredServices );
}
|
diff --git a/CometDServer/src/org/BB/interactive/SimpleUserStatistics.java b/CometDServer/src/org/BB/interactive/SimpleUserStatistics.java
index 6ec7d12..f10105f 100644
--- a/CometDServer/src/org/BB/interactive/SimpleUserStatistics.java
+++ b/CometDServer/src/org/BB/interactive/SimpleUserStatistics.java
@@ -1,170 +1,170 @@
package org.BB.interactive;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.server.AbstractService;
public class SimpleUserStatistics extends AbstractService {
long time;
// channel => number of users
Map<String,Integer> messages;
// page => language => user session
Map<String, Map<String, Set<ServerSession>>> pages;
// user session => language, page
Map<ServerSession, String[]> users;
final long TIME_SPAN = 3*60000;
boolean log_messages;
public SimpleUserStatistics(BayeuxServer bayeux, boolean log_messages)
{
super(bayeux, "statistics-service");
addService("/**", "all");
time = System.currentTimeMillis();
messages = new TreeMap<String, Integer>();
pages = new TreeMap<String, Map<String, Set<ServerSession>>>();
users = new HashMap<ServerSession, String[]>();
this.log_messages = log_messages;
}
// TODO(kolman): Remove synchronized by writing data structure module.
// This module has to store all user actions for statistics.
// Different kinds of statistics can be derived later.
// This synchronized is waste of CPU, make non blocking concurent
// queue instead and handling thread.
public synchronized void all(ServerSession remote, Message message) {
if (message != null) {
if (messages.containsKey(message.getChannel())) {
messages.put(message.getChannel(), messages.get(message.getChannel())+1);
} else {
messages.put(message.getChannel(), 1);
}
if (log_messages) {
System.err.println(message.getJSON());
}
Object pageObj = message.get("page");
if (pageObj instanceof String) {
String page = (String)pageObj;
// Canonic URL
page = page.startsWith("http://") ? page.substring(7) : page;
page = page.startsWith("www") ? page.substring(3) : page;
page = page.startsWith("kabbalahgroup.info/internet/") ? page.substring(28) : page;
page = page.startsWith("localhost:3000/") ? page.substring(15) : page;
String language = page.substring(0, 2);
page = page.substring(2, page.length());
page = page.startsWith("#") ? page.substring(1) : page;
Map<String, Set<ServerSession>> page_data = null;
Set<ServerSession> sessions = null;
page_data = pages.get(page);
if (page_data == null) {
page_data = new TreeMap<String, Set<ServerSession>>();
}
sessions = page_data.get(language);
if (sessions == null) {
sessions = new HashSet<ServerSession>();
}
sessions.add(remote);
page_data.put(language, sessions);
pages.put(page, page_data);
// Remove existing user from previous page.
// Check use exists and check page is different.
if (users.containsKey(remote)) {
String[] lang_page = users.get(remote);
if (lang_page == null || lang_page.length < 2 ||
lang_page[0].compareTo(language) != 0 ||
lang_page[1].compareTo(page) != 0) {
Map<String, Set<ServerSession>> pages_page_data = pages.get(users.get(remote)[1]);
- Set<ServerSession> pages_sessions = pages_page_data.get(language);
+ Set<ServerSession> pages_sessions = pages_page_data.get(users.get(remote)[0]);
pages_sessions.remove(remote);
if (pages_sessions.size() == 0) {
pages_page_data.remove(language);
if (pages_page_data.size() == 0) {
pages.remove(users.get(remote));
}
}
}
}
users.put(remote, new String[] {language, page});
}
}
update();
}
public void update() {
if (System.currentTimeMillis() - time > TIME_SPAN) {
int connected = 0;
for(ServerSession s : getBayeux().getSessions()) {
if (!s.isLocalSession()) {
connected++;
}
}
// Print statistics header
System.err.println();
for(Entry<String, Integer> e : messages.entrySet()) {
System.err.print(e.getKey() + ":" + e.getValue() + " ");
}
// print timestamp
System.err.println("in timespan:" + String.valueOf(System.currentTimeMillis() - time));
// Print number of users.
System.err.println("Users:" + connected);
// Print users locations.
for(Entry<String, Map<String, Set<ServerSession>>> e : pages.entrySet()) {
int total_count = 0;
System.err.print("page:\"" + e.getKey() + "\" languages:");
for(Entry<String, Set<ServerSession>> f : e.getValue().entrySet()) {
System.err.print(f.getKey() + ":" + e.getValue().size() + " ");
total_count += f.getValue().size();
}
System.err.println("total:" + total_count);
}
HashSet<ServerSession> liveSessions =
new HashSet<ServerSession>(getBayeux().getSessions());
HashSet<ServerSession> toRemove = new HashSet<ServerSession>();
for(ServerSession s : users.keySet()) {
if (!liveSessions.contains(s)) {
toRemove.add(s);
}
}
for(ServerSession s : toRemove) {
String[] lang_page = users.get(s);
Set<ServerSession> sessions = pages.get(lang_page[1]).get(lang_page[0]);
sessions.remove(s);
if (sessions.size() == 0) {
pages.remove(users.get(s));
}
users.remove(s);
}
messages = new TreeMap<String, Integer>();
time = System.currentTimeMillis();
}
}
}
| true | true | public synchronized void all(ServerSession remote, Message message) {
if (message != null) {
if (messages.containsKey(message.getChannel())) {
messages.put(message.getChannel(), messages.get(message.getChannel())+1);
} else {
messages.put(message.getChannel(), 1);
}
if (log_messages) {
System.err.println(message.getJSON());
}
Object pageObj = message.get("page");
if (pageObj instanceof String) {
String page = (String)pageObj;
// Canonic URL
page = page.startsWith("http://") ? page.substring(7) : page;
page = page.startsWith("www") ? page.substring(3) : page;
page = page.startsWith("kabbalahgroup.info/internet/") ? page.substring(28) : page;
page = page.startsWith("localhost:3000/") ? page.substring(15) : page;
String language = page.substring(0, 2);
page = page.substring(2, page.length());
page = page.startsWith("#") ? page.substring(1) : page;
Map<String, Set<ServerSession>> page_data = null;
Set<ServerSession> sessions = null;
page_data = pages.get(page);
if (page_data == null) {
page_data = new TreeMap<String, Set<ServerSession>>();
}
sessions = page_data.get(language);
if (sessions == null) {
sessions = new HashSet<ServerSession>();
}
sessions.add(remote);
page_data.put(language, sessions);
pages.put(page, page_data);
// Remove existing user from previous page.
// Check use exists and check page is different.
if (users.containsKey(remote)) {
String[] lang_page = users.get(remote);
if (lang_page == null || lang_page.length < 2 ||
lang_page[0].compareTo(language) != 0 ||
lang_page[1].compareTo(page) != 0) {
Map<String, Set<ServerSession>> pages_page_data = pages.get(users.get(remote)[1]);
Set<ServerSession> pages_sessions = pages_page_data.get(language);
pages_sessions.remove(remote);
if (pages_sessions.size() == 0) {
pages_page_data.remove(language);
if (pages_page_data.size() == 0) {
pages.remove(users.get(remote));
}
}
}
}
users.put(remote, new String[] {language, page});
}
}
update();
}
| public synchronized void all(ServerSession remote, Message message) {
if (message != null) {
if (messages.containsKey(message.getChannel())) {
messages.put(message.getChannel(), messages.get(message.getChannel())+1);
} else {
messages.put(message.getChannel(), 1);
}
if (log_messages) {
System.err.println(message.getJSON());
}
Object pageObj = message.get("page");
if (pageObj instanceof String) {
String page = (String)pageObj;
// Canonic URL
page = page.startsWith("http://") ? page.substring(7) : page;
page = page.startsWith("www") ? page.substring(3) : page;
page = page.startsWith("kabbalahgroup.info/internet/") ? page.substring(28) : page;
page = page.startsWith("localhost:3000/") ? page.substring(15) : page;
String language = page.substring(0, 2);
page = page.substring(2, page.length());
page = page.startsWith("#") ? page.substring(1) : page;
Map<String, Set<ServerSession>> page_data = null;
Set<ServerSession> sessions = null;
page_data = pages.get(page);
if (page_data == null) {
page_data = new TreeMap<String, Set<ServerSession>>();
}
sessions = page_data.get(language);
if (sessions == null) {
sessions = new HashSet<ServerSession>();
}
sessions.add(remote);
page_data.put(language, sessions);
pages.put(page, page_data);
// Remove existing user from previous page.
// Check use exists and check page is different.
if (users.containsKey(remote)) {
String[] lang_page = users.get(remote);
if (lang_page == null || lang_page.length < 2 ||
lang_page[0].compareTo(language) != 0 ||
lang_page[1].compareTo(page) != 0) {
Map<String, Set<ServerSession>> pages_page_data = pages.get(users.get(remote)[1]);
Set<ServerSession> pages_sessions = pages_page_data.get(users.get(remote)[0]);
pages_sessions.remove(remote);
if (pages_sessions.size() == 0) {
pages_page_data.remove(language);
if (pages_page_data.size() == 0) {
pages.remove(users.get(remote));
}
}
}
}
users.put(remote, new String[] {language, page});
}
}
update();
}
|
diff --git a/app/controllers/SImages.java b/app/controllers/SImages.java
index 0d1acb1..d79ce8c 100644
--- a/app/controllers/SImages.java
+++ b/app/controllers/SImages.java
@@ -1,359 +1,358 @@
package controllers;
import static play.libs.Json.toJson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonNode;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFSDBFile;
import models.*;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Results;
import play.mvc.Http.MultipartFormData.FilePart;
import scala.util.control.Exception.Finally;
import utils.GridFsHelper;
/**
* @author Muhammad Fahied
*/
public class SImages extends Controller {
public static Result fetchImagesById(String imageId) {
SGroup group = SGroup.find.filter("simages.id", imageId).get();
SImage res = null;
for (SImage p : group.simages) {
if (p.id.equals(imageId)) {
res = p;
break;
}
}
if (res == null) {
return ok("{}");
}
return ok(toJson(res));
}
public static Result fetchImagesByGroupId(String groupId) {
SGroup group = SGroup.find.byId(groupId);
List<SImage> images = group.simages;
if (images == null)
return ok("[]");
else
return ok(toJson(images));
}
//
// private static final Form<SImage> uploadForm = form(SImage.class);
//
// public static Result showBlank(){
// return ok(upload.render(uploadForm));
// }
public static Result addImage(String groupId, String taskId, String runId) {
FilePart filePart = ctx().request().body().asMultipartFormData()
.getFile("picture");
SImage image = null;
if (filePart.getFile() == null)
return ok(toJson("{status: No Image found}"));
try {
image = new SImage(filePart.getFile(), filePart.getFilename(),
filePart.getContentType(), taskId);
SGroup group = SGroup.find.byId(groupId);
if (group.simages == null) {
group.simages = new ArrayList<SImage>();
}
group.addImage(image);
group.save();
}
catch (IOException e) {
flash("uploadError", e.getMessage());
}
return ok(toJson(image));
}
public static Result teacherAddImage() {
FilePart filePart = ctx().request().body().asMultipartFormData()
.getFile("picture");
List<SImage> images = new ArrayList<SImage>();
if (filePart.getFile() == null)
return ok(toJson("{status: No Image found}"));
Set<String> taskIds = new HashSet<String>();
taskIds.add("50ab46d2300480c12ec3695d"); // spry box
taskIds.add("50ab4724300480c12ec36967"); // SYKKELPUMPE
taskIds.add("50ab4779300480c12ec36972");
// fetch 3 tasks
// create 3 images for each task
for (String taskId : taskIds) {
SImage one;
try {
one = new SImage(filePart.getFile(),
filePart.getFilename(), filePart.getContentType(),
taskId);
images.add(one);
} catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ flash("uploadError", e.getMessage());
}
}
List<SGroup> groups = SGroup.find.asList();
for (SGroup group : groups) {
if (group.simages == null) {
group.simages = new ArrayList<SImage>();
group.simages = images;
group.save();
}
}
return ok(toJson("Status Code"));
}
public static Result addTeacherImageByTaskId(String taskId) {
FilePart filePart = ctx().request().body().asMultipartFormData()
.getFile("picture");
SImage image = null;
if (filePart.getFile() == null)
return ok(toJson("{status: No Image found}"));
try {
image = new SImage(filePart.getFile(), filePart.getFilename(),
filePart.getContentType(), taskId);
final int runId = 3;
List<SGroup> groups = SGroup.find.filter("runId", runId).asList();
for (SGroup group : groups) {
if (group.simages == null) {
group.simages = new ArrayList<SImage>();
}
group.addImage(image);
group.save();
if (group.taskCompleted == null) {
group.taskCompleted = new HashSet<String>();
}
if (!group.taskCompleted.contains(taskId)) {
group.taskCompleted.add(taskId);
group.save();
}
}
} catch (IOException e) {
flash("uploadError", e.getMessage());
}
return ok(toJson(image));
}
public static Result showImage(String imageId) throws IOException {
GridFSDBFile file = GridFsHelper.getFile(imageId);
byte[] bytes = IOUtils.toByteArray(file.getInputStream());
return Results.ok(bytes).as(file.getContentType());
}
// {"imageId":"3423j342kjl23h1", "wxpos":120, "wypos":32}
public static Result updateImage() {
JsonNode node = ctx().request().body().asJson();
String imageId = node.get("id").asText();
if (SGroup.find.field("simages.id").equal(imageId).get() == null) {
return status(401, "Not Authorized");
}
int xpos = node.get("xpos").asInt();
int ypos = node.get("ypos").asInt();
Boolean isPortfolio = node.get("isPortfolio").asBoolean();
Boolean isFinalPortfolio = node.get("isFinalPortfolio").asBoolean();
Query<SGroup> query = SGroup.datastore.createQuery(SGroup.class)
.field("simages.id").equal(imageId);
UpdateOperations<SGroup> ops = SGroup.datastore
.createUpdateOperations(SGroup.class).disableValidation()
.set("simages.$.xpos", xpos).set("simages.$.ypos", ypos)
.set("simages.$.isPortfolio", isPortfolio)
.set("simages.$.isFinalPortfolio", isFinalPortfolio);
SGroup.datastore.findAndModify(query, ops);
return status(200, "OK");
}
public static Result deleteImageById(String imageId) throws MongoException,
IOException {
SGroup group = SGroup.find.filter("simages.id", imageId).get();
// Second locate the fruit and remove it:
for (SImage p : group.simages) {
if (p.id.equals(imageId)) {
// delete file from gridFS
p.deleteImage(p.fileId);
// Remove meta info and Group Document
group.simages.remove(p);
group.save();
break;
}
}
return ok("deleted successfully");
}
public static Result postCommentOnImage() {
JsonNode node = ctx().request().body().asJson();
String imageId = node.get("imageId").asText();
String content = node.get("content").asText();
// Second locate the fruit and remove it:
SComment comment = new SComment(content);
// update member of embedded object list
Query<SGroup> query = SGroup.datastore.createQuery(SGroup.class)
.field("simages.id").equal(imageId);
UpdateOperations<SGroup> ops = SGroup.datastore
.createUpdateOperations(SGroup.class).disableValidation()
.add("simages.$.scomments", comment);
SGroup group = SGroup.datastore.findAndModify(query, ops);
SImage image = null;
for (SImage p : group.simages) {
if (p.id.equals(imageId)) {
image = p;
break;
}
}
return ok(toJson(image));
}
public static Result fetchCommentsByImage(String imageId) {
SGroup group = SGroup.find.filter("simages.id", imageId).get();
List<SComment> comments = null;
for (SImage p : group.simages) {
if (p.id.equals(imageId)) {
comments = p.scomments;
break;
}
}
if (comments == null) {
return ok("[]");
}
return ok(toJson(comments));
}
public static String getFileExtension(String filePath) {
StringTokenizer stk = new StringTokenizer(filePath, ".");
String FileExt = "";
while (stk.hasMoreTokens()) {
FileExt = stk.nextToken();
}
return FileExt;
}
}
| true | true | public static Result teacherAddImage() {
FilePart filePart = ctx().request().body().asMultipartFormData()
.getFile("picture");
List<SImage> images = new ArrayList<SImage>();
if (filePart.getFile() == null)
return ok(toJson("{status: No Image found}"));
Set<String> taskIds = new HashSet<String>();
taskIds.add("50ab46d2300480c12ec3695d"); // spry box
taskIds.add("50ab4724300480c12ec36967"); // SYKKELPUMPE
taskIds.add("50ab4779300480c12ec36972");
// fetch 3 tasks
// create 3 images for each task
for (String taskId : taskIds) {
SImage one;
try {
one = new SImage(filePart.getFile(),
filePart.getFilename(), filePart.getContentType(),
taskId);
images.add(one);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
List<SGroup> groups = SGroup.find.asList();
for (SGroup group : groups) {
if (group.simages == null) {
group.simages = new ArrayList<SImage>();
group.simages = images;
group.save();
}
}
return ok(toJson("Status Code"));
}
| public static Result teacherAddImage() {
FilePart filePart = ctx().request().body().asMultipartFormData()
.getFile("picture");
List<SImage> images = new ArrayList<SImage>();
if (filePart.getFile() == null)
return ok(toJson("{status: No Image found}"));
Set<String> taskIds = new HashSet<String>();
taskIds.add("50ab46d2300480c12ec3695d"); // spry box
taskIds.add("50ab4724300480c12ec36967"); // SYKKELPUMPE
taskIds.add("50ab4779300480c12ec36972");
// fetch 3 tasks
// create 3 images for each task
for (String taskId : taskIds) {
SImage one;
try {
one = new SImage(filePart.getFile(),
filePart.getFilename(), filePart.getContentType(),
taskId);
images.add(one);
} catch (IOException e) {
flash("uploadError", e.getMessage());
}
}
List<SGroup> groups = SGroup.find.asList();
for (SGroup group : groups) {
if (group.simages == null) {
group.simages = new ArrayList<SImage>();
group.simages = images;
group.save();
}
}
return ok(toJson("Status Code"));
}
|
diff --git a/dcm4chee-arc-service/src/main/java/org/dcm4chee/archive/retrieve/CMoveSCP.java b/dcm4chee-arc-service/src/main/java/org/dcm4chee/archive/retrieve/CMoveSCP.java
index 671c98f..b40720d 100644
--- a/dcm4chee-arc-service/src/main/java/org/dcm4chee/archive/retrieve/CMoveSCP.java
+++ b/dcm4chee-arc-service/src/main/java/org/dcm4chee/archive/retrieve/CMoveSCP.java
@@ -1,156 +1,156 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at https://github.com/gunterze/dcm4che.
*
* The Initial Developer of the Original Code is
* Agfa Healthcare.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* See @authors listed below
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chee.archive.retrieve;
import static org.dcm4che.net.service.BasicRetrieveTask.Service.C_MOVE;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.EnumSet;
import java.util.List;
import org.dcm4che.conf.api.ApplicationEntityCache;
import org.dcm4che.data.Attributes;
import org.dcm4che.data.Tag;
import org.dcm4che.net.ApplicationEntity;
import org.dcm4che.net.Association;
import org.dcm4che.net.IncompatibleConnectionException;
import org.dcm4che.net.QueryOption;
import org.dcm4che.net.Status;
import org.dcm4che.net.pdu.ExtendedNegotiation;
import org.dcm4che.net.pdu.PresentationContext;
import org.dcm4che.net.service.BasicCMoveSCP;
import org.dcm4che.net.service.DicomServiceException;
import org.dcm4che.net.service.InstanceLocator;
import org.dcm4che.net.service.QueryRetrieveLevel;
import org.dcm4che.net.service.RetrieveTask;
import org.dcm4che.util.AttributesValidator;
import org.dcm4chee.archive.conf.ArchiveApplicationEntity;
import org.dcm4chee.archive.pix.PIXConsumer;
import org.dcm4chee.archive.query.util.IDWithIssuer;
import org.dcm4chee.archive.query.util.QueryParam;
import org.dcm4chee.archive.retrieve.dao.RetrieveService;
/**
* @author Gunter Zeilinger <[email protected]>
*/
public class CMoveSCP extends BasicCMoveSCP {
private final String[] qrLevels;
private final QueryRetrieveLevel rootLevel;
private final ApplicationEntityCache aeCache;
private final PIXConsumer pixConsumer;
private final RetrieveService retrieveService;
public CMoveSCP(String sopClass,
ApplicationEntityCache aeCache,
PIXConsumer pixConsumer,
RetrieveService retrieveService,
String... qrLevels) {
super(sopClass);
this.qrLevels = qrLevels;
this.rootLevel = QueryRetrieveLevel.valueOf(qrLevels[0]);
this.aeCache = aeCache;
this.pixConsumer = pixConsumer;
this.retrieveService = retrieveService;
}
@Override
protected RetrieveTask calculateMatches(Association as, PresentationContext pc,
final Attributes rq, Attributes keys) throws DicomServiceException {
AttributesValidator validator = new AttributesValidator(keys);
QueryRetrieveLevel level = QueryRetrieveLevel.valueOf(validator, qrLevels);
String cuid = rq.getString(Tag.AffectedSOPClassUID);
ExtendedNegotiation extNeg = as.getAAssociateAC().getExtNegotiationFor(cuid);
EnumSet<QueryOption> queryOpts = QueryOption.toOptions(extNeg);
boolean relational = queryOpts.contains(QueryOption.RELATIONAL);
level.validateRetrieveKeys(validator, rootLevel, relational);
try {
String dest = rq.getString(Tag.MoveDestination);
final ApplicationEntity destAE = aeCache.get(dest);
if (destAE == null)
throw new DicomServiceException(Status.MoveDestinationUnknown,
"Unknown Move Destination: " + destAE);
ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity();
ApplicationEntity sourceAE = aeCache.get(as.getRemoteAET());
QueryParam queryParam = QueryParam.valueOf(ae, queryOpts, sourceAE, roles());
IDWithIssuer pid = IDWithIssuer.pidWithIssuer(keys,
queryParam.getDefaultIssuerOfPatientID());
IDWithIssuer[] pids = pixConsumer.pixQuery(ae, pid);
List<InstanceLocator> matches =
retrieveService.calculateMatches(pids, keys, queryParam);
RetrieveTaskImpl retrieveTask = new RetrieveTaskImpl(C_MOVE, as,
pc, rq, matches, pids, pixConsumer, retrieveService, false) {
@Override
protected Association getStoreAssociation() throws DicomServiceException {
try {
return as.getApplicationEntity().connect(destAE, makeAAssociateRQ());
} catch (IOException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (InterruptedException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (IncompatibleConnectionException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (GeneralSecurityException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
}
}
};
retrieveTask.setDestinationDevice(destAE.getDevice());
retrieveTask.setSendPendingRSPInterval(ae.getSendPendingCMoveInterval());
retrieveTask.setReturnOtherPatientIDs(ae.isReturnOtherPatientIDs());
retrieveTask.setReturnOtherPatientNames(ae.isReturnOtherPatientNames());
return retrieveTask;
} catch (DicomServiceException e) {
throw e;
} catch (Exception e) {
- throw new DicomServiceException(Status.UnableToProcess, e);
+ throw new DicomServiceException(Status.UnableToCalculateNumberOfMatches, e);
}
}
private String[] roles() {
// TODO Auto-generated method stub
return null;
}
}
| true | true | protected RetrieveTask calculateMatches(Association as, PresentationContext pc,
final Attributes rq, Attributes keys) throws DicomServiceException {
AttributesValidator validator = new AttributesValidator(keys);
QueryRetrieveLevel level = QueryRetrieveLevel.valueOf(validator, qrLevels);
String cuid = rq.getString(Tag.AffectedSOPClassUID);
ExtendedNegotiation extNeg = as.getAAssociateAC().getExtNegotiationFor(cuid);
EnumSet<QueryOption> queryOpts = QueryOption.toOptions(extNeg);
boolean relational = queryOpts.contains(QueryOption.RELATIONAL);
level.validateRetrieveKeys(validator, rootLevel, relational);
try {
String dest = rq.getString(Tag.MoveDestination);
final ApplicationEntity destAE = aeCache.get(dest);
if (destAE == null)
throw new DicomServiceException(Status.MoveDestinationUnknown,
"Unknown Move Destination: " + destAE);
ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity();
ApplicationEntity sourceAE = aeCache.get(as.getRemoteAET());
QueryParam queryParam = QueryParam.valueOf(ae, queryOpts, sourceAE, roles());
IDWithIssuer pid = IDWithIssuer.pidWithIssuer(keys,
queryParam.getDefaultIssuerOfPatientID());
IDWithIssuer[] pids = pixConsumer.pixQuery(ae, pid);
List<InstanceLocator> matches =
retrieveService.calculateMatches(pids, keys, queryParam);
RetrieveTaskImpl retrieveTask = new RetrieveTaskImpl(C_MOVE, as,
pc, rq, matches, pids, pixConsumer, retrieveService, false) {
@Override
protected Association getStoreAssociation() throws DicomServiceException {
try {
return as.getApplicationEntity().connect(destAE, makeAAssociateRQ());
} catch (IOException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (InterruptedException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (IncompatibleConnectionException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (GeneralSecurityException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
}
}
};
retrieveTask.setDestinationDevice(destAE.getDevice());
retrieveTask.setSendPendingRSPInterval(ae.getSendPendingCMoveInterval());
retrieveTask.setReturnOtherPatientIDs(ae.isReturnOtherPatientIDs());
retrieveTask.setReturnOtherPatientNames(ae.isReturnOtherPatientNames());
return retrieveTask;
} catch (DicomServiceException e) {
throw e;
} catch (Exception e) {
throw new DicomServiceException(Status.UnableToProcess, e);
}
}
| protected RetrieveTask calculateMatches(Association as, PresentationContext pc,
final Attributes rq, Attributes keys) throws DicomServiceException {
AttributesValidator validator = new AttributesValidator(keys);
QueryRetrieveLevel level = QueryRetrieveLevel.valueOf(validator, qrLevels);
String cuid = rq.getString(Tag.AffectedSOPClassUID);
ExtendedNegotiation extNeg = as.getAAssociateAC().getExtNegotiationFor(cuid);
EnumSet<QueryOption> queryOpts = QueryOption.toOptions(extNeg);
boolean relational = queryOpts.contains(QueryOption.RELATIONAL);
level.validateRetrieveKeys(validator, rootLevel, relational);
try {
String dest = rq.getString(Tag.MoveDestination);
final ApplicationEntity destAE = aeCache.get(dest);
if (destAE == null)
throw new DicomServiceException(Status.MoveDestinationUnknown,
"Unknown Move Destination: " + destAE);
ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity();
ApplicationEntity sourceAE = aeCache.get(as.getRemoteAET());
QueryParam queryParam = QueryParam.valueOf(ae, queryOpts, sourceAE, roles());
IDWithIssuer pid = IDWithIssuer.pidWithIssuer(keys,
queryParam.getDefaultIssuerOfPatientID());
IDWithIssuer[] pids = pixConsumer.pixQuery(ae, pid);
List<InstanceLocator> matches =
retrieveService.calculateMatches(pids, keys, queryParam);
RetrieveTaskImpl retrieveTask = new RetrieveTaskImpl(C_MOVE, as,
pc, rq, matches, pids, pixConsumer, retrieveService, false) {
@Override
protected Association getStoreAssociation() throws DicomServiceException {
try {
return as.getApplicationEntity().connect(destAE, makeAAssociateRQ());
} catch (IOException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (InterruptedException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (IncompatibleConnectionException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
} catch (GeneralSecurityException e) {
throw new DicomServiceException(Status.UnableToPerformSubOperations, e);
}
}
};
retrieveTask.setDestinationDevice(destAE.getDevice());
retrieveTask.setSendPendingRSPInterval(ae.getSendPendingCMoveInterval());
retrieveTask.setReturnOtherPatientIDs(ae.isReturnOtherPatientIDs());
retrieveTask.setReturnOtherPatientNames(ae.isReturnOtherPatientNames());
return retrieveTask;
} catch (DicomServiceException e) {
throw e;
} catch (Exception e) {
throw new DicomServiceException(Status.UnableToCalculateNumberOfMatches, e);
}
}
|
diff --git a/core/src/ditl/cli/App.java b/core/src/ditl/cli/App.java
index 6c45f41..d46889f 100644
--- a/core/src/ditl/cli/App.java
+++ b/core/src/ditl/cli/App.java
@@ -1,127 +1,127 @@
/*******************************************************************************
* This file is part of DITL. *
* *
* Copyright (C) 2011 John Whitbeck <[email protected]> *
* *
* DITL 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. *
* *
* DITL 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 ditl.cli;
import java.io.IOException;
import org.apache.commons.cli.*;
import ditl.*;
import ditl.Store.*;
import ditl.WritableStore.AlreadyExistsException;
public abstract class App {
protected final static String offsetOption = "offset";
protected final static String origTimeUnitOption = "orig-time-unit";
protected final static String destTimeUnitOption = "dest-time-unit";
protected final static String maxTimeOption = "max-time";
protected final static String minTimeOption = "min-time";
protected final static String snapIntervalOption = "snap-interval";
protected final static String intervalOption = "interval";
protected final static String traceOption = "trace";
protected final static String outputOption = "output";
protected final static String storeOutputOption = "out-store";
protected final static String forceOption = "force";
protected final static String typeOption = "type";
protected Options options = new Options();
protected String usageString;
protected boolean showHelp = false;
protected String _name;
protected void initOptions() {}
protected abstract String getUsageString();
protected abstract void parseArgs(CommandLine cli, String[] args)
throws ParseException, ArrayIndexOutOfBoundsException, HelpException;
@SuppressWarnings("serial")
public class HelpException extends Exception {}
protected abstract void run() throws IOException, NoSuchTraceException, AlreadyExistsException, LoadTraceException;
protected void init() throws IOException {}
protected void close() throws IOException {};
public boolean ready(String name, String[] args){
_name = name;
options.addOption(new Option("h","help",false,"Print help"));
initOptions();
- usageString = "Usage: "+_name+" "+getUsageString();
+ usageString = _name+" "+getUsageString();
try {
CommandLine cli = new PosixParser().parse(options, args);
if ( cli.hasOption("help") )
throw new HelpException();
parseArgs(cli, cli.getArgs());
return true;
} catch (ParseException e) {
System.err.println(e);
printHelp();
} catch ( ArrayIndexOutOfBoundsException e){
printHelp();
} catch ( NumberFormatException nfe ){
System.err.println(nfe);
printHelp();
} catch ( HelpException he ){
printHelp();
}
return false;
}
public void exec() throws IOException {
init();
try {
run();
} catch ( Store.NoSuchTraceException mte ){
System.err.println(mte);
System.exit(1);
} catch (AlreadyExistsException e) {
System.err.println(e);
System.err.println("Use --"+forceOption+" to overwrite existing traces");
} catch (LoadTraceException e) {
System.err.println(e);
}
close();
}
protected void printHelp(){
new HelpFormatter().printHelp(usageString, options);
System.exit(1);
}
protected Long getTicsPerSecond(String timeUnit){
if ( timeUnit.equals("s") ){
return 1L;
} else if ( timeUnit.equals("ms") ){
return 1000L;
} else if ( timeUnit.equals("us") ){
return 1000000L;
} else if ( timeUnit.equals("ns") ){
return 1000000000L;
}
return null;
}
protected Double getTimeMul(Long otps, Long dtps){
if ( otps != null && dtps != null ){
return dtps.doubleValue()/otps.doubleValue();
}
return null;
}
}
| true | true | public boolean ready(String name, String[] args){
_name = name;
options.addOption(new Option("h","help",false,"Print help"));
initOptions();
usageString = "Usage: "+_name+" "+getUsageString();
try {
CommandLine cli = new PosixParser().parse(options, args);
if ( cli.hasOption("help") )
throw new HelpException();
parseArgs(cli, cli.getArgs());
return true;
} catch (ParseException e) {
System.err.println(e);
printHelp();
} catch ( ArrayIndexOutOfBoundsException e){
printHelp();
} catch ( NumberFormatException nfe ){
System.err.println(nfe);
printHelp();
} catch ( HelpException he ){
printHelp();
}
return false;
}
| public boolean ready(String name, String[] args){
_name = name;
options.addOption(new Option("h","help",false,"Print help"));
initOptions();
usageString = _name+" "+getUsageString();
try {
CommandLine cli = new PosixParser().parse(options, args);
if ( cli.hasOption("help") )
throw new HelpException();
parseArgs(cli, cli.getArgs());
return true;
} catch (ParseException e) {
System.err.println(e);
printHelp();
} catch ( ArrayIndexOutOfBoundsException e){
printHelp();
} catch ( NumberFormatException nfe ){
System.err.println(nfe);
printHelp();
} catch ( HelpException he ){
printHelp();
}
return false;
}
|
diff --git a/src/bottomUpTree/rdp/MakeSHFileRDP.java b/src/bottomUpTree/rdp/MakeSHFileRDP.java
index 8997c097..8f813cd8 100644
--- a/src/bottomUpTree/rdp/MakeSHFileRDP.java
+++ b/src/bottomUpTree/rdp/MakeSHFileRDP.java
@@ -1,58 +1,58 @@
/**
* Author: [email protected]
* This code 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,
* provided that any use properly credits the author.
* 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 at http://www.gnu.org * * */
package bottomUpTree.rdp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import utils.ConfigReader;
public class MakeSHFileRDP
{
/*
* For the ISME colorectal adenomas dataset
*/
public static void main(String[] args) throws Exception
{
File dir = new File(ConfigReader.getNinaWithDuplicatesDir() + File.separator + "rdp");
List<String> fileNames = new ArrayList<String>();
for( String s : dir.list())
fileNames.add(s);
BufferedWriter mainBatFile = new BufferedWriter(new FileWriter(new File(
dir.getAbsolutePath()+ File.separator + "runAll.sh")));
for(String s : fileNames)
if( s.endsWith("fas"))
{
File shFile =
- new File( dir.getAbsolutePath()+ File.separator + "runAll" + ".sh");
+ new File( dir.getAbsolutePath()+ File.separator + "run" + s + ".sh");
BufferedWriter aSHWriter = new BufferedWriter(new FileWriter(shFile));
aSHWriter.write("java -jar /users/afodor/rdp/rdp_classifier_2.6/dist/classifier.jar -q " +
dir.getAbsolutePath() + File.separator + s + " -o " + dir.getAbsolutePath() + File.separator + s +"_rdpOut.txt");
mainBatFile.write("qsub -N \"RunClust" + s+ "\" -q \"viper\" " + shFile.getAbsolutePath() + "\n");
aSHWriter.flush(); aSHWriter.close();
}
mainBatFile.flush(); mainBatFile.close();
}
}
| true | true | public static void main(String[] args) throws Exception
{
File dir = new File(ConfigReader.getNinaWithDuplicatesDir() + File.separator + "rdp");
List<String> fileNames = new ArrayList<String>();
for( String s : dir.list())
fileNames.add(s);
BufferedWriter mainBatFile = new BufferedWriter(new FileWriter(new File(
dir.getAbsolutePath()+ File.separator + "runAll.sh")));
for(String s : fileNames)
if( s.endsWith("fas"))
{
File shFile =
new File( dir.getAbsolutePath()+ File.separator + "runAll" + ".sh");
BufferedWriter aSHWriter = new BufferedWriter(new FileWriter(shFile));
aSHWriter.write("java -jar /users/afodor/rdp/rdp_classifier_2.6/dist/classifier.jar -q " +
dir.getAbsolutePath() + File.separator + s + " -o " + dir.getAbsolutePath() + File.separator + s +"_rdpOut.txt");
mainBatFile.write("qsub -N \"RunClust" + s+ "\" -q \"viper\" " + shFile.getAbsolutePath() + "\n");
aSHWriter.flush(); aSHWriter.close();
}
mainBatFile.flush(); mainBatFile.close();
}
| public static void main(String[] args) throws Exception
{
File dir = new File(ConfigReader.getNinaWithDuplicatesDir() + File.separator + "rdp");
List<String> fileNames = new ArrayList<String>();
for( String s : dir.list())
fileNames.add(s);
BufferedWriter mainBatFile = new BufferedWriter(new FileWriter(new File(
dir.getAbsolutePath()+ File.separator + "runAll.sh")));
for(String s : fileNames)
if( s.endsWith("fas"))
{
File shFile =
new File( dir.getAbsolutePath()+ File.separator + "run" + s + ".sh");
BufferedWriter aSHWriter = new BufferedWriter(new FileWriter(shFile));
aSHWriter.write("java -jar /users/afodor/rdp/rdp_classifier_2.6/dist/classifier.jar -q " +
dir.getAbsolutePath() + File.separator + s + " -o " + dir.getAbsolutePath() + File.separator + s +"_rdpOut.txt");
mainBatFile.write("qsub -N \"RunClust" + s+ "\" -q \"viper\" " + shFile.getAbsolutePath() + "\n");
aSHWriter.flush(); aSHWriter.close();
}
mainBatFile.flush(); mainBatFile.close();
}
|
diff --git a/plugins/org.eclipse.jst.j2ee.web/webproject/org/eclipse/jst/j2ee/internal/web/classpath/WebAppLibrariesContainer.java b/plugins/org.eclipse.jst.j2ee.web/webproject/org/eclipse/jst/j2ee/internal/web/classpath/WebAppLibrariesContainer.java
index 9c8ed29bc..4c45cd70d 100644
--- a/plugins/org.eclipse.jst.j2ee.web/webproject/org/eclipse/jst/j2ee/internal/web/classpath/WebAppLibrariesContainer.java
+++ b/plugins/org.eclipse.jst.j2ee.web/webproject/org/eclipse/jst/j2ee/internal/web/classpath/WebAppLibrariesContainer.java
@@ -1,163 +1,168 @@
/******************************************************************************
* Copyright (c) 2005-2006 BEA Systems, Inc.
* 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:
* Konstantin Komissarchik - initial API and implementation
******************************************************************************/
package org.eclipse.jst.j2ee.internal.web.classpath;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jst.common.internal.modulecore.ClasspathContainerVirtualComponent;
import org.eclipse.jst.common.jdt.internal.classpath.FlexibleProjectContainer;
import org.eclipse.jst.j2ee.internal.web.plugin.WebPlugin;
import org.eclipse.osgi.util.NLS;
import org.eclipse.wst.common.componentcore.internal.resources.VirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
/**
* @author <a href="mailto:[email protected]">Konstantin Komissarchik</a>
*/
public final class WebAppLibrariesContainer
extends FlexibleProjectContainer
{
private static final IPath[] paths
= new IPath[] { new Path( "WEB-INF/lib" ), //$NON-NLS-1$
new Path( "WEB-INF/classes" ) }; //$NON-NLS-1$
private static final PathType[] types
= new PathType[] { PathType.LIB_DIRECTORY, PathType.CLASSES_DIRECTORY };
public static final String CONTAINER_ID
= "org.eclipse.jst.j2ee.internal.web.container"; //$NON-NLS-1$
public WebAppLibrariesContainer( final IPath path,
final IJavaProject jproject )
{
super( path, jproject, getProject( path, jproject), paths, types );
}
public String getDescription()
{
if( this.owner.getProject() != this.project )
{
return NLS.bind( Resources.labelWithProject, this.project.getName() );
}
return Resources.label;
}
public void install()
{
final IJavaProject[] projects = new IJavaProject[] { this.owner };
final IClasspathContainer[] conts = new IClasspathContainer[] { this };
try
{
JavaCore.setClasspathContainer( path, projects, conts, null );
}
catch( JavaModelException e )
{
WebPlugin.log( e );
}
}
@Override
public void refresh()
{
( new WebAppLibrariesContainer( this.path, this.owner ) ).install();
}
private static Map<String, Object> referenceOptions = new HashMap<String, Object>();
static {
referenceOptions.put("GET_JAVA_REFS", Boolean.FALSE); //$NON-NLS-1$
}
protected List <IVirtualReference>consumedReferences;
@Override
protected IVirtualReference[] computeReferences(IVirtualComponent vc) {
IVirtualReference [] baseRefs = ((VirtualComponent)vc).getReferences(referenceOptions);
List <IVirtualReference> refs = new ArrayList <IVirtualReference>();
for(IVirtualReference ref: baseRefs){
if(ref.getDependencyType() == IVirtualReference.DEPENDENCY_TYPE_USES){
refs.add(ref);
} else {
if (ref.getRuntimePath().equals(paths[0].makeAbsolute())){
if(consumedReferences == null){
consumedReferences = new ArrayList<IVirtualReference>();
}
consumedReferences.add(ref);
}
}
}
return refs.toArray(new IVirtualReference[refs.size()]);
}
@Override
protected List computeClasspathEntries() {
List <IPath>entries = super.computeClasspathEntries();
if(consumedReferences != null){
for(IVirtualReference ref:consumedReferences){
if(ref.getReferencedComponent() instanceof ClasspathContainerVirtualComponent){
ClasspathContainerVirtualComponent cpvc = (ClasspathContainerVirtualComponent)ref.getReferencedComponent();
- IClasspathEntry [] newEntries = cpvc.getClasspathContainer().getClasspathEntries();
- for(IClasspathEntry entry:newEntries){
- IPath entryPath = entry.getPath();
- if(!entries.contains(entryPath)){
- entries.add(entryPath);
+ if(cpvc != null){
+ IClasspathContainer container = cpvc.getClasspathContainer();
+ if(container != null){
+ IClasspathEntry [] newEntries = container.getClasspathEntries();
+ for(IClasspathEntry entry:newEntries){
+ IPath entryPath = entry.getPath();
+ if(!entries.contains(entryPath)){
+ entries.add(entryPath);
+ }
+ }
}
}
}
}
}
return entries;
}
private static final IProject getProject( final IPath path,
final IJavaProject jproject )
{
if( path.segmentCount() == 1 )
{
return jproject.getProject();
}
final String name = path.segment( 1 );
return ResourcesPlugin.getWorkspace().getRoot().getProject( name );
}
private static final class Resources
extends NLS
{
public static String label;
public static String labelWithProject;
static
{
initializeMessages( WebAppLibrariesContainer.class.getName(),
Resources.class );
}
}
}
| true | true | protected List computeClasspathEntries() {
List <IPath>entries = super.computeClasspathEntries();
if(consumedReferences != null){
for(IVirtualReference ref:consumedReferences){
if(ref.getReferencedComponent() instanceof ClasspathContainerVirtualComponent){
ClasspathContainerVirtualComponent cpvc = (ClasspathContainerVirtualComponent)ref.getReferencedComponent();
IClasspathEntry [] newEntries = cpvc.getClasspathContainer().getClasspathEntries();
for(IClasspathEntry entry:newEntries){
IPath entryPath = entry.getPath();
if(!entries.contains(entryPath)){
entries.add(entryPath);
}
}
}
}
}
return entries;
}
| protected List computeClasspathEntries() {
List <IPath>entries = super.computeClasspathEntries();
if(consumedReferences != null){
for(IVirtualReference ref:consumedReferences){
if(ref.getReferencedComponent() instanceof ClasspathContainerVirtualComponent){
ClasspathContainerVirtualComponent cpvc = (ClasspathContainerVirtualComponent)ref.getReferencedComponent();
if(cpvc != null){
IClasspathContainer container = cpvc.getClasspathContainer();
if(container != null){
IClasspathEntry [] newEntries = container.getClasspathEntries();
for(IClasspathEntry entry:newEntries){
IPath entryPath = entry.getPath();
if(!entries.contains(entryPath)){
entries.add(entryPath);
}
}
}
}
}
}
}
return entries;
}
|
diff --git a/src/main/java/org/basex/io/serial/JSONSerializer.java b/src/main/java/org/basex/io/serial/JSONSerializer.java
index 68d76b96e..7174c322d 100644
--- a/src/main/java/org/basex/io/serial/JSONSerializer.java
+++ b/src/main/java/org/basex/io/serial/JSONSerializer.java
@@ -1,260 +1,261 @@
package org.basex.io.serial;
import static org.basex.data.DataText.*;
import static org.basex.query.util.Err.*;
import static org.basex.util.Token.*;
import java.io.*;
import org.basex.query.util.json.*;
import org.basex.query.value.item.*;
import org.basex.util.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;
/**
* This class serializes data as JSON. The input must conform to the rules
* defined in the {@link JSONConverter} class.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public final class JSONSerializer extends OutputSerializer {
/** Plural. */
private static final byte[] S = { 's' };
/** Global data type attributes. */
private static final byte[][] ATTRS = {
concat(T_BOOLEAN, S), concat(T_NUMBER, S),
concat(NULL, S), concat(T_ARRAY, S),
concat(T_OBJECT, S), concat(T_STRING, S) };
/** Supported data types. */
private static final byte[][] TYPES = {
T_BOOLEAN, T_NUMBER, NULL, T_ARRAY, T_OBJECT, T_STRING };
/** Cached data types. */
private final TokenSet[] typeCache = new TokenSet[TYPES.length];
/** Comma flag. */
private final BoolList comma = new BoolList();
/** Types. */
private final TokenList types = new TokenList();
/**
* Constructor.
* @param os output stream reference
* @param props serialization properties
* @throws IOException I/O exception
*/
public JSONSerializer(final OutputStream os, final SerializerProp props)
throws IOException {
super(os, props);
for(int t = 0; t < typeCache.length; t++) typeCache[t] = new TokenMap();
}
@Override
protected void startOpen(final byte[] name) throws IOException {
if(level == 0 && !eq(name, T_JSON))
error("<%> expected as root node", T_JSON);
types.set(level, null);
comma.set(level + 1, false);
}
@Override
protected void attribute(final byte[] name, final byte[] value) throws IOException {
if(level == 0) {
final int tl = typeCache.length;
for(int t = 0; t < tl; t++) {
if(eq(name, ATTRS[t])) {
for(final byte[] b : split(value, ' ')) typeCache[t].add(b);
return;
}
}
}
if(eq(name, T_TYPE)) {
types.set(level, value);
if(!eq(value, TYPES))
error("Element <%> has invalid type \"%\"", elem, value);
} else {
error("Element <%> has invalid attribute \"%\"", elem, name);
}
}
@Override
protected void finishOpen() throws IOException {
if(comma.get(level)) print(',');
else comma.set(level, true);
if(level > 0) {
indent(level);
final byte[] par = types.get(level - 1);
if(eq(par, T_OBJECT)) {
print('"');
print(name(elem));
print("\": ");
} else if(!eq(par, T_ARRAY)) {
error("Element <%> is typed as \"%\" and cannot be nested",
tags.get(level - 1), par);
}
}
byte[] type = types.get(level);
if(type == null) {
int t = -1;
final int tl = typeCache.length;
while(++t < tl && !typeCache[t].contains(elem));
if(t != tl) type = TYPES[t];
else type = T_STRING;
types.set(level, type);
}
if(eq(type, T_OBJECT)) {
print('{');
} else if(eq(type, T_ARRAY)) {
print('[');
} else if(level == 0) {
error("Element <%> must be typed as \"%\" or \"%\"",
T_JSON, T_OBJECT, T_ARRAY);
}
}
@Override
protected void finishText(final byte[] text) throws IOException {
final byte[] type = types.get(level - 1);
if(eq(type, T_STRING)) {
print('"');
for(final byte ch : text) code(ch);
print('"');
} else if(eq(type, T_BOOLEAN, T_NUMBER)) {
print(text);
} else if(trim(text).length != 0) {
error("Element <%> is typed as \"%\" and cannot have a value",
tags.get(level - 1), type);
}
}
@Override
protected void finishEmpty() throws IOException {
finishOpen();
final byte[] type = types.get(level);
if(eq(type, T_STRING)) {
print("\"\"");
} else if(eq(type, NULL)) {
print(NULL);
} else if(!eq(type, T_OBJECT, T_ARRAY)) {
error("Value expected for type \"%\"", type);
}
finishClose();
}
@Override
protected void finishClose() throws IOException {
final byte[] type = types.get(level);
if(eq(type, T_ARRAY)) {
indent(level);
print(']');
} else if(eq(type, T_OBJECT)) {
indent(level);
print('}');
}
}
@Override
protected void code(final int ch) throws IOException {
switch(ch) {
case '\b': print("\\b"); break;
case '\f': print("\\f"); break;
case '\n': print("\\n"); break;
case '\r': print("\\r"); break;
case '\t': print("\\t"); break;
case '"': print("\\\""); break;
case '/': print("\\/"); break;
case '\\': print("\\\\"); break;
default: print(ch); break;
}
}
@Override
protected void finishComment(final byte[] value) throws IOException {
error("Comments cannot be serialized");
}
@Override
protected void finishPi(final byte[] name, final byte[] value) throws IOException {
error("Processing instructions cannot be serialized");
}
@Override
protected void atomic(final Item value) throws IOException {
error("Atomic values cannot be serialized");
}
/**
* Prints some indentation.
* @param lvl level
* @throws IOException I/O exception
*/
void indent(final int lvl) throws IOException {
if(!indent) return;
print(nl);
final int ls = lvl * indents;
for(int l = 0; l < ls; ++l) print(tab);
}
/**
* Converts an XML element name to a JSON name.
* @param name name
* @return cached QName
*/
private static byte[] name(final byte[] name) {
// convert name to valid XML representation
final TokenBuilder tb = new TokenBuilder();
int uc = 0;
// mode: 0=normal, 1=unicode, 2=underscore, 3=building unicode
int mode = 0;
for(int n = 0; n < name.length;) {
final int cp = cp(name, n);
if(mode >= 3) {
uc = (uc << 4) + cp - (cp >= '0' && cp <= '9' ? '0' : 0x37);
if(++mode == 7) {
tb.add(uc);
mode = 0;
+ uc = 0;
}
} else if(cp == '_') {
// limit underscore counter
if(++mode == 3) {
tb.add('_');
mode = 0;
continue;
}
} else if(mode == 1) {
// unicode
mode = 3;
continue;
} else if(mode == 2) {
// underscore
tb.add('_');
mode = 0;
continue;
} else {
// normal character
tb.add(cp);
mode = 0;
}
n += cl(name, n);
}
if(mode == 2) {
tb.add('_');
} else if(mode > 0 && !tb.isEmpty()) {
tb.add('?');
}
return tb.finish();
}
/**
* Raises an error with the specified message.
* @param msg error message
* @param ext error details
* @throws IOException I/O exception
*/
private static void error(final String msg, final Object... ext) throws IOException {
throw BXJS_SER.thrwSerial(Util.inf(msg, ext));
}
}
| true | true | private static byte[] name(final byte[] name) {
// convert name to valid XML representation
final TokenBuilder tb = new TokenBuilder();
int uc = 0;
// mode: 0=normal, 1=unicode, 2=underscore, 3=building unicode
int mode = 0;
for(int n = 0; n < name.length;) {
final int cp = cp(name, n);
if(mode >= 3) {
uc = (uc << 4) + cp - (cp >= '0' && cp <= '9' ? '0' : 0x37);
if(++mode == 7) {
tb.add(uc);
mode = 0;
}
} else if(cp == '_') {
// limit underscore counter
if(++mode == 3) {
tb.add('_');
mode = 0;
continue;
}
} else if(mode == 1) {
// unicode
mode = 3;
continue;
} else if(mode == 2) {
// underscore
tb.add('_');
mode = 0;
continue;
} else {
// normal character
tb.add(cp);
mode = 0;
}
n += cl(name, n);
}
if(mode == 2) {
tb.add('_');
} else if(mode > 0 && !tb.isEmpty()) {
tb.add('?');
}
return tb.finish();
}
| private static byte[] name(final byte[] name) {
// convert name to valid XML representation
final TokenBuilder tb = new TokenBuilder();
int uc = 0;
// mode: 0=normal, 1=unicode, 2=underscore, 3=building unicode
int mode = 0;
for(int n = 0; n < name.length;) {
final int cp = cp(name, n);
if(mode >= 3) {
uc = (uc << 4) + cp - (cp >= '0' && cp <= '9' ? '0' : 0x37);
if(++mode == 7) {
tb.add(uc);
mode = 0;
uc = 0;
}
} else if(cp == '_') {
// limit underscore counter
if(++mode == 3) {
tb.add('_');
mode = 0;
continue;
}
} else if(mode == 1) {
// unicode
mode = 3;
continue;
} else if(mode == 2) {
// underscore
tb.add('_');
mode = 0;
continue;
} else {
// normal character
tb.add(cp);
mode = 0;
}
n += cl(name, n);
}
if(mode == 2) {
tb.add('_');
} else if(mode > 0 && !tb.isEmpty()) {
tb.add('?');
}
return tb.finish();
}
|
diff --git a/src/org/rascalmpl/interpreter/env/Environment.java b/src/org/rascalmpl/interpreter/env/Environment.java
index f32f5243b7..ec55b3e16e 100644
--- a/src/org/rascalmpl/interpreter/env/Environment.java
+++ b/src/org/rascalmpl/interpreter/env/Environment.java
@@ -1,769 +1,769 @@
/*******************************************************************************
* Copyright (c) 2009-2013 CWI
* 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:
* * Jurgen J. Vinju - [email protected] - CWI
* * Tijs van der Storm - [email protected]
* * Emilie Balland - (CWI)
* * Anya Helene Bagge - (UiB)
* * Paul Klint - [email protected] - CWI
* * Mark Hills - [email protected] (CWI)
* * Arnold Lankamp - [email protected]
*******************************************************************************/
package org.rascalmpl.interpreter.env;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.ISourceLocation;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeStore;
import org.rascalmpl.ast.AbstractAST;
import org.rascalmpl.ast.Name;
import org.rascalmpl.ast.QualifiedName;
import org.rascalmpl.interpreter.Evaluator;
import org.rascalmpl.interpreter.asserts.ImplementationError;
import org.rascalmpl.interpreter.result.AbstractFunction;
import org.rascalmpl.interpreter.result.ConstructorFunction;
import org.rascalmpl.interpreter.result.OverloadedFunction;
import org.rascalmpl.interpreter.result.Result;
import org.rascalmpl.interpreter.result.ResultFactory;
import org.rascalmpl.interpreter.utils.Names;
/**
* A simple environment for variables and functions and types.
* TODO: this class does not support shadowing of variables and functions yet, which is wrong.
*/
public class Environment {
// TODO: these NameFlags should also be used to implement Public & Private ??
protected static class NameFlags {
public final static int FINAL_NAME = 0x01;
public final static int OVERLOADABLE_NAME = 0x02;
private int flags = 0;
public NameFlags(int flags) {
this.flags = flags;
}
public int getFlags() {
return flags;
}
public void setFlags(int flags) {
this.flags = flags;
}
}
protected Map<String, Result<IValue>> variableEnvironment;
protected Map<String, List<AbstractFunction>> functionEnvironment;
protected Map<String,NameFlags> nameFlags;
protected Map<Type, Type> typeParameters;
protected final Environment parent;
protected final Environment callerScope;
protected ISourceLocation callerLocation; // different from the scope location (more precise)
protected final ISourceLocation loc;
protected final String name;
private Environment myRoot;
public Environment(ISourceLocation loc, String name) {
this(null, null, null, loc, name);
}
public Environment(Environment parent, ISourceLocation loc, String name) {
this(parent, null, null, loc, name);
}
public Environment(Environment parent, Environment callerScope, ISourceLocation callerLocation, ISourceLocation loc, String name) {
this.parent = parent;
if(loc == null && !(this instanceof ModuleEnvironment)) {
System.err.println("*** Environment created with empty location");
}
this.loc = loc;
this.name = name;
this.callerScope = callerScope;
this.callerLocation = callerLocation;
if (parent == this) {
throw new ImplementationError("internal error: cyclic environment");
}
}
protected Environment(Environment old) {
this.parent = old.parent;
this.loc = old.loc;
this.name = old.name;
this.callerScope = old.callerScope;
this.callerLocation = old.callerLocation;
this.variableEnvironment = old.variableEnvironment;
this.functionEnvironment = old.functionEnvironment;
this.typeParameters = old.typeParameters;
this.nameFlags = old.nameFlags;
}
/**
* @return the name of this environment/stack frame for use in tracing
*/
public String getName() {
return name;
}
/**
* @return the location where this environment was created (i.e. call site) for use in tracing
*/
public ISourceLocation getLocation() {
return loc;
}
public boolean isRootScope() {
if (!(this instanceof ModuleEnvironment)) {
return false;
}
return parent == null;
}
public boolean isRootStackFrame() {
return getCallerScope() == null;
}
/**
* Look up a variable, traversing the parents of the current scope
* until it is found.
* @param name
* @return value of variable
*/
public Result<IValue> getVariable(QualifiedName name) {
if (name.getNames().size() > 1) {
Environment current = this;
while (!current.isRootScope()) {
current = current.parent;
}
return current.getVariable(name);
}
String varName = Names.name(Names.lastName(name));
return getVariable(varName);
}
public Result<IValue> getVariable(Name name) {
return getVariable(Names.name(name));
}
public void storeVariable(QualifiedName name, Result<IValue> result) {
if (name.getNames().size() > 1) {
if (!isRootScope()) {
parent.storeVariable(name, result);
}
}
else {
String varName = Names.name(Names.lastName(name));
storeVariable(varName, result);
}
}
public Result<IValue> getSimpleVariable(QualifiedName name) {
if (name.getNames().size() > 1) {
Environment current = this;
while (!current.isRootScope()) {
current = current.parent;
}
return current.getSimpleVariable(name);
}
String varName = Names.name(Names.lastName(name));
return getSimpleVariable(varName);
}
public Result<IValue> getVariable(String name) {
Result<IValue> t = getSimpleVariable(name);
if (t != null) {
return t;
}
List<AbstractFunction> funcs = new LinkedList<AbstractFunction>();
getAllFunctions(name, funcs);
if (funcs.isEmpty()) {
return null;
}
return new OverloadedFunction(name, funcs);
}
public Result<IValue> getSimpleVariable(Name name) {
return getSimpleVariable(Names.name(name));
}
public Result<IValue> getSimpleVariable(String name) {
Result<IValue> t = null;
if (variableEnvironment != null) {
t = variableEnvironment.get(name);
}
if (t != null) {
return t;
}
if (!isRootScope()) {
return parent.getSimpleVariable(name);
}
return null;
}
public void getAllFunctions(String name, List<AbstractFunction> collection) {
if (functionEnvironment != null) {
List<AbstractFunction> locals = functionEnvironment.get(name);
if (locals != null) {
collection.addAll(locals);
}
}
if (parent != null) {
parent.getAllFunctions(name, collection);
}
}
public void getAllFunctions(Type returnType, String name, List<AbstractFunction> collection) {
if (functionEnvironment != null) {
List<AbstractFunction> locals = functionEnvironment.get(name);
if (locals != null) {
for (AbstractFunction func : locals) {
if (func.getReturnType().isSubtypeOf(returnType)) {
collection.add(func);
}
}
}
}
if (parent != null) {
parent.getAllFunctions(returnType, name, collection);
}
}
protected boolean isNameFlagged(QualifiedName name, int flags) {
if (name.getNames().size() > 1) {
Environment current = this;
while (!current.isRootScope()) {
current = current.parent;
}
return current.isNameFlagged(name, flags);
}
String simpleName = Names.name(Names.lastName(name));
return isNameFlagged(simpleName, flags);
}
protected boolean isNameFlagged(String name, int flags) {
Environment flaggingEnvironment = getFlagsEnvironment(name);
if (flaggingEnvironment == null) {
return false;
}
return flaggingEnvironment.nameFlags.containsKey(name) && (0 != (flaggingEnvironment.nameFlags.get(name).getFlags() & flags));
}
public boolean isNameFinal(QualifiedName name) {
return isNameFlagged(name, NameFlags.FINAL_NAME);
}
public boolean isNameOverloadable(QualifiedName name) {
return isNameFlagged(name, NameFlags.OVERLOADABLE_NAME);
}
protected void flagName(QualifiedName name, int flags) {
if (name.getNames().size() > 1) {
Environment current = this;
while (!current.isRootScope()) {
current = current.parent;
}
current.flagName(name, flags);
}
String simpleName = Names.name(Names.lastName(name));
flagName(simpleName, flags);
}
protected void flagName(String name, int flags) {
// NOTE: This assumption is that the environment level is already correct, i.e.,
// we are not requested to mark a name that is higher up in the hierarchy.
if (nameFlags == null) {
nameFlags = new HashMap<String,NameFlags>();
}
if (nameFlags.containsKey(name)) {
nameFlags.get(name).setFlags(nameFlags.get(name).getFlags() | flags);
}
else {
nameFlags.put(name, new NameFlags(flags));
}
}
public void markNameFinal(QualifiedName name) {
flagName(name, NameFlags.FINAL_NAME);
}
public void markNameFinal(String name) {
flagName(name, NameFlags.FINAL_NAME);
}
public void markNameOverloadable(QualifiedName name) {
flagName(name, NameFlags.OVERLOADABLE_NAME);
}
public void markNameOverloadable(String name) {
flagName(name, NameFlags.OVERLOADABLE_NAME);
}
public void storeParameterType(Type par, Type type) {
if (typeParameters == null) {
typeParameters = new HashMap<Type,Type>();
}
typeParameters.put(par, type);
}
public Type getParameterType(Type par) {
if (typeParameters != null) {
return typeParameters.get(par);
}
return null;
}
/**
* Search for the environment that declared a variable.
*/
protected Map<String,Result<IValue>> getVariableDefiningEnvironment(String name) {
if (variableEnvironment != null) {
Result<IValue> r = variableEnvironment.get(name);
if (r != null) {
return variableEnvironment;
}
}
return (parent == null) ? null : parent.getVariableDefiningEnvironment(name);
}
/**
* Search for the environment that declared a variable, but stop just above
* the module scope such that we end up in a function scope or a shell scope.
*/
private Map<String,Result<IValue>> getLocalVariableDefiningEnvironment(String name) {
if (variableEnvironment != null) {
Result<IValue> r = variableEnvironment.get(name);
if (r != null) {
return variableEnvironment;
}
}
if (parent == null || parent.isRootScope()) {
return variableEnvironment;
}
return parent.getLocalVariableDefiningEnvironment(name);
}
/**
* Store a variable the scope that it is declared in, down to the
* module scope if needed.
*/
public void storeVariable(String name, Result<IValue> value) {
//System.err.println("storeVariable: " + name + value.getValue());
Map<String,Result<IValue>> env = getVariableDefiningEnvironment(name);
if (env == null) {
// an undeclared variable, which gets an inferred type
if (variableEnvironment == null) {
variableEnvironment = new HashMap<String,Result<IValue>>();
}
variableEnvironment.put(name, value);
//System.out.println("Inferred: " + name);
if (value != null) {
// this is a dangerous design decision, even typed declared variables will not be "inferred"
// it could lead to subtle bugs
value.setInferredType(true);
}
}
else {
// a declared variable
Result<IValue> old = env.get(name);
value.setPublic(old.isPublic());
env.put(name, value);
}
}
public void declareAndStoreInferredInnerScopeVariable(String name, Result<IValue> value) {
declareVariable(value.getType(), name);
// this is dangerous to do and should be rethought, it could lead to variabled being inferred while they should not be.
value.setInferredType(true);
variableEnvironment.put(name, value);
}
/**
* Store a variable the scope that it is declared in, but not in the
* module (root) scope. This should result in storing variables in either
* the function scope or the shell scope. If a variable is not declared yet,
* this function will store it in the function scope.
*/
public void storeLocalVariable(String name, Result<IValue> value) {
Map<String,Result<IValue>> env = getLocalVariableDefiningEnvironment(name);
if (env == null) {
throw new ImplementationError("storeVariable should always find a scope");
}
Result<IValue> old = env.get(name);
if (old == null) {
value.setInferredType(true);
}
env.put(name, value);
}
public void storeVariable(Name name, Result<IValue> r) {
storeVariable(Names.name(name), r);
}
public void storeFunction(String name, AbstractFunction function) {
List<AbstractFunction> list = null;
if (functionEnvironment != null) {
list = functionEnvironment.get(name);
}
if (list == null || !this.isNameFlagged(name,NameFlags.OVERLOADABLE_NAME)) {
list = new LinkedList<AbstractFunction>();
if (functionEnvironment == null) {
functionEnvironment = new HashMap<String, List<AbstractFunction>>();
}
functionEnvironment.put(name, list);
}
list.add(function);
functionEnvironment.put(name, list);
if (function.hasResourceScheme()) {
if (getRoot() instanceof ModuleEnvironment) {
((ModuleEnvironment)getRoot()).addResourceImporter(function);
}
}
}
public boolean declareVariable(Type type, Name name) {
return declareVariable(type, Names.name(name));
}
public boolean declareVariable(Type type, String name) {
if (variableEnvironment != null) {
if (variableEnvironment.get(name) != null) {
return false;
}
}
if (variableEnvironment == null) {
variableEnvironment = new HashMap<String,Result<IValue>>();
}
variableEnvironment.put(name, ResultFactory.nothing(type));
return true;
}
public Map<Type, Type> getTypeBindings() {
Environment env = this;
Map<Type, Type> result = new HashMap<Type,Type>();
while (env != null) {
if (env.typeParameters != null) {
for (Type key : env.typeParameters.keySet()) {
if (!result.containsKey(key)) {
result.put(key, env.typeParameters.get(key));
}
}
}
env = env.parent;
}
return Collections.unmodifiableMap(result);
}
public void storeTypeBindings(Map<Type, Type> bindings) {
if (typeParameters == null) {
typeParameters = new HashMap<Type, Type>();
}
typeParameters.putAll(bindings);
}
@Override
public String toString(){
StringBuffer res = new StringBuffer();
if (functionEnvironment != null) {
for(String name : functionEnvironment.keySet()){
res.append(name).append(": ").append(functionEnvironment.get(name)).append("\n");
}
}
if (variableEnvironment != null) {
for(String name : variableEnvironment.keySet()){
res.append(name).append(": ").append(variableEnvironment.get(name)).append("\n");
}
}
return res.toString();
}
public ModuleEnvironment getImport(String moduleName) {
return getRoot().getImport(moduleName);
}
public boolean isTreeConstructorName(QualifiedName name, Type signature) {
return getRoot().isTreeConstructorName(name, signature);
}
public Environment getRoot() {
if (this.isRootScope()) {
return this;
}
if (myRoot == null) {
myRoot = parent.getRoot();
}
return myRoot;
}
public GlobalEnvironment getHeap() {
return getRoot().getHeap();
}
public Type getConstructor(Type sort, String cons, Type args) {
return getRoot().getConstructor(sort, cons, args);
}
public Type getConstructor(String cons, Type args) {
return getRoot().getConstructor(cons, args);
}
public Type getAbstractDataType(String sort) {
return getRoot().getAbstractDataType(sort);
}
public Type lookupAbstractDataType(String name) {
return getRoot().lookupAbstractDataType(name);
}
public Type lookupConcreteSyntaxType(String name) {
return getRoot().lookupConcreteSyntaxType(name);
}
public Type lookupAlias(String name) {
return getRoot().lookupAlias(name);
}
public Set<Type> lookupAlternatives(Type adt) {
return getRoot().lookupAlternatives(adt);
}
public Type lookupConstructor(Type adt, String cons, Type args) {
return getRoot().lookupConstructor(adt, cons, args);
}
public Set<Type> lookupConstructor(Type adt, String constructorName)
throws FactTypeUseException {
return getRoot().lookupConstructor(adt, constructorName);
}
public Set<Type> lookupConstructors(String constructorName) {
return getRoot().lookupConstructors(constructorName);
}
public Type lookupFirstConstructor(String cons, Type args) {
return getRoot().lookupFirstConstructor(cons, args);
}
public boolean declaresAnnotation(Type type, String label) {
return getRoot().declaresAnnotation(type, label);
}
public Type getAnnotationType(Type type, String label) {
return getRoot().getAnnotationType(type, label);
}
public void declareAnnotation(Type onType, String label, Type valueType) {
getRoot().declareAnnotation(onType, label, valueType);
}
public Type abstractDataType(String name, Type...parameters) {
return getRoot().abstractDataType(name, parameters);
}
public Type concreteSyntaxType(String name, IConstructor symbol) {
return getRoot().concreteSyntaxType(name, symbol);
}
public ConstructorFunction constructorFromTuple(AbstractAST ast, Evaluator eval, Type adt, String name, Type tupleType, List<KeywordParameter> keyargs) {
return getRoot().constructorFromTuple(ast, eval, adt, name, tupleType, keyargs);
}
public ConstructorFunction constructor(AbstractAST ast, Evaluator eval, Type nodeType, String name, List<KeywordParameter> keyargs, Object... childrenAndLabels ) {
return getRoot().constructor(ast, eval, nodeType, name, keyargs, childrenAndLabels);
}
public ConstructorFunction constructor(AbstractAST ast, Evaluator eval, Type nodeType, String name, List<KeywordParameter> keyargs, Type... children ) {
return getRoot().constructor(ast, eval, nodeType, name, keyargs, children);
}
public Type aliasType(String name, Type aliased, Type...parameters) {
return getRoot().aliasType(name, aliased, parameters);
}
public TypeStore getStore() {
return getRoot().getStore();
}
public Map<String, Result<IValue>> getVariables() {
Map<String, Result<IValue>> vars = new HashMap<String, Result<IValue>>();
if (parent != null) {
vars.putAll(parent.getVariables());
}
if (variableEnvironment != null) {
vars.putAll(variableEnvironment);
}
return vars;
}
public List<Pair<String, List<AbstractFunction>>> getFunctions() {
ArrayList<Pair<String, List<AbstractFunction>>> functions = new ArrayList<Pair<String, List<AbstractFunction>>>();
if (parent != null) {
functions.addAll(parent.getFunctions());
}
if (functionEnvironment != null) {
// don't just add the Map.Entries, as they may not live outside the iteration
for (Entry<String, List<AbstractFunction>> entry : functionEnvironment.entrySet()) {
functions.add(new Pair<String, List<AbstractFunction>>(entry.getKey(), entry.getValue()));
}
}
return functions;
}
public Environment getParent() {
return parent;
}
public Environment getCallerScope() {
if (callerScope != null) {
return callerScope;
} else if (parent != null) {
return parent.getCallerScope();
}
return null;
}
public ISourceLocation getCallerLocation() {
if (callerLocation != null) {
return callerLocation;
} else if (parent != null) {
return parent.getCallerLocation();
}
return null;
}
public Set<String> getImports() {
return getRoot().getImports();
}
public void reset() {
this.variableEnvironment = null;
this.functionEnvironment = null;
this.typeParameters = null;
this.nameFlags = null;
}
public void extend(Environment other) {
if (other.variableEnvironment != null) {
if (this.variableEnvironment == null) {
this.variableEnvironment = new HashMap<String, Result<IValue>>();
}
this.variableEnvironment.putAll(other.variableEnvironment);
}
if (other.functionEnvironment != null) {
if (this.functionEnvironment == null) {
this.functionEnvironment = new HashMap<String, List<AbstractFunction>>();
}
for (String name : other.functionEnvironment.keySet()) {
- List<AbstractFunction> functions = other.functionEnvironment.get(name);
+ List<AbstractFunction> otherFunctions = other.functionEnvironment.get(name);
- if (functions != null) {
- for (AbstractFunction function : functions) {
+ if (otherFunctions != null) {
+ for (AbstractFunction function : otherFunctions) {
storeFunction(name, function);
}
}
}
}
if (other.typeParameters != null) {
if (this.typeParameters == null) {
this.typeParameters = new HashMap<Type, Type>();
}
this.typeParameters.putAll(other.typeParameters);
}
if (other.nameFlags != null) {
if (this.nameFlags == null) {
this.nameFlags = new HashMap<String, NameFlags>();
}
this.nameFlags.putAll(other.nameFlags);
}
}
// TODO: We should have an extensible environment model that doesn't
// require this type of checking, but instead stores all the info on
// a name in one location...
protected Environment getFlagsEnvironment(String name) {
if (this.variableEnvironment != null) {
if (this.variableEnvironment.get(name) != null) {
if (this.nameFlags != null) {
if (nameFlags.get(name) != null) {
return this; // Found it at this level, return the environment
}
}
return null; // Found the name, but no flags, so return null
}
}
if (this.functionEnvironment != null) {
if (this.functionEnvironment.get(name) != null) {
if (this.nameFlags != null) {
if (nameFlags.get(name) != null) {
return this; // Found it at this level, return the environment
}
}
return null; // Found the name, but no flags, so return null
}
}
if (!isRootScope()) return parent.getFlagsEnvironment(name);
return null;
}
}
| false | true | public void extend(Environment other) {
if (other.variableEnvironment != null) {
if (this.variableEnvironment == null) {
this.variableEnvironment = new HashMap<String, Result<IValue>>();
}
this.variableEnvironment.putAll(other.variableEnvironment);
}
if (other.functionEnvironment != null) {
if (this.functionEnvironment == null) {
this.functionEnvironment = new HashMap<String, List<AbstractFunction>>();
}
for (String name : other.functionEnvironment.keySet()) {
List<AbstractFunction> functions = other.functionEnvironment.get(name);
if (functions != null) {
for (AbstractFunction function : functions) {
storeFunction(name, function);
}
}
}
}
if (other.typeParameters != null) {
if (this.typeParameters == null) {
this.typeParameters = new HashMap<Type, Type>();
}
this.typeParameters.putAll(other.typeParameters);
}
if (other.nameFlags != null) {
if (this.nameFlags == null) {
this.nameFlags = new HashMap<String, NameFlags>();
}
this.nameFlags.putAll(other.nameFlags);
}
}
| public void extend(Environment other) {
if (other.variableEnvironment != null) {
if (this.variableEnvironment == null) {
this.variableEnvironment = new HashMap<String, Result<IValue>>();
}
this.variableEnvironment.putAll(other.variableEnvironment);
}
if (other.functionEnvironment != null) {
if (this.functionEnvironment == null) {
this.functionEnvironment = new HashMap<String, List<AbstractFunction>>();
}
for (String name : other.functionEnvironment.keySet()) {
List<AbstractFunction> otherFunctions = other.functionEnvironment.get(name);
if (otherFunctions != null) {
for (AbstractFunction function : otherFunctions) {
storeFunction(name, function);
}
}
}
}
if (other.typeParameters != null) {
if (this.typeParameters == null) {
this.typeParameters = new HashMap<Type, Type>();
}
this.typeParameters.putAll(other.typeParameters);
}
if (other.nameFlags != null) {
if (this.nameFlags == null) {
this.nameFlags = new HashMap<String, NameFlags>();
}
this.nameFlags.putAll(other.nameFlags);
}
}
|
diff --git a/src/main/java/org/got5/tapestry5/jquery/internal/DefaultDataTableModel.java b/src/main/java/org/got5/tapestry5/jquery/internal/DefaultDataTableModel.java
index e9d6088a..ba6fa246 100644
--- a/src/main/java/org/got5/tapestry5/jquery/internal/DefaultDataTableModel.java
+++ b/src/main/java/org/got5/tapestry5/jquery/internal/DefaultDataTableModel.java
@@ -1,229 +1,229 @@
package org.got5.tapestry5.jquery.internal;
import java.util.ArrayList;
import java.util.List;
import org.apache.tapestry5.PropertyConduit;
import org.apache.tapestry5.PropertyOverrides;
import org.apache.tapestry5.Translator;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.grid.ColumnSort;
import org.apache.tapestry5.grid.GridDataSource;
import org.apache.tapestry5.grid.GridSortModel;
import org.apache.tapestry5.grid.SortConstraint;
import org.apache.tapestry5.internal.grid.CollectionGridDataSource;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.ioc.services.TypeCoercer;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.TranslatorSource;
import org.got5.tapestry5.jquery.DataTableConstants;
/**
* This is the default implementation of the DataTableModel
*/
public class DefaultDataTableModel implements DataTableModel {
private TypeCoercer typeCoercer;
private Request request;
private GridSortModel sortModel;
private BeanModel model;
private PropertyOverrides overrides;
private TranslatorSource translatorSource;
private JSONObject response = new JSONObject();
public DefaultDataTableModel(TypeCoercer typeCoercer,TranslatorSource translatorSource) {
super();
this.typeCoercer = typeCoercer;
this.translatorSource = translatorSource;
}
/**
* This method will filter all your data by using the search input from your datatable.
*/
public GridDataSource filterData(GridDataSource source){
final List<Object> datas = new ArrayList<Object>();
for(int index=0;index<source.getAvailableRows();index++){
boolean flag = false;
for (Object name: model.getPropertyNames())
{
PropertyConduit conduit = model.get((String) name).getConduit();
Class type = conduit.getPropertyType();
try{
String val = (String) conduit.get(source.getRowValue(index));
if(val.contains(request.getParameter(DataTableConstants.SEARCH)))
flag = true;
}
catch (Exception e){
}
}
if(flag){
datas.add(source.getRowValue(index));
}
}
return new GridDataSource() {
private CollectionGridDataSource cgds = new CollectionGridDataSource(datas);
public void prepare(int startIndex, int endIndex,
List<SortConstraint> sortConstraints) {
this.cgds.prepare(startIndex, endIndex, sortConstraints);
}
public Object getRowValue(int index) {
return this.cgds.getRowValue(index);
}
public Class getRowType() {
return this.cgds .getRowType();
}
public int getAvailableRows() {
return this.cgds.getAvailableRows();
}
};
}
/**
* This method will set all the Sorting stuffs, thanks to sSortDir and iSortCol DataTable parameters, coming from the request
*/
public void prepareResponse(GridDataSource source){
String sortingCols = request.getParameter(DataTableConstants.SORTING_COLS);
int nbSortingCols = Integer.parseInt(sortingCols);
String sord = request.getParameter(DataTableConstants.SORT_DIR+"0");
String sidx = request.getParameter(DataTableConstants.SORT_COL+"0");
if(nbSortingCols>0)
{
List<String> names = model.getPropertyNames();
int indexProperty = Integer.parseInt(sidx);
String propName = names.get(indexProperty);
ColumnSort colSort =sortModel.getColumnSort(propName);
sortModel.updateSort(propName);
}
}
/**
* methdo returning the desired data
*/
public JSONObject getResponse(GridDataSource source){
response.put("sEcho", request.getParameter(DataTableConstants.ECHO));
int records = source.getAvailableRows();
response.put("iTotalDisplayRecords", records);
response.put("iTotalRecords", records);
String displayStart = request.getParameter(DataTableConstants.DISPLAY_START);
int startIndex=Integer.parseInt(displayStart);
String displayLength = request.getParameter(DataTableConstants.DISPLAY_LENGTH);
int rowsPerPage=Integer.parseInt(displayLength);
int endIndex= startIndex + rowsPerPage -1;
if(endIndex>records-1) endIndex= records-1;
- source.prepare(startIndex,endIndex + rowsPerPage,sortModel.getSortConstraints() );
+ source.prepare(startIndex,endIndex,sortModel.getSortConstraints() );
JSONArray rows = new JSONArray();
for(int index=startIndex;index<=endIndex;index++)
{
JSONArray cell = new JSONArray();
Object obj = source.getRowValue(index);
List<String> names = model.getPropertyNames();
for (String name: names)
{
PropertyConduit conduit = model.get(name).getConduit();
Class type = conduit.getPropertyType();
String cellValue;
Object val = conduit.get(obj);
if (!String.class.equals(model.get(name).getClass())
&& !Number.class.isAssignableFrom(model.get(name).getClass()))
{
Translator<Object> translator = translatorSource.findByType(model.get(name).getPropertyType());
if (translator != null)
{
val = translator.toClient(val);
}
else
{
val = val.toString();
}
}
cell.put(val);
}
rows.put(cell);
}
response.put("aaData", rows);
return response;
}
/**
* This is the method we have to implement for the DataTableModel interface.
* This is called in the DataTable component, when the datas are loaded by ajax.
*/
public JSONObject sendResponse(Request request, GridDataSource source, BeanModel model, GridSortModel sortModel, PropertyOverrides overrides) {
this.request = request;
this.sortModel = sortModel;
this.model = model;
this.overrides = overrides;
GridDataSource s = source;
if(InternalUtils.isNonBlank(request.getParameter(DataTableConstants.SEARCH))) s = filterData(source);
prepareResponse(s);
return getResponse(s);
}
}
| true | true | public JSONObject getResponse(GridDataSource source){
response.put("sEcho", request.getParameter(DataTableConstants.ECHO));
int records = source.getAvailableRows();
response.put("iTotalDisplayRecords", records);
response.put("iTotalRecords", records);
String displayStart = request.getParameter(DataTableConstants.DISPLAY_START);
int startIndex=Integer.parseInt(displayStart);
String displayLength = request.getParameter(DataTableConstants.DISPLAY_LENGTH);
int rowsPerPage=Integer.parseInt(displayLength);
int endIndex= startIndex + rowsPerPage -1;
if(endIndex>records-1) endIndex= records-1;
source.prepare(startIndex,endIndex + rowsPerPage,sortModel.getSortConstraints() );
JSONArray rows = new JSONArray();
for(int index=startIndex;index<=endIndex;index++)
{
JSONArray cell = new JSONArray();
Object obj = source.getRowValue(index);
List<String> names = model.getPropertyNames();
for (String name: names)
{
PropertyConduit conduit = model.get(name).getConduit();
Class type = conduit.getPropertyType();
String cellValue;
Object val = conduit.get(obj);
if (!String.class.equals(model.get(name).getClass())
&& !Number.class.isAssignableFrom(model.get(name).getClass()))
{
Translator<Object> translator = translatorSource.findByType(model.get(name).getPropertyType());
if (translator != null)
{
val = translator.toClient(val);
}
else
{
val = val.toString();
}
}
cell.put(val);
}
rows.put(cell);
}
response.put("aaData", rows);
return response;
}
| public JSONObject getResponse(GridDataSource source){
response.put("sEcho", request.getParameter(DataTableConstants.ECHO));
int records = source.getAvailableRows();
response.put("iTotalDisplayRecords", records);
response.put("iTotalRecords", records);
String displayStart = request.getParameter(DataTableConstants.DISPLAY_START);
int startIndex=Integer.parseInt(displayStart);
String displayLength = request.getParameter(DataTableConstants.DISPLAY_LENGTH);
int rowsPerPage=Integer.parseInt(displayLength);
int endIndex= startIndex + rowsPerPage -1;
if(endIndex>records-1) endIndex= records-1;
source.prepare(startIndex,endIndex,sortModel.getSortConstraints() );
JSONArray rows = new JSONArray();
for(int index=startIndex;index<=endIndex;index++)
{
JSONArray cell = new JSONArray();
Object obj = source.getRowValue(index);
List<String> names = model.getPropertyNames();
for (String name: names)
{
PropertyConduit conduit = model.get(name).getConduit();
Class type = conduit.getPropertyType();
String cellValue;
Object val = conduit.get(obj);
if (!String.class.equals(model.get(name).getClass())
&& !Number.class.isAssignableFrom(model.get(name).getClass()))
{
Translator<Object> translator = translatorSource.findByType(model.get(name).getPropertyType());
if (translator != null)
{
val = translator.toClient(val);
}
else
{
val = val.toString();
}
}
cell.put(val);
}
rows.put(cell);
}
response.put("aaData", rows);
return response;
}
|
diff --git a/application/src/main/java/org/richfaces/tests/metamer/bean/RichCollapsiblePanelBean.java b/application/src/main/java/org/richfaces/tests/metamer/bean/RichCollapsiblePanelBean.java
index 4845b465..f84339bf 100644
--- a/application/src/main/java/org/richfaces/tests/metamer/bean/RichCollapsiblePanelBean.java
+++ b/application/src/main/java/org/richfaces/tests/metamer/bean/RichCollapsiblePanelBean.java
@@ -1,77 +1,78 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt 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.richfaces.tests.metamer.bean;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.richfaces.component.UICollapsiblePanel;
import org.richfaces.tests.metamer.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Managed bean for rich:collapsiblePanel.
*
* @author <a href="mailto:[email protected]">Pavol Pitonak</a>
* @version $Revision$
*/
@ManagedBean(name = "richCollapsiblePanelBean")
@ViewScoped
public class RichCollapsiblePanelBean implements Serializable {
private static final long serialVersionUID = -1L;
private static Logger logger;
private Attributes attributes;
/**
* Initializes the managed bean.
*/
@PostConstruct
public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getUIComponentAttributes(UICollapsiblePanel.class, getClass());
attributes.setAttribute("rendered", true);
attributes.setAttribute("header", "collapsible panel header");
// TODO has to be tested in another way
attributes.remove("changeExpandListener");
attributes.remove("converter");
+ attributes.remove("itemChangeListener");
// hidden attributes
attributes.remove("changeExpandListeners");
}
public Attributes getAttributes() {
return attributes;
}
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
}
| true | true | public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getUIComponentAttributes(UICollapsiblePanel.class, getClass());
attributes.setAttribute("rendered", true);
attributes.setAttribute("header", "collapsible panel header");
// TODO has to be tested in another way
attributes.remove("changeExpandListener");
attributes.remove("converter");
// hidden attributes
attributes.remove("changeExpandListeners");
}
| public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getUIComponentAttributes(UICollapsiblePanel.class, getClass());
attributes.setAttribute("rendered", true);
attributes.setAttribute("header", "collapsible panel header");
// TODO has to be tested in another way
attributes.remove("changeExpandListener");
attributes.remove("converter");
attributes.remove("itemChangeListener");
// hidden attributes
attributes.remove("changeExpandListeners");
}
|
diff --git a/simulator-ui/src/java/main/ca/nengo/ui/actions/PlotTimeSeries.java b/simulator-ui/src/java/main/ca/nengo/ui/actions/PlotTimeSeries.java
index 87796dfd..0f6bc2b4 100644
--- a/simulator-ui/src/java/main/ca/nengo/ui/actions/PlotTimeSeries.java
+++ b/simulator-ui/src/java/main/ca/nengo/ui/actions/PlotTimeSeries.java
@@ -1,119 +1,120 @@
/*
The contents of this file are subject to the Mozilla 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/MPL/
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.
The Original Code is "PlotAdvanced.java". Description:
"Action for Plotting with additional options
@author Shu Wu"
The Initial Developer of the Original Code is Bryan Tripp & Centre for Theoretical Neuroscience, University of Waterloo. Copyright (C) 2006-2008. All Rights Reserved.
Alternatively, the contents of this file may be used under the terms of the GNU
Public License license (the GPL License), in which case the provisions of GPL
License 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 License and not to allow
others to use your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice and other
provisions required by the GPL License. If you do not delete the provisions above,
a recipient may use your version of this file under either the MPL or the GPL License.
*/
package ca.nengo.ui.actions;
import ca.nengo.plot.Plotter;
import ca.nengo.ui.configurable.ConfigException;
import ca.nengo.ui.configurable.ConfigResult;
import ca.nengo.ui.configurable.Property;
import ca.nengo.ui.configurable.descriptors.PFloat;
import ca.nengo.ui.configurable.descriptors.PInt;
import ca.nengo.ui.configurable.managers.UserConfigurer;
import ca.nengo.ui.configurable.managers.ConfigManager.ConfigMode;
import ca.nengo.ui.dataList.ProbePlotHelper;
import ca.nengo.ui.lib.actions.ActionException;
import ca.nengo.ui.lib.actions.StandardAction;
import ca.nengo.ui.lib.util.UIEnvironment;
import ca.nengo.ui.lib.util.UserMessages;
import ca.nengo.util.DataUtils;
import ca.nengo.util.TimeSeries;
/**
* Action for Plotting with additional options
*
* @author Shu Wu
*/
public class PlotTimeSeries extends StandardAction {
private static final long serialVersionUID = 1L;
private TimeSeries timeSeries;
private String plotName;
private boolean showUserConfigDialog = false;
private float tauFilter;
private int subSampling;
public PlotTimeSeries(
String actionName,
TimeSeries timeSeries,
String plotName,
boolean showUserConfigDialog,
float defaultTau,
int defaultSubSampling) {
super(actionName);
this.timeSeries = timeSeries;
this.showUserConfigDialog = showUserConfigDialog;
this.plotName = plotName + " [ " + timeSeries.getName() + " ]";
this.tauFilter = defaultTau;
this.subSampling = defaultSubSampling;
}
@Override
protected void action() throws ActionException {
try {
PFloat pTauFilter = new PFloat("Time constant of display filter [0 = off]", tauFilter);
PInt pSubSampling = new PInt("Subsampling [0 = off]", subSampling);
if (showUserConfigDialog) {
ConfigResult result;
try {
result = UserConfigurer.configure(new Property[] { pTauFilter, pSubSampling },
"Plot Options",
UIEnvironment.getInstance(),
ConfigMode.TEMPLATE_NOT_CHOOSABLE);
tauFilter = (Float) result.getValue(pTauFilter);
subSampling = (Integer) result.getValue(pSubSampling);
ProbePlotHelper.getInstance().setDefaultTauFilter(tauFilter);
ProbePlotHelper.getInstance().setDefaultSubSampling(subSampling);
} catch (ConfigException e) {
e.defaultHandleBehavior();
+ return;
}
}
TimeSeries timeSeriesToShow = timeSeries;
if (subSampling != 0) {
timeSeriesToShow = DataUtils.subsample(timeSeriesToShow, subSampling);
}
if (tauFilter != 0) {
timeSeriesToShow = DataUtils.filter(timeSeriesToShow, tauFilter);
}
Plotter.plot(timeSeriesToShow, plotName);
} catch (java.lang.NumberFormatException exception) {
exception.printStackTrace();
UserMessages.showWarning("Could not parse number");
}
}
}
| true | true | protected void action() throws ActionException {
try {
PFloat pTauFilter = new PFloat("Time constant of display filter [0 = off]", tauFilter);
PInt pSubSampling = new PInt("Subsampling [0 = off]", subSampling);
if (showUserConfigDialog) {
ConfigResult result;
try {
result = UserConfigurer.configure(new Property[] { pTauFilter, pSubSampling },
"Plot Options",
UIEnvironment.getInstance(),
ConfigMode.TEMPLATE_NOT_CHOOSABLE);
tauFilter = (Float) result.getValue(pTauFilter);
subSampling = (Integer) result.getValue(pSubSampling);
ProbePlotHelper.getInstance().setDefaultTauFilter(tauFilter);
ProbePlotHelper.getInstance().setDefaultSubSampling(subSampling);
} catch (ConfigException e) {
e.defaultHandleBehavior();
}
}
TimeSeries timeSeriesToShow = timeSeries;
if (subSampling != 0) {
timeSeriesToShow = DataUtils.subsample(timeSeriesToShow, subSampling);
}
if (tauFilter != 0) {
timeSeriesToShow = DataUtils.filter(timeSeriesToShow, tauFilter);
}
Plotter.plot(timeSeriesToShow, plotName);
} catch (java.lang.NumberFormatException exception) {
exception.printStackTrace();
UserMessages.showWarning("Could not parse number");
}
}
| protected void action() throws ActionException {
try {
PFloat pTauFilter = new PFloat("Time constant of display filter [0 = off]", tauFilter);
PInt pSubSampling = new PInt("Subsampling [0 = off]", subSampling);
if (showUserConfigDialog) {
ConfigResult result;
try {
result = UserConfigurer.configure(new Property[] { pTauFilter, pSubSampling },
"Plot Options",
UIEnvironment.getInstance(),
ConfigMode.TEMPLATE_NOT_CHOOSABLE);
tauFilter = (Float) result.getValue(pTauFilter);
subSampling = (Integer) result.getValue(pSubSampling);
ProbePlotHelper.getInstance().setDefaultTauFilter(tauFilter);
ProbePlotHelper.getInstance().setDefaultSubSampling(subSampling);
} catch (ConfigException e) {
e.defaultHandleBehavior();
return;
}
}
TimeSeries timeSeriesToShow = timeSeries;
if (subSampling != 0) {
timeSeriesToShow = DataUtils.subsample(timeSeriesToShow, subSampling);
}
if (tauFilter != 0) {
timeSeriesToShow = DataUtils.filter(timeSeriesToShow, tauFilter);
}
Plotter.plot(timeSeriesToShow, plotName);
} catch (java.lang.NumberFormatException exception) {
exception.printStackTrace();
UserMessages.showWarning("Could not parse number");
}
}
|
diff --git a/src/main/org/codehaus/groovy/classgen/CompileStack.java b/src/main/org/codehaus/groovy/classgen/CompileStack.java
index cd995c3e5..8ccdb708b 100644
--- a/src/main/org/codehaus/groovy/classgen/CompileStack.java
+++ b/src/main/org/codehaus/groovy/classgen/CompileStack.java
@@ -1,626 +1,626 @@
/*
* Copyright 2003-2007 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.classgen;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.VariableScope;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import java.util.*;
/**
* This class is a helper for AsmClassGenerator. It manages
* different aspects of the code of a code block like
* handling labels, defining variables, and scopes.
* After a MethodNode is visited clear should be called, for
* initialization the method init should be used.
* <p>
* Some Notes:
* <ul>
* <li> every push method will require a later pop call
* <li> method parameters may define a category 2 variable, so
* don't ignore the type stored in the variable object
* <li> the index of the variable may not be as assumed when
* the variable is a parameter of a method because the
* parameter may be used in a closure, so don't ignore
* the stored variable index
* <li> the names of temporary variables can be ignored. The names
* are only used for debugging and do not conflict with each
* other or normal variables. For accessing, the index of the
* variable must be used.
* <li> never mix temporary and normal variables by changes to this class.
* While the name is very important for a normal variable, it is only a
* helper construct for temporary variables. That means for example a
* name for a temporary variable can be used multiple times without
* conflict. So mixing them both may lead to the problem that a normal
* or temporary variable is hidden or even removed. That must not happen!
* </ul>
*
*
* @see org.codehaus.groovy.classgen.AsmClassGenerator
* @author Jochen Theodorou
*/
public class CompileStack implements Opcodes {
/**
* @todo remove optimization of this.foo -> this.@foo
*
*/
// state flag
private boolean clear=true;
// current scope
private VariableScope scope;
// current label for continue
private Label continueLabel;
// current label for break
private Label breakLabel;
// available variables on stack
private Map stackVariables = new HashMap();
// index of the last variable on stack
private int currentVariableIndex = 1;
// index for the next variable on stack
private int nextVariableIndex = 1;
// currently temporary variables in use
private final LinkedList temporaryVariables = new LinkedList();
// overall used variables for a method/constructor
private final LinkedList usedVariables = new LinkedList();
// map containing named labels of parenting blocks
private Map superBlockNamedLabels = new HashMap();
// map containing named labels of current block
private Map currentBlockNamedLabels = new HashMap();
// list containing runnables representing a finally block
// such a block is created by synchronized or finally and
// must be called for break/continue/return
private LinkedList finallyBlocks = new LinkedList();
// a list of blocks already visiting.
private final List visitedBlocks = new LinkedList();
private Label thisStartLabel, thisEndLabel;
private MethodVisitor mv;
private BytecodeHelper helper;
// helper to handle different stack based variables
private final LinkedList stateStack = new LinkedList();
// defines the first variable index useable after
// all parameters of a method
private int localVariableOffset;
// this is used to store the goals for a "break foo" call
// in a loop where foo is a label.
private final Map namedLoopBreakLabel = new HashMap();
//this is used to store the goals for a "continue foo" call
// in a loop where foo is a label.
private final Map namedLoopContinueLabel = new HashMap();
private String className;
private class StateStackElement {
final VariableScope scope;
final Label continueLabel;
final Label breakLabel;
Label finallyLabel;
final int lastVariableIndex;
final int nextVariableIndex;
final Map stackVariables;
List temporaryVariables = new LinkedList();
List usedVariables = new LinkedList();
final Map superBlockNamedLabels;
final Map currentBlockNamedLabels;
final LinkedList finallyBlocks;
StateStackElement() {
scope = CompileStack.this.scope;
continueLabel = CompileStack.this.continueLabel;
breakLabel = CompileStack.this.breakLabel;
lastVariableIndex = CompileStack.this.currentVariableIndex;
stackVariables = CompileStack.this.stackVariables;
temporaryVariables = CompileStack.this.temporaryVariables;
nextVariableIndex = CompileStack.this.nextVariableIndex;
superBlockNamedLabels = CompileStack.this.superBlockNamedLabels;
currentBlockNamedLabels = CompileStack.this.currentBlockNamedLabels;
finallyBlocks = CompileStack.this.finallyBlocks;
}
}
protected void pushState() {
stateStack.add(new StateStackElement());
stackVariables = new HashMap(stackVariables);
finallyBlocks = new LinkedList(finallyBlocks);
}
private void popState() {
if (stateStack.size()==0) {
throw new GroovyBugError("Tried to do a pop on the compile stack without push.");
}
StateStackElement element = (StateStackElement) stateStack.removeLast();
scope = element.scope;
continueLabel = element.continueLabel;
breakLabel = element.breakLabel;
currentVariableIndex = element.lastVariableIndex;
stackVariables = element.stackVariables;
nextVariableIndex = element.nextVariableIndex;
finallyBlocks = element.finallyBlocks;
}
public Label getContinueLabel() {
return continueLabel;
}
public Label getBreakLabel() {
return breakLabel;
}
public void removeVar(int tempIndex) {
final Variable head = (Variable) temporaryVariables.removeFirst();
if (head.getIndex() != tempIndex)
throw new GroovyBugError("CompileStack#removeVar: tried to remove a temporary variable in wrong order");
currentVariableIndex = head.getPrevIndex ();
nextVariableIndex = tempIndex;
}
private void setEndLabels(){
Label endLabel = new Label();
mv.visitLabel(endLabel);
for (Iterator iter = stackVariables.values().iterator(); iter.hasNext();) {
Variable var = (Variable) iter.next();
var.setEndLabel(endLabel);
}
thisEndLabel = endLabel;
}
public void pop() {
setEndLabels();
popState();
}
public VariableScope getScope() {
return scope;
}
/**
* creates a temporary variable.
*
* @param var defines type and name
* @param store defines if the toplevel argument of the stack should be stored
* @return the index used for this temporary variable
*/
public int defineTemporaryVariable(org.codehaus.groovy.ast.Variable var, boolean store) {
return defineTemporaryVariable(var.getName(), var.getType(),store);
}
public Variable getVariable(String variableName ) {
return getVariable(variableName,true);
}
/**
* Returns a normal variable.
* <p/>
* If <code>mustExist</code> is true and the normal variable doesn't exist,
* then this method will throw a GroovyBugError. It is not the intention of
* this method to let this happen! And the exception should not be used for
* flow control - it is just acting as an assertion. If the exception is thrown
* then it indicates a bug in the class using CompileStack.
* This method can also not be used to return a temporary variable.
* Temporary variables are not normal variables.
*
* @param variableName name of the variable
* @param mustExist throw exception if variable does not exist
* @return the normal variable or null if not found (and <code>mustExist</code> not true)
*/
public Variable getVariable(String variableName, boolean mustExist) {
if (variableName.equals("this")) return Variable.THIS_VARIABLE;
if (variableName.equals("super")) return Variable.SUPER_VARIABLE;
Variable v = (Variable) stackVariables.get(variableName);
if (v == null && mustExist)
throw new GroovyBugError("tried to get a variable with the name " + variableName + " as stack variable, but a variable with this name was not created");
return v;
}
/**
* creates a temporary variable.
*
* @param name defines type and name
* @param store defines if the toplevel argument of the stack should be stored
* @return the index used for this temporary variable
*/
public int defineTemporaryVariable(String name,boolean store) {
return defineTemporaryVariable(name, ClassHelper.DYNAMIC_TYPE,store);
}
/**
* creates a temporary variable.
*
* @param name defines the name
* @param node defines the node
* @param store defines if the toplevel argument of the stack should be stored
* @return the index used for this temporary variable
*/
public int defineTemporaryVariable(String name, ClassNode node, boolean store) {
Variable answer = defineVar(name,node,false);
temporaryVariables.addFirst(answer); // TRICK: we add at the beginning so when we find for remove or get we always have the last one
usedVariables.removeLast();
if (store) mv.visitVarInsn(ASTORE, currentVariableIndex);
return answer.getIndex();
}
private void resetVariableIndex(boolean isStatic) {
if (!isStatic) {
currentVariableIndex=1;
nextVariableIndex=1;
} else {
currentVariableIndex=0;
nextVariableIndex=0;
}
}
/**
* Clears the state of the class. This method should be called
* after a MethodNode is visited. Note that a call to init will
* fail if clear is not called before
*/
public void clear() {
if (stateStack.size()>1) {
int size = stateStack.size()-1;
throw new GroovyBugError("the compile stack contains "+size+" more push instruction"+(size==1?"":"s")+" than pops.");
}
clear = true;
// br experiment with local var table so debuggers can retrieve variable names
if (true) {//AsmClassGenerator.CREATE_DEBUG_INFO) {
if (thisEndLabel==null) setEndLabels();
if (!scope.isInStaticContext()) {
// write "this"
mv.visitLocalVariable("this", className, null, thisStartLabel, thisEndLabel, 0);
}
for (Iterator iterator = usedVariables.iterator(); iterator.hasNext();) {
Variable v = (Variable) iterator.next();
String type = BytecodeHelper.getTypeDescription(v.getType());
Label start = v.getStartLabel();
Label end = v.getEndLabel();
mv.visitLocalVariable(v.getName(), type, null, start, end, v.getIndex());
}
}
pop();
stackVariables.clear();
usedVariables.clear();
scope = null;
mv=null;
resetVariableIndex(false);
superBlockNamedLabels.clear();
currentBlockNamedLabels.clear();
namedLoopBreakLabel.clear();
namedLoopContinueLabel.clear();
continueLabel=null;
breakLabel=null;
helper = null;
thisStartLabel=null;
thisEndLabel=null;
}
/**
* initializes this class for a MethodNode. This method will
- * automatically define varibales for the method parameters
- * and will create references if needed. the created variables
- * can be get by getVariable
+ * automatically define variables for the method parameters
+ * and will create references if needed. The created variables
+ * can be accessed by calling getVariable().
*
*/
protected void init(VariableScope el, Parameter[] parameters, MethodVisitor mv, ClassNode cn) {
if (!clear) throw new GroovyBugError("CompileStack#init called without calling clear before");
clear=false;
pushVariableScope(el);
this.mv = mv;
this.helper = new BytecodeHelper(mv);
defineMethodVariables(parameters,el.isInStaticContext());
this.className = BytecodeHelper.getTypeDescription(cn);
}
/**
* Causes the statestack to add an element and sets
* the given scope as new current variable scope. Creates
* a element for the state stack so pop has to be called later
*/
protected void pushVariableScope(VariableScope el) {
pushState();
scope = el;
superBlockNamedLabels = new HashMap(superBlockNamedLabels);
superBlockNamedLabels.putAll(currentBlockNamedLabels);
currentBlockNamedLabels = new HashMap();
}
/**
* Should be called when decending into a loop that defines
* also a scope. Calls pushVariableScope and prepares labels
* for a loop structure. Creates a element for the state stack
* so pop has to be called later
*/
protected void pushLoop(VariableScope el, String labelName) {
pushVariableScope(el);
initLoopLabels(labelName);
}
private void initLoopLabels(String labelName) {
continueLabel = new Label();
breakLabel = new Label();
if (labelName!=null) {
namedLoopBreakLabel.put(labelName,breakLabel);
namedLoopContinueLabel.put(labelName,continueLabel);
}
}
/**
* Should be called when decending into a loop that does
* not define a scope. Creates a element for the state stack
* so pop has to be called later
*/
protected void pushLoop(String labelName) {
pushState();
initLoopLabels(labelName);
}
/**
* Used for <code>break foo</code> inside a loop to end the
* execution of the marked loop. This method will return the
* break label of the loop if there is one found for the name.
* If not, the current break label is returned.
*/
protected Label getNamedBreakLabel(String name) {
Label label = getBreakLabel();
Label endLabel = null;
if (name!=null) endLabel = (Label) namedLoopBreakLabel.get(name);
if (endLabel!=null) label = endLabel;
return label;
}
/**
* Used for <code>continue foo</code> inside a loop to continue
* the execution of the marked loop. This method will return
* the break label of the loop if there is one found for the
* name. If not, getLabel is used.
*/
protected Label getNamedContinueLabel(String name) {
Label label = getLabel(name);
Label endLabel = null;
if (name!=null) endLabel = (Label) namedLoopContinueLabel.get(name);
if (endLabel!=null) label = endLabel;
return label;
}
/**
* Creates a new break label and a element for the state stack
* so pop has to be called later
*/
protected Label pushSwitch(){
pushState();
breakLabel = new Label();
return breakLabel;
}
/**
* because a boolean Expression may not be evaluated completly
* it is important to keep the registers clean
*/
protected void pushBooleanExpression(){
pushState();
}
private Variable defineVar(String name, ClassNode type, boolean methodParameterUsedInClosure) {
int prevCurrent = currentVariableIndex;
makeNextVariableID(type);
int index = currentVariableIndex;
if (methodParameterUsedInClosure) {
index = localVariableOffset++;
type = ClassHelper.getWrapper(type);
}
Variable answer = new Variable(index, type, name, prevCurrent);
usedVariables.add(answer);
answer.setHolder(methodParameterUsedInClosure);
return answer;
}
private void makeLocalVariablesOffset(Parameter[] paras,boolean isInStaticContext) {
resetVariableIndex(isInStaticContext);
for (int i = 0; i < paras.length; i++) {
makeNextVariableID(paras[i].getType());
}
localVariableOffset = nextVariableIndex;
resetVariableIndex(isInStaticContext);
}
private void defineMethodVariables(Parameter[] paras,boolean isInStaticContext) {
Label startLabel = new Label();
thisStartLabel = startLabel;
mv.visitLabel(startLabel);
makeLocalVariablesOffset(paras,isInStaticContext);
boolean hasHolder = false;
for (int i = 0; i < paras.length; i++) {
String name = paras[i].getName();
Variable answer;
ClassNode type = paras[i].getType();
if (paras[i].isClosureSharedVariable()) {
answer = defineVar(name, type, true);
helper.load(type,currentVariableIndex);
helper.box(type);
createReference(answer);
hasHolder = true;
} else {
answer = defineVar(name,type,false);
}
answer.setStartLabel(startLabel);
stackVariables.put(name, answer);
}
if (hasHolder) {
nextVariableIndex = localVariableOffset;
}
}
private void createReference(Variable reference) {
mv.visitTypeInsn(NEW, "groovy/lang/Reference");
mv.visitInsn(DUP_X1);
mv.visitInsn(SWAP);
mv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "<init>", "(Ljava/lang/Object;)V");
mv.visitVarInsn(ASTORE, reference.getIndex());
}
/**
* Defines a new Variable using an AST variable.
* @param initFromStack if true the last element of the
* stack will be used to initilize
* the new variable. If false null
* will be used.
*/
public Variable defineVariable(org.codehaus.groovy.ast.Variable v, boolean initFromStack) {
String name = v.getName();
Variable answer = defineVar(name,v.getType(),false);
if (v.isClosureSharedVariable()) answer.setHolder(true);
stackVariables.put(name, answer);
Label startLabel = new Label();
answer.setStartLabel(startLabel);
if (answer.isHolder()) {
if (!initFromStack) mv.visitInsn(ACONST_NULL);
createReference(answer);
} else {
if (!initFromStack) mv.visitInsn(ACONST_NULL);
mv.visitVarInsn(ASTORE, currentVariableIndex);
}
mv.visitLabel(startLabel);
return answer;
}
/**
* @param name the name of the variable of interest
* @return true if a variable is already defined
*/
public boolean containsVariable(String name) {
return stackVariables.containsKey(name);
}
/**
* Calculates the index of the next free register stores ir
* and sets the current variable index to the old value
*/
private void makeNextVariableID(ClassNode type) {
currentVariableIndex = nextVariableIndex;
if (type==ClassHelper.long_TYPE || type==ClassHelper.double_TYPE) {
nextVariableIndex++;
}
nextVariableIndex++;
}
/**
* Returns the label for the given name
*/
public Label getLabel(String name) {
if (name==null) return null;
Label l = (Label) superBlockNamedLabels.get(name);
if (l==null) l = createLocalLabel(name);
return l;
}
/**
* creates a new named label
*/
public Label createLocalLabel(String name) {
Label l = (Label) currentBlockNamedLabels.get(name);
if (l==null) {
l = new Label();
currentBlockNamedLabels.put(name,l);
}
return l;
}
public void applyFinallyBlocks(Label label, boolean isBreakLabel) {
// first find the state defining the label. That is the state
// directly after the state not knowing this label. If no state
// in the list knows that label, then the defining state is the
// current state.
StateStackElement result = null;
for (ListIterator iter = stateStack.listIterator(stateStack.size()); iter.hasPrevious();) {
StateStackElement element = (StateStackElement) iter.previous();
if (!element.currentBlockNamedLabels.values().contains(label)) {
if (isBreakLabel && element.breakLabel != label) {
result = element;
break;
}
if (!isBreakLabel && element.continueLabel != label) {
result = element;
break;
}
}
}
List blocksToRemove;
if (result==null) {
// all Blocks do know the label, so use all finally blocks
blocksToRemove = Collections.EMPTY_LIST;
} else {
blocksToRemove = result.finallyBlocks;
}
ArrayList blocks = new ArrayList(finallyBlocks);
blocks.removeAll(blocksToRemove);
applyFinallyBlocks(blocks);
}
private void applyFinallyBlocks(List blocks) {
for (Iterator iter = blocks.iterator(); iter.hasNext();) {
Runnable block = (Runnable) iter.next();
if (visitedBlocks.contains(block)) continue;
block.run();
}
}
public void applyFinallyBlocks() {
applyFinallyBlocks(finallyBlocks);
}
public boolean hasFinallyBlocks() {
return !finallyBlocks.isEmpty();
}
public void pushFinallyBlock(Runnable block) {
finallyBlocks.addFirst(block);
pushState();
}
public void popFinallyBlock() {
popState();
finallyBlocks.removeFirst();
}
public void pushFinallyBlockVisit(Runnable block) {
visitedBlocks.add(block);
}
public void popFinallyBlockVisit(Runnable block) {
visitedBlocks.remove(block);
}
}
| true | true | public void clear() {
if (stateStack.size()>1) {
int size = stateStack.size()-1;
throw new GroovyBugError("the compile stack contains "+size+" more push instruction"+(size==1?"":"s")+" than pops.");
}
clear = true;
// br experiment with local var table so debuggers can retrieve variable names
if (true) {//AsmClassGenerator.CREATE_DEBUG_INFO) {
if (thisEndLabel==null) setEndLabels();
if (!scope.isInStaticContext()) {
// write "this"
mv.visitLocalVariable("this", className, null, thisStartLabel, thisEndLabel, 0);
}
for (Iterator iterator = usedVariables.iterator(); iterator.hasNext();) {
Variable v = (Variable) iterator.next();
String type = BytecodeHelper.getTypeDescription(v.getType());
Label start = v.getStartLabel();
Label end = v.getEndLabel();
mv.visitLocalVariable(v.getName(), type, null, start, end, v.getIndex());
}
}
pop();
stackVariables.clear();
usedVariables.clear();
scope = null;
mv=null;
resetVariableIndex(false);
superBlockNamedLabels.clear();
currentBlockNamedLabels.clear();
namedLoopBreakLabel.clear();
namedLoopContinueLabel.clear();
continueLabel=null;
breakLabel=null;
helper = null;
thisStartLabel=null;
thisEndLabel=null;
}
/**
* initializes this class for a MethodNode. This method will
* automatically define varibales for the method parameters
* and will create references if needed. the created variables
* can be get by getVariable
*
*/
protected void init(VariableScope el, Parameter[] parameters, MethodVisitor mv, ClassNode cn) {
if (!clear) throw new GroovyBugError("CompileStack#init called without calling clear before");
clear=false;
pushVariableScope(el);
this.mv = mv;
this.helper = new BytecodeHelper(mv);
defineMethodVariables(parameters,el.isInStaticContext());
this.className = BytecodeHelper.getTypeDescription(cn);
}
/**
* Causes the statestack to add an element and sets
* the given scope as new current variable scope. Creates
* a element for the state stack so pop has to be called later
*/
protected void pushVariableScope(VariableScope el) {
pushState();
scope = el;
superBlockNamedLabels = new HashMap(superBlockNamedLabels);
superBlockNamedLabels.putAll(currentBlockNamedLabels);
currentBlockNamedLabels = new HashMap();
}
/**
* Should be called when decending into a loop that defines
* also a scope. Calls pushVariableScope and prepares labels
* for a loop structure. Creates a element for the state stack
* so pop has to be called later
*/
protected void pushLoop(VariableScope el, String labelName) {
pushVariableScope(el);
initLoopLabels(labelName);
}
private void initLoopLabels(String labelName) {
continueLabel = new Label();
breakLabel = new Label();
if (labelName!=null) {
namedLoopBreakLabel.put(labelName,breakLabel);
namedLoopContinueLabel.put(labelName,continueLabel);
}
}
/**
* Should be called when decending into a loop that does
* not define a scope. Creates a element for the state stack
* so pop has to be called later
*/
protected void pushLoop(String labelName) {
pushState();
initLoopLabels(labelName);
}
/**
* Used for <code>break foo</code> inside a loop to end the
* execution of the marked loop. This method will return the
* break label of the loop if there is one found for the name.
* If not, the current break label is returned.
*/
protected Label getNamedBreakLabel(String name) {
Label label = getBreakLabel();
Label endLabel = null;
if (name!=null) endLabel = (Label) namedLoopBreakLabel.get(name);
if (endLabel!=null) label = endLabel;
return label;
}
/**
* Used for <code>continue foo</code> inside a loop to continue
* the execution of the marked loop. This method will return
* the break label of the loop if there is one found for the
* name. If not, getLabel is used.
*/
protected Label getNamedContinueLabel(String name) {
Label label = getLabel(name);
Label endLabel = null;
if (name!=null) endLabel = (Label) namedLoopContinueLabel.get(name);
if (endLabel!=null) label = endLabel;
return label;
}
/**
* Creates a new break label and a element for the state stack
* so pop has to be called later
*/
protected Label pushSwitch(){
pushState();
breakLabel = new Label();
return breakLabel;
}
/**
* because a boolean Expression may not be evaluated completly
* it is important to keep the registers clean
*/
protected void pushBooleanExpression(){
pushState();
}
private Variable defineVar(String name, ClassNode type, boolean methodParameterUsedInClosure) {
int prevCurrent = currentVariableIndex;
makeNextVariableID(type);
int index = currentVariableIndex;
if (methodParameterUsedInClosure) {
index = localVariableOffset++;
type = ClassHelper.getWrapper(type);
}
Variable answer = new Variable(index, type, name, prevCurrent);
usedVariables.add(answer);
answer.setHolder(methodParameterUsedInClosure);
return answer;
}
private void makeLocalVariablesOffset(Parameter[] paras,boolean isInStaticContext) {
resetVariableIndex(isInStaticContext);
for (int i = 0; i < paras.length; i++) {
makeNextVariableID(paras[i].getType());
}
localVariableOffset = nextVariableIndex;
resetVariableIndex(isInStaticContext);
}
private void defineMethodVariables(Parameter[] paras,boolean isInStaticContext) {
Label startLabel = new Label();
thisStartLabel = startLabel;
mv.visitLabel(startLabel);
makeLocalVariablesOffset(paras,isInStaticContext);
boolean hasHolder = false;
for (int i = 0; i < paras.length; i++) {
String name = paras[i].getName();
Variable answer;
ClassNode type = paras[i].getType();
if (paras[i].isClosureSharedVariable()) {
answer = defineVar(name, type, true);
helper.load(type,currentVariableIndex);
helper.box(type);
createReference(answer);
hasHolder = true;
} else {
answer = defineVar(name,type,false);
}
answer.setStartLabel(startLabel);
stackVariables.put(name, answer);
}
if (hasHolder) {
nextVariableIndex = localVariableOffset;
}
}
private void createReference(Variable reference) {
mv.visitTypeInsn(NEW, "groovy/lang/Reference");
mv.visitInsn(DUP_X1);
mv.visitInsn(SWAP);
mv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "<init>", "(Ljava/lang/Object;)V");
mv.visitVarInsn(ASTORE, reference.getIndex());
}
/**
* Defines a new Variable using an AST variable.
* @param initFromStack if true the last element of the
* stack will be used to initilize
* the new variable. If false null
* will be used.
*/
public Variable defineVariable(org.codehaus.groovy.ast.Variable v, boolean initFromStack) {
String name = v.getName();
Variable answer = defineVar(name,v.getType(),false);
if (v.isClosureSharedVariable()) answer.setHolder(true);
stackVariables.put(name, answer);
Label startLabel = new Label();
answer.setStartLabel(startLabel);
if (answer.isHolder()) {
if (!initFromStack) mv.visitInsn(ACONST_NULL);
createReference(answer);
} else {
if (!initFromStack) mv.visitInsn(ACONST_NULL);
mv.visitVarInsn(ASTORE, currentVariableIndex);
}
mv.visitLabel(startLabel);
return answer;
}
/**
* @param name the name of the variable of interest
* @return true if a variable is already defined
*/
public boolean containsVariable(String name) {
return stackVariables.containsKey(name);
}
/**
* Calculates the index of the next free register stores ir
* and sets the current variable index to the old value
*/
private void makeNextVariableID(ClassNode type) {
currentVariableIndex = nextVariableIndex;
if (type==ClassHelper.long_TYPE || type==ClassHelper.double_TYPE) {
nextVariableIndex++;
}
nextVariableIndex++;
}
/**
* Returns the label for the given name
*/
public Label getLabel(String name) {
if (name==null) return null;
Label l = (Label) superBlockNamedLabels.get(name);
if (l==null) l = createLocalLabel(name);
return l;
}
/**
* creates a new named label
*/
public Label createLocalLabel(String name) {
Label l = (Label) currentBlockNamedLabels.get(name);
if (l==null) {
l = new Label();
currentBlockNamedLabels.put(name,l);
}
return l;
}
public void applyFinallyBlocks(Label label, boolean isBreakLabel) {
// first find the state defining the label. That is the state
// directly after the state not knowing this label. If no state
// in the list knows that label, then the defining state is the
// current state.
StateStackElement result = null;
for (ListIterator iter = stateStack.listIterator(stateStack.size()); iter.hasPrevious();) {
StateStackElement element = (StateStackElement) iter.previous();
if (!element.currentBlockNamedLabels.values().contains(label)) {
if (isBreakLabel && element.breakLabel != label) {
result = element;
break;
}
if (!isBreakLabel && element.continueLabel != label) {
result = element;
break;
}
}
}
List blocksToRemove;
if (result==null) {
// all Blocks do know the label, so use all finally blocks
blocksToRemove = Collections.EMPTY_LIST;
} else {
blocksToRemove = result.finallyBlocks;
}
ArrayList blocks = new ArrayList(finallyBlocks);
blocks.removeAll(blocksToRemove);
applyFinallyBlocks(blocks);
}
private void applyFinallyBlocks(List blocks) {
for (Iterator iter = blocks.iterator(); iter.hasNext();) {
Runnable block = (Runnable) iter.next();
if (visitedBlocks.contains(block)) continue;
block.run();
}
}
public void applyFinallyBlocks() {
applyFinallyBlocks(finallyBlocks);
}
public boolean hasFinallyBlocks() {
return !finallyBlocks.isEmpty();
}
public void pushFinallyBlock(Runnable block) {
finallyBlocks.addFirst(block);
pushState();
}
public void popFinallyBlock() {
popState();
finallyBlocks.removeFirst();
}
public void pushFinallyBlockVisit(Runnable block) {
visitedBlocks.add(block);
}
public void popFinallyBlockVisit(Runnable block) {
visitedBlocks.remove(block);
}
}
| public void clear() {
if (stateStack.size()>1) {
int size = stateStack.size()-1;
throw new GroovyBugError("the compile stack contains "+size+" more push instruction"+(size==1?"":"s")+" than pops.");
}
clear = true;
// br experiment with local var table so debuggers can retrieve variable names
if (true) {//AsmClassGenerator.CREATE_DEBUG_INFO) {
if (thisEndLabel==null) setEndLabels();
if (!scope.isInStaticContext()) {
// write "this"
mv.visitLocalVariable("this", className, null, thisStartLabel, thisEndLabel, 0);
}
for (Iterator iterator = usedVariables.iterator(); iterator.hasNext();) {
Variable v = (Variable) iterator.next();
String type = BytecodeHelper.getTypeDescription(v.getType());
Label start = v.getStartLabel();
Label end = v.getEndLabel();
mv.visitLocalVariable(v.getName(), type, null, start, end, v.getIndex());
}
}
pop();
stackVariables.clear();
usedVariables.clear();
scope = null;
mv=null;
resetVariableIndex(false);
superBlockNamedLabels.clear();
currentBlockNamedLabels.clear();
namedLoopBreakLabel.clear();
namedLoopContinueLabel.clear();
continueLabel=null;
breakLabel=null;
helper = null;
thisStartLabel=null;
thisEndLabel=null;
}
/**
* initializes this class for a MethodNode. This method will
* automatically define variables for the method parameters
* and will create references if needed. The created variables
* can be accessed by calling getVariable().
*
*/
protected void init(VariableScope el, Parameter[] parameters, MethodVisitor mv, ClassNode cn) {
if (!clear) throw new GroovyBugError("CompileStack#init called without calling clear before");
clear=false;
pushVariableScope(el);
this.mv = mv;
this.helper = new BytecodeHelper(mv);
defineMethodVariables(parameters,el.isInStaticContext());
this.className = BytecodeHelper.getTypeDescription(cn);
}
/**
* Causes the statestack to add an element and sets
* the given scope as new current variable scope. Creates
* a element for the state stack so pop has to be called later
*/
protected void pushVariableScope(VariableScope el) {
pushState();
scope = el;
superBlockNamedLabels = new HashMap(superBlockNamedLabels);
superBlockNamedLabels.putAll(currentBlockNamedLabels);
currentBlockNamedLabels = new HashMap();
}
/**
* Should be called when decending into a loop that defines
* also a scope. Calls pushVariableScope and prepares labels
* for a loop structure. Creates a element for the state stack
* so pop has to be called later
*/
protected void pushLoop(VariableScope el, String labelName) {
pushVariableScope(el);
initLoopLabels(labelName);
}
private void initLoopLabels(String labelName) {
continueLabel = new Label();
breakLabel = new Label();
if (labelName!=null) {
namedLoopBreakLabel.put(labelName,breakLabel);
namedLoopContinueLabel.put(labelName,continueLabel);
}
}
/**
* Should be called when decending into a loop that does
* not define a scope. Creates a element for the state stack
* so pop has to be called later
*/
protected void pushLoop(String labelName) {
pushState();
initLoopLabels(labelName);
}
/**
* Used for <code>break foo</code> inside a loop to end the
* execution of the marked loop. This method will return the
* break label of the loop if there is one found for the name.
* If not, the current break label is returned.
*/
protected Label getNamedBreakLabel(String name) {
Label label = getBreakLabel();
Label endLabel = null;
if (name!=null) endLabel = (Label) namedLoopBreakLabel.get(name);
if (endLabel!=null) label = endLabel;
return label;
}
/**
* Used for <code>continue foo</code> inside a loop to continue
* the execution of the marked loop. This method will return
* the break label of the loop if there is one found for the
* name. If not, getLabel is used.
*/
protected Label getNamedContinueLabel(String name) {
Label label = getLabel(name);
Label endLabel = null;
if (name!=null) endLabel = (Label) namedLoopContinueLabel.get(name);
if (endLabel!=null) label = endLabel;
return label;
}
/**
* Creates a new break label and a element for the state stack
* so pop has to be called later
*/
protected Label pushSwitch(){
pushState();
breakLabel = new Label();
return breakLabel;
}
/**
* because a boolean Expression may not be evaluated completly
* it is important to keep the registers clean
*/
protected void pushBooleanExpression(){
pushState();
}
private Variable defineVar(String name, ClassNode type, boolean methodParameterUsedInClosure) {
int prevCurrent = currentVariableIndex;
makeNextVariableID(type);
int index = currentVariableIndex;
if (methodParameterUsedInClosure) {
index = localVariableOffset++;
type = ClassHelper.getWrapper(type);
}
Variable answer = new Variable(index, type, name, prevCurrent);
usedVariables.add(answer);
answer.setHolder(methodParameterUsedInClosure);
return answer;
}
private void makeLocalVariablesOffset(Parameter[] paras,boolean isInStaticContext) {
resetVariableIndex(isInStaticContext);
for (int i = 0; i < paras.length; i++) {
makeNextVariableID(paras[i].getType());
}
localVariableOffset = nextVariableIndex;
resetVariableIndex(isInStaticContext);
}
private void defineMethodVariables(Parameter[] paras,boolean isInStaticContext) {
Label startLabel = new Label();
thisStartLabel = startLabel;
mv.visitLabel(startLabel);
makeLocalVariablesOffset(paras,isInStaticContext);
boolean hasHolder = false;
for (int i = 0; i < paras.length; i++) {
String name = paras[i].getName();
Variable answer;
ClassNode type = paras[i].getType();
if (paras[i].isClosureSharedVariable()) {
answer = defineVar(name, type, true);
helper.load(type,currentVariableIndex);
helper.box(type);
createReference(answer);
hasHolder = true;
} else {
answer = defineVar(name,type,false);
}
answer.setStartLabel(startLabel);
stackVariables.put(name, answer);
}
if (hasHolder) {
nextVariableIndex = localVariableOffset;
}
}
private void createReference(Variable reference) {
mv.visitTypeInsn(NEW, "groovy/lang/Reference");
mv.visitInsn(DUP_X1);
mv.visitInsn(SWAP);
mv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "<init>", "(Ljava/lang/Object;)V");
mv.visitVarInsn(ASTORE, reference.getIndex());
}
/**
* Defines a new Variable using an AST variable.
* @param initFromStack if true the last element of the
* stack will be used to initilize
* the new variable. If false null
* will be used.
*/
public Variable defineVariable(org.codehaus.groovy.ast.Variable v, boolean initFromStack) {
String name = v.getName();
Variable answer = defineVar(name,v.getType(),false);
if (v.isClosureSharedVariable()) answer.setHolder(true);
stackVariables.put(name, answer);
Label startLabel = new Label();
answer.setStartLabel(startLabel);
if (answer.isHolder()) {
if (!initFromStack) mv.visitInsn(ACONST_NULL);
createReference(answer);
} else {
if (!initFromStack) mv.visitInsn(ACONST_NULL);
mv.visitVarInsn(ASTORE, currentVariableIndex);
}
mv.visitLabel(startLabel);
return answer;
}
/**
* @param name the name of the variable of interest
* @return true if a variable is already defined
*/
public boolean containsVariable(String name) {
return stackVariables.containsKey(name);
}
/**
* Calculates the index of the next free register stores ir
* and sets the current variable index to the old value
*/
private void makeNextVariableID(ClassNode type) {
currentVariableIndex = nextVariableIndex;
if (type==ClassHelper.long_TYPE || type==ClassHelper.double_TYPE) {
nextVariableIndex++;
}
nextVariableIndex++;
}
/**
* Returns the label for the given name
*/
public Label getLabel(String name) {
if (name==null) return null;
Label l = (Label) superBlockNamedLabels.get(name);
if (l==null) l = createLocalLabel(name);
return l;
}
/**
* creates a new named label
*/
public Label createLocalLabel(String name) {
Label l = (Label) currentBlockNamedLabels.get(name);
if (l==null) {
l = new Label();
currentBlockNamedLabels.put(name,l);
}
return l;
}
public void applyFinallyBlocks(Label label, boolean isBreakLabel) {
// first find the state defining the label. That is the state
// directly after the state not knowing this label. If no state
// in the list knows that label, then the defining state is the
// current state.
StateStackElement result = null;
for (ListIterator iter = stateStack.listIterator(stateStack.size()); iter.hasPrevious();) {
StateStackElement element = (StateStackElement) iter.previous();
if (!element.currentBlockNamedLabels.values().contains(label)) {
if (isBreakLabel && element.breakLabel != label) {
result = element;
break;
}
if (!isBreakLabel && element.continueLabel != label) {
result = element;
break;
}
}
}
List blocksToRemove;
if (result==null) {
// all Blocks do know the label, so use all finally blocks
blocksToRemove = Collections.EMPTY_LIST;
} else {
blocksToRemove = result.finallyBlocks;
}
ArrayList blocks = new ArrayList(finallyBlocks);
blocks.removeAll(blocksToRemove);
applyFinallyBlocks(blocks);
}
private void applyFinallyBlocks(List blocks) {
for (Iterator iter = blocks.iterator(); iter.hasNext();) {
Runnable block = (Runnable) iter.next();
if (visitedBlocks.contains(block)) continue;
block.run();
}
}
public void applyFinallyBlocks() {
applyFinallyBlocks(finallyBlocks);
}
public boolean hasFinallyBlocks() {
return !finallyBlocks.isEmpty();
}
public void pushFinallyBlock(Runnable block) {
finallyBlocks.addFirst(block);
pushState();
}
public void popFinallyBlock() {
popState();
finallyBlocks.removeFirst();
}
public void pushFinallyBlockVisit(Runnable block) {
visitedBlocks.add(block);
}
public void popFinallyBlockVisit(Runnable block) {
visitedBlocks.remove(block);
}
}
|
diff --git a/src/main/java/org/elasticsearch/shell/client/DefaultClientFactory.java b/src/main/java/org/elasticsearch/shell/client/DefaultClientFactory.java
index e2e78a5..004503e 100644
--- a/src/main/java/org/elasticsearch/shell/client/DefaultClientFactory.java
+++ b/src/main/java/org/elasticsearch/shell/client/DefaultClientFactory.java
@@ -1,177 +1,177 @@
/*
* Licensed to Luca Cavanna (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.shell.client;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.elasticsearch.shell.ResourceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Cavanna
*
* Base implementation of {@link ClientFactory}
* Contains the generic elasticsearch node creation and delegates to a {@link ClientWrapper} object
* the creation of the shell specific wrapper, which depends on the script engine in use
*
* @param <ShellNativeClient> the shell native class used to represent a client within the shell
* @param <JsonInput> the shell native object that represents a json object received as input from the shell
* @param <JsonOutput> the shell native object that represents a json object that we give as output to the shell
*/
public class DefaultClientFactory<ShellNativeClient, JsonInput, JsonOutput> implements ClientFactory<ShellNativeClient> {
private static final Logger logger = LoggerFactory.getLogger(DefaultClientFactory.class);
private static final String DEFAULT_NODE_NAME = "elasticshell";
private static final String DEFAULT_CLUSTER_NAME = "elasticsearch";
private static final String DEFAULT_TRANSPORT_HOST = "localhost";
private static final int DEFAULT_TRANSPORT_PORT = 9300;
private final ClientWrapper<ShellNativeClient, JsonInput, JsonOutput> clientWrapper;
private final ResourceRegistry resourceRegistry;
private final ClientScopeSynchronizerRunner<ShellNativeClient> clientScopeSynchronizerRunner;
/**
* Creates the DefaultClientFactory given the shell scope and the scheduler
*
* @param clientWrapper the wrapper from elasticsearch client to shell native client
*/
@Inject
DefaultClientFactory(ClientWrapper<ShellNativeClient, JsonInput, JsonOutput> clientWrapper,
ResourceRegistry resourceRegistry,
ClientScopeSynchronizerRunner<ShellNativeClient> clientScopeSynchronizerRunner) {
this.clientWrapper = clientWrapper;
this.resourceRegistry = resourceRegistry;
this.clientScopeSynchronizerRunner = clientScopeSynchronizerRunner;
}
@Override
public ShellNativeClient newNodeClient() {
return newNodeClient(DEFAULT_CLUSTER_NAME);
}
/**
* Creates a new {@link org.elasticsearch.client.node.NodeClient}, wraps it into a shell {@link NodeClient},
* register it as a closeable resource to the shell scope, and optionally schedules the runnable action to
* keep the scope up-to-date for what concerns the name of the indexes and their types
*
* @param clusterName the name of the elasticsearch cluster to connect to
* @return the native client that will be used within the shell
*/
@Override
public ShellNativeClient newNodeClient(String clusterName) {
Settings settings = ImmutableSettings.settingsBuilder()
.put("node.name", DEFAULT_NODE_NAME)
.put("http.enabled", false)
.build();
Node node = NodeBuilder.nodeBuilder().clusterName(clusterName).client(true).settings(settings).build();
node.start();
//unfortunately the es clients are not type safe, need to cast itr
Client client = node.client();
- if (client instanceof org.elasticsearch.client.node.NodeClient) {
+ if (! (client instanceof org.elasticsearch.client.node.NodeClient) ) {
throw new RuntimeException("Unable to create node client: the returned node isn't a NodeClient!");
}
org.elasticsearch.client.node.NodeClient nodeClient = (org.elasticsearch.client.node.NodeClient)client;
//if clusterKo we immediately close both the client and the node that we just created
if (clusterKo(nodeClient)) {
nodeClient.close();
node.close();
return null;
}
AbstractClient<org.elasticsearch.client.node.NodeClient, JsonInput, JsonOutput> shellClient = clientWrapper.wrapEsNodeClient(node, nodeClient);
resourceRegistry.registerResource(shellClient);
ShellNativeClient shellNativeClient = clientWrapper.wrapShellClient(shellClient);
clientScopeSynchronizerRunner.startSynchronizer(shellNativeClient);
return shellNativeClient;
}
/* Should be useful if a client node is started and it's the only node in the cluster.
* It means that there is no master and the checkCluster fails */
protected boolean clusterKo(Client client) {
try {
client.admin().cluster().prepareHealth().setTimeout(TimeValue.timeValueSeconds(1)).execute().actionGet();
return false;
} catch(Exception e) {
return true;
}
}
@Override
public ShellNativeClient newTransportClient() {
return newTransportClient(new InetSocketTransportAddress(DEFAULT_TRANSPORT_HOST, DEFAULT_TRANSPORT_PORT));
}
@Override
public ShellNativeClient newTransportClient(String... addresses) {
TransportAddress[] transportAddresses = new TransportAddress[addresses.length];
for (int i = 0; i < addresses.length; i++) {
String address = addresses[i];
String[] splitAddress = address.split(":");
String host = DEFAULT_TRANSPORT_HOST;
if (splitAddress.length>=1) {
host = splitAddress[0];
}
int port = DEFAULT_TRANSPORT_PORT;
if (splitAddress.length>=2) {
try {
port = Integer.valueOf(splitAddress[1]);
} catch(NumberFormatException e) {
logger.warn("Unable to parse port [{}]", splitAddress[1], e);
}
}
transportAddresses[i] = new InetSocketTransportAddress(host, port);
}
return newTransportClient(transportAddresses);
}
protected ShellNativeClient newTransportClient(TransportAddress... addresses) {
Settings settings = ImmutableSettings.settingsBuilder().put("client.transport.ignore_cluster_name", true).build();
org.elasticsearch.client.transport.TransportClient client = new TransportClient(settings).addTransportAddresses(addresses);
//if no connected node we can already close the (useless) client
if (client.connectedNodes().size() == 0) {
client.close();
return null;
}
AbstractClient<TransportClient, JsonInput, JsonOutput> shellClient = clientWrapper.wrapEsTransportClient(client);
resourceRegistry.registerResource(shellClient);
ShellNativeClient shellNativeClient = clientWrapper.wrapShellClient(shellClient);
clientScopeSynchronizerRunner.startSynchronizer(shellNativeClient);
return shellNativeClient;
}
}
| true | true | public ShellNativeClient newNodeClient(String clusterName) {
Settings settings = ImmutableSettings.settingsBuilder()
.put("node.name", DEFAULT_NODE_NAME)
.put("http.enabled", false)
.build();
Node node = NodeBuilder.nodeBuilder().clusterName(clusterName).client(true).settings(settings).build();
node.start();
//unfortunately the es clients are not type safe, need to cast itr
Client client = node.client();
if (client instanceof org.elasticsearch.client.node.NodeClient) {
throw new RuntimeException("Unable to create node client: the returned node isn't a NodeClient!");
}
org.elasticsearch.client.node.NodeClient nodeClient = (org.elasticsearch.client.node.NodeClient)client;
//if clusterKo we immediately close both the client and the node that we just created
if (clusterKo(nodeClient)) {
nodeClient.close();
node.close();
return null;
}
AbstractClient<org.elasticsearch.client.node.NodeClient, JsonInput, JsonOutput> shellClient = clientWrapper.wrapEsNodeClient(node, nodeClient);
resourceRegistry.registerResource(shellClient);
ShellNativeClient shellNativeClient = clientWrapper.wrapShellClient(shellClient);
clientScopeSynchronizerRunner.startSynchronizer(shellNativeClient);
return shellNativeClient;
}
| public ShellNativeClient newNodeClient(String clusterName) {
Settings settings = ImmutableSettings.settingsBuilder()
.put("node.name", DEFAULT_NODE_NAME)
.put("http.enabled", false)
.build();
Node node = NodeBuilder.nodeBuilder().clusterName(clusterName).client(true).settings(settings).build();
node.start();
//unfortunately the es clients are not type safe, need to cast itr
Client client = node.client();
if (! (client instanceof org.elasticsearch.client.node.NodeClient) ) {
throw new RuntimeException("Unable to create node client: the returned node isn't a NodeClient!");
}
org.elasticsearch.client.node.NodeClient nodeClient = (org.elasticsearch.client.node.NodeClient)client;
//if clusterKo we immediately close both the client and the node that we just created
if (clusterKo(nodeClient)) {
nodeClient.close();
node.close();
return null;
}
AbstractClient<org.elasticsearch.client.node.NodeClient, JsonInput, JsonOutput> shellClient = clientWrapper.wrapEsNodeClient(node, nodeClient);
resourceRegistry.registerResource(shellClient);
ShellNativeClient shellNativeClient = clientWrapper.wrapShellClient(shellClient);
clientScopeSynchronizerRunner.startSynchronizer(shellNativeClient);
return shellNativeClient;
}
|
diff --git a/src/MPIODA.java b/src/MPIODA.java
index 330b8dd..6894014 100644
--- a/src/MPIODA.java
+++ b/src/MPIODA.java
@@ -1,338 +1,338 @@
import java.io.File;
import java.util.Vector;
import mpi.Datatype;
import util.KullBackLeibler;
import mpi.MPI;
import mpi.MPIException;
import incrementallda.IncrEstimator;
import incrementallda.MixedDataset;
import jgibblda.Document;
import jgibblda.LDACmdOption;
public class MPIODA {
static int phase;
static int[] nw, nwsum, nw_p, nwsum_p;
static int[][][] nd_p; // phases * batch * nbr_wor_in_doc
static int[][] ndsum_p;
static Vector<Integer>[][] z_p; // z[i][d] : assignment vector for the d^th document in i^th phase
static Document[][] data_p;
static int K = 10;
static int V, M;
static int basis_size = 1000;
static int batch_size = 100;
static double alpha = 50.0 / K;
static double beta = 0.1;
static double[] p;
static int[] indices; // indices of the current document for each process
static int rank;
static int size;
static int root = 0;
static int niters = 10;
public static void main(String[] args) {
MPI.Init(args);
rank = MPI.COMM_WORLD.Rank();
size = MPI.COMM_WORLD.Size();
int last_process = size-1; // process taking care of the last new batch of data
int next_process = 0; // process that are going to taking care of the new batch of data
/**
* Declare data only initialized by root process
*/
MixedDataset dataset = null;
int[] parameters = new int[2];
Object[] data = null;
double[] theta_all = null;
int[] indices_all = null;
/**
* Initialize data for root process
*/
if (rank == root) {
String dir = "/home/larsen/idea-IC-107.587/Online-Document-Aligner/corpus/lda";
dataset = MixedDataset.readDataSet(dir + File.separator + "en_2005_02.bag", dir + File.separator + "ensy_2005_02.bag");
parameters[0] = dataset.V;
parameters[1] = dataset.M;
data = dataset.docs;
theta_all = new double[basis_size*K];
indices_all = new int[basis_size];
}
/**
* Broadcast and scatter data to other processes
*/
MPI.COMM_WORLD.Bcast(parameters, 0, parameters.length, MPI.INT, root);
V = parameters[0];
M = parameters[1];
int num_batch = (M - (basis_size - batch_size)) / batch_size;
int phase_size = M / basis_size;
nd_p = new int[phase_size][batch_size][K];
ndsum_p = new int[phase_size][batch_size];
z_p = new Vector[phase_size][batch_size];
data_p = new Document[phase_size][batch_size];
nw = new int[V*K];
nwsum = new int[K];
p = new double[K];
for (int phase = 0; phase < phase_size; phase++) {
Object[] data_p_local = new Object[batch_size];
MPI.COMM_WORLD.Scatter(data, phase*basis_size, batch_size, MPI.OBJECT, data_p_local, 0, batch_size, MPI.OBJECT, root);
for (int i = 0; i < batch_size; i++)
data_p[phase][i] = (Document) data_p_local[i];
}
/**
* Initialize:
* Calculate nw_p and nwsum_p and distribute them to all processes
*/
phase = 0;
nw_p = new int[V*K];
nwsum_p = new int[K];
initialSample(true);
indices = computeIndices();
MPI.COMM_WORLD.Allreduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM);
MPI.COMM_WORLD.Allreduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM);
/**
* Start Estimation
*/
for (int batch = 0; batch < num_batch; batch++) {
if (rank == root)
System.out.println("Processing on basis documents, with " + batch + " batches added and removed.");
/**
* Sample
*/
for (int iter = 0; iter < (batch==0 ? niters*size : niters); iter++) {
/**
* Clear the number of instances of a word assigned to a topic,
* and also the number of words assigned to a topic.
*/
nw_p = new int[V*K];
nwsum_p = new int[K];
/**
* Sample
*/
for (int m = 0; m < batch_size; m++){
for (int n = 0; n < z_p[phase][m].size(); n++){
int topic = sample(m,n);
z_p[phase][m].set(n, topic);
}// end for each word
}// end for each document
/**
* If it's the last round of sampling, remove the previous batch from the next process so it's ready
* to receive new batch.
*/
if (iter == (batch==0 ? niters*size : niters) - 1) {
if (next_process == rank) {
nw_p = new int[V*K];
nwsum_p = new int[K];
}
MPI.COMM_WORLD.Reduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM, next_process);
MPI.COMM_WORLD.Reduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM, next_process);
} else {
/**
* Update nw and nwsum for all processes
*/
MPI.COMM_WORLD.Allreduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM);
MPI.COMM_WORLD.Allreduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM);
}
}
/**
* Compute best matches for the current batch by sending necessary info to root process
*/
double[] theta = computeTheta();
MPI.COMM_WORLD.Gather(theta, 0, K*batch_size, MPI.DOUBLE, theta_all, 0, K*batch_size, MPI.DOUBLE, root);
MPI.COMM_WORLD.Gather(indices, 0, batch_size, MPI.INT, indices_all, 0, batch_size, MPI.INT, root);
/**
* Represent result for the batch by use of root process
*/
if (rank == root) {
representResult(batch, theta_all, last_process, dataset, indices_all);
}
/*
- Reassign the oldest process to the new batch and update nw for all processes
+ Reassign the next process to the new batch and update nw for all processes
*/
if (rank == next_process) {
phase++;
initialSample(false);
indices = computeIndices();
System.out.println("Process " + rank + " takes the lead");
}
MPI.COMM_WORLD.Bcast(nw, 0, V*K, MPI.INT, next_process);
/**
* Shift the processes
*/
last_process = (last_process + 1) % size;
next_process = (next_process + 1) % size;
}
MPI.Finalize();
}
/*
Returns the document indices from the current working batch
*/
private static int[] computeIndices() {
int[] ret = new int[batch_size];
for (int i = 0; i < batch_size; i++) {
ret[i] = data_p[phase][i].index;
}
return ret;
}
private static void initialSample(boolean first_sampling) {
for (int m = 0; m < batch_size; m++){
int N = data_p[phase][m].length;
z_p[phase][m] = new Vector<Integer>();
//initiliaze for z_p
for (int n = 0; n < N; n++){
int topic = (int)Math.floor(Math.random() * K);
z_p[phase][m].add(topic);
// number of instances of word assigned to topic j
int w = data_p[phase][m].words[n];
if (first_sampling)
nw_p[topic*V + w] += 1;
else
nw[topic*V + w] += 1;
// number of words in document i assigned to topic j
nd_p[phase][m][topic] += 1;
if (first_sampling)
nwsum_p[topic] += 1;
else
nwsum[topic] += 1;
}
// total number of words in document i
ndsum_p[phase][m] = N;
}
}
public static int sample(int m, int n){
/**
* Remove z_i from the count variable
*/
int topic = z_p[phase][m].get(n);
int w = data_p[phase][m].words[n];
nw[w+topic*V] -= 1;
nd_p[phase][m][topic] -= 1;
nwsum[topic] -= 1;
ndsum_p[phase][m] -= 1;
double Vbeta = V * beta;
double Kalpha = K * alpha;
/**
* Do multinominal sampling via cumulative method
*/
for (int k = 0; k < K; k++) {
p[k] = (nw[w+k*V] + beta)/(nwsum[k] + Vbeta) *
(nd_p[phase][m][k] + alpha)/(ndsum_p[phase][m] + Kalpha);
}
/**
* Cumulate multinomial parameters
*/
for (int k = 1; k < K; k++){
p[k] += p[k - 1];
}
/**
* Scaled sample because of unnormalized p[]
*/
double u = Math.random() * p[K - 1];
/**
* Sample topic w.r.t distribution p
*/
for (topic = 0; topic < K; topic++){
if (p[topic] > u)
break;
}
/**
* Add newly estimated z_i to count variables
*/
nw[w+V*topic] += 1;
nd_p[phase][m][topic] += 1;
nwsum[topic] += 1;
ndsum_p[phase][m] += 1;
nw_p[w+V*topic] += 1;
nwsum_p[topic] += 1;
return topic;
}
public static double[] computeTheta(){
double[] ret = new double[batch_size*K];
for (int m = 0; m < batch_size; m++){
for (int k = 0; k < K; k++){
ret[m*K+k] = (nd_p[phase][m][k] + alpha) / (ndsum_p[phase][m] + K * alpha);
}
}
return ret;
}
private static double[][] getTheta2d(double[] theta_all){
double[][] theta = new double[basis_size][K]; // 2d representation of theta_all
for (int i = 0; i < basis_size; i++) {
for (int k = 0; k < K; k++) {
theta[i][k] = theta_all[k+i*K];
}
}
return theta;
}
private static void representResult(int batch, double[] theta_all, int last_process, MixedDataset dataset,
int[] indices_all){
double[][] theta2d = getTheta2d(theta_all);
int start_q = batch==0 ? 0 : batch_size*last_process;
int end_q = batch==0 ? basis_size : batch_size*(last_process+1);
for (int q = start_q; q < end_q; q++) {
double min_div = Double.MAX_VALUE;
int best = -1;
for (int c = 0; c < basis_size; c++) {
/**
* If it's the same document, skip it
*/
if (c == q)
continue;
/**
* If it's the same language, skip it
*/
if (dataset.type[indices_all[c]] == dataset.type[indices_all[q]])
continue;
/**
* Else caluclate the similarities between the documents
*/
double js_div = KullBackLeibler.sym_divergence(theta2d[c], theta2d[q]);
if (js_div < min_div) {
min_div = js_div;
best = c;
}
}
/**
* If they are similiar, show it.
*/
if (min_div < 0.005) {
System.out.println("======================================");
System.out.println("Score for (" + indices_all[q] + ", " + indices_all[best] + ") = " + min_div);
System.out.println("--------------------------------------");
System.out.println(dataset.getRawDoc(indices_all[q]));
System.out.println("--------------------------------------");
System.out.println(dataset.getRawDoc(indices_all[best]));
System.out.println("======================================");
}
}
}
}
| true | true | public static void main(String[] args) {
MPI.Init(args);
rank = MPI.COMM_WORLD.Rank();
size = MPI.COMM_WORLD.Size();
int last_process = size-1; // process taking care of the last new batch of data
int next_process = 0; // process that are going to taking care of the new batch of data
/**
* Declare data only initialized by root process
*/
MixedDataset dataset = null;
int[] parameters = new int[2];
Object[] data = null;
double[] theta_all = null;
int[] indices_all = null;
/**
* Initialize data for root process
*/
if (rank == root) {
String dir = "/home/larsen/idea-IC-107.587/Online-Document-Aligner/corpus/lda";
dataset = MixedDataset.readDataSet(dir + File.separator + "en_2005_02.bag", dir + File.separator + "ensy_2005_02.bag");
parameters[0] = dataset.V;
parameters[1] = dataset.M;
data = dataset.docs;
theta_all = new double[basis_size*K];
indices_all = new int[basis_size];
}
/**
* Broadcast and scatter data to other processes
*/
MPI.COMM_WORLD.Bcast(parameters, 0, parameters.length, MPI.INT, root);
V = parameters[0];
M = parameters[1];
int num_batch = (M - (basis_size - batch_size)) / batch_size;
int phase_size = M / basis_size;
nd_p = new int[phase_size][batch_size][K];
ndsum_p = new int[phase_size][batch_size];
z_p = new Vector[phase_size][batch_size];
data_p = new Document[phase_size][batch_size];
nw = new int[V*K];
nwsum = new int[K];
p = new double[K];
for (int phase = 0; phase < phase_size; phase++) {
Object[] data_p_local = new Object[batch_size];
MPI.COMM_WORLD.Scatter(data, phase*basis_size, batch_size, MPI.OBJECT, data_p_local, 0, batch_size, MPI.OBJECT, root);
for (int i = 0; i < batch_size; i++)
data_p[phase][i] = (Document) data_p_local[i];
}
/**
* Initialize:
* Calculate nw_p and nwsum_p and distribute them to all processes
*/
phase = 0;
nw_p = new int[V*K];
nwsum_p = new int[K];
initialSample(true);
indices = computeIndices();
MPI.COMM_WORLD.Allreduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM);
MPI.COMM_WORLD.Allreduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM);
/**
* Start Estimation
*/
for (int batch = 0; batch < num_batch; batch++) {
if (rank == root)
System.out.println("Processing on basis documents, with " + batch + " batches added and removed.");
/**
* Sample
*/
for (int iter = 0; iter < (batch==0 ? niters*size : niters); iter++) {
/**
* Clear the number of instances of a word assigned to a topic,
* and also the number of words assigned to a topic.
*/
nw_p = new int[V*K];
nwsum_p = new int[K];
/**
* Sample
*/
for (int m = 0; m < batch_size; m++){
for (int n = 0; n < z_p[phase][m].size(); n++){
int topic = sample(m,n);
z_p[phase][m].set(n, topic);
}// end for each word
}// end for each document
/**
* If it's the last round of sampling, remove the previous batch from the next process so it's ready
* to receive new batch.
*/
if (iter == (batch==0 ? niters*size : niters) - 1) {
if (next_process == rank) {
nw_p = new int[V*K];
nwsum_p = new int[K];
}
MPI.COMM_WORLD.Reduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM, next_process);
MPI.COMM_WORLD.Reduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM, next_process);
} else {
/**
* Update nw and nwsum for all processes
*/
MPI.COMM_WORLD.Allreduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM);
MPI.COMM_WORLD.Allreduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM);
}
}
/**
* Compute best matches for the current batch by sending necessary info to root process
*/
double[] theta = computeTheta();
MPI.COMM_WORLD.Gather(theta, 0, K*batch_size, MPI.DOUBLE, theta_all, 0, K*batch_size, MPI.DOUBLE, root);
MPI.COMM_WORLD.Gather(indices, 0, batch_size, MPI.INT, indices_all, 0, batch_size, MPI.INT, root);
/**
* Represent result for the batch by use of root process
*/
if (rank == root) {
representResult(batch, theta_all, last_process, dataset, indices_all);
}
/*
Reassign the oldest process to the new batch and update nw for all processes
*/
if (rank == next_process) {
phase++;
initialSample(false);
indices = computeIndices();
System.out.println("Process " + rank + " takes the lead");
}
MPI.COMM_WORLD.Bcast(nw, 0, V*K, MPI.INT, next_process);
/**
* Shift the processes
*/
last_process = (last_process + 1) % size;
next_process = (next_process + 1) % size;
}
MPI.Finalize();
}
| public static void main(String[] args) {
MPI.Init(args);
rank = MPI.COMM_WORLD.Rank();
size = MPI.COMM_WORLD.Size();
int last_process = size-1; // process taking care of the last new batch of data
int next_process = 0; // process that are going to taking care of the new batch of data
/**
* Declare data only initialized by root process
*/
MixedDataset dataset = null;
int[] parameters = new int[2];
Object[] data = null;
double[] theta_all = null;
int[] indices_all = null;
/**
* Initialize data for root process
*/
if (rank == root) {
String dir = "/home/larsen/idea-IC-107.587/Online-Document-Aligner/corpus/lda";
dataset = MixedDataset.readDataSet(dir + File.separator + "en_2005_02.bag", dir + File.separator + "ensy_2005_02.bag");
parameters[0] = dataset.V;
parameters[1] = dataset.M;
data = dataset.docs;
theta_all = new double[basis_size*K];
indices_all = new int[basis_size];
}
/**
* Broadcast and scatter data to other processes
*/
MPI.COMM_WORLD.Bcast(parameters, 0, parameters.length, MPI.INT, root);
V = parameters[0];
M = parameters[1];
int num_batch = (M - (basis_size - batch_size)) / batch_size;
int phase_size = M / basis_size;
nd_p = new int[phase_size][batch_size][K];
ndsum_p = new int[phase_size][batch_size];
z_p = new Vector[phase_size][batch_size];
data_p = new Document[phase_size][batch_size];
nw = new int[V*K];
nwsum = new int[K];
p = new double[K];
for (int phase = 0; phase < phase_size; phase++) {
Object[] data_p_local = new Object[batch_size];
MPI.COMM_WORLD.Scatter(data, phase*basis_size, batch_size, MPI.OBJECT, data_p_local, 0, batch_size, MPI.OBJECT, root);
for (int i = 0; i < batch_size; i++)
data_p[phase][i] = (Document) data_p_local[i];
}
/**
* Initialize:
* Calculate nw_p and nwsum_p and distribute them to all processes
*/
phase = 0;
nw_p = new int[V*K];
nwsum_p = new int[K];
initialSample(true);
indices = computeIndices();
MPI.COMM_WORLD.Allreduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM);
MPI.COMM_WORLD.Allreduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM);
/**
* Start Estimation
*/
for (int batch = 0; batch < num_batch; batch++) {
if (rank == root)
System.out.println("Processing on basis documents, with " + batch + " batches added and removed.");
/**
* Sample
*/
for (int iter = 0; iter < (batch==0 ? niters*size : niters); iter++) {
/**
* Clear the number of instances of a word assigned to a topic,
* and also the number of words assigned to a topic.
*/
nw_p = new int[V*K];
nwsum_p = new int[K];
/**
* Sample
*/
for (int m = 0; m < batch_size; m++){
for (int n = 0; n < z_p[phase][m].size(); n++){
int topic = sample(m,n);
z_p[phase][m].set(n, topic);
}// end for each word
}// end for each document
/**
* If it's the last round of sampling, remove the previous batch from the next process so it's ready
* to receive new batch.
*/
if (iter == (batch==0 ? niters*size : niters) - 1) {
if (next_process == rank) {
nw_p = new int[V*K];
nwsum_p = new int[K];
}
MPI.COMM_WORLD.Reduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM, next_process);
MPI.COMM_WORLD.Reduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM, next_process);
} else {
/**
* Update nw and nwsum for all processes
*/
MPI.COMM_WORLD.Allreduce(nw_p, 0, nw, 0, V*K, MPI.INT, MPI.SUM);
MPI.COMM_WORLD.Allreduce(nwsum_p, 0, nwsum, 0, K, MPI.INT, MPI.SUM);
}
}
/**
* Compute best matches for the current batch by sending necessary info to root process
*/
double[] theta = computeTheta();
MPI.COMM_WORLD.Gather(theta, 0, K*batch_size, MPI.DOUBLE, theta_all, 0, K*batch_size, MPI.DOUBLE, root);
MPI.COMM_WORLD.Gather(indices, 0, batch_size, MPI.INT, indices_all, 0, batch_size, MPI.INT, root);
/**
* Represent result for the batch by use of root process
*/
if (rank == root) {
representResult(batch, theta_all, last_process, dataset, indices_all);
}
/*
Reassign the next process to the new batch and update nw for all processes
*/
if (rank == next_process) {
phase++;
initialSample(false);
indices = computeIndices();
System.out.println("Process " + rank + " takes the lead");
}
MPI.COMM_WORLD.Bcast(nw, 0, V*K, MPI.INT, next_process);
/**
* Shift the processes
*/
last_process = (last_process + 1) % size;
next_process = (next_process + 1) % size;
}
MPI.Finalize();
}
|
diff --git a/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java b/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java
index 872ca50c9a..149dfa8f5f 100644
--- a/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java
+++ b/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java
@@ -1,123 +1,123 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
Occam Labs UG (haftungsbeschränkt)
Godesberger Allee 139, 53175 Bonn
Germany
http://www.occamlabs.de/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wms;
import static org.deegree.commons.utils.io.Utils.determineSimilarity;
import static org.deegree.commons.utils.net.HttpUtils.STREAM;
import static org.deegree.commons.utils.net.HttpUtils.retrieve;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
import org.deegree.commons.utils.test.IntegrationTestUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* <code>WMSSimilarityIntegrationTest</code>
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author: mschneider $
*
* @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $
*/
@RunWith(Parameterized.class)
public class WMSSimilarityIntegrationTest {
private String request;
private byte[] response;
public WMSSimilarityIntegrationTest( Object wasXml, String request, byte[] response ) {
// we only use .kvp for WMS
this.request = (String) request;
if ( !this.request.startsWith( "?" ) ) {
this.request = "?" + this.request;
}
this.response = (byte[]) response;
}
@Parameters
public static Collection<Object[]> getParameters() {
return IntegrationTestUtils.getTestRequests();
}
@Test
public void testSimilarity()
throws IOException {
String base = "http://localhost:" + System.getProperty( "portnumber" );
base += "/deegree-wms-similarity-tests/services" + request;
InputStream in = retrieve( STREAM, base );
try {
BufferedImage img2 = ImageIO.read( new ByteArrayInputStream( response ) );
byte[] bs = IOUtils.toByteArray( in );
BufferedImage img1 = ImageIO.read( new ByteArrayInputStream( bs ) );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write( img1, "tif", bos );
bos.close();
in = new ByteArrayInputStream( bos.toByteArray() );
bos = new ByteArrayOutputStream();
bos.close();
ImageIO.write( img2, "tif", bos );
this.response = bos.toByteArray();
} catch ( Throwable t ) {
t.printStackTrace();
// just compare initial byte arrays
}
double sim = determineSimilarity( in, new ByteArrayInputStream( response ) );
- Assert.assertEquals( "Images are not similar enough.", 1.0, sim, 0.01 );
+ Assert.assertEquals( "Images are not similar enough. Request: " + request, 1.0, sim, 0.01 );
}
}
| true | true | public void testSimilarity()
throws IOException {
String base = "http://localhost:" + System.getProperty( "portnumber" );
base += "/deegree-wms-similarity-tests/services" + request;
InputStream in = retrieve( STREAM, base );
try {
BufferedImage img2 = ImageIO.read( new ByteArrayInputStream( response ) );
byte[] bs = IOUtils.toByteArray( in );
BufferedImage img1 = ImageIO.read( new ByteArrayInputStream( bs ) );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write( img1, "tif", bos );
bos.close();
in = new ByteArrayInputStream( bos.toByteArray() );
bos = new ByteArrayOutputStream();
bos.close();
ImageIO.write( img2, "tif", bos );
this.response = bos.toByteArray();
} catch ( Throwable t ) {
t.printStackTrace();
// just compare initial byte arrays
}
double sim = determineSimilarity( in, new ByteArrayInputStream( response ) );
Assert.assertEquals( "Images are not similar enough.", 1.0, sim, 0.01 );
}
| public void testSimilarity()
throws IOException {
String base = "http://localhost:" + System.getProperty( "portnumber" );
base += "/deegree-wms-similarity-tests/services" + request;
InputStream in = retrieve( STREAM, base );
try {
BufferedImage img2 = ImageIO.read( new ByteArrayInputStream( response ) );
byte[] bs = IOUtils.toByteArray( in );
BufferedImage img1 = ImageIO.read( new ByteArrayInputStream( bs ) );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write( img1, "tif", bos );
bos.close();
in = new ByteArrayInputStream( bos.toByteArray() );
bos = new ByteArrayOutputStream();
bos.close();
ImageIO.write( img2, "tif", bos );
this.response = bos.toByteArray();
} catch ( Throwable t ) {
t.printStackTrace();
// just compare initial byte arrays
}
double sim = determineSimilarity( in, new ByteArrayInputStream( response ) );
Assert.assertEquals( "Images are not similar enough. Request: " + request, 1.0, sim, 0.01 );
}
|
diff --git a/wayback-core/src/main/java/org/archive/wayback/archivalurl/requestparser/ReplayRequestParser.java b/wayback-core/src/main/java/org/archive/wayback/archivalurl/requestparser/ReplayRequestParser.java
index 6a730ecde..784fc4379 100644
--- a/wayback-core/src/main/java/org/archive/wayback/archivalurl/requestparser/ReplayRequestParser.java
+++ b/wayback-core/src/main/java/org/archive/wayback/archivalurl/requestparser/ReplayRequestParser.java
@@ -1,92 +1,95 @@
/* ReplayRequestParser
*
* $Id$
*
* Created on 6:39:51 PM Apr 24, 2007.
*
* Copyright (C) 2007 Internet Archive.
*
* This file is part of wayback-core.
*
* wayback-core is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* any later version.
*
* wayback-core 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with wayback-core; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.archive.wayback.archivalurl.requestparser;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.archive.wayback.core.WaybackRequest;
import org.archive.wayback.requestparser.PathRequestParser;
import org.archive.wayback.util.Timestamp;
/**
* RequestParser implementation that extracts request info from a Replay
* Archival Url path.
*
* @author brad
* @version $Date$, $Revision$
*/
public class ReplayRequestParser extends PathRequestParser {
/**
* Regex which parses Archival URL replay requests into timestamp + url
*/
private final Pattern WB_REQUEST_REGEX = Pattern
.compile("^(\\d{1,14})/(.*)$");
public WaybackRequest parse(String requestPath) {
WaybackRequest wbRequest = null;
Matcher matcher = WB_REQUEST_REGEX.matcher(requestPath);
String urlStr = null;
if (matcher != null && matcher.matches()) {
wbRequest = new WaybackRequest();
String dateStr = matcher.group(1);
urlStr = matcher.group(2);
// The logic of the classic WM wrt timestamp bounding:
// if 14-digits are specified, assume min-max range boundaries
// if less than 14 are specified, assume min-max range boundaries
// based upon amount given (2001 => 20010101... - 20011231...)
// AND assume the user asked for the LATEST possible date
// within that range...
String startDate = null;
String endDate = null;
if (dateStr.length() == 14) {
startDate = getEarliestTimestamp();
endDate = getLatestTimestamp();
+ if(endDate == null) {
+ endDate = Timestamp.currentTimestamp().getDateStr();
+ }
} else {
// classic behavior:
startDate = Timestamp.parseBefore(dateStr).getDateStr();
endDate = Timestamp.parseAfter(dateStr).getDateStr();
dateStr = endDate;
// maybe "better" behavior:
// startDate = getEarliestTimestamp();
// endDate = getLatestTimestamp();
// dateStr = Timestamp.parseAfter(dateStr).getDateStr();
}
wbRequest.setReplayTimestamp(dateStr);
wbRequest.setStartTimestamp(startDate);
wbRequest.setEndTimestamp(endDate);
wbRequest.setReplayRequest();
wbRequest.setRequestUrl(urlStr);
}
return wbRequest;
}
}
| true | true | public WaybackRequest parse(String requestPath) {
WaybackRequest wbRequest = null;
Matcher matcher = WB_REQUEST_REGEX.matcher(requestPath);
String urlStr = null;
if (matcher != null && matcher.matches()) {
wbRequest = new WaybackRequest();
String dateStr = matcher.group(1);
urlStr = matcher.group(2);
// The logic of the classic WM wrt timestamp bounding:
// if 14-digits are specified, assume min-max range boundaries
// if less than 14 are specified, assume min-max range boundaries
// based upon amount given (2001 => 20010101... - 20011231...)
// AND assume the user asked for the LATEST possible date
// within that range...
String startDate = null;
String endDate = null;
if (dateStr.length() == 14) {
startDate = getEarliestTimestamp();
endDate = getLatestTimestamp();
} else {
// classic behavior:
startDate = Timestamp.parseBefore(dateStr).getDateStr();
endDate = Timestamp.parseAfter(dateStr).getDateStr();
dateStr = endDate;
// maybe "better" behavior:
// startDate = getEarliestTimestamp();
// endDate = getLatestTimestamp();
// dateStr = Timestamp.parseAfter(dateStr).getDateStr();
}
wbRequest.setReplayTimestamp(dateStr);
wbRequest.setStartTimestamp(startDate);
wbRequest.setEndTimestamp(endDate);
wbRequest.setReplayRequest();
wbRequest.setRequestUrl(urlStr);
}
return wbRequest;
}
| public WaybackRequest parse(String requestPath) {
WaybackRequest wbRequest = null;
Matcher matcher = WB_REQUEST_REGEX.matcher(requestPath);
String urlStr = null;
if (matcher != null && matcher.matches()) {
wbRequest = new WaybackRequest();
String dateStr = matcher.group(1);
urlStr = matcher.group(2);
// The logic of the classic WM wrt timestamp bounding:
// if 14-digits are specified, assume min-max range boundaries
// if less than 14 are specified, assume min-max range boundaries
// based upon amount given (2001 => 20010101... - 20011231...)
// AND assume the user asked for the LATEST possible date
// within that range...
String startDate = null;
String endDate = null;
if (dateStr.length() == 14) {
startDate = getEarliestTimestamp();
endDate = getLatestTimestamp();
if(endDate == null) {
endDate = Timestamp.currentTimestamp().getDateStr();
}
} else {
// classic behavior:
startDate = Timestamp.parseBefore(dateStr).getDateStr();
endDate = Timestamp.parseAfter(dateStr).getDateStr();
dateStr = endDate;
// maybe "better" behavior:
// startDate = getEarliestTimestamp();
// endDate = getLatestTimestamp();
// dateStr = Timestamp.parseAfter(dateStr).getDateStr();
}
wbRequest.setReplayTimestamp(dateStr);
wbRequest.setStartTimestamp(startDate);
wbRequest.setEndTimestamp(endDate);
wbRequest.setReplayRequest();
wbRequest.setRequestUrl(urlStr);
}
return wbRequest;
}
|
diff --git a/BinaryTreeMaximPathSum/Solution.java b/BinaryTreeMaximPathSum/Solution.java
index 9d52b91..afef0a8 100644
--- a/BinaryTreeMaximPathSum/Solution.java
+++ b/BinaryTreeMaximPathSum/Solution.java
@@ -1,45 +1,45 @@
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class MetaData{
int maxPathSum;
int maxSinglePath;
public MetaData(int maxPathSum, int maxSinglePath){
this.maxPathSum = maxPathSum;
this.maxSinglePath = maxSinglePath;
}
}
public MetaData maxPathSumWithMeta(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null){
return new MetaData(Integer.MIN_VALUE,0);
}
- MetaData leftData = maxPathSum(root.left);
- MetaData rightData = maxPathSum(root.right);
+ MetaData leftData = maxPathSumWithMeta(root.left);
+ MetaData rightData = maxPathSumWithMeta(root.right);
int maxSinglePath = ((leftData.maxSinglePath > rightData.maxSinglePath)?
- (leftData.maxSinglePath):(rightData.maxSinglePath))+val;
+ (leftData.maxSinglePath):(rightData.maxSinglePath))+root.val;
- int myPathSumWithNode = leftData.maxSinglePath + rightData.maxSinglePath +val;
+ int myPathSumWithNode = leftData.maxSinglePath + rightData.maxSinglePath +root.val;
int maxPathSumOfChildren = ((leftData.maxPathSum > rightData.maxPathSum)?
(leftData.maxPathSum):(rightData.maxPathSum));
int myMaxPathSum = (myPathSumWithNode > maxPathSumOfChildren)?
(myPathSumWithNode):(maxPathSumOfChildren);
return new MetaData(myMaxPathSum, maxSinglePath);
}
public int maxPathSum(TreeNode root) {
if(root == null)
return 0;
return maxPathSumWithMeta(root).maxPathSum;
}
}
| false | true | public MetaData maxPathSumWithMeta(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null){
return new MetaData(Integer.MIN_VALUE,0);
}
MetaData leftData = maxPathSum(root.left);
MetaData rightData = maxPathSum(root.right);
int maxSinglePath = ((leftData.maxSinglePath > rightData.maxSinglePath)?
(leftData.maxSinglePath):(rightData.maxSinglePath))+val;
int myPathSumWithNode = leftData.maxSinglePath + rightData.maxSinglePath +val;
int maxPathSumOfChildren = ((leftData.maxPathSum > rightData.maxPathSum)?
(leftData.maxPathSum):(rightData.maxPathSum));
int myMaxPathSum = (myPathSumWithNode > maxPathSumOfChildren)?
(myPathSumWithNode):(maxPathSumOfChildren);
return new MetaData(myMaxPathSum, maxSinglePath);
}
| public MetaData maxPathSumWithMeta(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null){
return new MetaData(Integer.MIN_VALUE,0);
}
MetaData leftData = maxPathSumWithMeta(root.left);
MetaData rightData = maxPathSumWithMeta(root.right);
int maxSinglePath = ((leftData.maxSinglePath > rightData.maxSinglePath)?
(leftData.maxSinglePath):(rightData.maxSinglePath))+root.val;
int myPathSumWithNode = leftData.maxSinglePath + rightData.maxSinglePath +root.val;
int maxPathSumOfChildren = ((leftData.maxPathSum > rightData.maxPathSum)?
(leftData.maxPathSum):(rightData.maxPathSum));
int myMaxPathSum = (myPathSumWithNode > maxPathSumOfChildren)?
(myPathSumWithNode):(maxPathSumOfChildren);
return new MetaData(myMaxPathSum, maxSinglePath);
}
|
diff --git a/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java b/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java
index 9bb900c..c41f3a3 100644
--- a/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java
+++ b/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java
@@ -1,535 +1,535 @@
package me.libraryaddict.disguise.utilities;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.TargetedDisguise;
import me.libraryaddict.disguise.disguisetypes.watchers.AgeableWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.ZombieWatcher;
import me.libraryaddict.disguise.disguisetypes.TargetedDisguise.TargetType;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
public class DisguiseUtilities {
private static LibsDisguises libsDisguises;
// A internal storage of fake entity ID's I can use.
// Realistically I could probably use a ID like "4" for everyone, seeing as no one shares the ID
private static HashMap<Integer, Integer> selfDisguisesIds = new HashMap<Integer, Integer>();
// Store the entity IDs instead of entitys because then I can disguise entitys even before they exist
private static HashMap<Integer, HashSet<TargetedDisguise>> targetedDisguises = new HashMap<Integer, HashSet<TargetedDisguise>>();
public static void addDisguise(int entityId, TargetedDisguise disguise) {
if (!getDisguises().containsKey(entityId)) {
getDisguises().put(entityId, new HashSet<TargetedDisguise>());
}
getDisguises().get(entityId).add(disguise);
checkConflicts(disguise, null);
if (disguise.getDisguiseTarget() == TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS && disguise.isModifyBoundingBox()) {
doBoundingBox(disguise);
}
}
/**
* If name isn't null. Make sure that the name doesn't see any other disguise. Else if name is null. Make sure that the
* observers in the disguise don't see any other disguise.
*/
public static void checkConflicts(TargetedDisguise disguise, String name) {
// If the disguise is being used.. Else we may accidentally undisguise something else
if (DisguiseAPI.isDisguiseInUse(disguise)) {
Iterator<TargetedDisguise> disguiseItel = getDisguises().get(disguise.getEntity().getEntityId()).iterator();
// Iterate through the disguises
while (disguiseItel.hasNext()) {
TargetedDisguise d = disguiseItel.next();
// Make sure the disguise isn't the same thing
if (d != disguise) {
// If the loop'd disguise is hiding the disguise to everyone in its list
if (d.getDisguiseTarget() == TargetType.HIDE_DISGUISE_TO_EVERYONE_BUT_THESE_PLAYERS) {
// If player is a observer in the loop
if (disguise.getDisguiseTarget() == TargetType.HIDE_DISGUISE_TO_EVERYONE_BUT_THESE_PLAYERS) {
// If player is a observer in the disguise
// Remove them from the loop
if (name != null) {
d.removePlayer(name);
} else {
for (String playername : disguise.getObservers()) {
d.silentlyRemovePlayer(playername);
}
}
} else if (disguise.getDisguiseTarget() == TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS) {
// If player is not a observer in the loop
if (name != null) {
if (!disguise.getObservers().contains(name)) {
d.removePlayer(name);
}
} else {
for (String playername : d.getObservers()) {
if (!disguise.getObservers().contains(playername)) {
d.silentlyRemovePlayer(playername);
}
}
}
}
} else if (d.getDisguiseTarget() == TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS) {
// Here you add it to the loop if they see the disguise
if (disguise.getDisguiseTarget() == TargetType.HIDE_DISGUISE_TO_EVERYONE_BUT_THESE_PLAYERS) {
// Everyone who is in the disguise needs to be added to the loop
if (name != null) {
d.addPlayer(name);
} else {
for (String playername : disguise.getObservers()) {
d.silentlyAddPlayer(playername);
}
}
} else if (disguise.getDisguiseTarget() == TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS) {
// This here is a paradox.
// If fed a name. I can do this.
// But the rest of the time.. Its going to conflict.
// The below is debug output. Most people wouldn't care for it.
// System.out.print("Cannot set more than one " + TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS
// + " on a entity. Removed the old disguise.");
disguiseItel.remove();
/* if (name != null) {
if (!disguise.getObservers().contains(name)) {
d.setViewDisguise(name);
}
} else {
for (String playername : d.getObservers()) {
if (!disguise.getObservers().contains(playername)) {
d.setViewDisguise(playername);
}
}
}*/
}
}
}
}
}
}
public static void doBoundingBox(TargetedDisguise disguise) {
// TODO Slimes
Entity entity = disguise.getEntity();
if (entity != null) {
if (isDisguiseInUse(disguise)) {
DisguiseValues disguiseValues = DisguiseValues.getDisguiseValues(disguise.getType());
FakeBoundingBox disguiseBox = disguiseValues.getAdultBox();
if (disguiseValues.getBabyBox() != null) {
if ((disguise.getWatcher() instanceof AgeableWatcher && ((AgeableWatcher) disguise.getWatcher()).isBaby())
|| (disguise.getWatcher() instanceof ZombieWatcher && ((ZombieWatcher) disguise.getWatcher())
.isBaby())) {
disguiseBox = disguiseValues.getBabyBox();
}
}
ReflectionManager.setBoundingBox(entity, disguiseBox, disguiseValues.getEntitySize());
} else {
DisguiseValues entityValues = DisguiseValues.getDisguiseValues(DisguiseType.getType(entity.getType()));
FakeBoundingBox entityBox = entityValues.getAdultBox();
if (entityValues.getBabyBox() != null) {
if ((entity instanceof Ageable && !((Ageable) entity).isAdult())
|| (entity instanceof Zombie && ((Zombie) entity).isBaby())) {
entityBox = entityValues.getBabyBox();
}
}
ReflectionManager.setBoundingBox(entity, entityBox, entityValues.getEntitySize());
}
}
}
@Deprecated
public static TargetedDisguise getDisguise(int entityId) {
TargetedDisguise toReturn = null;
if (getDisguises().containsKey(entityId)) {
for (TargetedDisguise disguise : getDisguises().get(entityId)) {
if (disguise.getDisguiseTarget() == TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS
&& disguise.getObservers().isEmpty()) {
return disguise;
}
if (toReturn == null) {
toReturn = disguise;
}
}
}
return toReturn;
}
public static TargetedDisguise getDisguise(Player observer, int entityId) {
if (getDisguises().containsKey(entityId)) {
for (TargetedDisguise disguise : getDisguises().get(entityId)) {
if (disguise.canSee(observer)) {
return disguise;
}
}
}
return null;
}
public static HashMap<Integer, HashSet<TargetedDisguise>> getDisguises() {
return targetedDisguises;
}
public static TargetedDisguise[] getDisguises(int entityId) {
if (getDisguises().containsKey(entityId)) {
return getDisguises().get(entityId).toArray(new TargetedDisguise[getDisguises().get(entityId).size()]);
}
return new TargetedDisguise[0];
}
/**
* Get all EntityPlayers who have this entity in their Entity Tracker And they are in the targetted disguise.
*/
public static ArrayList<Player> getPerverts(Disguise disguise) {
ArrayList<Player> players = new ArrayList<Player>();
try {
Object world = ReflectionManager.getWorld(disguise.getEntity().getWorld());
Object tracker = world.getClass().getField("tracker").get(world);
Object trackedEntities = tracker.getClass().getField("trackedEntities").get(tracker);
Object entityTrackerEntry = trackedEntities.getClass().getMethod("get", int.class)
.invoke(trackedEntities, disguise.getEntity().getEntityId());
if (entityTrackerEntry != null) {
HashSet trackedPlayers = (HashSet) entityTrackerEntry.getClass().getField("trackedPlayers")
.get(entityTrackerEntry);
for (Object p : trackedPlayers) {
Player player = (Player) ReflectionManager.getBukkitEntity(p);
if (((TargetedDisguise) disguise).canSee(player)) {
players.add(player);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return players;
}
public static List<TargetedDisguise> getSeenDisguises(String viewer) {
List<TargetedDisguise> dis = new ArrayList<TargetedDisguise>();
for (HashSet<TargetedDisguise> disguises : getDisguises().values()) {
for (TargetedDisguise disguise : disguises) {
if (disguise.getDisguiseTarget() == TargetType.HIDE_DISGUISE_TO_EVERYONE_BUT_THESE_PLAYERS) {
if (disguise.canSee(viewer)) {
boolean add = true;
for (String observer : disguise.getObservers()) {
if (!observer.equals(viewer) && Bukkit.getPlayerExact(observer) != null) {
add = false;
break;
}
}
if (add) {
dis.add(disguise);
}
}
}
}
}
return dis;
}
public static HashMap<Integer, Integer> getSelfDisguisesIds() {
return selfDisguisesIds;
}
public static void init(LibsDisguises disguises) {
libsDisguises = disguises;
}
public static boolean isDisguiseInUse(Disguise disguise) {
if (disguise.getEntity() != null && getDisguises().containsKey(disguise.getEntity().getEntityId())
&& getDisguises().get(disguise.getEntity().getEntityId()).contains(disguise)) {
return true;
}
return false;
}
/**
* @param Resends
* the entity to all the watching players, which is where the magic begins
*/
public static void refreshTracker(TargetedDisguise disguise, String player) {
try {
Object world = ReflectionManager.getWorld(disguise.getEntity().getWorld());
Object tracker = world.getClass().getField("tracker").get(world);
Object trackedEntities = tracker.getClass().getField("trackedEntities").get(tracker);
Object entityTrackerEntry = trackedEntities.getClass().getMethod("get", int.class)
.invoke(trackedEntities, disguise.getEntity().getEntityId());
if (entityTrackerEntry != null) {
HashSet trackedPlayers = (HashSet) entityTrackerEntry.getClass().getField("trackedPlayers")
.get(entityTrackerEntry);
Method clear = entityTrackerEntry.getClass().getMethod("clear", ReflectionManager.getNmsClass("EntityPlayer"));
Method updatePlayer = entityTrackerEntry.getClass().getMethod("updatePlayer",
ReflectionManager.getNmsClass("EntityPlayer"));
HashSet cloned = (HashSet) trackedPlayers.clone();
for (Object p : cloned) {
if (player.equals(((Player) ReflectionManager.getBukkitEntity(p)).getName())) {
clear.invoke(entityTrackerEntry, p);
updatePlayer.invoke(entityTrackerEntry, p);
break;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* @param Resends
* the entity to all the watching players, which is where the magic begins
*/
public static void refreshTrackers(TargetedDisguise disguise) {
try {
Object world = ReflectionManager.getWorld(disguise.getEntity().getWorld());
Object tracker = world.getClass().getField("tracker").get(world);
Object trackedEntities = tracker.getClass().getField("trackedEntities").get(tracker);
Object entityTrackerEntry = trackedEntities.getClass().getMethod("get", int.class)
.invoke(trackedEntities, disguise.getEntity().getEntityId());
if (entityTrackerEntry != null) {
HashSet trackedPlayers = (HashSet) entityTrackerEntry.getClass().getField("trackedPlayers")
.get(entityTrackerEntry);
Method clear = entityTrackerEntry.getClass().getMethod("clear", ReflectionManager.getNmsClass("EntityPlayer"));
Method updatePlayer = entityTrackerEntry.getClass().getMethod("updatePlayer",
ReflectionManager.getNmsClass("EntityPlayer"));
HashSet cloned = (HashSet) trackedPlayers.clone();
for (Object p : cloned) {
Player player = (Player) ReflectionManager.getBukkitEntity(p);
// if (entity instanceof Player && !((Player) ReflectionManager.getBukkitEntity(player)).canSee((Player)
// entity))
// continue;
if (disguise.canSee(player.getName())) {
clear.invoke(entityTrackerEntry, p);
updatePlayer.invoke(entityTrackerEntry, p);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static boolean removeDisguise(TargetedDisguise disguise) {
int entityId = disguise.getEntity().getEntityId();
if (getDisguises().containsKey(entityId) && getDisguises().get(entityId).remove(disguise)) {
if (getDisguises().get(entityId).isEmpty()) {
getDisguises().remove(entityId);
}
if (disguise.getDisguiseTarget() == TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS && disguise.isModifyBoundingBox()) {
doBoundingBox(disguise);
}
return true;
}
return false;
}
public static void removeSelfDisguise(Player player) {
if (selfDisguisesIds.containsKey(player.getEntityId())) {
// Send a packet to destroy the fake entity
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
packet.getModifier().write(0, new int[] { selfDisguisesIds.get(player.getEntityId()) });
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
} catch (Exception ex) {
ex.printStackTrace();
}
// Remove the fake entity ID from the disguise bin
selfDisguisesIds.remove(player.getEntityId());
// Get the entity tracker
try {
Object world = ReflectionManager.getWorld(player.getWorld());
Object tracker = world.getClass().getField("tracker").get(world);
Object trackedEntities = tracker.getClass().getField("trackedEntities").get(tracker);
Object entityTrackerEntry = trackedEntities.getClass().getMethod("get", int.class)
.invoke(trackedEntities, player.getEntityId());
if (entityTrackerEntry != null) {
HashSet trackedPlayers = (HashSet) entityTrackerEntry.getClass().getField("trackedPlayers")
.get(entityTrackerEntry);
// If the tracker exists. Remove himself from his tracker
trackedPlayers.remove(ReflectionManager.getNmsEntity(player));
}
} catch (Exception ex) {
ex.printStackTrace();
}
// Resend entity metadata else he will be invisible to himself until its resent
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(
player,
ProtocolLibrary
.getProtocolManager()
.createPacketConstructor(PacketType.Play.Server.ENTITY_METADATA, player.getEntityId(),
WrappedDataWatcher.getEntityWatcher(player), true)
.createPacket(player.getEntityId(), WrappedDataWatcher.getEntityWatcher(player), true));
} catch (Exception ex) {
ex.printStackTrace();
}
player.updateInventory();
}
}
/**
* Sends the self disguise to the player
*/
public static void sendSelfDisguise(final Player player) {
try {
if (!player.isValid()) {
return;
}
Object world = ReflectionManager.getWorld(player.getWorld());
Object tracker = world.getClass().getField("tracker").get(world);
Object trackedEntities = tracker.getClass().getField("trackedEntities").get(tracker);
Object entityTrackerEntry = trackedEntities.getClass().getMethod("get", int.class)
.invoke(trackedEntities, player.getEntityId());
if (entityTrackerEntry == null) {
// A check incase the tracker is null.
// If it is, then this method will be run again in one tick. Which is when it should be constructed.
// Else its going to run in a infinite loop hue hue hue..
Bukkit.getScheduler().scheduleSyncDelayedTask(libsDisguises, new Runnable() {
public void run() {
sendSelfDisguise(player);
}
});
return;
}
// Add himself to his own entity tracker
((HashSet) entityTrackerEntry.getClass().getField("trackedPlayers").get(entityTrackerEntry)).add(ReflectionManager
.getNmsEntity(player));
ProtocolManager manager = ProtocolLibrary.getProtocolManager();
// Send the player a packet with himself being spawned
manager.sendServerPacket(player, manager.createPacketConstructor(PacketType.Play.Server.NAMED_ENTITY_SPAWN, player)
.createPacket(player));
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_METADATA, player.getEntityId(),
WrappedDataWatcher.getEntityWatcher(player), true).createPacket(player.getEntityId(),
WrappedDataWatcher.getEntityWatcher(player), true));
boolean isMoving = false;
try {
Field field = ReflectionManager.getNmsClass("EntityTrackerEntry").getDeclaredField("isMoving");
field.setAccessible(true);
isMoving = field.getBoolean(entityTrackerEntry);
} catch (Exception ex) {
ex.printStackTrace();
}
// Send the velocity packets
if (isMoving) {
Vector velocity = player.getVelocity();
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_VELOCITY, player.getEntityId(),
velocity.getX(), velocity.getY(), velocity.getZ()).createPacket(player.getEntityId(),
velocity.getX(), velocity.getY(), velocity.getZ()));
}
// Why the hell would he even need this. Meh.
if (player.getVehicle() != null && player.getEntityId() > player.getVehicle().getEntityId()) {
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ATTACH_ENTITY, 0, player, player.getVehicle())
.createPacket(0, player, player.getVehicle()));
} else if (player.getPassenger() != null && player.getEntityId() > player.getPassenger().getEntityId()) {
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ATTACH_ENTITY, 0, player.getPassenger(), player)
.createPacket(0, player.getPassenger(), player));
}
// Resend the armor
for (int i = 0; i < 5; i++) {
ItemStack item;
if (i == 0) {
item = player.getItemInHand();
} else {
item = player.getInventory().getArmorContents()[i - 1];
}
if (item != null && item.getType() != Material.AIR) {
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_EQUIPMENT, player.getEntityId(), i,
item).createPacket(player.getEntityId(), i, item));
}
}
Location loc = player.getLocation();
// If the disguised is sleeping for w/e reason
if (player.isSleeping()) {
manager.sendServerPacket(
player,
- manager.createPacketConstructor(PacketType.Play.Server.BED, player, 0, loc.getBlockX(), loc.getBlockY(),
- loc.getBlockZ()).createPacket(player, 0, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
+ manager.createPacketConstructor(PacketType.Play.Server.BED, player, loc.getBlockX(), loc.getBlockY(),
+ loc.getBlockZ()).createPacket(player, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
// Resend any active potion effects
Iterator iterator = player.getActivePotionEffects().iterator();
while (iterator.hasNext()) {
PotionEffect potionEffect = (PotionEffect) iterator.next();
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_EFFECT, player.getEntityId(), potionEffect)
.createPacket(player.getEntityId(), potionEffect));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Setup it so he can see himself when disguised
*/
public static void setupFakeDisguise(final Disguise disguise) {
Entity e = disguise.getEntity();
// If the disguises entity is null, or the disguised entity isn't a player return
if (e == null || !(e instanceof Player) || !getDisguises().containsKey(e.getEntityId())
|| !getDisguises().get(e.getEntityId()).contains(disguise)) {
return;
}
Player player = (Player) e;
// Check if he can even see this..
if (!((TargetedDisguise) disguise).canSee(player)) {
return;
}
// Remove the old disguise, else we have weird disguises around the place
DisguiseUtilities.removeSelfDisguise(player);
// If the disguised player can't see himself. Return
if (!disguise.isSelfDisguiseVisible() || !PacketsManager.isViewDisguisesListenerEnabled() || player.getVehicle() != null) {
return;
}
try {
// Grab the entity ID the fake disguise will use
Field field = ReflectionManager.getNmsClass("Entity").getDeclaredField("entityCount");
field.setAccessible(true);
int id = field.getInt(null);
// Set the entitycount plus one so we don't have the id being reused
field.set(null, id + 1);
selfDisguisesIds.put(player.getEntityId(), id);
} catch (Exception ex) {
ex.printStackTrace();
}
sendSelfDisguise(player);
if (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf()) {
if (PacketsManager.isInventoryListenerEnabled()) {
player.updateInventory();
}
}
}
}
| true | true | public static void sendSelfDisguise(final Player player) {
try {
if (!player.isValid()) {
return;
}
Object world = ReflectionManager.getWorld(player.getWorld());
Object tracker = world.getClass().getField("tracker").get(world);
Object trackedEntities = tracker.getClass().getField("trackedEntities").get(tracker);
Object entityTrackerEntry = trackedEntities.getClass().getMethod("get", int.class)
.invoke(trackedEntities, player.getEntityId());
if (entityTrackerEntry == null) {
// A check incase the tracker is null.
// If it is, then this method will be run again in one tick. Which is when it should be constructed.
// Else its going to run in a infinite loop hue hue hue..
Bukkit.getScheduler().scheduleSyncDelayedTask(libsDisguises, new Runnable() {
public void run() {
sendSelfDisguise(player);
}
});
return;
}
// Add himself to his own entity tracker
((HashSet) entityTrackerEntry.getClass().getField("trackedPlayers").get(entityTrackerEntry)).add(ReflectionManager
.getNmsEntity(player));
ProtocolManager manager = ProtocolLibrary.getProtocolManager();
// Send the player a packet with himself being spawned
manager.sendServerPacket(player, manager.createPacketConstructor(PacketType.Play.Server.NAMED_ENTITY_SPAWN, player)
.createPacket(player));
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_METADATA, player.getEntityId(),
WrappedDataWatcher.getEntityWatcher(player), true).createPacket(player.getEntityId(),
WrappedDataWatcher.getEntityWatcher(player), true));
boolean isMoving = false;
try {
Field field = ReflectionManager.getNmsClass("EntityTrackerEntry").getDeclaredField("isMoving");
field.setAccessible(true);
isMoving = field.getBoolean(entityTrackerEntry);
} catch (Exception ex) {
ex.printStackTrace();
}
// Send the velocity packets
if (isMoving) {
Vector velocity = player.getVelocity();
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_VELOCITY, player.getEntityId(),
velocity.getX(), velocity.getY(), velocity.getZ()).createPacket(player.getEntityId(),
velocity.getX(), velocity.getY(), velocity.getZ()));
}
// Why the hell would he even need this. Meh.
if (player.getVehicle() != null && player.getEntityId() > player.getVehicle().getEntityId()) {
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ATTACH_ENTITY, 0, player, player.getVehicle())
.createPacket(0, player, player.getVehicle()));
} else if (player.getPassenger() != null && player.getEntityId() > player.getPassenger().getEntityId()) {
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ATTACH_ENTITY, 0, player.getPassenger(), player)
.createPacket(0, player.getPassenger(), player));
}
// Resend the armor
for (int i = 0; i < 5; i++) {
ItemStack item;
if (i == 0) {
item = player.getItemInHand();
} else {
item = player.getInventory().getArmorContents()[i - 1];
}
if (item != null && item.getType() != Material.AIR) {
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_EQUIPMENT, player.getEntityId(), i,
item).createPacket(player.getEntityId(), i, item));
}
}
Location loc = player.getLocation();
// If the disguised is sleeping for w/e reason
if (player.isSleeping()) {
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.BED, player, 0, loc.getBlockX(), loc.getBlockY(),
loc.getBlockZ()).createPacket(player, 0, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
// Resend any active potion effects
Iterator iterator = player.getActivePotionEffects().iterator();
while (iterator.hasNext()) {
PotionEffect potionEffect = (PotionEffect) iterator.next();
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_EFFECT, player.getEntityId(), potionEffect)
.createPacket(player.getEntityId(), potionEffect));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
| public static void sendSelfDisguise(final Player player) {
try {
if (!player.isValid()) {
return;
}
Object world = ReflectionManager.getWorld(player.getWorld());
Object tracker = world.getClass().getField("tracker").get(world);
Object trackedEntities = tracker.getClass().getField("trackedEntities").get(tracker);
Object entityTrackerEntry = trackedEntities.getClass().getMethod("get", int.class)
.invoke(trackedEntities, player.getEntityId());
if (entityTrackerEntry == null) {
// A check incase the tracker is null.
// If it is, then this method will be run again in one tick. Which is when it should be constructed.
// Else its going to run in a infinite loop hue hue hue..
Bukkit.getScheduler().scheduleSyncDelayedTask(libsDisguises, new Runnable() {
public void run() {
sendSelfDisguise(player);
}
});
return;
}
// Add himself to his own entity tracker
((HashSet) entityTrackerEntry.getClass().getField("trackedPlayers").get(entityTrackerEntry)).add(ReflectionManager
.getNmsEntity(player));
ProtocolManager manager = ProtocolLibrary.getProtocolManager();
// Send the player a packet with himself being spawned
manager.sendServerPacket(player, manager.createPacketConstructor(PacketType.Play.Server.NAMED_ENTITY_SPAWN, player)
.createPacket(player));
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_METADATA, player.getEntityId(),
WrappedDataWatcher.getEntityWatcher(player), true).createPacket(player.getEntityId(),
WrappedDataWatcher.getEntityWatcher(player), true));
boolean isMoving = false;
try {
Field field = ReflectionManager.getNmsClass("EntityTrackerEntry").getDeclaredField("isMoving");
field.setAccessible(true);
isMoving = field.getBoolean(entityTrackerEntry);
} catch (Exception ex) {
ex.printStackTrace();
}
// Send the velocity packets
if (isMoving) {
Vector velocity = player.getVelocity();
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_VELOCITY, player.getEntityId(),
velocity.getX(), velocity.getY(), velocity.getZ()).createPacket(player.getEntityId(),
velocity.getX(), velocity.getY(), velocity.getZ()));
}
// Why the hell would he even need this. Meh.
if (player.getVehicle() != null && player.getEntityId() > player.getVehicle().getEntityId()) {
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ATTACH_ENTITY, 0, player, player.getVehicle())
.createPacket(0, player, player.getVehicle()));
} else if (player.getPassenger() != null && player.getEntityId() > player.getPassenger().getEntityId()) {
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ATTACH_ENTITY, 0, player.getPassenger(), player)
.createPacket(0, player.getPassenger(), player));
}
// Resend the armor
for (int i = 0; i < 5; i++) {
ItemStack item;
if (i == 0) {
item = player.getItemInHand();
} else {
item = player.getInventory().getArmorContents()[i - 1];
}
if (item != null && item.getType() != Material.AIR) {
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_EQUIPMENT, player.getEntityId(), i,
item).createPacket(player.getEntityId(), i, item));
}
}
Location loc = player.getLocation();
// If the disguised is sleeping for w/e reason
if (player.isSleeping()) {
manager.sendServerPacket(
player,
manager.createPacketConstructor(PacketType.Play.Server.BED, player, loc.getBlockX(), loc.getBlockY(),
loc.getBlockZ()).createPacket(player, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
// Resend any active potion effects
Iterator iterator = player.getActivePotionEffects().iterator();
while (iterator.hasNext()) {
PotionEffect potionEffect = (PotionEffect) iterator.next();
manager.sendServerPacket(player,
manager.createPacketConstructor(PacketType.Play.Server.ENTITY_EFFECT, player.getEntityId(), potionEffect)
.createPacket(player.getEntityId(), potionEffect));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
|
diff --git a/forms/src/org/riotfamily/forms/element/ColorPicker.java b/forms/src/org/riotfamily/forms/element/ColorPicker.java
index e38a51409..74c60011a 100644
--- a/forms/src/org/riotfamily/forms/element/ColorPicker.java
+++ b/forms/src/org/riotfamily/forms/element/ColorPicker.java
@@ -1,76 +1,76 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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.
*
* The Original Code is Riot.
*
* The Initial Developer of the Original Code is
* Neteye GmbH.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Felix Gnass [fgnass at neteye dot de]
*
* ***** END LICENSE BLOCK ***** */
package org.riotfamily.forms.element;
import java.io.PrintWriter;
import org.riotfamily.common.markup.Html;
import org.riotfamily.common.markup.TagWriter;
import org.riotfamily.forms.DHTMLElement;
import org.riotfamily.forms.resource.FormResource;
import org.riotfamily.forms.resource.ResourceElement;
import org.riotfamily.forms.resource.Resources;
import org.riotfamily.forms.resource.ScriptResource;
import org.riotfamily.forms.resource.StylesheetResource;
/**
* @author Felix Gnass [fgnass at neteye dot de]
* @since 6.5
*/
public class ColorPicker extends AbstractTextElement
implements ResourceElement, DHTMLElement {
public ColorPicker() {
setStyleClass("text color-input");
setMaxLength(new Integer(6));
}
public void renderInternal(PrintWriter writer) {
super.renderInternal(writer);
TagWriter tag = new TagWriter(writer);
tag.startEmpty(Html.BUTTON).attribute(Html.COMMON_ID, getId() + "-swatch")
.attribute(Html.COMMON_CLASS, "color-swatch").end();
}
public FormResource getResource() {
return new ScriptResource(
"form/colorPicker/colorPicker.js", "Control.ColorPicker",
Resources.SCRIPTACULOUS_SLIDER,
Resources.SCRIPTACULOUS_DRAG_DROP,
new ScriptResource("form/colorPicker/yahoo.color.js", "YAHOO.util.Color"),
new StylesheetResource("form/colorPicker/colorPicker.css")
);
}
public String getInitScript() {
StringBuffer sb = new StringBuffer("new Control.ColorPicker('")
- .append(getId()).append("', {IMAGE_BASE: '")
+ .append(getEventTriggerId()).append("', {IMAGE_BASE: '")
.append(getFormContext().getContextPath())
.append(getFormContext().getResourcePath())
.append("form/colorPicker/").append("', swatch: '")
.append(getId() + "-swatch").append("'});");
return sb.toString();
}
}
| true | true | public String getInitScript() {
StringBuffer sb = new StringBuffer("new Control.ColorPicker('")
.append(getId()).append("', {IMAGE_BASE: '")
.append(getFormContext().getContextPath())
.append(getFormContext().getResourcePath())
.append("form/colorPicker/").append("', swatch: '")
.append(getId() + "-swatch").append("'});");
return sb.toString();
}
| public String getInitScript() {
StringBuffer sb = new StringBuffer("new Control.ColorPicker('")
.append(getEventTriggerId()).append("', {IMAGE_BASE: '")
.append(getFormContext().getContextPath())
.append(getFormContext().getResourcePath())
.append("form/colorPicker/").append("', swatch: '")
.append(getId() + "-swatch").append("'});");
return sb.toString();
}
|
diff --git a/Group4Shop_App/src/main/java/dit126/group4/group4shop_app/controller/RenderPDFController.java b/Group4Shop_App/src/main/java/dit126/group4/group4shop_app/controller/RenderPDFController.java
index a9df2e0..c2afd60 100644
--- a/Group4Shop_App/src/main/java/dit126/group4/group4shop_app/controller/RenderPDFController.java
+++ b/Group4Shop_App/src/main/java/dit126/group4/group4shop_app/controller/RenderPDFController.java
@@ -1,71 +1,71 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dit126.group4.group4shop_app.controller;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.pdf.ITextUserAgent;
/**
*
* @author emilbogren
*/
@Named("pdfbean")
@RequestScoped
public class RenderPDFController {
@Inject
private Provider<EmailController> emailController;
private String filepath;
public void createPDF(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpSession session = (HttpSession) externalContext.getSession(true);
String url = "http://localhost:8080/Group4Shop_App/content/checkout/receiptframe.xhtml"+";jsessionid=" + session.getId();
try {
System.out.println("Trying to create receipt");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new URL(url).toString());
//ITextUserAgent callback = new ITextUserAgent(renderer.getOutputDevice());
//callback.
filepath = "";
OutputStream filepath = new FileOutputStream("/Users/emilbogren/Documents/"
+ "WebbApp/Project/WebApplikationer/Group4Shop_App/src/main/webapp/"
- + "content/checkout/receipts/Receipt#"+"orderID"+ ".pdf");
+ + "content/checkout/receipts/Receipt#"+ " " + ".pdf");
renderer.layout();
renderer.createPDF(filepath);
filepath.close();
System.out.println("SUCCESS FILE IS CREATED");
sendReceiptAsMail();
} catch (Exception ex) {
System.out.println("FAILED : " + ex.getMessage());
}
}
private void sendReceiptAsMail(){
emailController.get().sendEmail(" ", "SPAM", filepath);
}
}
| true | true | public void createPDF(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpSession session = (HttpSession) externalContext.getSession(true);
String url = "http://localhost:8080/Group4Shop_App/content/checkout/receiptframe.xhtml"+";jsessionid=" + session.getId();
try {
System.out.println("Trying to create receipt");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new URL(url).toString());
//ITextUserAgent callback = new ITextUserAgent(renderer.getOutputDevice());
//callback.
filepath = "";
OutputStream filepath = new FileOutputStream("/Users/emilbogren/Documents/"
+ "WebbApp/Project/WebApplikationer/Group4Shop_App/src/main/webapp/"
+ "content/checkout/receipts/Receipt#"+"orderID"+ ".pdf");
renderer.layout();
renderer.createPDF(filepath);
filepath.close();
System.out.println("SUCCESS FILE IS CREATED");
sendReceiptAsMail();
} catch (Exception ex) {
System.out.println("FAILED : " + ex.getMessage());
}
}
| public void createPDF(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpSession session = (HttpSession) externalContext.getSession(true);
String url = "http://localhost:8080/Group4Shop_App/content/checkout/receiptframe.xhtml"+";jsessionid=" + session.getId();
try {
System.out.println("Trying to create receipt");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new URL(url).toString());
//ITextUserAgent callback = new ITextUserAgent(renderer.getOutputDevice());
//callback.
filepath = "";
OutputStream filepath = new FileOutputStream("/Users/emilbogren/Documents/"
+ "WebbApp/Project/WebApplikationer/Group4Shop_App/src/main/webapp/"
+ "content/checkout/receipts/Receipt#"+ " " + ".pdf");
renderer.layout();
renderer.createPDF(filepath);
filepath.close();
System.out.println("SUCCESS FILE IS CREATED");
sendReceiptAsMail();
} catch (Exception ex) {
System.out.println("FAILED : " + ex.getMessage());
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StepIntoSelectionActionDelegate.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StepIntoSelectionActionDelegate.java
index be554c394..ce8c06c1f 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StepIntoSelectionActionDelegate.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StepIntoSelectionActionDelegate.java
@@ -1,312 +1,312 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.actions;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.ui.actions.IRunToLineTarget;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin;
import org.eclipse.jdt.internal.debug.ui.EvaluationContextManager;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* Steps into the selected method.
*/
public class StepIntoSelectionActionDelegate implements IEditorActionDelegate, IWorkbenchWindowActionDelegate {
private IEditorPart fEditorPart = null;
private IWorkbenchWindow fWindow = null;
/**
* The name of the type being "run to".
* @see StepIntoSelectionActionDelegate#runToLineBeforeStepIn(ITextSelection, IJavaStackFrame, IMethod)
*/
private String runToLineType= null;
/**
* The line number being "run to."
* @see StepIntoSelectionActionDelegate#runToLineBeforeStepIn(ITextSelection, IJavaStackFrame, IMethod)
*/
private int runToLineLine= -1;
/**
* The debug event list listener used to know when a run to line has finished.
* @see StepIntoSelectionActionDelegate#runToLineBeforeStepIn(ITextSelection, IJavaStackFrame, IMethod)
*/
private IDebugEventSetListener listener= null;
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
IJavaStackFrame frame = getStackFrame();
if (frame == null || !frame.isSuspended()) {
// no longer suspended - unexpected
return;
}
ITextSelection textSelection= getTextSelection();
IMethod method= getMethod();
if (method == null) {
return;
}
try {
int lineNumber = frame.getLineNumber();
// debug line numbers are 1 based, document line numbers are 0 based
if (textSelection.getStartLine() == (lineNumber - 1)) {
doStepIn(frame, method);
} else {
// not on current line
runToLineBeforeStepIn(textSelection, frame, method);
return;
}
} catch (DebugException e) {
showErrorMessage(e.getStatus().getMessage());
return;
}
}
/**
* Steps into the given method in the given stack frame
* @param frame the frame in which the step should begin
* @param method the method to step into
* @throws DebugException
*/
private void doStepIn(IJavaStackFrame frame, IMethod method) throws DebugException {
// ensure top stack frame
if (!frame.getThread().getTopStackFrame().equals(frame)) {
showErrorMessage(ActionMessages.getString("StepIntoSelectionActionDelegate.Step_into_selection_only_available_in_top_stack_frame._3")); //$NON-NLS-1$
return;
}
StepIntoSelectionHandler handler = new StepIntoSelectionHandler((IJavaThread)frame.getThread(), frame, method);
handler.step();
}
/**
* When the user chooses to "step into selection" on a line other than
* the currently executing one, first perform a "run to line" to get to
* the desired location, then perform a "step into selection."
*/
private void runToLineBeforeStepIn(ITextSelection textSelection, final IJavaStackFrame startFrame, final IMethod method) throws DebugException {
IRunToLineTarget runToLineAction = new RunToLineAdapter();
runToLineType= startFrame.getReceivingTypeName();
runToLineLine= textSelection.getStartLine() + 1;
if (runToLineType == null || runToLineLine == -1) {
return;
}
listener= new IDebugEventSetListener() {
/**
* @see IDebugEventSetListener#handleDebugEvents(DebugEvent[])
*/
public void handleDebugEvents(DebugEvent[] events) {
for (int i = 0; i < events.length; i++) {
DebugEvent event = events[i];
switch (event.getKind()) {
case DebugEvent.SUSPEND :
handleSuspendEvent(event);
break;
case DebugEvent.TERMINATE :
handleTerminateEvent(event);
break;
default :
break;
}
}
}
/**
* Listen for the completion of the "run to line." When the thread
* suspends at the correct location, perform a "step into selection"
* @param event the debug event
*/
private void handleSuspendEvent(DebugEvent event) {
Object source = event.getSource();
if (source instanceof IJavaThread) {
IJavaStackFrame frame= null;
try {
frame= (IJavaStackFrame) ((IJavaThread) source).getTopStackFrame();
if (isExpectedFrame(frame)) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
try {
doStepIn(frame, method);
} catch (DebugException e) {
showErrorMessage(e.getStatus().getMessage());
}
}
} catch (DebugException e) {
return;
}
}
}
/**
* Returns whether the given frame is the frame that this action is expecting.
* This frame is expecting a stack frame for the suspension of the "run to line".
* @param frame the given stack frame or <code>null</code>
* @return whether the given stack frame is the expected frame
* @throws DebugException
*/
private boolean isExpectedFrame(IJavaStackFrame frame) throws DebugException {
return frame != null &&
runToLineLine == frame.getLineNumber() &&
frame.getReceivingTypeName().equals(runToLineType);
}
/**
* When the debug target we're listening for terminates, stop listening
* to debug events.
* @param event the debug event
*/
private void handleTerminateEvent(DebugEvent event) {
Object source = event.getSource();
if (startFrame.getDebugTarget() == source) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
}
}
};
DebugPlugin.getDefault().addDebugEventListener(listener);
try {
- runToLineAction.runToLine(fEditorPart, textSelection, startFrame);
+ runToLineAction.runToLine(getActiveEditor(), textSelection, startFrame);
} catch (CoreException e) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
showErrorMessage(ActionMessages.getString("StepIntoSelectionActionDelegate.4")); //$NON-NLS-1$
JDIDebugUIPlugin.log(e.getStatus());
}
}
private ITextSelection getTextSelection() {
IEditorPart part = getActiveEditor();
if (part instanceof ITextEditor) {
ITextEditor editor = (ITextEditor)part;
return (ITextSelection)editor.getSelectionProvider().getSelection();
} else {
showErrorMessage(ActionMessages.getString("StepIntoSelectionActionDelegate.Step_into_selection_only_available_in_Java_editor._4")); //$NON-NLS-1$
return null;
}
}
private IMethod getMethod() {
ITextSelection textSelection= getTextSelection();
IEditorInput input = getActiveEditor().getEditorInput();
ICodeAssist codeAssist = null;
Object element = JavaUI.getWorkingCopyManager().getWorkingCopy(input);
if (element == null) {
element = input.getAdapter(IClassFile.class);
}
if (element instanceof ICodeAssist) {
codeAssist = ((ICodeAssist)element);
} else {
// editor does not support code assist
showErrorMessage(ActionMessages.getString("StepIntoSelectionActionDelegate.Step_into_selection_only_available_for_types_in_Java_projects._1")); //$NON-NLS-1$
return null;
}
IMethod method = null;
try {
IJavaElement[] resolve = codeAssist.codeSelect(textSelection.getOffset(), 0);
for (int i = 0; i < resolve.length; i++) {
IJavaElement javaElement = resolve[i];
if (javaElement instanceof IMethod) {
method = (IMethod)javaElement;
break;
}
}
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
if (method == null) {
// no resolved method
showErrorMessage(ActionMessages.getString("StepIntoSelectionActionDelegate.No_Method")); //$NON-NLS-1$
}
return method;
}
/**
* Displays an error message in the status area
*
* @param message
*/
protected void showErrorMessage(String message) {
if (getActiveEditor() != null) {
IEditorStatusLine statusLine= (IEditorStatusLine) getActiveEditor().getAdapter(IEditorStatusLine.class);
if (statusLine != null) {
statusLine.setMessage(true, message, null);
}
}
JDIDebugUIPlugin.getStandardDisplay().beep();
}
/**
* @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart)
*/
public void setActiveEditor(IAction action, IEditorPart targetEditor) {
fEditorPart = targetEditor;
}
/**
* Returns the active editor or <code>null</code>.
*
* @return active editor or <code>null</code>
*/
protected IEditorPart getActiveEditor() {
if (fWindow != null) {
// global action
return fWindow.getActivePage().getActiveEditor();
} else {
// pop-up action
return fEditorPart;
}
}
/**
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
}
/**
* Returns the current stack frame context, or <code>null</code> if none.
*
* @return the current stack frame context, or <code>null</code> if none
*/
protected IJavaStackFrame getStackFrame() {
return EvaluationContextManager.getEvaluationContext(getActiveEditor());
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
*/
public void dispose() {
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
*/
public void init(IWorkbenchWindow window) {
fWindow = window;
}
}
| true | true | private void runToLineBeforeStepIn(ITextSelection textSelection, final IJavaStackFrame startFrame, final IMethod method) throws DebugException {
IRunToLineTarget runToLineAction = new RunToLineAdapter();
runToLineType= startFrame.getReceivingTypeName();
runToLineLine= textSelection.getStartLine() + 1;
if (runToLineType == null || runToLineLine == -1) {
return;
}
listener= new IDebugEventSetListener() {
/**
* @see IDebugEventSetListener#handleDebugEvents(DebugEvent[])
*/
public void handleDebugEvents(DebugEvent[] events) {
for (int i = 0; i < events.length; i++) {
DebugEvent event = events[i];
switch (event.getKind()) {
case DebugEvent.SUSPEND :
handleSuspendEvent(event);
break;
case DebugEvent.TERMINATE :
handleTerminateEvent(event);
break;
default :
break;
}
}
}
/**
* Listen for the completion of the "run to line." When the thread
* suspends at the correct location, perform a "step into selection"
* @param event the debug event
*/
private void handleSuspendEvent(DebugEvent event) {
Object source = event.getSource();
if (source instanceof IJavaThread) {
IJavaStackFrame frame= null;
try {
frame= (IJavaStackFrame) ((IJavaThread) source).getTopStackFrame();
if (isExpectedFrame(frame)) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
try {
doStepIn(frame, method);
} catch (DebugException e) {
showErrorMessage(e.getStatus().getMessage());
}
}
} catch (DebugException e) {
return;
}
}
}
/**
* Returns whether the given frame is the frame that this action is expecting.
* This frame is expecting a stack frame for the suspension of the "run to line".
* @param frame the given stack frame or <code>null</code>
* @return whether the given stack frame is the expected frame
* @throws DebugException
*/
private boolean isExpectedFrame(IJavaStackFrame frame) throws DebugException {
return frame != null &&
runToLineLine == frame.getLineNumber() &&
frame.getReceivingTypeName().equals(runToLineType);
}
/**
* When the debug target we're listening for terminates, stop listening
* to debug events.
* @param event the debug event
*/
private void handleTerminateEvent(DebugEvent event) {
Object source = event.getSource();
if (startFrame.getDebugTarget() == source) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
}
}
};
DebugPlugin.getDefault().addDebugEventListener(listener);
try {
runToLineAction.runToLine(fEditorPart, textSelection, startFrame);
} catch (CoreException e) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
showErrorMessage(ActionMessages.getString("StepIntoSelectionActionDelegate.4")); //$NON-NLS-1$
JDIDebugUIPlugin.log(e.getStatus());
}
}
| private void runToLineBeforeStepIn(ITextSelection textSelection, final IJavaStackFrame startFrame, final IMethod method) throws DebugException {
IRunToLineTarget runToLineAction = new RunToLineAdapter();
runToLineType= startFrame.getReceivingTypeName();
runToLineLine= textSelection.getStartLine() + 1;
if (runToLineType == null || runToLineLine == -1) {
return;
}
listener= new IDebugEventSetListener() {
/**
* @see IDebugEventSetListener#handleDebugEvents(DebugEvent[])
*/
public void handleDebugEvents(DebugEvent[] events) {
for (int i = 0; i < events.length; i++) {
DebugEvent event = events[i];
switch (event.getKind()) {
case DebugEvent.SUSPEND :
handleSuspendEvent(event);
break;
case DebugEvent.TERMINATE :
handleTerminateEvent(event);
break;
default :
break;
}
}
}
/**
* Listen for the completion of the "run to line." When the thread
* suspends at the correct location, perform a "step into selection"
* @param event the debug event
*/
private void handleSuspendEvent(DebugEvent event) {
Object source = event.getSource();
if (source instanceof IJavaThread) {
IJavaStackFrame frame= null;
try {
frame= (IJavaStackFrame) ((IJavaThread) source).getTopStackFrame();
if (isExpectedFrame(frame)) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
try {
doStepIn(frame, method);
} catch (DebugException e) {
showErrorMessage(e.getStatus().getMessage());
}
}
} catch (DebugException e) {
return;
}
}
}
/**
* Returns whether the given frame is the frame that this action is expecting.
* This frame is expecting a stack frame for the suspension of the "run to line".
* @param frame the given stack frame or <code>null</code>
* @return whether the given stack frame is the expected frame
* @throws DebugException
*/
private boolean isExpectedFrame(IJavaStackFrame frame) throws DebugException {
return frame != null &&
runToLineLine == frame.getLineNumber() &&
frame.getReceivingTypeName().equals(runToLineType);
}
/**
* When the debug target we're listening for terminates, stop listening
* to debug events.
* @param event the debug event
*/
private void handleTerminateEvent(DebugEvent event) {
Object source = event.getSource();
if (startFrame.getDebugTarget() == source) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
}
}
};
DebugPlugin.getDefault().addDebugEventListener(listener);
try {
runToLineAction.runToLine(getActiveEditor(), textSelection, startFrame);
} catch (CoreException e) {
DebugPlugin.getDefault().removeDebugEventListener(listener);
showErrorMessage(ActionMessages.getString("StepIntoSelectionActionDelegate.4")); //$NON-NLS-1$
JDIDebugUIPlugin.log(e.getStatus());
}
}
|
diff --git a/source/de/anomic/server/logging/LogalizerHandler.java b/source/de/anomic/server/logging/LogalizerHandler.java
index ea54f55dd..daf09c159 100644
--- a/source/de/anomic/server/logging/LogalizerHandler.java
+++ b/source/de/anomic/server/logging/LogalizerHandler.java
@@ -1,171 +1,171 @@
//LogalizerHandler.java
//-------------------------------------
//part of YACY
//(C) by Michael Peter Christen; [email protected]
//first published on http://www.anomic.de
//Frankfurt, Germany, 2004
//
//This file ist contributed by Matthias Soehnholz
//last major change: $LastChangedDate$ by $LastChangedBy$
//Revision: $LastChangedRevision$
//
//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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.anomic.server.logging;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.anomic.plasma.plasmaParser;
import de.anomic.server.logging.logParsers.LogParser;
import de.anomic.tools.ListDirs;
public class LogalizerHandler extends Handler {
public static boolean enabled=false;
public static boolean debug=false;
private String logParserPackage;
private HashMap<String, Object> parsers;
public LogalizerHandler() {
super();
configure();
}
private HashMap<String, Object> loadParsers() {
final HashMap<String, Object> logParsers = new HashMap<String, Object>();
try {
if (debug) System.out.println("Searching for additional content parsers in package " + logParserPackage);
// getting an uri to the parser subpackage
final String packageURI = plasmaParser.class.getResource("/"+logParserPackage.replace('.','/')).toString();
if (debug) System.out.println("LogParser directory is " + packageURI);
final ListDirs parserDir = new ListDirs(packageURI);
final ArrayList<String> parserDirFiles = parserDir.listFiles(".*\\.class");
if(parserDirFiles.size() == 0 && debug) {
System.out.println("Can't find any parsers in "+parserDir.toString());
}
for(final String filename: parserDirFiles) {
- final Pattern patternGetClassName = Pattern.compile(".*"+ File.separator +"([^"+ File.separator +"]+)\\.class");
+ final Pattern patternGetClassName = Pattern.compile(".*\\"+ File.separator +"([^\\"+ File.separator +"]+)\\.class");
final Matcher matcherClassName = patternGetClassName.matcher(filename);
matcherClassName.find();
final String className = matcherClassName.group(1);
final Class<?> tempClass = Class.forName(logParserPackage+"."+className);
if (tempClass.isInterface()) {
if (debug) System.out.println(tempClass.getName() + " is an Interface");
} else {
final Object theParser = tempClass.newInstance();
if (theParser instanceof LogParser) {
final LogParser theLogParser = (LogParser) theParser;
//System.out.println(bla.getName() + " is a logParser");
logParsers.put(theLogParser.getParserType(), theParser);
if (debug) System.out.println("Added " + theLogParser.getClass().getName() + " as " + theLogParser.getParserType() + " Parser.");
}
else {
//System.out.println(bla.getName() + " is not a logParser");
if (debug) System.out.println("Rejected " + tempClass.getName() + ". Class does not implement the logParser-Interface");
}
}
}
} catch (final ClassNotFoundException e) {
e.printStackTrace();
} catch (final InstantiationException e) {
e.printStackTrace();
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final URISyntaxException e) {
e.printStackTrace();
}
return logParsers;
}
/**
* Get any configuration properties set
*/
private void configure() {
final LogManager manager = LogManager.getLogManager();
final String className = getClass().getName();
if(manager.getProperty(className + ".enabled").equalsIgnoreCase("true")) enabled = true;
if(manager.getProperty(className + ".debug").equalsIgnoreCase("true")) debug = true;
logParserPackage = manager.getProperty(className + ".parserPackage");
parsers = loadParsers();
}
public void publish(final LogRecord record) {
if (enabled) {
final LogParser temp = (LogParser) parsers.get(record.getLoggerName());
if (temp != null) {
final int returnV = temp.parse(record.getLevel().toString(), record.getMessage());
//if (debug) System.out.println("Logalizertest: " + returnV + " --- " + record.getLevel() + " --- " + record.getMessage());
if (debug) System.out.println("Logalizertest: " + returnV + " --- " + record.getLevel());
}
}
}
public Set<String> getParserNames() {
return parsers.keySet();
}
public LogParser getParser(final int number) {
String o;
final Iterator<String> it = parsers.keySet().iterator();
int i = 0;
while (it.hasNext()) {
o = it.next();
if (i++ == number)
return (LogParser) parsers.get(o);
}
return null;
}
public Hashtable<String, Object> getParserResults(final LogParser parsername) {
return parsername.getResults();
}
public void close() throws SecurityException {
// TODO Auto-generated method stub
}
public void flush() {
// TODO Auto-generated method stub
}
/*
private static final FilenameFilter parserNameFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches(".*.class");
}
};
*/
}
| true | true | private HashMap<String, Object> loadParsers() {
final HashMap<String, Object> logParsers = new HashMap<String, Object>();
try {
if (debug) System.out.println("Searching for additional content parsers in package " + logParserPackage);
// getting an uri to the parser subpackage
final String packageURI = plasmaParser.class.getResource("/"+logParserPackage.replace('.','/')).toString();
if (debug) System.out.println("LogParser directory is " + packageURI);
final ListDirs parserDir = new ListDirs(packageURI);
final ArrayList<String> parserDirFiles = parserDir.listFiles(".*\\.class");
if(parserDirFiles.size() == 0 && debug) {
System.out.println("Can't find any parsers in "+parserDir.toString());
}
for(final String filename: parserDirFiles) {
final Pattern patternGetClassName = Pattern.compile(".*"+ File.separator +"([^"+ File.separator +"]+)\\.class");
final Matcher matcherClassName = patternGetClassName.matcher(filename);
matcherClassName.find();
final String className = matcherClassName.group(1);
final Class<?> tempClass = Class.forName(logParserPackage+"."+className);
if (tempClass.isInterface()) {
if (debug) System.out.println(tempClass.getName() + " is an Interface");
} else {
final Object theParser = tempClass.newInstance();
if (theParser instanceof LogParser) {
final LogParser theLogParser = (LogParser) theParser;
//System.out.println(bla.getName() + " is a logParser");
logParsers.put(theLogParser.getParserType(), theParser);
if (debug) System.out.println("Added " + theLogParser.getClass().getName() + " as " + theLogParser.getParserType() + " Parser.");
}
else {
//System.out.println(bla.getName() + " is not a logParser");
if (debug) System.out.println("Rejected " + tempClass.getName() + ". Class does not implement the logParser-Interface");
}
}
}
} catch (final ClassNotFoundException e) {
e.printStackTrace();
} catch (final InstantiationException e) {
e.printStackTrace();
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final URISyntaxException e) {
e.printStackTrace();
}
return logParsers;
}
| private HashMap<String, Object> loadParsers() {
final HashMap<String, Object> logParsers = new HashMap<String, Object>();
try {
if (debug) System.out.println("Searching for additional content parsers in package " + logParserPackage);
// getting an uri to the parser subpackage
final String packageURI = plasmaParser.class.getResource("/"+logParserPackage.replace('.','/')).toString();
if (debug) System.out.println("LogParser directory is " + packageURI);
final ListDirs parserDir = new ListDirs(packageURI);
final ArrayList<String> parserDirFiles = parserDir.listFiles(".*\\.class");
if(parserDirFiles.size() == 0 && debug) {
System.out.println("Can't find any parsers in "+parserDir.toString());
}
for(final String filename: parserDirFiles) {
final Pattern patternGetClassName = Pattern.compile(".*\\"+ File.separator +"([^\\"+ File.separator +"]+)\\.class");
final Matcher matcherClassName = patternGetClassName.matcher(filename);
matcherClassName.find();
final String className = matcherClassName.group(1);
final Class<?> tempClass = Class.forName(logParserPackage+"."+className);
if (tempClass.isInterface()) {
if (debug) System.out.println(tempClass.getName() + " is an Interface");
} else {
final Object theParser = tempClass.newInstance();
if (theParser instanceof LogParser) {
final LogParser theLogParser = (LogParser) theParser;
//System.out.println(bla.getName() + " is a logParser");
logParsers.put(theLogParser.getParserType(), theParser);
if (debug) System.out.println("Added " + theLogParser.getClass().getName() + " as " + theLogParser.getParserType() + " Parser.");
}
else {
//System.out.println(bla.getName() + " is not a logParser");
if (debug) System.out.println("Rejected " + tempClass.getName() + ". Class does not implement the logParser-Interface");
}
}
}
} catch (final ClassNotFoundException e) {
e.printStackTrace();
} catch (final InstantiationException e) {
e.printStackTrace();
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final URISyntaxException e) {
e.printStackTrace();
}
return logParsers;
}
|
diff --git a/src/main/java/com/laytonsmith/abstraction/bukkit/events/drivers/BukkitPlayerListener.java b/src/main/java/com/laytonsmith/abstraction/bukkit/events/drivers/BukkitPlayerListener.java
index b12c417b..0d196b33 100644
--- a/src/main/java/com/laytonsmith/abstraction/bukkit/events/drivers/BukkitPlayerListener.java
+++ b/src/main/java/com/laytonsmith/abstraction/bukkit/events/drivers/BukkitPlayerListener.java
@@ -1,171 +1,173 @@
package com.laytonsmith.abstraction.bukkit.events.drivers;
import com.laytonsmith.abstraction.bukkit.BukkitMCPlayer;
import com.laytonsmith.abstraction.bukkit.events.BukkitPlayerEvents;
import com.laytonsmith.commandhelper.CommandHelperPlugin;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.events.Driver;
import com.laytonsmith.core.events.EventUtils;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.*;
/**
*
* @author Layton
*/
public class BukkitPlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerKick(PlayerKickEvent e) {
EventUtils.TriggerListener(Driver.PLAYER_KICK, "player_kick", new BukkitPlayerEvents.BukkitMCPlayerKickEvent(e));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(PlayerLoginEvent e) {
EventUtils.TriggerListener(Driver.PLAYER_LOGIN, "player_login", new BukkitPlayerEvents.BukkitMCPlayerLoginEvent(e));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerPreLogin(PlayerPreLoginEvent e) {
EventUtils.TriggerListener(Driver.PLAYER_PRELOGIN, "player_prelogin", new BukkitPlayerEvents.BukkitMCPlayerPreLoginEvent(e));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent e) {
EventUtils.TriggerListener(Driver.PLAYER_JOIN, "player_join", new BukkitPlayerEvents.BukkitMCPlayerJoinEvent(e));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent e) {
EventUtils.TriggerListener(Driver.PLAYER_INTERACT, "player_interact", new BukkitPlayerEvents.BukkitMCPlayerInteractEvent(e));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
EventUtils.TriggerListener(Driver.PLAYER_SPAWN, "player_spawn", new BukkitPlayerEvents.BukkitMCPlayerRespawnEvent(event));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChat(final AsyncPlayerChatEvent event) {
if (EventUtils.GetEvents(Driver.PLAYER_CHAT) != null
&& !EventUtils.GetEvents(Driver.PLAYER_CHAT).isEmpty()) {
if (event.isAsynchronous()) {
//We have to do the full processing on the main server thread, and
//block on it as well, so if we cancel it or something, the change
//will actually take effect. The easiest way to do this is to cancel the
//chat event, then re-run it on the main server thread. Since we're
//registering on lowest, this will hopefully not cause any problems,
//but if it does, tough. Barring play-dirty mode, there's not a whole
//lot that can be done reasonably.
// SortedSet<BoundEvent> events = EventUtils.GetEvents(Driver.PLAYER_CHAT);
// Event driver = EventList.getEvent(Driver.PLAYER_CHAT, "player_chat");
// //Unfortunately, due to priority issues, if any event is syncronous, all of them
// //have to be synchronous.
// boolean canBeAsync = true;
// boolean actuallyNeedToFire = false;
// //If all the events are asynchronous, we can just run it as is.
// for(BoundEvent b : events){
// //We can't just use isSync here, because cancel and modify event,
// //normally synchronous, aren't in this case, so we need to manually
// //check the full function list.
// for(Function f : b.getParseTree().getFunctions()){
// if(f instanceof EventBinding.cancel || f instanceof EventBinding.modify_event){
// continue;
// }
// if(f.runAsync() != null && f.runAsync() == false){
// //Nope, can't be run async :(
// canBeAsync = false;
// }
// }
// try {
// if(driver.matches(b.getPrefilter(), new BukkitPlayerEvents.BukkitMCPlayerChatEvent(event))){
// //Yeah, we need to fire it, so we have to continue
// actuallyNeedToFire = true;
// }
// } catch (PrefilterNonMatchException ex) {
// //No need to fire this one
// }
// }
//
// if(!actuallyNeedToFire){
// //Yay! Prefilters finally actually optimized something!
// return;
// }
//Until there is a more reliable way to detect isConst() on a parse tree, (that supports procs)
//this must always be synchronous.
boolean canBeAsync = false;
if(canBeAsync){
//Fire away!
fireChat(event);
} else {
final AsyncPlayerChatEvent copy = new AsyncPlayerChatEvent(false, event.getPlayer(), event.getMessage(), event.getRecipients());
+ copy.setFormat(event.getFormat());
//event.setCancelled(true);
Future f = Bukkit.getServer().getScheduler().callSyncMethod(CommandHelperPlugin.self, new Callable() {
public Object call() throws Exception {
Bukkit.getServer().getPluginManager().callEvent(copy);
return null;
}
});
while(true){
try {
f.get();
break;
} catch (InterruptedException ex) {
//I don't know why this happens, but screw it, we're gonna try again, and it's gonna like it.
} catch (ExecutionException ex) {
Logger.getLogger(BukkitPlayerListener.class.getName()).log(Level.SEVERE, null, ex);
break;
}
}
event.setCancelled(copy.isCancelled());
event.setMessage(copy.getMessage());
+ event.setFormat(copy.getFormat());
}
} else {
fireChat(event);
}
}
}
private void fireChat(AsyncPlayerChatEvent event) {
EventUtils.TriggerListener(Driver.PLAYER_CHAT, "player_chat", new BukkitPlayerEvents.BukkitMCPlayerChatEvent(event));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerQuit(PlayerQuitEvent event) {
EventUtils.TriggerListener(Driver.PLAYER_QUIT, "player_quit", new BukkitPlayerEvents.BukkitMCPlayerQuitEvent(event));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChangedWorld(PlayerChangedWorldEvent event) {
BukkitMCPlayer currentPlayer = (BukkitMCPlayer) Static.GetPlayer(event.getPlayer().getName(), Target.UNKNOWN);
//Apparently this happens sometimes, so prevent it
if (!event.getFrom().equals(currentPlayer._Player().getWorld())) {
EventUtils.TriggerListener(Driver.WORLD_CHANGED, "world_changed", new BukkitPlayerEvents.BukkitMCWorldChangedEvent(event));
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerTeleport(PlayerTeleportEvent event) {
if (event.getFrom().equals(event.getTo())) {
return;
}
EventUtils.TriggerListener(Driver.PLAYER_TELEPORT, "player_teleport", new BukkitPlayerEvents.BukkitMCPlayerTeleportEvent(event));
if (!event.getFrom().getWorld().equals(event.getTo().getWorld()) && !event.isCancelled()) {
EventUtils.TriggerListener(Driver.WORLD_CHANGED, "world_changed", new BukkitPlayerEvents.BukkitMCWorldChangedEvent(new PlayerChangedWorldEvent(event.getPlayer(), event.getFrom().getWorld())));
}
}
}
| false | true | public void onPlayerChat(final AsyncPlayerChatEvent event) {
if (EventUtils.GetEvents(Driver.PLAYER_CHAT) != null
&& !EventUtils.GetEvents(Driver.PLAYER_CHAT).isEmpty()) {
if (event.isAsynchronous()) {
//We have to do the full processing on the main server thread, and
//block on it as well, so if we cancel it or something, the change
//will actually take effect. The easiest way to do this is to cancel the
//chat event, then re-run it on the main server thread. Since we're
//registering on lowest, this will hopefully not cause any problems,
//but if it does, tough. Barring play-dirty mode, there's not a whole
//lot that can be done reasonably.
// SortedSet<BoundEvent> events = EventUtils.GetEvents(Driver.PLAYER_CHAT);
// Event driver = EventList.getEvent(Driver.PLAYER_CHAT, "player_chat");
// //Unfortunately, due to priority issues, if any event is syncronous, all of them
// //have to be synchronous.
// boolean canBeAsync = true;
// boolean actuallyNeedToFire = false;
// //If all the events are asynchronous, we can just run it as is.
// for(BoundEvent b : events){
// //We can't just use isSync here, because cancel and modify event,
// //normally synchronous, aren't in this case, so we need to manually
// //check the full function list.
// for(Function f : b.getParseTree().getFunctions()){
// if(f instanceof EventBinding.cancel || f instanceof EventBinding.modify_event){
// continue;
// }
// if(f.runAsync() != null && f.runAsync() == false){
// //Nope, can't be run async :(
// canBeAsync = false;
// }
// }
// try {
// if(driver.matches(b.getPrefilter(), new BukkitPlayerEvents.BukkitMCPlayerChatEvent(event))){
// //Yeah, we need to fire it, so we have to continue
// actuallyNeedToFire = true;
// }
// } catch (PrefilterNonMatchException ex) {
// //No need to fire this one
// }
// }
//
// if(!actuallyNeedToFire){
// //Yay! Prefilters finally actually optimized something!
// return;
// }
//Until there is a more reliable way to detect isConst() on a parse tree, (that supports procs)
//this must always be synchronous.
boolean canBeAsync = false;
if(canBeAsync){
//Fire away!
fireChat(event);
} else {
final AsyncPlayerChatEvent copy = new AsyncPlayerChatEvent(false, event.getPlayer(), event.getMessage(), event.getRecipients());
//event.setCancelled(true);
Future f = Bukkit.getServer().getScheduler().callSyncMethod(CommandHelperPlugin.self, new Callable() {
public Object call() throws Exception {
Bukkit.getServer().getPluginManager().callEvent(copy);
return null;
}
});
while(true){
try {
f.get();
break;
} catch (InterruptedException ex) {
//I don't know why this happens, but screw it, we're gonna try again, and it's gonna like it.
} catch (ExecutionException ex) {
Logger.getLogger(BukkitPlayerListener.class.getName()).log(Level.SEVERE, null, ex);
break;
}
}
event.setCancelled(copy.isCancelled());
event.setMessage(copy.getMessage());
}
} else {
fireChat(event);
}
}
}
| public void onPlayerChat(final AsyncPlayerChatEvent event) {
if (EventUtils.GetEvents(Driver.PLAYER_CHAT) != null
&& !EventUtils.GetEvents(Driver.PLAYER_CHAT).isEmpty()) {
if (event.isAsynchronous()) {
//We have to do the full processing on the main server thread, and
//block on it as well, so if we cancel it or something, the change
//will actually take effect. The easiest way to do this is to cancel the
//chat event, then re-run it on the main server thread. Since we're
//registering on lowest, this will hopefully not cause any problems,
//but if it does, tough. Barring play-dirty mode, there's not a whole
//lot that can be done reasonably.
// SortedSet<BoundEvent> events = EventUtils.GetEvents(Driver.PLAYER_CHAT);
// Event driver = EventList.getEvent(Driver.PLAYER_CHAT, "player_chat");
// //Unfortunately, due to priority issues, if any event is syncronous, all of them
// //have to be synchronous.
// boolean canBeAsync = true;
// boolean actuallyNeedToFire = false;
// //If all the events are asynchronous, we can just run it as is.
// for(BoundEvent b : events){
// //We can't just use isSync here, because cancel and modify event,
// //normally synchronous, aren't in this case, so we need to manually
// //check the full function list.
// for(Function f : b.getParseTree().getFunctions()){
// if(f instanceof EventBinding.cancel || f instanceof EventBinding.modify_event){
// continue;
// }
// if(f.runAsync() != null && f.runAsync() == false){
// //Nope, can't be run async :(
// canBeAsync = false;
// }
// }
// try {
// if(driver.matches(b.getPrefilter(), new BukkitPlayerEvents.BukkitMCPlayerChatEvent(event))){
// //Yeah, we need to fire it, so we have to continue
// actuallyNeedToFire = true;
// }
// } catch (PrefilterNonMatchException ex) {
// //No need to fire this one
// }
// }
//
// if(!actuallyNeedToFire){
// //Yay! Prefilters finally actually optimized something!
// return;
// }
//Until there is a more reliable way to detect isConst() on a parse tree, (that supports procs)
//this must always be synchronous.
boolean canBeAsync = false;
if(canBeAsync){
//Fire away!
fireChat(event);
} else {
final AsyncPlayerChatEvent copy = new AsyncPlayerChatEvent(false, event.getPlayer(), event.getMessage(), event.getRecipients());
copy.setFormat(event.getFormat());
//event.setCancelled(true);
Future f = Bukkit.getServer().getScheduler().callSyncMethod(CommandHelperPlugin.self, new Callable() {
public Object call() throws Exception {
Bukkit.getServer().getPluginManager().callEvent(copy);
return null;
}
});
while(true){
try {
f.get();
break;
} catch (InterruptedException ex) {
//I don't know why this happens, but screw it, we're gonna try again, and it's gonna like it.
} catch (ExecutionException ex) {
Logger.getLogger(BukkitPlayerListener.class.getName()).log(Level.SEVERE, null, ex);
break;
}
}
event.setCancelled(copy.isCancelled());
event.setMessage(copy.getMessage());
event.setFormat(copy.getFormat());
}
} else {
fireChat(event);
}
}
}
|
diff --git a/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java b/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java
index ae9f7fc0..92435f0a 100644
--- a/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java
+++ b/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java
@@ -1,99 +1,99 @@
package com.github.seqware.queryengine.system.exporters;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import com.github.seqware.queryengine.model.Reference;
import com.github.seqware.queryengine.plugins.PluginInterface;
import com.github.seqware.queryengine.system.Utility;
import com.github.seqware.queryengine.system.importers.FeatureImporter;
import com.github.seqware.queryengine.system.importers.SOFeatureImporter;
import com.github.seqware.queryengine.factory.SWQEFactory;
public class ArbitraryPluginRunner {
/** Constant <code>OUTPUT_FILE_PARAM='o'</code> */
public static final char OUTPUT_FILE_PARAM = 'o';
/** Constant <code>REFERENCE_ID_PARAM='r'</code> */
public static final char REFERENCE_ID_PARAM = 'r';
/** Constant <code>PLUGIN_CLASS_PARAM='p'</code>*/
public static final char PLUGIN_CLASS_PARAM = 'p';
/** Constant <code>SUCCESS</code>*/
private static final int SUCCESS = 1;
/** Constant <code>FAILIURE</code>*/
private static final int FAILIURE = 1;
private String[] args;
public static void main(String[] args) {
int mainMethod = ArbitraryPluginRunner.runArbitraryPluginRunner(args);
if (mainMethod == FAILIURE) {
System.exit(FeatureImporter.EXIT_CODE_INVALID_FILE);
}
}
public static int runArbitraryPluginRunner(String[] args){
Options options = new Options();
Option option1 = OptionBuilder.withArgName("outputFile").withDescription("(required) output file").hasArgs(1).isRequired().create(OUTPUT_FILE_PARAM);
options.addOption(option1);
Option option2 = OptionBuilder.withArgName("reference").withDescription("(required) the reference ID of the FeatureSet to run plugin on").hasArgs(1).isRequired().create(REFERENCE_ID_PARAM);
options.addOption(option2);
Option option3 = OptionBuilder.withArgName("pluginClass").withDescription("(required) the plugin to be run, full package path").hasArgs(1).isRequired().create(PLUGIN_CLASS_PARAM);
options.addOption(option3);
try{
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String referenceName = cmd.getOptionValue(REFERENCE_ID_PARAM);
String plugin = cmd.getOptionValue(PLUGIN_CLASS_PARAM);
String outputFile = cmd.getOptionValue(OUTPUT_FILE_PARAM);
Class<? extends PluginInterface> arbitraryPluginClass;
Reference ref = null;
for (Reference r : SWQEFactory.getQueryInterface().getReferences()){
if (referenceName.equals(r.getName())){
ref = r;
break;
}
}
arbitraryPluginClass = (Class<? extends PluginInterface>) Class.forName(plugin);
long start = new Date().getTime();
System.out.println("Running plugin: " + plugin);
Utility.dumpFromMapReducePlugin(plugin, ref, null, arbitraryPluginClass, outputFile);
long stop = new Date().getTime();
float diff = ((stop - start) / 1000) / 60;
System.out.println("Minutes to query: "+diff);
if (ref == null){
System.out.println("Reference was not found.");
System.exit(-2);
}
return SUCCESS;
} catch (MissingOptionException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
+ formatter.printHelp("ArbitraryPluginRunner usage:", options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ParseException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
+ formatter.printHelp("ArbitraryPluginRunner usage:", options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FAILIURE;
}
}
| false | true | public static int runArbitraryPluginRunner(String[] args){
Options options = new Options();
Option option1 = OptionBuilder.withArgName("outputFile").withDescription("(required) output file").hasArgs(1).isRequired().create(OUTPUT_FILE_PARAM);
options.addOption(option1);
Option option2 = OptionBuilder.withArgName("reference").withDescription("(required) the reference ID of the FeatureSet to run plugin on").hasArgs(1).isRequired().create(REFERENCE_ID_PARAM);
options.addOption(option2);
Option option3 = OptionBuilder.withArgName("pluginClass").withDescription("(required) the plugin to be run, full package path").hasArgs(1).isRequired().create(PLUGIN_CLASS_PARAM);
options.addOption(option3);
try{
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String referenceName = cmd.getOptionValue(REFERENCE_ID_PARAM);
String plugin = cmd.getOptionValue(PLUGIN_CLASS_PARAM);
String outputFile = cmd.getOptionValue(OUTPUT_FILE_PARAM);
Class<? extends PluginInterface> arbitraryPluginClass;
Reference ref = null;
for (Reference r : SWQEFactory.getQueryInterface().getReferences()){
if (referenceName.equals(r.getName())){
ref = r;
break;
}
}
arbitraryPluginClass = (Class<? extends PluginInterface>) Class.forName(plugin);
long start = new Date().getTime();
System.out.println("Running plugin: " + plugin);
Utility.dumpFromMapReducePlugin(plugin, ref, null, arbitraryPluginClass, outputFile);
long stop = new Date().getTime();
float diff = ((stop - start) / 1000) / 60;
System.out.println("Minutes to query: "+diff);
if (ref == null){
System.out.println("Reference was not found.");
System.exit(-2);
}
return SUCCESS;
} catch (MissingOptionException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ParseException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FAILIURE;
}
| public static int runArbitraryPluginRunner(String[] args){
Options options = new Options();
Option option1 = OptionBuilder.withArgName("outputFile").withDescription("(required) output file").hasArgs(1).isRequired().create(OUTPUT_FILE_PARAM);
options.addOption(option1);
Option option2 = OptionBuilder.withArgName("reference").withDescription("(required) the reference ID of the FeatureSet to run plugin on").hasArgs(1).isRequired().create(REFERENCE_ID_PARAM);
options.addOption(option2);
Option option3 = OptionBuilder.withArgName("pluginClass").withDescription("(required) the plugin to be run, full package path").hasArgs(1).isRequired().create(PLUGIN_CLASS_PARAM);
options.addOption(option3);
try{
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String referenceName = cmd.getOptionValue(REFERENCE_ID_PARAM);
String plugin = cmd.getOptionValue(PLUGIN_CLASS_PARAM);
String outputFile = cmd.getOptionValue(OUTPUT_FILE_PARAM);
Class<? extends PluginInterface> arbitraryPluginClass;
Reference ref = null;
for (Reference r : SWQEFactory.getQueryInterface().getReferences()){
if (referenceName.equals(r.getName())){
ref = r;
break;
}
}
arbitraryPluginClass = (Class<? extends PluginInterface>) Class.forName(plugin);
long start = new Date().getTime();
System.out.println("Running plugin: " + plugin);
Utility.dumpFromMapReducePlugin(plugin, ref, null, arbitraryPluginClass, outputFile);
long stop = new Date().getTime();
float diff = ((stop - start) / 1000) / 60;
System.out.println("Minutes to query: "+diff);
if (ref == null){
System.out.println("Reference was not found.");
System.exit(-2);
}
return SUCCESS;
} catch (MissingOptionException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ArbitraryPluginRunner usage:", options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ParseException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ArbitraryPluginRunner usage:", options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FAILIURE;
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/SubmitForApproval.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/SubmitForApproval.java
index 0a31c4e6..ca818808 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/SubmitForApproval.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/SubmitForApproval.java
@@ -1,81 +1,81 @@
/*
* @(#)SubmitForApproval.java
*
* Copyright 2009 Instituto Superior Tecnico
* Founding Authors: Luis Cruz, Nuno Ochoa, Paulo Abrantes
*
* https://fenix-ashes.ist.utl.pt/
*
* This file is part of the Expenditure Tracking Module.
*
* The Expenditure Tracking Module 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.
*
* The Expenditure Tracking Module 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 the Expenditure Tracking Module. If not, see <http://www.gnu.org/licenses/>.
*
*/
package pt.ist.expenditureTrackingSystem.domain.acquisitions.simplified.activities;
import module.workflow.activities.ActivityInformation;
import module.workflow.activities.WorkflowActivity;
import myorg.domain.User;
import myorg.domain.exceptions.DomainException;
import myorg.util.BundleUtil;
import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.RegularAcquisitionProcess;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.simplified.SimplifiedProcedureProcess;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.simplified.SimplifiedProcedureProcess.ProcessClassification;
/**
*
* @author Paulo Abrantes
* @author Luis Cruz
*
*/
public class SubmitForApproval extends
WorkflowActivity<RegularAcquisitionProcess, ActivityInformation<RegularAcquisitionProcess>> {
@Override
public boolean isActive(RegularAcquisitionProcess process, User user) {
return user.getExpenditurePerson() == process.getRequestor()
&& isUserProcessOwner(process, user)
&& process.getAcquisitionProcessState().isInGenesis()
&& process.getAcquisitionRequest().isFilled()
&& process.getAcquisitionRequest().isEveryItemFullyAttributedToPayingUnits();
}
@Override
protected void process(ActivityInformation<RegularAcquisitionProcess> activityInformation) {
final RegularAcquisitionProcess process = activityInformation.getProcess();
if (process.isSimplifiedProcedureProcess()
- && ((SimplifiedProcedureProcess) process).getProcessClassification() != ProcessClassification.CT75000
- && !process.hasAcquisitionProposalDocument()
+ //&& ((SimplifiedProcedureProcess) process).getProcessClassification() != ProcessClassification.CT75000
+ //&& !process.hasAcquisitionProposalDocument()
&& ((SimplifiedProcedureProcess) process).hasInvoiceFile()
&& process.getTotalValue().isGreaterThan(ExpenditureTrackingSystem.getInstance().getMaxValueStartedWithInvoive())
) {
final String message = BundleUtil.getStringFromResourceBundle(getUsedBundle(),
"activities.message.exception.exceeded.limit.to.start.process.with.invoice");
throw new DomainException(message);
}
process.submitForApproval();
}
@Override
public String getLocalizedName() {
return BundleUtil.getStringFromResourceBundle(getUsedBundle(), "label." + getClass().getName());
}
@Override
public String getUsedBundle() {
return "resources/AcquisitionResources";
}
}
| true | true | protected void process(ActivityInformation<RegularAcquisitionProcess> activityInformation) {
final RegularAcquisitionProcess process = activityInformation.getProcess();
if (process.isSimplifiedProcedureProcess()
&& ((SimplifiedProcedureProcess) process).getProcessClassification() != ProcessClassification.CT75000
&& !process.hasAcquisitionProposalDocument()
&& ((SimplifiedProcedureProcess) process).hasInvoiceFile()
&& process.getTotalValue().isGreaterThan(ExpenditureTrackingSystem.getInstance().getMaxValueStartedWithInvoive())
) {
final String message = BundleUtil.getStringFromResourceBundle(getUsedBundle(),
"activities.message.exception.exceeded.limit.to.start.process.with.invoice");
throw new DomainException(message);
}
process.submitForApproval();
}
| protected void process(ActivityInformation<RegularAcquisitionProcess> activityInformation) {
final RegularAcquisitionProcess process = activityInformation.getProcess();
if (process.isSimplifiedProcedureProcess()
//&& ((SimplifiedProcedureProcess) process).getProcessClassification() != ProcessClassification.CT75000
//&& !process.hasAcquisitionProposalDocument()
&& ((SimplifiedProcedureProcess) process).hasInvoiceFile()
&& process.getTotalValue().isGreaterThan(ExpenditureTrackingSystem.getInstance().getMaxValueStartedWithInvoive())
) {
final String message = BundleUtil.getStringFromResourceBundle(getUsedBundle(),
"activities.message.exception.exceeded.limit.to.start.process.with.invoice");
throw new DomainException(message);
}
process.submitForApproval();
}
|
diff --git a/src/main/java/ljdp/minechem/common/recipe/MinechemRecipes.java b/src/main/java/ljdp/minechem/common/recipe/MinechemRecipes.java
index 5db8f4c..039d2d4 100644
--- a/src/main/java/ljdp/minechem/common/recipe/MinechemRecipes.java
+++ b/src/main/java/ljdp/minechem/common/recipe/MinechemRecipes.java
@@ -1,1715 +1,1715 @@
package ljdp.minechem.common.recipe;
import java.util.ArrayList;
import java.util.Iterator;
import ljdp.minechem.api.core.Chemical;
import ljdp.minechem.api.core.Element;
import ljdp.minechem.api.core.EnumElement;
import ljdp.minechem.api.core.EnumMolecule;
import ljdp.minechem.api.core.Molecule;
import ljdp.minechem.api.recipe.DecomposerRecipe;
import ljdp.minechem.api.recipe.DecomposerRecipeChance;
import ljdp.minechem.api.recipe.DecomposerRecipeSelect;
import ljdp.minechem.api.recipe.SynthesisRecipe;
import ljdp.minechem.api.util.Util;
import ljdp.minechem.common.MinechemBlocks;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.blueprint.MinechemBlueprint;
import ljdp.minechem.common.items.ItemBlueprint;
import ljdp.minechem.common.items.ItemElement;
import ljdp.minechem.common.recipe.handlers.AppliedEnergisticsOreDictionaryHandler;
import ljdp.minechem.common.recipe.handlers.DefaultOreDictionaryHandler;
import ljdp.minechem.common.recipe.handlers.GregTechOreDictionaryHandler;
import ljdp.minechem.common.recipe.handlers.IC2OreDictionaryHandler;
import ljdp.minechem.common.recipe.handlers.MekanismOreDictionaryHandler;
import ljdp.minechem.common.recipe.handlers.UndergroundBiomesOreDictionaryHandler;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
public class MinechemRecipes {
private static final MinechemRecipes instance = new MinechemRecipes();
public ArrayList unbondingRecipes = new ArrayList();
public ArrayList synthesisRecipes = new ArrayList();
public static MinechemRecipes getInstance() {
return instance;
}
public void registerVanillaChemicalRecipes() {
// Molecules
Molecule moleculeSiliconDioxide = this.molecule(
EnumMolecule.siliconDioxide, 4);
Molecule moleculeCellulose = this.molecule(EnumMolecule.cellulose, 1);
Molecule moleculePolyvinylChloride = this
.molecule(EnumMolecule.polyvinylChloride);
// Elements
Element elementHydrogen = this.element(EnumElement.H, 64);
Element elementHelium = this.element(EnumElement.He, 64);
Element elementCarbon = this.element(EnumElement.C, 64);
// Section 1 - Blocks
// Stone
ItemStack blockStone = new ItemStack(Block.stone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockStone, 0.2F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7),
true, 50, new Chemical[] { this.element(EnumElement.Si), null,
null, this.element(EnumElement.O, 2), null, null }));
// Grass Block
ItemStack blockGrass = new ItemStack(Block.grass);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockGrass, 0.07F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }),
new DecomposerRecipe(
new Chemical[] { moleculeCellulose }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.grass, 16),
true, 50, new Chemical[] { null, moleculeCellulose, null, null,
this.element(EnumElement.O, 2),
this.element(EnumElement.Si) }));
// Dirt
ItemStack blockDirt = new ItemStack(Block.dirt);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockDirt, 0.07F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16),
true, 50, new Chemical[] { null, null, null, null,
this.element(EnumElement.O, 2),
this.element(EnumElement.Si) }));
// Cobblestone
ItemStack blockCobblestone = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockCobblestone, 0.1F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Na),
this.element(EnumElement.Cl) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(
Block.cobblestone, 8), true, 50, new Chemical[] {
this.element(EnumElement.Si), null, null, null,
this.element(EnumElement.O, 2), null }));
// Planks
// TODO: Add synthesizer recipes?
ItemStack blockOakWoodPlanks = new ItemStack(Block.planks, 1, 0);
ItemStack blockSpruceWoodPlanks = new ItemStack(Block.planks, 1, 1);
ItemStack blockBirchWoodPlanks = new ItemStack(Block.planks, 1, 2);
ItemStack blockJungleWoodPlanks = new ItemStack(Block.planks, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
// Saplings
ItemStack blockOakSapling = new ItemStack(Block.sapling, 1, 0);
ItemStack blockSpruceSapling = new ItemStack(Block.sapling, 1, 1);
ItemStack blockBirchSapling = new ItemStack(Block.sapling, 1, 2);
ItemStack blockJungleSapling = new ItemStack(Block.sapling, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakSapling, 0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockSpruceSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockBirchSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockJungleSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOakSapling, true, 20,
new Chemical[] { null, null, null, null, null, null, null,
null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSpruceSapling, true, 20,
new Chemical[] { null, null, null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(blockBirchSapling, true, 20,
new Chemical[] { null, null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe
.add(new SynthesisRecipe(blockJungleSapling, true, 20,
new Chemical[] { null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null,
null, null }));
// Water
ItemStack blockWaterSource = new ItemStack(Block.waterMoving);
ItemStack blockWaterStill = new ItemStack(Block.waterStill);
DecomposerRecipe.add(new DecomposerRecipe(blockWaterSource,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(blockWaterStill,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockWaterSource, false, 20,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
// Lava
// TODO: Add support for lava
// Sand
ItemStack blockSand = new ItemStack(Block.sand);
DecomposerRecipe
.add(new DecomposerRecipe(blockSand, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSand, true, 200,
new Chemical[] { moleculeSiliconDioxide,
moleculeSiliconDioxide, moleculeSiliconDioxide,
moleculeSiliconDioxide }));
// Gravel
ItemStack blockGravel = new ItemStack(Block.gravel);
DecomposerRecipe.add(new DecomposerRecipeChance(blockGravel, 0.35F,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGravel, true, 30,
new Chemical[] { null, null, null, null, null, null, null,
null, this.molecule(EnumMolecule.siliconDioxide) }));
// Gold Ore
ItemStack oreGold = new ItemStack(Block.oreGold);
DecomposerRecipe.add(new DecomposerRecipe(oreGold,
new Chemical[] { this.element(EnumElement.Au, 48) }));
// Iron Ore
ItemStack oreIron = new ItemStack(Block.oreIron);
DecomposerRecipe.add(new DecomposerRecipe(oreIron,
new Chemical[] { this.element(EnumElement.Fe, 48) }));
// Coal Ore
ItemStack oreCoal = new ItemStack(Block.oreCoal);
DecomposerRecipe.add(new DecomposerRecipe(oreCoal,
new Chemical[] { this.element(EnumElement.C, 48) }));
// Wood
ItemStack blockOakWood = new ItemStack(Block.wood, 1, 0);
ItemStack blockSpruceWood = new ItemStack(Block.wood, 1, 1);
ItemStack blockBirchWood = new ItemStack(Block.wood, 1, 2);
ItemStack blockJungleWood = new ItemStack(Block.wood, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOakWood, true, 100,
new Chemical[] { moleculeCellulose, moleculeCellulose,
moleculeCellulose, null, moleculeCellulose, null, null,
null, null }));
SynthesisRecipe.add(new SynthesisRecipe(blockSpruceWood, true, 100,
new Chemical[] { null, null, null, null, moleculeCellulose,
null, moleculeCellulose, moleculeCellulose,
moleculeCellulose }));
SynthesisRecipe.add(new SynthesisRecipe(blockBirchWood, true, 100,
new Chemical[] { moleculeCellulose, null, moleculeCellulose,
null, null, null, moleculeCellulose, null,
moleculeCellulose }));
SynthesisRecipe.add(new SynthesisRecipe(blockJungleWood, true, 100,
new Chemical[] { moleculeCellulose, null, null,
moleculeCellulose, moleculeCellulose, null,
moleculeCellulose, null, null }));
// Leaves
// TODO: Add support for leaves
// Glass
ItemStack blockGlass = new ItemStack(Block.glass);
DecomposerRecipe
.add(new DecomposerRecipe(blockGlass, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe
.add(new SynthesisRecipe(blockGlass, true, 500, new Chemical[] {
moleculeSiliconDioxide, null, moleculeSiliconDioxide,
null, null, null, moleculeSiliconDioxide, null,
moleculeSiliconDioxide }));
// Lapis Lazuli Ore
ItemStack blockOreLapis = new ItemStack(Block.oreLapis);
DecomposerRecipe.add(new DecomposerRecipe(blockOreLapis,
new Chemical[] { this.molecule(EnumMolecule.lazurite, 6),
this.molecule(EnumMolecule.sodalite),
this.molecule(EnumMolecule.noselite),
this.molecule(EnumMolecule.calcite),
this.molecule(EnumMolecule.pyrite) }));
// Lapis Lazuli Block
// TODO: Add support for Lapis Lazuli Block?
// Cobweb
ItemStack blockCobweb = new ItemStack(Block.web);
DecomposerRecipe.add(new DecomposerRecipe(blockCobweb,
new Chemical[] { this.molecule(EnumMolecule.fibroin) }));
// Tall Grass
ItemStack blockTallGrass = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(blockTallGrass, 0.1F,
new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
// Sandstone
ItemStack blockSandStone = new ItemStack(Block.sandStone, 1, 0);
ItemStack blockChiseledSandStone = new ItemStack(Block.sandStone, 1, 1);
ItemStack blockSmoothSandStone = new ItemStack(Block.sandStone, 1, 2);
DecomposerRecipe
.add(new DecomposerRecipe(blockSandStone, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe
.add(new DecomposerRecipe(blockChiseledSandStone,
new Chemical[] { this.molecule(
EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe
.add(new DecomposerRecipe(blockSmoothSandStone,
new Chemical[] { this.molecule(
EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSandStone, true, 20,
new Chemical[] { null, null, null, null,
this.molecule(EnumMolecule.siliconDioxide, 16), null,
null, null, null }));
SynthesisRecipe
.add(new SynthesisRecipe(blockChiseledSandStone, true, 20,
new Chemical[] { null, null, null, null, null, null,
null,
this.molecule(EnumMolecule.siliconDioxide, 16),
null }));
SynthesisRecipe.add(new SynthesisRecipe(blockSmoothSandStone, true, 20,
new Chemical[] { null,
this.molecule(EnumMolecule.siliconDioxide, 16), null,
null, null, null, null, null, null }));
// Wool
ItemStack blockWool = new ItemStack(Block.cloth, 1, 0);
ItemStack blockOrangeWool = new ItemStack(Block.cloth, 1, 1);
ItemStack blockMagentaWool = new ItemStack(Block.cloth, 1, 2);
ItemStack blockLightBlueWool = new ItemStack(Block.cloth, 1, 3);
ItemStack blockYellowWool = new ItemStack(Block.cloth, 1, 4);
ItemStack blockLimeWool = new ItemStack(Block.cloth, 1, 5);
ItemStack blockPinkWool = new ItemStack(Block.cloth, 1, 6);
ItemStack blockGrayWool = new ItemStack(Block.cloth, 1, 7);
ItemStack blockLightGrayWool = new ItemStack(Block.cloth, 1, 8);
ItemStack blockCyanWool = new ItemStack(Block.cloth, 1, 9);
ItemStack blockPurpleWool = new ItemStack(Block.cloth, 1, 10);
ItemStack blockBlueWool = new ItemStack(Block.cloth, 1, 11);
ItemStack blockBrownWool = new ItemStack(Block.cloth, 1, 12);
ItemStack blockGreenWool = new ItemStack(Block.cloth, 1, 13);
ItemStack blockRedWool = new ItemStack(Block.cloth, 1, 14);
ItemStack blockBlackWool = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(blockWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockOrangeWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockMagentaWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLightBlueWool,
0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockYellowWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLimeWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockPinkWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockGrayWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLightGrayWool,
0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockCyanWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockPurpleWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBlueWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBrownWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockGreenWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockRedWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBlackWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOrangeWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockMagentaWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLightBlueWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockYellowWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLimeWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPinkWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGrayWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLightGrayWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockCyanWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPurpleWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockBlueWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGreenWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockRedWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockBlackWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.blackPigment) }));
// Flowers
// TODO: Add support for Rose
ItemStack blockPlantYellow = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(blockPlantYellow, 0.3F,
new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
// Mushrooms
ItemStack blockMushroomBrown = new ItemStack(Block.mushroomBrown);
ItemStack blockMushroomRed = new ItemStack(Block.mushroomRed);
DecomposerRecipe.add(new DecomposerRecipe(blockMushroomBrown,
new Chemical[] { this.molecule(EnumMolecule.psilocybin),
this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(blockMushroomRed,
new Chemical[] { this.molecule(EnumMolecule.pantherine),
this.molecule(EnumMolecule.water, 2) }));
// Block of Gold
DecomposerRecipe.add(new DecomposerRecipe(
new ItemStack(Block.blockGold), new Chemical[] { this.element(
EnumElement.Au, 144) }));
// Block of Iron
DecomposerRecipe.add(new DecomposerRecipe(
new ItemStack(Block.blockIron), new Chemical[] { this.element(
EnumElement.Fe, 144) }));
// Slabs
// TODO: Add support for slabs?
// TNT
ItemStack blockTnt = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(blockTnt,
new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(blockTnt, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.tnt) }));
// Obsidian
ItemStack blockObsidian = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(blockObsidian,
new Chemical[] {
this.molecule(EnumMolecule.siliconDioxide, 16),
this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(blockObsidian, true, 1000,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.magnesiumOxide, 2), null,
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.magnesiumOxide, 2),
this.molecule(EnumMolecule.magnesiumOxide, 2),
this.molecule(EnumMolecule.magnesiumOxide, 2) }));
// Diamond Ore
ItemStack blockOreDiamond = new ItemStack(Block.oreDiamond);
DecomposerRecipe.add(new DecomposerRecipe(blockOreDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
// Block of Diamond
ItemStack blockDiamond = new ItemStack(Block.blockDiamond);
DecomposerRecipe.add(new DecomposerRecipe(blockDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
SynthesisRecipe.add(new SynthesisRecipe(blockDiamond, true, 120000,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4) }));
// Pressure Plate
ItemStack blockPressurePlatePlanks = new ItemStack(
Block.pressurePlatePlanks);
DecomposerRecipe.add(new DecomposerRecipeChance(
blockPressurePlatePlanks, 0.4F, new Chemical[] { this.molecule(
EnumMolecule.cellulose, 4) }));
// Redston Ore
ItemStack blockOreRedstone = new ItemStack(Block.oreRedstone);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOreRedstone, 0.8F,
new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 9),
this.element(EnumElement.Cu, 9) }));
// Cactus
ItemStack blockCactus = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(blockCactus, new Chemical[] {
this.molecule(EnumMolecule.mescaline),
this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(blockCactus, true, 200,
new Chemical[] { this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.mescaline), null,
this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.water, 5) }));
// Pumpkin
ItemStack blockPumpkin = new ItemStack(Block.pumpkin);
DecomposerRecipe.add(new DecomposerRecipe(blockPumpkin,
new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPumpkin, false, 400,
new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
// Netherrack
ItemStack blockNetherrack = new ItemStack(Block.netherrack);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockNetherrack, 0.1F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O),
this.element(EnumElement.Fe) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.Ni),
this.element(EnumElement.Tc) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 3),
this.element(EnumElement.Ti),
this.element(EnumElement.Fe) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 1),
this.element(EnumElement.W, 4),
this.element(EnumElement.Cr, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 10),
this.element(EnumElement.W, 1),
this.element(EnumElement.Zn, 8),
this.element(EnumElement.Be, 4) }) }));
// Water Bottle
ItemStack itemPotion = new ItemStack(Item.potion, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(itemPotion,
new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
// Soul Sand
ItemStack blockSlowSand = new ItemStack(Block.slowSand);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockSlowSand, 0.2F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb, 3),
this.element(EnumElement.Be, 1),
this.element(EnumElement.Si, 2),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb, 1),
this.element(EnumElement.Si, 5),
this.element(EnumElement.O, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 6),
this.element(EnumElement.O, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Es, 1),
this.element(EnumElement.O, 2) }) }));
// Glowstone
ItemStack blockGlowStone = new ItemStack(Block.glowStone);
DecomposerRecipe.add(new DecomposerRecipe(blockGlowStone,
new Chemical[] { this.element(EnumElement.P, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGlowStone, true, 500,
new Chemical[] { this.element(EnumElement.P), null,
this.element(EnumElement.P),
this.element(EnumElement.P), null,
this.element(EnumElement.P), null, null, null }));
// Glass Panes
ItemStack blockThinGlass = new ItemStack(Block.thinGlass);
DecomposerRecipe
.add(new DecomposerRecipe(blockThinGlass, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(blockThinGlass, true, 50,
new Chemical[] { null, null, null,
this.molecule(EnumMolecule.siliconDioxide), null, null,
null, null, null }));
// Melon
ItemStack blockMelon = new ItemStack(Block.melon);
DecomposerRecipe.add(new DecomposerRecipe(blockMelon, new Chemical[] {
this.molecule(EnumMolecule.cucurbitacin),
this.molecule(EnumMolecule.asparticAcid),
this.molecule(EnumMolecule.water, 16) }));
// Mycelium
ItemStack blockMycelium = new ItemStack(Block.mycelium);
DecomposerRecipe.add(new DecomposerRecipeChance(blockMycelium, 0.09F,
new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium,
16), false, 300, new Chemical[] { this
.molecule(EnumMolecule.fingolimod) }));
// End Stone
ItemStack blockWhiteStone = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockWhiteStone, 0.8F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O),
this.element(EnumElement.H, 4),
this.element(EnumElement.Li) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Es) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Pu) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Fr) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Nd) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O, 4) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.H, 4) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.Be, 8) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.Li, 2) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Zr) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Na) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Rb) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }) }));
// Emerald Ore
ItemStack blockOreEmerald = new ItemStack(Block.oreEmerald);
DecomposerRecipe.add(new DecomposerRecipe(blockOreEmerald,
new Chemical[] { this.molecule(EnumMolecule.beryl, 6),
this.element(EnumElement.Cr, 6),
this.element(EnumElement.V, 6) }));
// Emerald Block
ItemStack blockEmerald = new ItemStack(Block.blockEmerald);
SynthesisRecipe.add(new SynthesisRecipe(blockEmerald, true, 150000,
new Chemical[] { this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.V, 9),
this.molecule(EnumMolecule.beryl, 18),
this.element(EnumElement.V, 9),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(blockEmerald, new Chemical[] {
this.molecule(EnumMolecule.beryl, 18),
this.element(EnumElement.Cr, 18),
this.element(EnumElement.V, 18) }));
// Section 2 - Items
// Apple
ItemStack itemAppleRed = new ItemStack(Item.appleRed);
DecomposerRecipe.add(new DecomposerRecipe(itemAppleRed,
new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
SynthesisRecipe.add(new SynthesisRecipe(itemAppleRed, false, 400,
new Chemical[] { this.molecule(EnumMolecule.malicAcid),
this.molecule(EnumMolecule.water, 2) }));
// Arrow
ItemStack itemArrow = new ItemStack(Item.arrow);
DecomposerRecipe.add(new DecomposerRecipe(itemArrow, new Chemical[] {
this.element(EnumElement.Si), this.element(EnumElement.O, 2),
this.element(EnumElement.N, 6) }));
// Coal
ItemStack itemCoal = new ItemStack(Item.coal);
DecomposerRecipe.add(new DecomposerRecipe(itemCoal,
new Chemical[] { this.element(EnumElement.C, 16) }));
// Charcoal
// Does 16 charcoal to 1 coal seem balanced?
ItemStack itemChar = new ItemStack(Item.coal,1,1);
DecomposerRecipe.add(new DecomposerRecipe(itemChar, new Chemical[] { this.element(EnumElement.C, 30) }));
// Diamond
ItemStack itemDiamond = new ItemStack(Item.diamond);
DecomposerRecipe.add(new DecomposerRecipe(itemDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDiamond, true, '\uea60',
new Chemical[] { null, this.molecule(EnumMolecule.fullrene),
null, this.molecule(EnumMolecule.fullrene), null,
this.molecule(EnumMolecule.fullrene), null,
this.molecule(EnumMolecule.fullrene), null }));
// Iron Ingot
ItemStack itemIngotIron = new ItemStack(Item.ingotIron);
DecomposerRecipe.add(new DecomposerRecipe(itemIngotIron,
new Chemical[] { this.element(EnumElement.Fe, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(itemIngotIron, false, 1000,
new Chemical[] { this.element(EnumElement.Fe, 16) }));
// Gold Ingot
ItemStack itemIngotGold = new ItemStack(Item.ingotGold);
DecomposerRecipe.add(new DecomposerRecipe(itemIngotGold,
new Chemical[] { this.element(EnumElement.Au, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(itemIngotGold, false, 1000,
new Chemical[] { this.element(EnumElement.Au, 16) }));
// Stick
ItemStack itemStick = new ItemStack(Item.stick);
DecomposerRecipe.add(new DecomposerRecipeChance(itemStick, 0.3F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
// String
ItemStack itemSilk = new ItemStack(Item.silk);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSilk, 0.45F,
new Chemical[] { this.molecule(EnumMolecule.serine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSilk, true, 150,
new Chemical[] { this.molecule(EnumMolecule.serine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.alinine) }));
// Feather
ItemStack itemFeather = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(itemFeather, new Chemical[] {
this.molecule(EnumMolecule.water, 8),
this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(itemFeather, true, 800,
new Chemical[] { this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 2),
this.element(EnumElement.N),
this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 1),
this.element(EnumElement.N),
this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 5),
this.element(EnumElement.N) }));
// Gunpowder
ItemStack itemGunpowder = new ItemStack(Item.gunpowder);
DecomposerRecipe.add(new DecomposerRecipe(itemGunpowder,
new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate),
this.element(EnumElement.S, 2),
this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(itemGunpowder, true, 600,
new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate),
this.element(EnumElement.C), null,
this.element(EnumElement.S, 2), null, null, null, null,
null }));
// Bread
ItemStack itemBread = new ItemStack(Item.bread);
DecomposerRecipe.add(new DecomposerRecipeChance(itemBread, 0.1F,
new Chemical[] { this.molecule(EnumMolecule.starch),
this.molecule(EnumMolecule.sucrose) }));
// Flint
ItemStack itemFlint = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipeChance(itemFlint, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
SynthesisRecipe.add(new SynthesisRecipe(itemFlint, true, 100,
new Chemical[] { null, moleculeSiliconDioxide, null,
moleculeSiliconDioxide, moleculeSiliconDioxide,
moleculeSiliconDioxide, null, null, null }));
// Golden Apple
ItemStack itemAppleGold = new ItemStack(Item.appleGold, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(itemAppleGold,
new Chemical[] { this.molecule(EnumMolecule.malicAcid),
this.element(EnumElement.Au, 64) }));
// Wooden Door
ItemStack itemDoorWood = new ItemStack(Item.doorWood);
DecomposerRecipe.add(new DecomposerRecipeChance(itemDoorWood, 0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
// Water Bucket
ItemStack itemBucketWater = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipe(itemBucketWater,
- new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
+ new Chemical[] { this.molecule(EnumMolecule.water, 16),this.element(EnumElement.Fe, 48) }));
// Redstone
ItemStack itemRedstone = new ItemStack(Item.redstone);
DecomposerRecipe.add(new DecomposerRecipeChance(itemRedstone, 0.42F,
new Chemical[] { this.molecule(EnumMolecule.iron3oxide),
this.element(EnumElement.Cu) }));
SynthesisRecipe
.add(new SynthesisRecipe(itemRedstone, true, 100,
new Chemical[] { null, null,
this.molecule(EnumMolecule.iron3oxide), null,
this.element(EnumElement.Cu), null, null, null,
null }));
// Snowball
ItemStack itemSnowball = new ItemStack(Item.snowball);
DecomposerRecipe.add(new DecomposerRecipe(itemSnowball,
new Chemical[] { this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(
new ItemStack(Item.snowball, 5), true, 20, new Chemical[] {
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water) }));
// Leather
ItemStack itemLeather = new ItemStack(Item.leather);
DecomposerRecipe.add(new DecomposerRecipeChance(itemLeather, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.arginine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.keratin) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5),
true, 700, new Chemical[] {
this.molecule(EnumMolecule.arginine), null, null, null,
this.molecule(EnumMolecule.keratin), null, null, null,
this.molecule(EnumMolecule.glycine) }));
// Brick
ItemStack itemBrick = new ItemStack(Item.brick);
DecomposerRecipe.add(new DecomposerRecipeChance(itemBrick, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8),
true, 400, new Chemical[] {
this.molecule(EnumMolecule.kaolinite),
this.molecule(EnumMolecule.kaolinite), null,
this.molecule(EnumMolecule.kaolinite),
this.molecule(EnumMolecule.kaolinite), null }));
// Clay
ItemStack itemClay = new ItemStack(Item.clay);
DecomposerRecipe.add(new DecomposerRecipeChance(itemClay, 0.3F,
new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12),
false, 100, new Chemical[] { this
.molecule(EnumMolecule.kaolinite) }));
// Reed
ItemStack itemReed = new ItemStack(Item.reed);
DecomposerRecipe.add(new DecomposerRecipeChance(itemReed, 0.65F,
new Chemical[] { this.molecule(EnumMolecule.sucrose),
this.element(EnumElement.H, 2),
this.element(EnumElement.O) }));
// Paper
ItemStack itemPaper = new ItemStack(Item.paper);
DecomposerRecipe.add(new DecomposerRecipeChance(itemPaper, 0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16),
true, 150, new Chemical[] { null,
this.molecule(EnumMolecule.cellulose), null, null,
this.molecule(EnumMolecule.cellulose), null, null,
this.molecule(EnumMolecule.cellulose), null }));
// Slimeball
ItemStack itemSlimeBall = new ItemStack(Item.slimeBall);
DecomposerRecipe.add(new DecomposerRecipeSelect(itemSlimeBall, 0.9F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] { this
.molecule(EnumMolecule.polycyanoacrylate) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Hg) }),
new DecomposerRecipe(new Chemical[] { this.molecule(
EnumMolecule.water, 10) }) }));
// Glowstone Dust
ItemStack itemGlowstone = new ItemStack(Item.glowstone);
DecomposerRecipe.add(new DecomposerRecipe(itemGlowstone,
new Chemical[] { this.element(EnumElement.P) }));
// Dyes
ItemStack itemDyePowderBlack = new ItemStack(Item.dyePowder, 1, 0);
ItemStack itemDyePowderRed = new ItemStack(Item.dyePowder, 1, 1);
ItemStack itemDyePowderGreen = new ItemStack(Item.dyePowder, 1, 2);
ItemStack itemDyePowderBrown = new ItemStack(Item.dyePowder, 1, 3);
ItemStack itemDyePowderBlue = new ItemStack(Item.dyePowder, 1, 4);
ItemStack itemDyePowderPurple = new ItemStack(Item.dyePowder, 1, 5);
ItemStack itemDyePowderCyan = new ItemStack(Item.dyePowder, 1, 6);
ItemStack itemDyePowderLightGray = new ItemStack(Item.dyePowder, 1, 7);
ItemStack itemDyePowderGray = new ItemStack(Item.dyePowder, 1, 8);
ItemStack itemDyePowderPink = new ItemStack(Item.dyePowder, 1, 9);
ItemStack itemDyePowderLime = new ItemStack(Item.dyePowder, 1, 10);
ItemStack itemDyePowderYellow = new ItemStack(Item.dyePowder, 1, 11);
ItemStack itemDyePowderLightBlue = new ItemStack(Item.dyePowder, 1, 12);
ItemStack itemDyePowderMagenta = new ItemStack(Item.dyePowder, 1, 13);
ItemStack itemDyePowderOrange = new ItemStack(Item.dyePowder, 1, 14);
ItemStack itemDyePowderWhite = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlack,
new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderRed,
new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGreen,
new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(itemDyePowderBrown,
0.4F, new Chemical[] { this.molecule(EnumMolecule.theobromine),
this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlue,
new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPurple,
new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderCyan,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLightGray,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGray,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPink,
new Chemical[] { this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLime,
new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderYellow,
new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe
.add(new DecomposerRecipe(itemDyePowderLightBlue,
new Chemical[] { this
.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderMagenta,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderOrange,
new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderWhite,
new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlack, false, 50,
new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderRed, false, 50,
new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGreen, false, 50,
new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBrown, false, 400,
new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlue, false, 50,
new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPurple, false, 50,
new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderCyan, false, 50,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightGray, false,
50, new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGray, false, 50,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPink, false, 50,
new Chemical[] { this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLime, false, 50,
new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderYellow, false, 50,
new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightBlue, false,
50, new Chemical[] { this
.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderMagenta, false,
50, new Chemical[] {
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderOrange, false, 50,
new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderWhite, false, 50,
new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
// Bone
ItemStack itemBone = new ItemStack(Item.bone);
DecomposerRecipe
.add(new DecomposerRecipe(itemBone, new Chemical[] { this
.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe
.add(new SynthesisRecipe(itemBone, false, 100,
new Chemical[] { this
.molecule(EnumMolecule.hydroxylapatite) }));
// Sugar
ItemStack itemSugar = new ItemStack(Item.sugar);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSugar, 0.75F,
new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSugar, false, 400,
new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
// Melon
ItemStack itemMelon = new ItemStack(Item.melon);
DecomposerRecipe.add(new DecomposerRecipe(itemMelon,
new Chemical[] { this.molecule(EnumMolecule.water) }));
// Cooked Chicken
ItemStack itemChickenCooked = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipe(itemChickenCooked, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemChickenCooked, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
// Rotten Flesh
ItemStack itemRottenFlesh = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(itemRottenFlesh, 0.05F,
new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
// Enderpearl
ItemStack itemEnderPearl = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(itemEnderPearl,
new Chemical[] { this.element(EnumElement.Es),
this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(itemEnderPearl, true, 5000,
new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.element(EnumElement.Es),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate) }));
// Blaze Rod
ItemStack itemBlazeRod = new ItemStack(Item.blazeRod);
DecomposerRecipe.add(new DecomposerRecipe(itemBlazeRod,
new Chemical[] { this.element(EnumElement.Pu, 3) }));
SynthesisRecipe.add(new SynthesisRecipe(itemBlazeRod, true, 15000,
new Chemical[] { this.element(EnumElement.Pu), null, null,
this.element(EnumElement.Pu), null, null,
this.element(EnumElement.Pu), null, null }));
// Ghast Tear
ItemStack itemGhastTear = new ItemStack(Item.ghastTear);
DecomposerRecipe.add(new DecomposerRecipe(itemGhastTear,
new Chemical[] { this.element(EnumElement.Yb, 4),
this.element(EnumElement.No, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(itemGhastTear, true, 15000,
new Chemical[] { this.element(EnumElement.Yb),
this.element(EnumElement.Yb),
this.element(EnumElement.No), null,
this.element(EnumElement.Yb, 2),
this.element(EnumElement.No, 2), null,
this.element(EnumElement.No), null }));
// Nether Wart
ItemStack itemNetherStalkSeeds = new ItemStack(Item.netherStalkSeeds);
DecomposerRecipe.add(new DecomposerRecipeChance(itemNetherStalkSeeds,
0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) }));
// Spider Eye
ItemStack itemSpiderEye = new ItemStack(Item.spiderEye);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSpiderEye, 0.2F,
new Chemical[] { this.molecule(EnumMolecule.ttx) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSpiderEye, true, 2000,
new Chemical[] { this.element(EnumElement.C), null, null, null,
this.molecule(EnumMolecule.ttx), null, null, null,
this.element(EnumElement.C) }));
// Fermented Spider Eye
ItemStack itemFermentedSpiderEye = new ItemStack(
Item.fermentedSpiderEye);
DecomposerRecipe.add(new DecomposerRecipe(itemFermentedSpiderEye,
new Chemical[] { this.element(EnumElement.Po),
this.molecule(EnumMolecule.ethanol) }));
// Blaze Powder
ItemStack itemBlazePowder = new ItemStack(Item.blazePowder);
DecomposerRecipe.add(new DecomposerRecipe(itemBlazePowder,
new Chemical[] { this.element(EnumElement.Pu) }));
// Magma Cream
ItemStack itemMagmaCream = new ItemStack(Item.magmaCream);
DecomposerRecipe.add(new DecomposerRecipe(itemMagmaCream,
new Chemical[] { this.element(EnumElement.Hg),
this.element(EnumElement.Pu),
this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
SynthesisRecipe.add(new SynthesisRecipe(itemMagmaCream, true, 5000,
new Chemical[] { null, this.element(EnumElement.Pu), null,
this.molecule(EnumMolecule.polycyanoacrylate),
this.element(EnumElement.Hg),
this.molecule(EnumMolecule.polycyanoacrylate), null,
this.molecule(EnumMolecule.polycyanoacrylate), null }));
// Glistering Melon
ItemStack itemSpeckledMelon = new ItemStack(Item.speckledMelon);
DecomposerRecipe.add(new DecomposerRecipe(itemSpeckledMelon,
new Chemical[] { this.molecule(EnumMolecule.water, 4),
this.molecule(EnumMolecule.whitePigment),
this.element(EnumElement.Au, 1) }));
// Emerald
ItemStack itemEmerald = new ItemStack(Item.emerald);
DecomposerRecipe.add(new DecomposerRecipe(itemEmerald,
new Chemical[] { this.molecule(EnumMolecule.beryl, 2),
this.element(EnumElement.Cr, 2),
this.element(EnumElement.V, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemEmerald, true, 80000,
new Chemical[] { null, this.element(EnumElement.Cr), null,
this.element(EnumElement.V),
this.molecule(EnumMolecule.beryl, 2),
this.element(EnumElement.V), null,
this.element(EnumElement.Cr), null }));
// Carrot
ItemStack itemCarrot = new ItemStack(Item.carrot);
DecomposerRecipe.add(new DecomposerRecipe(itemCarrot,
new Chemical[] { this.molecule(EnumMolecule.ret) }));
// Potato
ItemStack itemPotato = new ItemStack(Item.potato);
DecomposerRecipe.add(new DecomposerRecipeChance(itemPotato, 0.4F,
new Chemical[] { this.molecule(EnumMolecule.water, 8),
this.element(EnumElement.K, 2),
this.molecule(EnumMolecule.cellulose) }));
// Golden Carrot
ItemStack itemGoldenCarrot = new ItemStack(Item.goldenCarrot);
DecomposerRecipe.add(new DecomposerRecipe(itemGoldenCarrot,
new Chemical[] { this.molecule(EnumMolecule.ret),
this.element(EnumElement.Au, 4) }));
// Nether Star
ItemStack itemNetherStar = new ItemStack(Item.netherStar);
DecomposerRecipe.add(new DecomposerRecipe(itemNetherStar,
new Chemical[] { this.element(EnumElement.Cn, 16),
elementHydrogen, elementHydrogen, elementHydrogen,
elementHelium, elementHelium, elementHelium,
elementCarbon, elementCarbon }));
SynthesisRecipe.add(new SynthesisRecipe(itemNetherStar, true, 500000,
new Chemical[] { elementHelium, elementHelium, elementHelium,
elementCarbon, this.element(EnumElement.Cn, 16),
elementHelium, elementHydrogen, elementHydrogen,
elementHydrogen }));
// Nether Quartz
ItemStack itemNetherQuartz = new ItemStack(Item.netherQuartz);
DecomposerRecipe.add(new DecomposerRecipe(itemNetherQuartz,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.galliumarsenide, 1) }));
// Music Records
ItemStack itemRecord13 = new ItemStack(Item.record13);
ItemStack itemRecordCat = new ItemStack(Item.recordCat);
ItemStack itemRecordFar = new ItemStack(Item.recordFar);
ItemStack itemRecordMall = new ItemStack(Item.recordMall);
ItemStack itemRecordMellohi = new ItemStack(Item.recordMellohi);
ItemStack itemRecordStal = new ItemStack(Item.recordStal);
ItemStack itemRecordStrad = new ItemStack(Item.recordStrad);
ItemStack itemRecordWard = new ItemStack(Item.recordWard);
ItemStack itemRecordChirp = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(itemRecord13,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordCat,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordFar,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMall,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMellohi,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStal,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStrad,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordWard,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordChirp,
new Chemical[] { moleculePolyvinylChloride }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecord13, true, 1000,
new Chemical[] { moleculePolyvinylChloride, null, null, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordCat, true, 1000,
new Chemical[] { null, moleculePolyvinylChloride, null, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordFar, true, 1000,
new Chemical[] { null, null, moleculePolyvinylChloride, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMall, true, 1000,
new Chemical[] { null, null, null, moleculePolyvinylChloride,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMellohi, true, 1000,
new Chemical[] { null, null, null, null,
moleculePolyvinylChloride, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStal, true, 1000,
new Chemical[] { null, null, null, null, null,
moleculePolyvinylChloride, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStrad, true, 1000,
new Chemical[] { null, null, null, null, null, null,
moleculePolyvinylChloride, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordWard, true, 1000,
new Chemical[] { null, null, null, null, null, null, null,
moleculePolyvinylChloride, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordChirp, true, 1000,
new Chemical[] { null, null, null, null, null, null, null,
null, moleculePolyvinylChloride }));
}
public void RegisterRecipes() {
this.registerVanillaChemicalRecipes();
ItemStack blockGlass = new ItemStack(Block.glass);
ItemStack blockThinGlass = new ItemStack(Block.thinGlass);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack itemIngotIron = new ItemStack(Item.ingotIron);
ItemStack itemRedstone = new ItemStack(Item.redstone);
ItemStack minechemItemsAtomicManipulator = new ItemStack(MinechemItems.atomicManipulator);
ItemStack mineChemItemsTestTube = new ItemStack(MinechemItems.testTube, 16);
ItemStack moleculePolyvinylChloride = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(mineChemItemsTestTube, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), blockGlass });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), blockGlass });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), blockGlass });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), blockThinGlass, Character.valueOf('I'), itemIngotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), minechemItemsAtomicManipulator, Character.valueOf('I'), itemIngotIron, Character.valueOf('R'), itemRedstone });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), minechemItemsAtomicManipulator, Character.valueOf('I'), itemIngotIron, Character.valueOf('R'), itemRedstone, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), itemIngotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), itemIngotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), itemIngotIron, Character.valueOf('P'), blockThinGlass, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), moleculePolyvinylChloride });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), moleculePolyvinylChloride });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), moleculePolyvinylChloride });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), moleculePolyvinylChloride });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.EmptyPillz,4), new Object[] { new ItemStack(Item.sugar), new ItemStack(Item.slimeBall), new ItemStack(Item.slimeBall) });
//Fusion
GameRegistry.addShapelessRecipe(ItemBlueprint.createItemStackFromBlueprint(MinechemBlueprint.fusion), new Object[] { new ItemStack(Item.paper), new ItemStack(Block.blockDiamond)});
//Fission
GameRegistry.addShapelessRecipe(ItemBlueprint.createItemStackFromBlueprint(MinechemBlueprint.fission), new Object[] { new ItemStack(Item.paper), new ItemStack(Item.diamond)});
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(MinechemBlocks.uranium), new Chemical[] { this.element(EnumElement.U, 32) }));
//
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
this.registerPoisonRecipes(EnumMolecule.radchlor); // Whoa, oh, oh, oh, I'm radioactive, radioactive
this.registerPoisonRecipes(EnumMolecule.redrocks);
this.registerPoisonRecipes(EnumMolecule.coke);
this.registerPoisonRecipes(EnumMolecule.theobromine);
this.registerPoisonRecipes(EnumMolecule.ctaxifolia);
this.registerPoisonRecipes(EnumMolecule.latropine);
}
private void addDecomposerRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
Chemical[] var6 = (Chemical[]) var5.toArray(new Chemical[var5.size()]);
ItemStack var7 = new ItemStack(MinechemItems.molecule, 1, var4.id());
DecomposerRecipe.add(new DecomposerRecipe(var7, var6));
}
}
private void addSynthesisRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
ItemStack var6 = new ItemStack(MinechemItems.molecule, 1, var4.id());
SynthesisRecipe.add(new SynthesisRecipe(var6, false, 50, var5));
}
}
private void addUnusedSynthesisRecipes() {
Iterator var1 = DecomposerRecipe.recipes.iterator();
while (var1.hasNext()) {
DecomposerRecipe var2 = (DecomposerRecipe) var1.next();
if (var2.getInput().getItemDamage() != -1) {
boolean var3 = false;
Iterator var4 = SynthesisRecipe.recipes.iterator();
//What kind of crappy code is this?
//I've got to fix it.....If I can figure out what it does
while (true) {
if (var4.hasNext()) {
SynthesisRecipe var5 = (SynthesisRecipe) var4.next();
if (!Util.stacksAreSameKind(var5.getOutput(), var2.getInput())) {
continue;
}
var3 = true;
}
if (!var3) {
ArrayList var6 = var2.getOutputRaw();
if (var6 != null) {
SynthesisRecipe.add(new SynthesisRecipe(var2.getInput(), false, 100, var6));
}
}
break;
}
}
}
}
private ItemStack createPoisonedItemStack(Item var1, int var2, EnumMolecule var3) {
ItemStack var4 = new ItemStack(MinechemItems.molecule, 1, var3.id());
ItemStack var5 = new ItemStack(var1, 1, var2);
ItemStack var6 = new ItemStack(var1, 1, var2);
NBTTagCompound var7 = new NBTTagCompound();
var7.setBoolean("minechem.isPoisoned", true);
var7.setInteger("minechem.effectType", var3.id());
var6.setTagCompound(var7);
GameRegistry.addShapelessRecipe(var6, new Object[]{var4, var5});
return var6;
}
private void registerPoisonRecipes(EnumMolecule molecule) {
for(Item i: Item.itemsList) { // Thanks Adrian!
if(i != null && i instanceof ItemFood) { // Should allow for lacing of BOP and AquaCulture foodstuffs.
this.createPoisonedItemStack(i, 0, molecule);
}
}
}
/*
* This stuff is unused and is replaced by ljdp.minechem.common.recipe.handlers.DefaultOreDictionaryHandler
String[] compounds = {"Aluminium","Titanium","Chrome",
"Tungsten", "Lead", "Zinc",
"Platinum", "Nickel", "Osmium",
"Iron", "Gold", "Coal",
"Copper", "Tin", "Silver",
"RefinedIron",
"Steel",
"Bronze", "Brass", "Electrum",
"Invar"};//,"Iridium"};
EnumElement[][] elements = {{EnumElement.Al}, {EnumElement.Ti}, {EnumElement.Cr},
{EnumElement.W}, {EnumElement.Pb}, {EnumElement.Zn},
{EnumElement.Pt}, {EnumElement.Ni}, {EnumElement.Os},
{EnumElement.Fe}, {EnumElement.Au}, {EnumElement.C},
{EnumElement.Cu}, {EnumElement.Sn}, {EnumElement.Ag},
{EnumElement.Fe},
{EnumElement.Fe, EnumElement.C}, //Steel
{EnumElement.Sn, EnumElement.Cu},
{EnumElement.Cu},//Bronze
{EnumElement.Zn, EnumElement.Cu}, //Brass
{EnumElement.Ag, EnumElement.Au}, //Electrum
{EnumElement.Fe, EnumElement.Ni} //Invar
};//, EnumElement.Ir
int[][] proportions = {{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},
{4,4},
{1,3},{1,3},{2,2},{2,1}};
String[] itemTypes = {"dustSmall", "dust", "ore" , "ingot", "block", "gear", "plate"}; //"nugget", "plate"
boolean[] craftable = {true, true, false, false, false, false, false};
int[] sizeCoeff = {1, 4, 8, 4, 36, 16, 4};
*/
private ArrayList<OreDictionaryHandler> oreDictionaryHandlers;
@ForgeSubscribe
public void oreEvent(OreDictionary.OreRegisterEvent var1) {
if (var1.Name.contains("gemApatite")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Ca, 5),
this.molecule(EnumMolecule.phosphate, 4),
this.element(EnumElement.Cl) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.element(EnumElement.Ca, 5),
this.molecule(EnumMolecule.phosphate, 4),
this.element(EnumElement.Cl) }));
} else if (var1.Name.contains("Ruby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.aluminiumOxide),
this.element(EnumElement.Cr) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] {
this.molecule(EnumMolecule.aluminiumOxide),
this.element(EnumElement.Cr) }));
} else if (var1.Name.contains("Sapphire")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore,
new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide,
2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide,
2) }));
} else if (var1.Name.contains("ingotBronze")) {
if (Loader.isModLoaded("Mekanism")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore,
new Chemical[] { this.element(EnumElement.Cu, 16),
this.element(EnumElement.Sn, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.element(EnumElement.Cu, 16),
this.element(EnumElement.Sn, 2) }));
} else {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore,
new Chemical[] { this.element(EnumElement.Cu, 24),
this.element(EnumElement.Sn, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.element(EnumElement.Cu, 24),
this.element(EnumElement.Sn, 8) }));
}
} else if (var1.Name.contains("plateSilicon")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore,
new Chemical[] { this.element(EnumElement.Si, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.element(EnumElement.Si, 2) }));
} else if (var1.Name.contains("xychoriumBlue")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Zr, 2),
this.element(EnumElement.Cu, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300,
new Chemical[] { this.element(EnumElement.Zr, 2),
this.element(EnumElement.Cu, 1) }));
} else if (var1.Name.contains("xychoriumRed")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Zr, 2),
this.element(EnumElement.Fe, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300,
new Chemical[] { this.element(EnumElement.Zr, 2),
this.element(EnumElement.Fe, 1) }));
} else if (var1.Name.contains("xychoriumGreen")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Zr, 2),
this.element(EnumElement.V, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300,
new Chemical[] { this.element(EnumElement.Zr, 2),
this.element(EnumElement.V, 1) }));
} else if (var1.Name.contains("xychoriumDark")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Zr, 2),
this.element(EnumElement.Si, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300,
new Chemical[] { this.element(EnumElement.Zr, 2),
this.element(EnumElement.Si, 1) }));
} else if (var1.Name.contains("xychoriumLight")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Zr, 2),
this.element(EnumElement.Ti, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300,
new Chemical[] { this.element(EnumElement.Zr, 2),
this.element(EnumElement.Ti, 1) }));
} else if (var1.Name.contains("ingotCobalt")) { // Tungsten - Cobalt
// Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Co, 2),
this.element(EnumElement.W, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000,
new Chemical[] { this.element(EnumElement.Co, 2),
this.element(EnumElement.W, 2) }));
} else if (var1.Name.contains("ingotArdite")) { // Tungsten - Iron -
// Silicon Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Fe, 2),
this.element(EnumElement.W, 2),
this.element(EnumElement.Si, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000,
new Chemical[] { this.element(EnumElement.Fe, 2),
this.element(EnumElement.W, 2),
this.element(EnumElement.Si, 2) }));
} else if (var1.Name.contains("ingotManyullyn")) { // Tungsten - Iron -
// Silicon - Cobalt
// Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.element(EnumElement.Fe, 2),
this.element(EnumElement.W, 2),
this.element(EnumElement.Si, 2),
this.element(EnumElement.Co, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 7000,
new Chemical[] { this.element(EnumElement.Fe, 2),
this.element(EnumElement.W, 2),
this.element(EnumElement.Si, 2),
this.element(EnumElement.Co, 2) }));
} else if (var1.Name.contains("gemRuby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.aluminiumOxide),
this.element(EnumElement.Cr) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] {
this.molecule(EnumMolecule.aluminiumOxide),
this.element(EnumElement.Cr) }));
} else if (var1.Name.contains("gemSapphire")) {
DecomposerRecipe
.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this
.molecule(EnumMolecule.aluminiumOxide) }));
SynthesisRecipe
.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this
.molecule(EnumMolecule.aluminiumOxide) }));
} else if (var1.Name.contains("gemPeridot")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore,
new Chemical[] { this.molecule(EnumMolecule.olivine) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.olivine) }));
} else if (var1.Name.contains("cropMaloberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.stevenk),
this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.stevenk),
this.molecule(EnumMolecule.sucrose) }));
} else if (var1.Name.contains("cropDuskberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.psilocybin),
this.element(EnumElement.S, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.psilocybin),
this.element(EnumElement.S, 2) }));
} else if (var1.Name.contains("cropSkyberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.theobromine),
this.element(EnumElement.S, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.theobromine),
this.element(EnumElement.S, 2) }));
} else if (var1.Name.contains("cropBlightberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.asprin),
this.element(EnumElement.S, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.asprin),
this.element(EnumElement.S, 2) }));
} else if (var1.Name.contains("cropBlueberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.blueorgodye),
this.molecule(EnumMolecule.sucrose, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.blueorgodye),
this.molecule(EnumMolecule.sucrose, 2) }));
} else if (var1.Name.contains("cropRaspberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.redorgodye),
this.molecule(EnumMolecule.sucrose, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.redorgodye),
this.molecule(EnumMolecule.sucrose, 2) }));
} else if (var1.Name.contains("cropBlackberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] {
this.molecule(EnumMolecule.purpleorgodye),
this.molecule(EnumMolecule.sucrose, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.purpleorgodye),
this.molecule(EnumMolecule.sucrose, 2) }));
} else {
for (OreDictionaryHandler handler : this.oreDictionaryHandlers) {
if (handler.canHandle(var1)) {
handler.handle(var1);
return;
}
}
}
}
// END
// BEGIN MISC FUNCTIONS
private Element element(EnumElement var1, int var2) {
return new Element(var1, var2);
}
private Element element(EnumElement var1) {
return new Element(var1, 1);
}
private Molecule molecule(EnumMolecule var1, int var2) {
return new Molecule(var1, var2);
}
private Molecule molecule(EnumMolecule var1) {
return new Molecule(var1, 1);
}
// END
public void RegisterHandlers() {
this.oreDictionaryHandlers = new ArrayList<OreDictionaryHandler>();
if (Loader.isModLoaded("Mekanism"))
this.oreDictionaryHandlers.add(new MekanismOreDictionaryHandler());
if (Loader.isModLoaded("UndergroundBiomes"))
this.oreDictionaryHandlers.add(new UndergroundBiomesOreDictionaryHandler());
if (Loader.isModLoaded("gregtech_addon"))
this.oreDictionaryHandlers.add(new GregTechOreDictionaryHandler());
if (Loader.isModLoaded("IC2"))
this.oreDictionaryHandlers.add(new IC2OreDictionaryHandler());
if (Loader.isModLoaded("AppliedEnergistics"))
this.oreDictionaryHandlers.add(new AppliedEnergisticsOreDictionaryHandler());
this.oreDictionaryHandlers.add(new DefaultOreDictionaryHandler());
}
} // EOF
| true | true | public void registerVanillaChemicalRecipes() {
// Molecules
Molecule moleculeSiliconDioxide = this.molecule(
EnumMolecule.siliconDioxide, 4);
Molecule moleculeCellulose = this.molecule(EnumMolecule.cellulose, 1);
Molecule moleculePolyvinylChloride = this
.molecule(EnumMolecule.polyvinylChloride);
// Elements
Element elementHydrogen = this.element(EnumElement.H, 64);
Element elementHelium = this.element(EnumElement.He, 64);
Element elementCarbon = this.element(EnumElement.C, 64);
// Section 1 - Blocks
// Stone
ItemStack blockStone = new ItemStack(Block.stone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockStone, 0.2F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7),
true, 50, new Chemical[] { this.element(EnumElement.Si), null,
null, this.element(EnumElement.O, 2), null, null }));
// Grass Block
ItemStack blockGrass = new ItemStack(Block.grass);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockGrass, 0.07F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }),
new DecomposerRecipe(
new Chemical[] { moleculeCellulose }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.grass, 16),
true, 50, new Chemical[] { null, moleculeCellulose, null, null,
this.element(EnumElement.O, 2),
this.element(EnumElement.Si) }));
// Dirt
ItemStack blockDirt = new ItemStack(Block.dirt);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockDirt, 0.07F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16),
true, 50, new Chemical[] { null, null, null, null,
this.element(EnumElement.O, 2),
this.element(EnumElement.Si) }));
// Cobblestone
ItemStack blockCobblestone = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockCobblestone, 0.1F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Na),
this.element(EnumElement.Cl) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(
Block.cobblestone, 8), true, 50, new Chemical[] {
this.element(EnumElement.Si), null, null, null,
this.element(EnumElement.O, 2), null }));
// Planks
// TODO: Add synthesizer recipes?
ItemStack blockOakWoodPlanks = new ItemStack(Block.planks, 1, 0);
ItemStack blockSpruceWoodPlanks = new ItemStack(Block.planks, 1, 1);
ItemStack blockBirchWoodPlanks = new ItemStack(Block.planks, 1, 2);
ItemStack blockJungleWoodPlanks = new ItemStack(Block.planks, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
// Saplings
ItemStack blockOakSapling = new ItemStack(Block.sapling, 1, 0);
ItemStack blockSpruceSapling = new ItemStack(Block.sapling, 1, 1);
ItemStack blockBirchSapling = new ItemStack(Block.sapling, 1, 2);
ItemStack blockJungleSapling = new ItemStack(Block.sapling, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakSapling, 0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockSpruceSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockBirchSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockJungleSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOakSapling, true, 20,
new Chemical[] { null, null, null, null, null, null, null,
null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSpruceSapling, true, 20,
new Chemical[] { null, null, null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(blockBirchSapling, true, 20,
new Chemical[] { null, null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe
.add(new SynthesisRecipe(blockJungleSapling, true, 20,
new Chemical[] { null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null,
null, null }));
// Water
ItemStack blockWaterSource = new ItemStack(Block.waterMoving);
ItemStack blockWaterStill = new ItemStack(Block.waterStill);
DecomposerRecipe.add(new DecomposerRecipe(blockWaterSource,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(blockWaterStill,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockWaterSource, false, 20,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
// Lava
// TODO: Add support for lava
// Sand
ItemStack blockSand = new ItemStack(Block.sand);
DecomposerRecipe
.add(new DecomposerRecipe(blockSand, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSand, true, 200,
new Chemical[] { moleculeSiliconDioxide,
moleculeSiliconDioxide, moleculeSiliconDioxide,
moleculeSiliconDioxide }));
// Gravel
ItemStack blockGravel = new ItemStack(Block.gravel);
DecomposerRecipe.add(new DecomposerRecipeChance(blockGravel, 0.35F,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGravel, true, 30,
new Chemical[] { null, null, null, null, null, null, null,
null, this.molecule(EnumMolecule.siliconDioxide) }));
// Gold Ore
ItemStack oreGold = new ItemStack(Block.oreGold);
DecomposerRecipe.add(new DecomposerRecipe(oreGold,
new Chemical[] { this.element(EnumElement.Au, 48) }));
// Iron Ore
ItemStack oreIron = new ItemStack(Block.oreIron);
DecomposerRecipe.add(new DecomposerRecipe(oreIron,
new Chemical[] { this.element(EnumElement.Fe, 48) }));
// Coal Ore
ItemStack oreCoal = new ItemStack(Block.oreCoal);
DecomposerRecipe.add(new DecomposerRecipe(oreCoal,
new Chemical[] { this.element(EnumElement.C, 48) }));
// Wood
ItemStack blockOakWood = new ItemStack(Block.wood, 1, 0);
ItemStack blockSpruceWood = new ItemStack(Block.wood, 1, 1);
ItemStack blockBirchWood = new ItemStack(Block.wood, 1, 2);
ItemStack blockJungleWood = new ItemStack(Block.wood, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOakWood, true, 100,
new Chemical[] { moleculeCellulose, moleculeCellulose,
moleculeCellulose, null, moleculeCellulose, null, null,
null, null }));
SynthesisRecipe.add(new SynthesisRecipe(blockSpruceWood, true, 100,
new Chemical[] { null, null, null, null, moleculeCellulose,
null, moleculeCellulose, moleculeCellulose,
moleculeCellulose }));
SynthesisRecipe.add(new SynthesisRecipe(blockBirchWood, true, 100,
new Chemical[] { moleculeCellulose, null, moleculeCellulose,
null, null, null, moleculeCellulose, null,
moleculeCellulose }));
SynthesisRecipe.add(new SynthesisRecipe(blockJungleWood, true, 100,
new Chemical[] { moleculeCellulose, null, null,
moleculeCellulose, moleculeCellulose, null,
moleculeCellulose, null, null }));
// Leaves
// TODO: Add support for leaves
// Glass
ItemStack blockGlass = new ItemStack(Block.glass);
DecomposerRecipe
.add(new DecomposerRecipe(blockGlass, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe
.add(new SynthesisRecipe(blockGlass, true, 500, new Chemical[] {
moleculeSiliconDioxide, null, moleculeSiliconDioxide,
null, null, null, moleculeSiliconDioxide, null,
moleculeSiliconDioxide }));
// Lapis Lazuli Ore
ItemStack blockOreLapis = new ItemStack(Block.oreLapis);
DecomposerRecipe.add(new DecomposerRecipe(blockOreLapis,
new Chemical[] { this.molecule(EnumMolecule.lazurite, 6),
this.molecule(EnumMolecule.sodalite),
this.molecule(EnumMolecule.noselite),
this.molecule(EnumMolecule.calcite),
this.molecule(EnumMolecule.pyrite) }));
// Lapis Lazuli Block
// TODO: Add support for Lapis Lazuli Block?
// Cobweb
ItemStack blockCobweb = new ItemStack(Block.web);
DecomposerRecipe.add(new DecomposerRecipe(blockCobweb,
new Chemical[] { this.molecule(EnumMolecule.fibroin) }));
// Tall Grass
ItemStack blockTallGrass = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(blockTallGrass, 0.1F,
new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
// Sandstone
ItemStack blockSandStone = new ItemStack(Block.sandStone, 1, 0);
ItemStack blockChiseledSandStone = new ItemStack(Block.sandStone, 1, 1);
ItemStack blockSmoothSandStone = new ItemStack(Block.sandStone, 1, 2);
DecomposerRecipe
.add(new DecomposerRecipe(blockSandStone, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe
.add(new DecomposerRecipe(blockChiseledSandStone,
new Chemical[] { this.molecule(
EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe
.add(new DecomposerRecipe(blockSmoothSandStone,
new Chemical[] { this.molecule(
EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSandStone, true, 20,
new Chemical[] { null, null, null, null,
this.molecule(EnumMolecule.siliconDioxide, 16), null,
null, null, null }));
SynthesisRecipe
.add(new SynthesisRecipe(blockChiseledSandStone, true, 20,
new Chemical[] { null, null, null, null, null, null,
null,
this.molecule(EnumMolecule.siliconDioxide, 16),
null }));
SynthesisRecipe.add(new SynthesisRecipe(blockSmoothSandStone, true, 20,
new Chemical[] { null,
this.molecule(EnumMolecule.siliconDioxide, 16), null,
null, null, null, null, null, null }));
// Wool
ItemStack blockWool = new ItemStack(Block.cloth, 1, 0);
ItemStack blockOrangeWool = new ItemStack(Block.cloth, 1, 1);
ItemStack blockMagentaWool = new ItemStack(Block.cloth, 1, 2);
ItemStack blockLightBlueWool = new ItemStack(Block.cloth, 1, 3);
ItemStack blockYellowWool = new ItemStack(Block.cloth, 1, 4);
ItemStack blockLimeWool = new ItemStack(Block.cloth, 1, 5);
ItemStack blockPinkWool = new ItemStack(Block.cloth, 1, 6);
ItemStack blockGrayWool = new ItemStack(Block.cloth, 1, 7);
ItemStack blockLightGrayWool = new ItemStack(Block.cloth, 1, 8);
ItemStack blockCyanWool = new ItemStack(Block.cloth, 1, 9);
ItemStack blockPurpleWool = new ItemStack(Block.cloth, 1, 10);
ItemStack blockBlueWool = new ItemStack(Block.cloth, 1, 11);
ItemStack blockBrownWool = new ItemStack(Block.cloth, 1, 12);
ItemStack blockGreenWool = new ItemStack(Block.cloth, 1, 13);
ItemStack blockRedWool = new ItemStack(Block.cloth, 1, 14);
ItemStack blockBlackWool = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(blockWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockOrangeWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockMagentaWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLightBlueWool,
0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockYellowWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLimeWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockPinkWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockGrayWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLightGrayWool,
0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockCyanWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockPurpleWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBlueWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBrownWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockGreenWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockRedWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBlackWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOrangeWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockMagentaWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLightBlueWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockYellowWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLimeWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPinkWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGrayWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLightGrayWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockCyanWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPurpleWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockBlueWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGreenWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockRedWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockBlackWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.blackPigment) }));
// Flowers
// TODO: Add support for Rose
ItemStack blockPlantYellow = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(blockPlantYellow, 0.3F,
new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
// Mushrooms
ItemStack blockMushroomBrown = new ItemStack(Block.mushroomBrown);
ItemStack blockMushroomRed = new ItemStack(Block.mushroomRed);
DecomposerRecipe.add(new DecomposerRecipe(blockMushroomBrown,
new Chemical[] { this.molecule(EnumMolecule.psilocybin),
this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(blockMushroomRed,
new Chemical[] { this.molecule(EnumMolecule.pantherine),
this.molecule(EnumMolecule.water, 2) }));
// Block of Gold
DecomposerRecipe.add(new DecomposerRecipe(
new ItemStack(Block.blockGold), new Chemical[] { this.element(
EnumElement.Au, 144) }));
// Block of Iron
DecomposerRecipe.add(new DecomposerRecipe(
new ItemStack(Block.blockIron), new Chemical[] { this.element(
EnumElement.Fe, 144) }));
// Slabs
// TODO: Add support for slabs?
// TNT
ItemStack blockTnt = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(blockTnt,
new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(blockTnt, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.tnt) }));
// Obsidian
ItemStack blockObsidian = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(blockObsidian,
new Chemical[] {
this.molecule(EnumMolecule.siliconDioxide, 16),
this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(blockObsidian, true, 1000,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.magnesiumOxide, 2), null,
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.magnesiumOxide, 2),
this.molecule(EnumMolecule.magnesiumOxide, 2),
this.molecule(EnumMolecule.magnesiumOxide, 2) }));
// Diamond Ore
ItemStack blockOreDiamond = new ItemStack(Block.oreDiamond);
DecomposerRecipe.add(new DecomposerRecipe(blockOreDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
// Block of Diamond
ItemStack blockDiamond = new ItemStack(Block.blockDiamond);
DecomposerRecipe.add(new DecomposerRecipe(blockDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
SynthesisRecipe.add(new SynthesisRecipe(blockDiamond, true, 120000,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4) }));
// Pressure Plate
ItemStack blockPressurePlatePlanks = new ItemStack(
Block.pressurePlatePlanks);
DecomposerRecipe.add(new DecomposerRecipeChance(
blockPressurePlatePlanks, 0.4F, new Chemical[] { this.molecule(
EnumMolecule.cellulose, 4) }));
// Redston Ore
ItemStack blockOreRedstone = new ItemStack(Block.oreRedstone);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOreRedstone, 0.8F,
new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 9),
this.element(EnumElement.Cu, 9) }));
// Cactus
ItemStack blockCactus = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(blockCactus, new Chemical[] {
this.molecule(EnumMolecule.mescaline),
this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(blockCactus, true, 200,
new Chemical[] { this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.mescaline), null,
this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.water, 5) }));
// Pumpkin
ItemStack blockPumpkin = new ItemStack(Block.pumpkin);
DecomposerRecipe.add(new DecomposerRecipe(blockPumpkin,
new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPumpkin, false, 400,
new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
// Netherrack
ItemStack blockNetherrack = new ItemStack(Block.netherrack);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockNetherrack, 0.1F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O),
this.element(EnumElement.Fe) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.Ni),
this.element(EnumElement.Tc) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 3),
this.element(EnumElement.Ti),
this.element(EnumElement.Fe) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 1),
this.element(EnumElement.W, 4),
this.element(EnumElement.Cr, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 10),
this.element(EnumElement.W, 1),
this.element(EnumElement.Zn, 8),
this.element(EnumElement.Be, 4) }) }));
// Water Bottle
ItemStack itemPotion = new ItemStack(Item.potion, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(itemPotion,
new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
// Soul Sand
ItemStack blockSlowSand = new ItemStack(Block.slowSand);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockSlowSand, 0.2F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb, 3),
this.element(EnumElement.Be, 1),
this.element(EnumElement.Si, 2),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb, 1),
this.element(EnumElement.Si, 5),
this.element(EnumElement.O, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 6),
this.element(EnumElement.O, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Es, 1),
this.element(EnumElement.O, 2) }) }));
// Glowstone
ItemStack blockGlowStone = new ItemStack(Block.glowStone);
DecomposerRecipe.add(new DecomposerRecipe(blockGlowStone,
new Chemical[] { this.element(EnumElement.P, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGlowStone, true, 500,
new Chemical[] { this.element(EnumElement.P), null,
this.element(EnumElement.P),
this.element(EnumElement.P), null,
this.element(EnumElement.P), null, null, null }));
// Glass Panes
ItemStack blockThinGlass = new ItemStack(Block.thinGlass);
DecomposerRecipe
.add(new DecomposerRecipe(blockThinGlass, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(blockThinGlass, true, 50,
new Chemical[] { null, null, null,
this.molecule(EnumMolecule.siliconDioxide), null, null,
null, null, null }));
// Melon
ItemStack blockMelon = new ItemStack(Block.melon);
DecomposerRecipe.add(new DecomposerRecipe(blockMelon, new Chemical[] {
this.molecule(EnumMolecule.cucurbitacin),
this.molecule(EnumMolecule.asparticAcid),
this.molecule(EnumMolecule.water, 16) }));
// Mycelium
ItemStack blockMycelium = new ItemStack(Block.mycelium);
DecomposerRecipe.add(new DecomposerRecipeChance(blockMycelium, 0.09F,
new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium,
16), false, 300, new Chemical[] { this
.molecule(EnumMolecule.fingolimod) }));
// End Stone
ItemStack blockWhiteStone = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockWhiteStone, 0.8F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O),
this.element(EnumElement.H, 4),
this.element(EnumElement.Li) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Es) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Pu) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Fr) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Nd) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O, 4) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.H, 4) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.Be, 8) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.Li, 2) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Zr) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Na) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Rb) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }) }));
// Emerald Ore
ItemStack blockOreEmerald = new ItemStack(Block.oreEmerald);
DecomposerRecipe.add(new DecomposerRecipe(blockOreEmerald,
new Chemical[] { this.molecule(EnumMolecule.beryl, 6),
this.element(EnumElement.Cr, 6),
this.element(EnumElement.V, 6) }));
// Emerald Block
ItemStack blockEmerald = new ItemStack(Block.blockEmerald);
SynthesisRecipe.add(new SynthesisRecipe(blockEmerald, true, 150000,
new Chemical[] { this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.V, 9),
this.molecule(EnumMolecule.beryl, 18),
this.element(EnumElement.V, 9),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(blockEmerald, new Chemical[] {
this.molecule(EnumMolecule.beryl, 18),
this.element(EnumElement.Cr, 18),
this.element(EnumElement.V, 18) }));
// Section 2 - Items
// Apple
ItemStack itemAppleRed = new ItemStack(Item.appleRed);
DecomposerRecipe.add(new DecomposerRecipe(itemAppleRed,
new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
SynthesisRecipe.add(new SynthesisRecipe(itemAppleRed, false, 400,
new Chemical[] { this.molecule(EnumMolecule.malicAcid),
this.molecule(EnumMolecule.water, 2) }));
// Arrow
ItemStack itemArrow = new ItemStack(Item.arrow);
DecomposerRecipe.add(new DecomposerRecipe(itemArrow, new Chemical[] {
this.element(EnumElement.Si), this.element(EnumElement.O, 2),
this.element(EnumElement.N, 6) }));
// Coal
ItemStack itemCoal = new ItemStack(Item.coal);
DecomposerRecipe.add(new DecomposerRecipe(itemCoal,
new Chemical[] { this.element(EnumElement.C, 16) }));
// Charcoal
// Does 16 charcoal to 1 coal seem balanced?
ItemStack itemChar = new ItemStack(Item.coal,1,1);
DecomposerRecipe.add(new DecomposerRecipe(itemChar, new Chemical[] { this.element(EnumElement.C, 30) }));
// Diamond
ItemStack itemDiamond = new ItemStack(Item.diamond);
DecomposerRecipe.add(new DecomposerRecipe(itemDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDiamond, true, '\uea60',
new Chemical[] { null, this.molecule(EnumMolecule.fullrene),
null, this.molecule(EnumMolecule.fullrene), null,
this.molecule(EnumMolecule.fullrene), null,
this.molecule(EnumMolecule.fullrene), null }));
// Iron Ingot
ItemStack itemIngotIron = new ItemStack(Item.ingotIron);
DecomposerRecipe.add(new DecomposerRecipe(itemIngotIron,
new Chemical[] { this.element(EnumElement.Fe, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(itemIngotIron, false, 1000,
new Chemical[] { this.element(EnumElement.Fe, 16) }));
// Gold Ingot
ItemStack itemIngotGold = new ItemStack(Item.ingotGold);
DecomposerRecipe.add(new DecomposerRecipe(itemIngotGold,
new Chemical[] { this.element(EnumElement.Au, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(itemIngotGold, false, 1000,
new Chemical[] { this.element(EnumElement.Au, 16) }));
// Stick
ItemStack itemStick = new ItemStack(Item.stick);
DecomposerRecipe.add(new DecomposerRecipeChance(itemStick, 0.3F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
// String
ItemStack itemSilk = new ItemStack(Item.silk);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSilk, 0.45F,
new Chemical[] { this.molecule(EnumMolecule.serine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSilk, true, 150,
new Chemical[] { this.molecule(EnumMolecule.serine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.alinine) }));
// Feather
ItemStack itemFeather = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(itemFeather, new Chemical[] {
this.molecule(EnumMolecule.water, 8),
this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(itemFeather, true, 800,
new Chemical[] { this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 2),
this.element(EnumElement.N),
this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 1),
this.element(EnumElement.N),
this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 5),
this.element(EnumElement.N) }));
// Gunpowder
ItemStack itemGunpowder = new ItemStack(Item.gunpowder);
DecomposerRecipe.add(new DecomposerRecipe(itemGunpowder,
new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate),
this.element(EnumElement.S, 2),
this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(itemGunpowder, true, 600,
new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate),
this.element(EnumElement.C), null,
this.element(EnumElement.S, 2), null, null, null, null,
null }));
// Bread
ItemStack itemBread = new ItemStack(Item.bread);
DecomposerRecipe.add(new DecomposerRecipeChance(itemBread, 0.1F,
new Chemical[] { this.molecule(EnumMolecule.starch),
this.molecule(EnumMolecule.sucrose) }));
// Flint
ItemStack itemFlint = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipeChance(itemFlint, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
SynthesisRecipe.add(new SynthesisRecipe(itemFlint, true, 100,
new Chemical[] { null, moleculeSiliconDioxide, null,
moleculeSiliconDioxide, moleculeSiliconDioxide,
moleculeSiliconDioxide, null, null, null }));
// Golden Apple
ItemStack itemAppleGold = new ItemStack(Item.appleGold, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(itemAppleGold,
new Chemical[] { this.molecule(EnumMolecule.malicAcid),
this.element(EnumElement.Au, 64) }));
// Wooden Door
ItemStack itemDoorWood = new ItemStack(Item.doorWood);
DecomposerRecipe.add(new DecomposerRecipeChance(itemDoorWood, 0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
// Water Bucket
ItemStack itemBucketWater = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipe(itemBucketWater,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
// Redstone
ItemStack itemRedstone = new ItemStack(Item.redstone);
DecomposerRecipe.add(new DecomposerRecipeChance(itemRedstone, 0.42F,
new Chemical[] { this.molecule(EnumMolecule.iron3oxide),
this.element(EnumElement.Cu) }));
SynthesisRecipe
.add(new SynthesisRecipe(itemRedstone, true, 100,
new Chemical[] { null, null,
this.molecule(EnumMolecule.iron3oxide), null,
this.element(EnumElement.Cu), null, null, null,
null }));
// Snowball
ItemStack itemSnowball = new ItemStack(Item.snowball);
DecomposerRecipe.add(new DecomposerRecipe(itemSnowball,
new Chemical[] { this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(
new ItemStack(Item.snowball, 5), true, 20, new Chemical[] {
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water) }));
// Leather
ItemStack itemLeather = new ItemStack(Item.leather);
DecomposerRecipe.add(new DecomposerRecipeChance(itemLeather, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.arginine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.keratin) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5),
true, 700, new Chemical[] {
this.molecule(EnumMolecule.arginine), null, null, null,
this.molecule(EnumMolecule.keratin), null, null, null,
this.molecule(EnumMolecule.glycine) }));
// Brick
ItemStack itemBrick = new ItemStack(Item.brick);
DecomposerRecipe.add(new DecomposerRecipeChance(itemBrick, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8),
true, 400, new Chemical[] {
this.molecule(EnumMolecule.kaolinite),
this.molecule(EnumMolecule.kaolinite), null,
this.molecule(EnumMolecule.kaolinite),
this.molecule(EnumMolecule.kaolinite), null }));
// Clay
ItemStack itemClay = new ItemStack(Item.clay);
DecomposerRecipe.add(new DecomposerRecipeChance(itemClay, 0.3F,
new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12),
false, 100, new Chemical[] { this
.molecule(EnumMolecule.kaolinite) }));
// Reed
ItemStack itemReed = new ItemStack(Item.reed);
DecomposerRecipe.add(new DecomposerRecipeChance(itemReed, 0.65F,
new Chemical[] { this.molecule(EnumMolecule.sucrose),
this.element(EnumElement.H, 2),
this.element(EnumElement.O) }));
// Paper
ItemStack itemPaper = new ItemStack(Item.paper);
DecomposerRecipe.add(new DecomposerRecipeChance(itemPaper, 0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16),
true, 150, new Chemical[] { null,
this.molecule(EnumMolecule.cellulose), null, null,
this.molecule(EnumMolecule.cellulose), null, null,
this.molecule(EnumMolecule.cellulose), null }));
// Slimeball
ItemStack itemSlimeBall = new ItemStack(Item.slimeBall);
DecomposerRecipe.add(new DecomposerRecipeSelect(itemSlimeBall, 0.9F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] { this
.molecule(EnumMolecule.polycyanoacrylate) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Hg) }),
new DecomposerRecipe(new Chemical[] { this.molecule(
EnumMolecule.water, 10) }) }));
// Glowstone Dust
ItemStack itemGlowstone = new ItemStack(Item.glowstone);
DecomposerRecipe.add(new DecomposerRecipe(itemGlowstone,
new Chemical[] { this.element(EnumElement.P) }));
// Dyes
ItemStack itemDyePowderBlack = new ItemStack(Item.dyePowder, 1, 0);
ItemStack itemDyePowderRed = new ItemStack(Item.dyePowder, 1, 1);
ItemStack itemDyePowderGreen = new ItemStack(Item.dyePowder, 1, 2);
ItemStack itemDyePowderBrown = new ItemStack(Item.dyePowder, 1, 3);
ItemStack itemDyePowderBlue = new ItemStack(Item.dyePowder, 1, 4);
ItemStack itemDyePowderPurple = new ItemStack(Item.dyePowder, 1, 5);
ItemStack itemDyePowderCyan = new ItemStack(Item.dyePowder, 1, 6);
ItemStack itemDyePowderLightGray = new ItemStack(Item.dyePowder, 1, 7);
ItemStack itemDyePowderGray = new ItemStack(Item.dyePowder, 1, 8);
ItemStack itemDyePowderPink = new ItemStack(Item.dyePowder, 1, 9);
ItemStack itemDyePowderLime = new ItemStack(Item.dyePowder, 1, 10);
ItemStack itemDyePowderYellow = new ItemStack(Item.dyePowder, 1, 11);
ItemStack itemDyePowderLightBlue = new ItemStack(Item.dyePowder, 1, 12);
ItemStack itemDyePowderMagenta = new ItemStack(Item.dyePowder, 1, 13);
ItemStack itemDyePowderOrange = new ItemStack(Item.dyePowder, 1, 14);
ItemStack itemDyePowderWhite = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlack,
new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderRed,
new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGreen,
new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(itemDyePowderBrown,
0.4F, new Chemical[] { this.molecule(EnumMolecule.theobromine),
this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlue,
new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPurple,
new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderCyan,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLightGray,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGray,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPink,
new Chemical[] { this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLime,
new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderYellow,
new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe
.add(new DecomposerRecipe(itemDyePowderLightBlue,
new Chemical[] { this
.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderMagenta,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderOrange,
new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderWhite,
new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlack, false, 50,
new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderRed, false, 50,
new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGreen, false, 50,
new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBrown, false, 400,
new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlue, false, 50,
new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPurple, false, 50,
new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderCyan, false, 50,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightGray, false,
50, new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGray, false, 50,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPink, false, 50,
new Chemical[] { this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLime, false, 50,
new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderYellow, false, 50,
new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightBlue, false,
50, new Chemical[] { this
.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderMagenta, false,
50, new Chemical[] {
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderOrange, false, 50,
new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderWhite, false, 50,
new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
// Bone
ItemStack itemBone = new ItemStack(Item.bone);
DecomposerRecipe
.add(new DecomposerRecipe(itemBone, new Chemical[] { this
.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe
.add(new SynthesisRecipe(itemBone, false, 100,
new Chemical[] { this
.molecule(EnumMolecule.hydroxylapatite) }));
// Sugar
ItemStack itemSugar = new ItemStack(Item.sugar);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSugar, 0.75F,
new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSugar, false, 400,
new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
// Melon
ItemStack itemMelon = new ItemStack(Item.melon);
DecomposerRecipe.add(new DecomposerRecipe(itemMelon,
new Chemical[] { this.molecule(EnumMolecule.water) }));
// Cooked Chicken
ItemStack itemChickenCooked = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipe(itemChickenCooked, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemChickenCooked, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
// Rotten Flesh
ItemStack itemRottenFlesh = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(itemRottenFlesh, 0.05F,
new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
// Enderpearl
ItemStack itemEnderPearl = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(itemEnderPearl,
new Chemical[] { this.element(EnumElement.Es),
this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(itemEnderPearl, true, 5000,
new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.element(EnumElement.Es),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate) }));
// Blaze Rod
ItemStack itemBlazeRod = new ItemStack(Item.blazeRod);
DecomposerRecipe.add(new DecomposerRecipe(itemBlazeRod,
new Chemical[] { this.element(EnumElement.Pu, 3) }));
SynthesisRecipe.add(new SynthesisRecipe(itemBlazeRod, true, 15000,
new Chemical[] { this.element(EnumElement.Pu), null, null,
this.element(EnumElement.Pu), null, null,
this.element(EnumElement.Pu), null, null }));
// Ghast Tear
ItemStack itemGhastTear = new ItemStack(Item.ghastTear);
DecomposerRecipe.add(new DecomposerRecipe(itemGhastTear,
new Chemical[] { this.element(EnumElement.Yb, 4),
this.element(EnumElement.No, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(itemGhastTear, true, 15000,
new Chemical[] { this.element(EnumElement.Yb),
this.element(EnumElement.Yb),
this.element(EnumElement.No), null,
this.element(EnumElement.Yb, 2),
this.element(EnumElement.No, 2), null,
this.element(EnumElement.No), null }));
// Nether Wart
ItemStack itemNetherStalkSeeds = new ItemStack(Item.netherStalkSeeds);
DecomposerRecipe.add(new DecomposerRecipeChance(itemNetherStalkSeeds,
0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) }));
// Spider Eye
ItemStack itemSpiderEye = new ItemStack(Item.spiderEye);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSpiderEye, 0.2F,
new Chemical[] { this.molecule(EnumMolecule.ttx) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSpiderEye, true, 2000,
new Chemical[] { this.element(EnumElement.C), null, null, null,
this.molecule(EnumMolecule.ttx), null, null, null,
this.element(EnumElement.C) }));
// Fermented Spider Eye
ItemStack itemFermentedSpiderEye = new ItemStack(
Item.fermentedSpiderEye);
DecomposerRecipe.add(new DecomposerRecipe(itemFermentedSpiderEye,
new Chemical[] { this.element(EnumElement.Po),
this.molecule(EnumMolecule.ethanol) }));
// Blaze Powder
ItemStack itemBlazePowder = new ItemStack(Item.blazePowder);
DecomposerRecipe.add(new DecomposerRecipe(itemBlazePowder,
new Chemical[] { this.element(EnumElement.Pu) }));
// Magma Cream
ItemStack itemMagmaCream = new ItemStack(Item.magmaCream);
DecomposerRecipe.add(new DecomposerRecipe(itemMagmaCream,
new Chemical[] { this.element(EnumElement.Hg),
this.element(EnumElement.Pu),
this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
SynthesisRecipe.add(new SynthesisRecipe(itemMagmaCream, true, 5000,
new Chemical[] { null, this.element(EnumElement.Pu), null,
this.molecule(EnumMolecule.polycyanoacrylate),
this.element(EnumElement.Hg),
this.molecule(EnumMolecule.polycyanoacrylate), null,
this.molecule(EnumMolecule.polycyanoacrylate), null }));
// Glistering Melon
ItemStack itemSpeckledMelon = new ItemStack(Item.speckledMelon);
DecomposerRecipe.add(new DecomposerRecipe(itemSpeckledMelon,
new Chemical[] { this.molecule(EnumMolecule.water, 4),
this.molecule(EnumMolecule.whitePigment),
this.element(EnumElement.Au, 1) }));
// Emerald
ItemStack itemEmerald = new ItemStack(Item.emerald);
DecomposerRecipe.add(new DecomposerRecipe(itemEmerald,
new Chemical[] { this.molecule(EnumMolecule.beryl, 2),
this.element(EnumElement.Cr, 2),
this.element(EnumElement.V, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemEmerald, true, 80000,
new Chemical[] { null, this.element(EnumElement.Cr), null,
this.element(EnumElement.V),
this.molecule(EnumMolecule.beryl, 2),
this.element(EnumElement.V), null,
this.element(EnumElement.Cr), null }));
// Carrot
ItemStack itemCarrot = new ItemStack(Item.carrot);
DecomposerRecipe.add(new DecomposerRecipe(itemCarrot,
new Chemical[] { this.molecule(EnumMolecule.ret) }));
// Potato
ItemStack itemPotato = new ItemStack(Item.potato);
DecomposerRecipe.add(new DecomposerRecipeChance(itemPotato, 0.4F,
new Chemical[] { this.molecule(EnumMolecule.water, 8),
this.element(EnumElement.K, 2),
this.molecule(EnumMolecule.cellulose) }));
// Golden Carrot
ItemStack itemGoldenCarrot = new ItemStack(Item.goldenCarrot);
DecomposerRecipe.add(new DecomposerRecipe(itemGoldenCarrot,
new Chemical[] { this.molecule(EnumMolecule.ret),
this.element(EnumElement.Au, 4) }));
// Nether Star
ItemStack itemNetherStar = new ItemStack(Item.netherStar);
DecomposerRecipe.add(new DecomposerRecipe(itemNetherStar,
new Chemical[] { this.element(EnumElement.Cn, 16),
elementHydrogen, elementHydrogen, elementHydrogen,
elementHelium, elementHelium, elementHelium,
elementCarbon, elementCarbon }));
SynthesisRecipe.add(new SynthesisRecipe(itemNetherStar, true, 500000,
new Chemical[] { elementHelium, elementHelium, elementHelium,
elementCarbon, this.element(EnumElement.Cn, 16),
elementHelium, elementHydrogen, elementHydrogen,
elementHydrogen }));
// Nether Quartz
ItemStack itemNetherQuartz = new ItemStack(Item.netherQuartz);
DecomposerRecipe.add(new DecomposerRecipe(itemNetherQuartz,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.galliumarsenide, 1) }));
// Music Records
ItemStack itemRecord13 = new ItemStack(Item.record13);
ItemStack itemRecordCat = new ItemStack(Item.recordCat);
ItemStack itemRecordFar = new ItemStack(Item.recordFar);
ItemStack itemRecordMall = new ItemStack(Item.recordMall);
ItemStack itemRecordMellohi = new ItemStack(Item.recordMellohi);
ItemStack itemRecordStal = new ItemStack(Item.recordStal);
ItemStack itemRecordStrad = new ItemStack(Item.recordStrad);
ItemStack itemRecordWard = new ItemStack(Item.recordWard);
ItemStack itemRecordChirp = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(itemRecord13,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordCat,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordFar,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMall,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMellohi,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStal,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStrad,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordWard,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordChirp,
new Chemical[] { moleculePolyvinylChloride }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecord13, true, 1000,
new Chemical[] { moleculePolyvinylChloride, null, null, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordCat, true, 1000,
new Chemical[] { null, moleculePolyvinylChloride, null, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordFar, true, 1000,
new Chemical[] { null, null, moleculePolyvinylChloride, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMall, true, 1000,
new Chemical[] { null, null, null, moleculePolyvinylChloride,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMellohi, true, 1000,
new Chemical[] { null, null, null, null,
moleculePolyvinylChloride, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStal, true, 1000,
new Chemical[] { null, null, null, null, null,
moleculePolyvinylChloride, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStrad, true, 1000,
new Chemical[] { null, null, null, null, null, null,
moleculePolyvinylChloride, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordWard, true, 1000,
new Chemical[] { null, null, null, null, null, null, null,
moleculePolyvinylChloride, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordChirp, true, 1000,
new Chemical[] { null, null, null, null, null, null, null,
null, moleculePolyvinylChloride }));
}
| public void registerVanillaChemicalRecipes() {
// Molecules
Molecule moleculeSiliconDioxide = this.molecule(
EnumMolecule.siliconDioxide, 4);
Molecule moleculeCellulose = this.molecule(EnumMolecule.cellulose, 1);
Molecule moleculePolyvinylChloride = this
.molecule(EnumMolecule.polyvinylChloride);
// Elements
Element elementHydrogen = this.element(EnumElement.H, 64);
Element elementHelium = this.element(EnumElement.He, 64);
Element elementCarbon = this.element(EnumElement.C, 64);
// Section 1 - Blocks
// Stone
ItemStack blockStone = new ItemStack(Block.stone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockStone, 0.2F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7),
true, 50, new Chemical[] { this.element(EnumElement.Si), null,
null, this.element(EnumElement.O, 2), null, null }));
// Grass Block
ItemStack blockGrass = new ItemStack(Block.grass);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockGrass, 0.07F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }),
new DecomposerRecipe(
new Chemical[] { moleculeCellulose }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.grass, 16),
true, 50, new Chemical[] { null, moleculeCellulose, null, null,
this.element(EnumElement.O, 2),
this.element(EnumElement.Si) }));
// Dirt
ItemStack blockDirt = new ItemStack(Block.dirt);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockDirt, 0.07F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Zn),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16),
true, 50, new Chemical[] { null, null, null, null,
this.element(EnumElement.O, 2),
this.element(EnumElement.Si) }));
// Cobblestone
ItemStack blockCobblestone = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockCobblestone, 0.1F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Fe),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Mg),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ti),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Na),
this.element(EnumElement.Cl) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(
Block.cobblestone, 8), true, 50, new Chemical[] {
this.element(EnumElement.Si), null, null, null,
this.element(EnumElement.O, 2), null }));
// Planks
// TODO: Add synthesizer recipes?
ItemStack blockOakWoodPlanks = new ItemStack(Block.planks, 1, 0);
ItemStack blockSpruceWoodPlanks = new ItemStack(Block.planks, 1, 1);
ItemStack blockBirchWoodPlanks = new ItemStack(Block.planks, 1, 2);
ItemStack blockJungleWoodPlanks = new ItemStack(Block.planks, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWoodPlanks,
0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
// Saplings
ItemStack blockOakSapling = new ItemStack(Block.sapling, 1, 0);
ItemStack blockSpruceSapling = new ItemStack(Block.sapling, 1, 1);
ItemStack blockBirchSapling = new ItemStack(Block.sapling, 1, 2);
ItemStack blockJungleSapling = new ItemStack(Block.sapling, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakSapling, 0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockSpruceSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockBirchSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe
.add(new DecomposerRecipeChance(
blockJungleSapling,
0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOakSapling, true, 20,
new Chemical[] { null, null, null, null, null, null, null,
null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSpruceSapling, true, 20,
new Chemical[] { null, null, null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(blockBirchSapling, true, 20,
new Chemical[] { null, null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe
.add(new SynthesisRecipe(blockJungleSapling, true, 20,
new Chemical[] { null, null, null, null, null,
this.molecule(EnumMolecule.cellulose), null,
null, null }));
// Water
ItemStack blockWaterSource = new ItemStack(Block.waterMoving);
ItemStack blockWaterStill = new ItemStack(Block.waterStill);
DecomposerRecipe.add(new DecomposerRecipe(blockWaterSource,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(blockWaterStill,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockWaterSource, false, 20,
new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
// Lava
// TODO: Add support for lava
// Sand
ItemStack blockSand = new ItemStack(Block.sand);
DecomposerRecipe
.add(new DecomposerRecipe(blockSand, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSand, true, 200,
new Chemical[] { moleculeSiliconDioxide,
moleculeSiliconDioxide, moleculeSiliconDioxide,
moleculeSiliconDioxide }));
// Gravel
ItemStack blockGravel = new ItemStack(Block.gravel);
DecomposerRecipe.add(new DecomposerRecipeChance(blockGravel, 0.35F,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGravel, true, 30,
new Chemical[] { null, null, null, null, null, null, null,
null, this.molecule(EnumMolecule.siliconDioxide) }));
// Gold Ore
ItemStack oreGold = new ItemStack(Block.oreGold);
DecomposerRecipe.add(new DecomposerRecipe(oreGold,
new Chemical[] { this.element(EnumElement.Au, 48) }));
// Iron Ore
ItemStack oreIron = new ItemStack(Block.oreIron);
DecomposerRecipe.add(new DecomposerRecipe(oreIron,
new Chemical[] { this.element(EnumElement.Fe, 48) }));
// Coal Ore
ItemStack oreCoal = new ItemStack(Block.oreCoal);
DecomposerRecipe.add(new DecomposerRecipe(oreCoal,
new Chemical[] { this.element(EnumElement.C, 48) }));
// Wood
ItemStack blockOakWood = new ItemStack(Block.wood, 1, 0);
ItemStack blockSpruceWood = new ItemStack(Block.wood, 1, 1);
ItemStack blockBirchWood = new ItemStack(Block.wood, 1, 2);
ItemStack blockJungleWood = new ItemStack(Block.wood, 1, 3);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWood, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOakWood, true, 100,
new Chemical[] { moleculeCellulose, moleculeCellulose,
moleculeCellulose, null, moleculeCellulose, null, null,
null, null }));
SynthesisRecipe.add(new SynthesisRecipe(blockSpruceWood, true, 100,
new Chemical[] { null, null, null, null, moleculeCellulose,
null, moleculeCellulose, moleculeCellulose,
moleculeCellulose }));
SynthesisRecipe.add(new SynthesisRecipe(blockBirchWood, true, 100,
new Chemical[] { moleculeCellulose, null, moleculeCellulose,
null, null, null, moleculeCellulose, null,
moleculeCellulose }));
SynthesisRecipe.add(new SynthesisRecipe(blockJungleWood, true, 100,
new Chemical[] { moleculeCellulose, null, null,
moleculeCellulose, moleculeCellulose, null,
moleculeCellulose, null, null }));
// Leaves
// TODO: Add support for leaves
// Glass
ItemStack blockGlass = new ItemStack(Block.glass);
DecomposerRecipe
.add(new DecomposerRecipe(blockGlass, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe
.add(new SynthesisRecipe(blockGlass, true, 500, new Chemical[] {
moleculeSiliconDioxide, null, moleculeSiliconDioxide,
null, null, null, moleculeSiliconDioxide, null,
moleculeSiliconDioxide }));
// Lapis Lazuli Ore
ItemStack blockOreLapis = new ItemStack(Block.oreLapis);
DecomposerRecipe.add(new DecomposerRecipe(blockOreLapis,
new Chemical[] { this.molecule(EnumMolecule.lazurite, 6),
this.molecule(EnumMolecule.sodalite),
this.molecule(EnumMolecule.noselite),
this.molecule(EnumMolecule.calcite),
this.molecule(EnumMolecule.pyrite) }));
// Lapis Lazuli Block
// TODO: Add support for Lapis Lazuli Block?
// Cobweb
ItemStack blockCobweb = new ItemStack(Block.web);
DecomposerRecipe.add(new DecomposerRecipe(blockCobweb,
new Chemical[] { this.molecule(EnumMolecule.fibroin) }));
// Tall Grass
ItemStack blockTallGrass = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(blockTallGrass, 0.1F,
new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
// Sandstone
ItemStack blockSandStone = new ItemStack(Block.sandStone, 1, 0);
ItemStack blockChiseledSandStone = new ItemStack(Block.sandStone, 1, 1);
ItemStack blockSmoothSandStone = new ItemStack(Block.sandStone, 1, 2);
DecomposerRecipe
.add(new DecomposerRecipe(blockSandStone, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe
.add(new DecomposerRecipe(blockChiseledSandStone,
new Chemical[] { this.molecule(
EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe
.add(new DecomposerRecipe(blockSmoothSandStone,
new Chemical[] { this.molecule(
EnumMolecule.siliconDioxide, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(blockSandStone, true, 20,
new Chemical[] { null, null, null, null,
this.molecule(EnumMolecule.siliconDioxide, 16), null,
null, null, null }));
SynthesisRecipe
.add(new SynthesisRecipe(blockChiseledSandStone, true, 20,
new Chemical[] { null, null, null, null, null, null,
null,
this.molecule(EnumMolecule.siliconDioxide, 16),
null }));
SynthesisRecipe.add(new SynthesisRecipe(blockSmoothSandStone, true, 20,
new Chemical[] { null,
this.molecule(EnumMolecule.siliconDioxide, 16), null,
null, null, null, null, null, null }));
// Wool
ItemStack blockWool = new ItemStack(Block.cloth, 1, 0);
ItemStack blockOrangeWool = new ItemStack(Block.cloth, 1, 1);
ItemStack blockMagentaWool = new ItemStack(Block.cloth, 1, 2);
ItemStack blockLightBlueWool = new ItemStack(Block.cloth, 1, 3);
ItemStack blockYellowWool = new ItemStack(Block.cloth, 1, 4);
ItemStack blockLimeWool = new ItemStack(Block.cloth, 1, 5);
ItemStack blockPinkWool = new ItemStack(Block.cloth, 1, 6);
ItemStack blockGrayWool = new ItemStack(Block.cloth, 1, 7);
ItemStack blockLightGrayWool = new ItemStack(Block.cloth, 1, 8);
ItemStack blockCyanWool = new ItemStack(Block.cloth, 1, 9);
ItemStack blockPurpleWool = new ItemStack(Block.cloth, 1, 10);
ItemStack blockBlueWool = new ItemStack(Block.cloth, 1, 11);
ItemStack blockBrownWool = new ItemStack(Block.cloth, 1, 12);
ItemStack blockGreenWool = new ItemStack(Block.cloth, 1, 13);
ItemStack blockRedWool = new ItemStack(Block.cloth, 1, 14);
ItemStack blockBlackWool = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(blockWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockOrangeWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockMagentaWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLightBlueWool,
0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockYellowWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLimeWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockPinkWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockGrayWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockLightGrayWool,
0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockCyanWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockPurpleWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBlueWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBrownWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockGreenWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockRedWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(blockBlackWool, 0.6F,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockOrangeWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockMagentaWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLightBlueWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockYellowWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLimeWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPinkWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGrayWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(blockLightGrayWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockCyanWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPurpleWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockBlueWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGreenWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockRedWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(blockBlackWool, false, 50,
new Chemical[] { this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.blackPigment) }));
// Flowers
// TODO: Add support for Rose
ItemStack blockPlantYellow = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(blockPlantYellow, 0.3F,
new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
// Mushrooms
ItemStack blockMushroomBrown = new ItemStack(Block.mushroomBrown);
ItemStack blockMushroomRed = new ItemStack(Block.mushroomRed);
DecomposerRecipe.add(new DecomposerRecipe(blockMushroomBrown,
new Chemical[] { this.molecule(EnumMolecule.psilocybin),
this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(blockMushroomRed,
new Chemical[] { this.molecule(EnumMolecule.pantherine),
this.molecule(EnumMolecule.water, 2) }));
// Block of Gold
DecomposerRecipe.add(new DecomposerRecipe(
new ItemStack(Block.blockGold), new Chemical[] { this.element(
EnumElement.Au, 144) }));
// Block of Iron
DecomposerRecipe.add(new DecomposerRecipe(
new ItemStack(Block.blockIron), new Chemical[] { this.element(
EnumElement.Fe, 144) }));
// Slabs
// TODO: Add support for slabs?
// TNT
ItemStack blockTnt = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(blockTnt,
new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(blockTnt, false, 1000,
new Chemical[] { this.molecule(EnumMolecule.tnt) }));
// Obsidian
ItemStack blockObsidian = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(blockObsidian,
new Chemical[] {
this.molecule(EnumMolecule.siliconDioxide, 16),
this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(blockObsidian, true, 1000,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.magnesiumOxide, 2), null,
this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.magnesiumOxide, 2),
this.molecule(EnumMolecule.magnesiumOxide, 2),
this.molecule(EnumMolecule.magnesiumOxide, 2) }));
// Diamond Ore
ItemStack blockOreDiamond = new ItemStack(Block.oreDiamond);
DecomposerRecipe.add(new DecomposerRecipe(blockOreDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
// Block of Diamond
ItemStack blockDiamond = new ItemStack(Block.blockDiamond);
DecomposerRecipe.add(new DecomposerRecipe(blockDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
SynthesisRecipe.add(new SynthesisRecipe(blockDiamond, true, 120000,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4),
this.molecule(EnumMolecule.fullrene, 4) }));
// Pressure Plate
ItemStack blockPressurePlatePlanks = new ItemStack(
Block.pressurePlatePlanks);
DecomposerRecipe.add(new DecomposerRecipeChance(
blockPressurePlatePlanks, 0.4F, new Chemical[] { this.molecule(
EnumMolecule.cellulose, 4) }));
// Redston Ore
ItemStack blockOreRedstone = new ItemStack(Block.oreRedstone);
DecomposerRecipe.add(new DecomposerRecipeChance(blockOreRedstone, 0.8F,
new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 9),
this.element(EnumElement.Cu, 9) }));
// Cactus
ItemStack blockCactus = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(blockCactus, new Chemical[] {
this.molecule(EnumMolecule.mescaline),
this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(blockCactus, true, 200,
new Chemical[] { this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.mescaline), null,
this.molecule(EnumMolecule.water, 5), null,
this.molecule(EnumMolecule.water, 5) }));
// Pumpkin
ItemStack blockPumpkin = new ItemStack(Block.pumpkin);
DecomposerRecipe.add(new DecomposerRecipe(blockPumpkin,
new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(blockPumpkin, false, 400,
new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
// Netherrack
ItemStack blockNetherrack = new ItemStack(Block.netherrack);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockNetherrack, 0.1F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O),
this.element(EnumElement.Fe) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.Ni),
this.element(EnumElement.Tc) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 3),
this.element(EnumElement.Ti),
this.element(EnumElement.Fe) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 1),
this.element(EnumElement.W, 4),
this.element(EnumElement.Cr, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 10),
this.element(EnumElement.W, 1),
this.element(EnumElement.Zn, 8),
this.element(EnumElement.Be, 4) }) }));
// Water Bottle
ItemStack itemPotion = new ItemStack(Item.potion, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(itemPotion,
new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
// Soul Sand
ItemStack blockSlowSand = new ItemStack(Block.slowSand);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockSlowSand, 0.2F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb, 3),
this.element(EnumElement.Be, 1),
this.element(EnumElement.Si, 2),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Pb, 1),
this.element(EnumElement.Si, 5),
this.element(EnumElement.O, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 6),
this.element(EnumElement.O, 2) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Es, 1),
this.element(EnumElement.O, 2) }) }));
// Glowstone
ItemStack blockGlowStone = new ItemStack(Block.glowStone);
DecomposerRecipe.add(new DecomposerRecipe(blockGlowStone,
new Chemical[] { this.element(EnumElement.P, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(blockGlowStone, true, 500,
new Chemical[] { this.element(EnumElement.P), null,
this.element(EnumElement.P),
this.element(EnumElement.P), null,
this.element(EnumElement.P), null, null, null }));
// Glass Panes
ItemStack blockThinGlass = new ItemStack(Block.thinGlass);
DecomposerRecipe
.add(new DecomposerRecipe(blockThinGlass, new Chemical[] { this
.molecule(EnumMolecule.siliconDioxide, 1) }));
SynthesisRecipe.add(new SynthesisRecipe(blockThinGlass, true, 50,
new Chemical[] { null, null, null,
this.molecule(EnumMolecule.siliconDioxide), null, null,
null, null, null }));
// Melon
ItemStack blockMelon = new ItemStack(Block.melon);
DecomposerRecipe.add(new DecomposerRecipe(blockMelon, new Chemical[] {
this.molecule(EnumMolecule.cucurbitacin),
this.molecule(EnumMolecule.asparticAcid),
this.molecule(EnumMolecule.water, 16) }));
// Mycelium
ItemStack blockMycelium = new ItemStack(Block.mycelium);
DecomposerRecipe.add(new DecomposerRecipeChance(blockMycelium, 0.09F,
new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium,
16), false, 300, new Chemical[] { this
.molecule(EnumMolecule.fingolimod) }));
// End Stone
ItemStack blockWhiteStone = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(blockWhiteStone, 0.8F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O),
this.element(EnumElement.H, 4),
this.element(EnumElement.Li) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Es) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Pu) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Fr) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Nd) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Si, 2),
this.element(EnumElement.O, 4) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.H, 4) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.Be, 8) }),
new DecomposerRecipe(new Chemical[] { this.element(
EnumElement.Li, 2) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Zr) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Na) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Rb) }),
new DecomposerRecipe(new Chemical[] {
this.element(EnumElement.Ga),
this.element(EnumElement.As) }) }));
// Emerald Ore
ItemStack blockOreEmerald = new ItemStack(Block.oreEmerald);
DecomposerRecipe.add(new DecomposerRecipe(blockOreEmerald,
new Chemical[] { this.molecule(EnumMolecule.beryl, 6),
this.element(EnumElement.Cr, 6),
this.element(EnumElement.V, 6) }));
// Emerald Block
ItemStack blockEmerald = new ItemStack(Block.blockEmerald);
SynthesisRecipe.add(new SynthesisRecipe(blockEmerald, true, 150000,
new Chemical[] { this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.V, 9),
this.molecule(EnumMolecule.beryl, 18),
this.element(EnumElement.V, 9),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3),
this.element(EnumElement.Cr, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(blockEmerald, new Chemical[] {
this.molecule(EnumMolecule.beryl, 18),
this.element(EnumElement.Cr, 18),
this.element(EnumElement.V, 18) }));
// Section 2 - Items
// Apple
ItemStack itemAppleRed = new ItemStack(Item.appleRed);
DecomposerRecipe.add(new DecomposerRecipe(itemAppleRed,
new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
SynthesisRecipe.add(new SynthesisRecipe(itemAppleRed, false, 400,
new Chemical[] { this.molecule(EnumMolecule.malicAcid),
this.molecule(EnumMolecule.water, 2) }));
// Arrow
ItemStack itemArrow = new ItemStack(Item.arrow);
DecomposerRecipe.add(new DecomposerRecipe(itemArrow, new Chemical[] {
this.element(EnumElement.Si), this.element(EnumElement.O, 2),
this.element(EnumElement.N, 6) }));
// Coal
ItemStack itemCoal = new ItemStack(Item.coal);
DecomposerRecipe.add(new DecomposerRecipe(itemCoal,
new Chemical[] { this.element(EnumElement.C, 16) }));
// Charcoal
// Does 16 charcoal to 1 coal seem balanced?
ItemStack itemChar = new ItemStack(Item.coal,1,1);
DecomposerRecipe.add(new DecomposerRecipe(itemChar, new Chemical[] { this.element(EnumElement.C, 30) }));
// Diamond
ItemStack itemDiamond = new ItemStack(Item.diamond);
DecomposerRecipe.add(new DecomposerRecipe(itemDiamond,
new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDiamond, true, '\uea60',
new Chemical[] { null, this.molecule(EnumMolecule.fullrene),
null, this.molecule(EnumMolecule.fullrene), null,
this.molecule(EnumMolecule.fullrene), null,
this.molecule(EnumMolecule.fullrene), null }));
// Iron Ingot
ItemStack itemIngotIron = new ItemStack(Item.ingotIron);
DecomposerRecipe.add(new DecomposerRecipe(itemIngotIron,
new Chemical[] { this.element(EnumElement.Fe, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(itemIngotIron, false, 1000,
new Chemical[] { this.element(EnumElement.Fe, 16) }));
// Gold Ingot
ItemStack itemIngotGold = new ItemStack(Item.ingotGold);
DecomposerRecipe.add(new DecomposerRecipe(itemIngotGold,
new Chemical[] { this.element(EnumElement.Au, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(itemIngotGold, false, 1000,
new Chemical[] { this.element(EnumElement.Au, 16) }));
// Stick
ItemStack itemStick = new ItemStack(Item.stick);
DecomposerRecipe.add(new DecomposerRecipeChance(itemStick, 0.3F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
// String
ItemStack itemSilk = new ItemStack(Item.silk);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSilk, 0.45F,
new Chemical[] { this.molecule(EnumMolecule.serine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSilk, true, 150,
new Chemical[] { this.molecule(EnumMolecule.serine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.alinine) }));
// Feather
ItemStack itemFeather = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(itemFeather, new Chemical[] {
this.molecule(EnumMolecule.water, 8),
this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(itemFeather, true, 800,
new Chemical[] { this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 2),
this.element(EnumElement.N),
this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 1),
this.element(EnumElement.N),
this.element(EnumElement.N),
this.molecule(EnumMolecule.water, 5),
this.element(EnumElement.N) }));
// Gunpowder
ItemStack itemGunpowder = new ItemStack(Item.gunpowder);
DecomposerRecipe.add(new DecomposerRecipe(itemGunpowder,
new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate),
this.element(EnumElement.S, 2),
this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(itemGunpowder, true, 600,
new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate),
this.element(EnumElement.C), null,
this.element(EnumElement.S, 2), null, null, null, null,
null }));
// Bread
ItemStack itemBread = new ItemStack(Item.bread);
DecomposerRecipe.add(new DecomposerRecipeChance(itemBread, 0.1F,
new Chemical[] { this.molecule(EnumMolecule.starch),
this.molecule(EnumMolecule.sucrose) }));
// Flint
ItemStack itemFlint = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipeChance(itemFlint, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
SynthesisRecipe.add(new SynthesisRecipe(itemFlint, true, 100,
new Chemical[] { null, moleculeSiliconDioxide, null,
moleculeSiliconDioxide, moleculeSiliconDioxide,
moleculeSiliconDioxide, null, null, null }));
// Golden Apple
ItemStack itemAppleGold = new ItemStack(Item.appleGold, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(itemAppleGold,
new Chemical[] { this.molecule(EnumMolecule.malicAcid),
this.element(EnumElement.Au, 64) }));
// Wooden Door
ItemStack itemDoorWood = new ItemStack(Item.doorWood);
DecomposerRecipe.add(new DecomposerRecipeChance(itemDoorWood, 0.4F,
new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
// Water Bucket
ItemStack itemBucketWater = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipe(itemBucketWater,
new Chemical[] { this.molecule(EnumMolecule.water, 16),this.element(EnumElement.Fe, 48) }));
// Redstone
ItemStack itemRedstone = new ItemStack(Item.redstone);
DecomposerRecipe.add(new DecomposerRecipeChance(itemRedstone, 0.42F,
new Chemical[] { this.molecule(EnumMolecule.iron3oxide),
this.element(EnumElement.Cu) }));
SynthesisRecipe
.add(new SynthesisRecipe(itemRedstone, true, 100,
new Chemical[] { null, null,
this.molecule(EnumMolecule.iron3oxide), null,
this.element(EnumElement.Cu), null, null, null,
null }));
// Snowball
ItemStack itemSnowball = new ItemStack(Item.snowball);
DecomposerRecipe.add(new DecomposerRecipe(itemSnowball,
new Chemical[] { this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(
new ItemStack(Item.snowball, 5), true, 20, new Chemical[] {
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water), null,
this.molecule(EnumMolecule.water) }));
// Leather
ItemStack itemLeather = new ItemStack(Item.leather);
DecomposerRecipe.add(new DecomposerRecipeChance(itemLeather, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.arginine),
this.molecule(EnumMolecule.glycine),
this.molecule(EnumMolecule.keratin) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5),
true, 700, new Chemical[] {
this.molecule(EnumMolecule.arginine), null, null, null,
this.molecule(EnumMolecule.keratin), null, null, null,
this.molecule(EnumMolecule.glycine) }));
// Brick
ItemStack itemBrick = new ItemStack(Item.brick);
DecomposerRecipe.add(new DecomposerRecipeChance(itemBrick, 0.5F,
new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8),
true, 400, new Chemical[] {
this.molecule(EnumMolecule.kaolinite),
this.molecule(EnumMolecule.kaolinite), null,
this.molecule(EnumMolecule.kaolinite),
this.molecule(EnumMolecule.kaolinite), null }));
// Clay
ItemStack itemClay = new ItemStack(Item.clay);
DecomposerRecipe.add(new DecomposerRecipeChance(itemClay, 0.3F,
new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12),
false, 100, new Chemical[] { this
.molecule(EnumMolecule.kaolinite) }));
// Reed
ItemStack itemReed = new ItemStack(Item.reed);
DecomposerRecipe.add(new DecomposerRecipeChance(itemReed, 0.65F,
new Chemical[] { this.molecule(EnumMolecule.sucrose),
this.element(EnumElement.H, 2),
this.element(EnumElement.O) }));
// Paper
ItemStack itemPaper = new ItemStack(Item.paper);
DecomposerRecipe.add(new DecomposerRecipeChance(itemPaper, 0.25F,
new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16),
true, 150, new Chemical[] { null,
this.molecule(EnumMolecule.cellulose), null, null,
this.molecule(EnumMolecule.cellulose), null, null,
this.molecule(EnumMolecule.cellulose), null }));
// Slimeball
ItemStack itemSlimeBall = new ItemStack(Item.slimeBall);
DecomposerRecipe.add(new DecomposerRecipeSelect(itemSlimeBall, 0.9F,
new DecomposerRecipe[] {
new DecomposerRecipe(new Chemical[] { this
.molecule(EnumMolecule.polycyanoacrylate) }),
new DecomposerRecipe(new Chemical[] { this
.element(EnumElement.Hg) }),
new DecomposerRecipe(new Chemical[] { this.molecule(
EnumMolecule.water, 10) }) }));
// Glowstone Dust
ItemStack itemGlowstone = new ItemStack(Item.glowstone);
DecomposerRecipe.add(new DecomposerRecipe(itemGlowstone,
new Chemical[] { this.element(EnumElement.P) }));
// Dyes
ItemStack itemDyePowderBlack = new ItemStack(Item.dyePowder, 1, 0);
ItemStack itemDyePowderRed = new ItemStack(Item.dyePowder, 1, 1);
ItemStack itemDyePowderGreen = new ItemStack(Item.dyePowder, 1, 2);
ItemStack itemDyePowderBrown = new ItemStack(Item.dyePowder, 1, 3);
ItemStack itemDyePowderBlue = new ItemStack(Item.dyePowder, 1, 4);
ItemStack itemDyePowderPurple = new ItemStack(Item.dyePowder, 1, 5);
ItemStack itemDyePowderCyan = new ItemStack(Item.dyePowder, 1, 6);
ItemStack itemDyePowderLightGray = new ItemStack(Item.dyePowder, 1, 7);
ItemStack itemDyePowderGray = new ItemStack(Item.dyePowder, 1, 8);
ItemStack itemDyePowderPink = new ItemStack(Item.dyePowder, 1, 9);
ItemStack itemDyePowderLime = new ItemStack(Item.dyePowder, 1, 10);
ItemStack itemDyePowderYellow = new ItemStack(Item.dyePowder, 1, 11);
ItemStack itemDyePowderLightBlue = new ItemStack(Item.dyePowder, 1, 12);
ItemStack itemDyePowderMagenta = new ItemStack(Item.dyePowder, 1, 13);
ItemStack itemDyePowderOrange = new ItemStack(Item.dyePowder, 1, 14);
ItemStack itemDyePowderWhite = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlack,
new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderRed,
new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGreen,
new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(itemDyePowderBrown,
0.4F, new Chemical[] { this.molecule(EnumMolecule.theobromine),
this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlue,
new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPurple,
new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderCyan,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLightGray,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGray,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPink,
new Chemical[] { this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLime,
new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderYellow,
new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe
.add(new DecomposerRecipe(itemDyePowderLightBlue,
new Chemical[] { this
.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderMagenta,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderOrange,
new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderWhite,
new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlack, false, 50,
new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderRed, false, 50,
new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGreen, false, 50,
new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBrown, false, 400,
new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlue, false, 50,
new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPurple, false, 50,
new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderCyan, false, 50,
new Chemical[] { this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightGray, false,
50, new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGray, false, 50,
new Chemical[] { this.molecule(EnumMolecule.whitePigment),
this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPink, false, 50,
new Chemical[] { this.molecule(EnumMolecule.redPigment),
this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLime, false, 50,
new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderYellow, false, 50,
new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightBlue, false,
50, new Chemical[] { this
.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderMagenta, false,
50, new Chemical[] {
this.molecule(EnumMolecule.lightbluePigment),
this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderOrange, false, 50,
new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderWhite, false, 50,
new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
// Bone
ItemStack itemBone = new ItemStack(Item.bone);
DecomposerRecipe
.add(new DecomposerRecipe(itemBone, new Chemical[] { this
.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe
.add(new SynthesisRecipe(itemBone, false, 100,
new Chemical[] { this
.molecule(EnumMolecule.hydroxylapatite) }));
// Sugar
ItemStack itemSugar = new ItemStack(Item.sugar);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSugar, 0.75F,
new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSugar, false, 400,
new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
// Melon
ItemStack itemMelon = new ItemStack(Item.melon);
DecomposerRecipe.add(new DecomposerRecipe(itemMelon,
new Chemical[] { this.molecule(EnumMolecule.water) }));
// Cooked Chicken
ItemStack itemChickenCooked = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipe(itemChickenCooked, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemChickenCooked, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
// Rotten Flesh
ItemStack itemRottenFlesh = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(itemRottenFlesh, 0.05F,
new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
// Enderpearl
ItemStack itemEnderPearl = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(itemEnderPearl,
new Chemical[] { this.element(EnumElement.Es),
this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(itemEnderPearl, true, 5000,
new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.element(EnumElement.Es),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate),
this.molecule(EnumMolecule.calciumCarbonate) }));
// Blaze Rod
ItemStack itemBlazeRod = new ItemStack(Item.blazeRod);
DecomposerRecipe.add(new DecomposerRecipe(itemBlazeRod,
new Chemical[] { this.element(EnumElement.Pu, 3) }));
SynthesisRecipe.add(new SynthesisRecipe(itemBlazeRod, true, 15000,
new Chemical[] { this.element(EnumElement.Pu), null, null,
this.element(EnumElement.Pu), null, null,
this.element(EnumElement.Pu), null, null }));
// Ghast Tear
ItemStack itemGhastTear = new ItemStack(Item.ghastTear);
DecomposerRecipe.add(new DecomposerRecipe(itemGhastTear,
new Chemical[] { this.element(EnumElement.Yb, 4),
this.element(EnumElement.No, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(itemGhastTear, true, 15000,
new Chemical[] { this.element(EnumElement.Yb),
this.element(EnumElement.Yb),
this.element(EnumElement.No), null,
this.element(EnumElement.Yb, 2),
this.element(EnumElement.No, 2), null,
this.element(EnumElement.No), null }));
// Nether Wart
ItemStack itemNetherStalkSeeds = new ItemStack(Item.netherStalkSeeds);
DecomposerRecipe.add(new DecomposerRecipeChance(itemNetherStalkSeeds,
0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) }));
// Spider Eye
ItemStack itemSpiderEye = new ItemStack(Item.spiderEye);
DecomposerRecipe.add(new DecomposerRecipeChance(itemSpiderEye, 0.2F,
new Chemical[] { this.molecule(EnumMolecule.ttx) }));
SynthesisRecipe.add(new SynthesisRecipe(itemSpiderEye, true, 2000,
new Chemical[] { this.element(EnumElement.C), null, null, null,
this.molecule(EnumMolecule.ttx), null, null, null,
this.element(EnumElement.C) }));
// Fermented Spider Eye
ItemStack itemFermentedSpiderEye = new ItemStack(
Item.fermentedSpiderEye);
DecomposerRecipe.add(new DecomposerRecipe(itemFermentedSpiderEye,
new Chemical[] { this.element(EnumElement.Po),
this.molecule(EnumMolecule.ethanol) }));
// Blaze Powder
ItemStack itemBlazePowder = new ItemStack(Item.blazePowder);
DecomposerRecipe.add(new DecomposerRecipe(itemBlazePowder,
new Chemical[] { this.element(EnumElement.Pu) }));
// Magma Cream
ItemStack itemMagmaCream = new ItemStack(Item.magmaCream);
DecomposerRecipe.add(new DecomposerRecipe(itemMagmaCream,
new Chemical[] { this.element(EnumElement.Hg),
this.element(EnumElement.Pu),
this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
SynthesisRecipe.add(new SynthesisRecipe(itemMagmaCream, true, 5000,
new Chemical[] { null, this.element(EnumElement.Pu), null,
this.molecule(EnumMolecule.polycyanoacrylate),
this.element(EnumElement.Hg),
this.molecule(EnumMolecule.polycyanoacrylate), null,
this.molecule(EnumMolecule.polycyanoacrylate), null }));
// Glistering Melon
ItemStack itemSpeckledMelon = new ItemStack(Item.speckledMelon);
DecomposerRecipe.add(new DecomposerRecipe(itemSpeckledMelon,
new Chemical[] { this.molecule(EnumMolecule.water, 4),
this.molecule(EnumMolecule.whitePigment),
this.element(EnumElement.Au, 1) }));
// Emerald
ItemStack itemEmerald = new ItemStack(Item.emerald);
DecomposerRecipe.add(new DecomposerRecipe(itemEmerald,
new Chemical[] { this.molecule(EnumMolecule.beryl, 2),
this.element(EnumElement.Cr, 2),
this.element(EnumElement.V, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(itemEmerald, true, 80000,
new Chemical[] { null, this.element(EnumElement.Cr), null,
this.element(EnumElement.V),
this.molecule(EnumMolecule.beryl, 2),
this.element(EnumElement.V), null,
this.element(EnumElement.Cr), null }));
// Carrot
ItemStack itemCarrot = new ItemStack(Item.carrot);
DecomposerRecipe.add(new DecomposerRecipe(itemCarrot,
new Chemical[] { this.molecule(EnumMolecule.ret) }));
// Potato
ItemStack itemPotato = new ItemStack(Item.potato);
DecomposerRecipe.add(new DecomposerRecipeChance(itemPotato, 0.4F,
new Chemical[] { this.molecule(EnumMolecule.water, 8),
this.element(EnumElement.K, 2),
this.molecule(EnumMolecule.cellulose) }));
// Golden Carrot
ItemStack itemGoldenCarrot = new ItemStack(Item.goldenCarrot);
DecomposerRecipe.add(new DecomposerRecipe(itemGoldenCarrot,
new Chemical[] { this.molecule(EnumMolecule.ret),
this.element(EnumElement.Au, 4) }));
// Nether Star
ItemStack itemNetherStar = new ItemStack(Item.netherStar);
DecomposerRecipe.add(new DecomposerRecipe(itemNetherStar,
new Chemical[] { this.element(EnumElement.Cn, 16),
elementHydrogen, elementHydrogen, elementHydrogen,
elementHelium, elementHelium, elementHelium,
elementCarbon, elementCarbon }));
SynthesisRecipe.add(new SynthesisRecipe(itemNetherStar, true, 500000,
new Chemical[] { elementHelium, elementHelium, elementHelium,
elementCarbon, this.element(EnumElement.Cn, 16),
elementHelium, elementHydrogen, elementHydrogen,
elementHydrogen }));
// Nether Quartz
ItemStack itemNetherQuartz = new ItemStack(Item.netherQuartz);
DecomposerRecipe.add(new DecomposerRecipe(itemNetherQuartz,
new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4),
this.molecule(EnumMolecule.galliumarsenide, 1) }));
// Music Records
ItemStack itemRecord13 = new ItemStack(Item.record13);
ItemStack itemRecordCat = new ItemStack(Item.recordCat);
ItemStack itemRecordFar = new ItemStack(Item.recordFar);
ItemStack itemRecordMall = new ItemStack(Item.recordMall);
ItemStack itemRecordMellohi = new ItemStack(Item.recordMellohi);
ItemStack itemRecordStal = new ItemStack(Item.recordStal);
ItemStack itemRecordStrad = new ItemStack(Item.recordStrad);
ItemStack itemRecordWard = new ItemStack(Item.recordWard);
ItemStack itemRecordChirp = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(itemRecord13,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordCat,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordFar,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMall,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMellohi,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStal,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStrad,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordWard,
new Chemical[] { moleculePolyvinylChloride }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordChirp,
new Chemical[] { moleculePolyvinylChloride }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecord13, true, 1000,
new Chemical[] { moleculePolyvinylChloride, null, null, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordCat, true, 1000,
new Chemical[] { null, moleculePolyvinylChloride, null, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordFar, true, 1000,
new Chemical[] { null, null, moleculePolyvinylChloride, null,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMall, true, 1000,
new Chemical[] { null, null, null, moleculePolyvinylChloride,
null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMellohi, true, 1000,
new Chemical[] { null, null, null, null,
moleculePolyvinylChloride, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStal, true, 1000,
new Chemical[] { null, null, null, null, null,
moleculePolyvinylChloride, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStrad, true, 1000,
new Chemical[] { null, null, null, null, null, null,
moleculePolyvinylChloride, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordWard, true, 1000,
new Chemical[] { null, null, null, null, null, null, null,
moleculePolyvinylChloride, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordChirp, true, 1000,
new Chemical[] { null, null, null, null, null, null, null,
null, moleculePolyvinylChloride }));
}
|
diff --git a/web/src/main/java/org/openmrs/module/web/taglib/ExtensionPointTag.java b/web/src/main/java/org/openmrs/module/web/taglib/ExtensionPointTag.java
index 328a74ec..2b891623 100644
--- a/web/src/main/java/org/openmrs/module/web/taglib/ExtensionPointTag.java
+++ b/web/src/main/java/org/openmrs/module/web/taglib/ExtensionPointTag.java
@@ -1,314 +1,316 @@
/**
* 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.web.taglib;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.module.Extension;
import org.openmrs.module.ModuleFactory;
import org.openmrs.util.OpenmrsUtil;
/**
* Extension point tag. Loops over all extensions defined for point "pointId". Makes the variable
* "extension" Usage:
*
* <pre>
* <openmrs:extensionPoint pointId="org.openmrs.cohortbuilder.links" type="html" varStatus="stat">
* <c:if test="${stat.first}">
* <br/>
* <b>Module Links:</b>
* </c:if>
* <ul>
* <openmrs:hasPrivilege privilege="${extension.requiredPrivilege}">
* <form method="post" action="${pageContext.request.contextPath}/${extension.url}">
* <input type="hidden" name="patientIds" value=""/>
* <li>
* <a href="#" onClick="javascript:submitLink(this)"><spring:message code="${extension.label}"/></a>
* </li>
* </form>
* </openmrs:hasPrivilege>
* <c:if test="${stat.last}">
* </ul>
* </c:if>
* </openmrs:extensionPoint>
* </pre>
*
* @see org.openmrs.module.Extension available in the loop.
*/
public class ExtensionPointTag extends TagSupport implements BodyTag {
// general variables
public static final long serialVersionUID = 12323003L;
private final Log log = LogFactory.getLog(getClass());
// variables for the varStatus map
private static final String STATUS_FIRST = "first";
private static final String STATUS_LAST = "last";
private static final String STATUS_INDEX = "index";
private Integer index = 0;
// private variables
private Iterator<Extension> extensions;
private Map<String, String> parameterMap;
private BodyContent bodyContent = null;
// tag attributes
private String pointId;
private String parameters = "";
private String requiredClass;
/** all tags using this should default to 'html' media type */
private String type = "html";
/** name of Map containing variables first/last/index */
private String varStatus = "varStatus";
/** actual map containing the status variables */
private Map<String, Object> status = new HashMap<String, Object>();
// methods
public int doStartTag() {
log.debug("Starting tag for extension point: " + pointId);
// "zero out" the extension list and other variables
extensions = null;
parameterMap = OpenmrsUtil.parseParameterList(parameters);
status = new HashMap<String, Object>();
List<Extension> extensionList = null;
List<Extension> validExtensions = new ArrayList<Extension>();
if (type != null && type.length() > 0) {
try {
Extension.MEDIA_TYPE mediaType = Enum.valueOf(Extension.MEDIA_TYPE.class, type);
log.debug("Getting extensions: " + pointId + " : " + mediaType);
extensionList = ModuleFactory.getExtensions(pointId, mediaType);
}
catch (IllegalArgumentException e) {
log.warn("extension point type: '" + type + "' is invalid. Must be enum of Extension.MEDIA_TYPE", e);
}
} else {
log.debug("Getting extensions: " + pointId);
extensionList = ModuleFactory.getExtensions(pointId);
}
if (extensionList != null) {
log.debug("Found " + extensionList.size() + " extensions");
- if (requiredClass != null) {
+ if (requiredClass == null) {
+ validExtensions = extensionList;
+ } else {
try {
Class<?> clazz = Class.forName(requiredClass);
for (Extension ext : extensionList) {
if (!clazz.isAssignableFrom(ext.getClass())) {
log.warn("Extensions at this point (" + pointId + ") are "
+ "required to be of " + clazz + " or a subclass. " + ext.getClass() + " is not.");
}
else
{
validExtensions.add(ext);
}
}
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(ex);
}
}
extensions = validExtensions.iterator();
}
if (extensions == null || extensions.hasNext() == false) {
extensions = null;
return SKIP_BODY;
} else {
return EVAL_BODY_BUFFERED;
}
}
/**
* @see javax.servlet.jsp.tagext.BodyTag#doInitBody()
*/
public void doInitBody() throws JspException {
getBodyContent().clearBody();
pageContext.removeAttribute("extension");
if (extensions.hasNext()) {
iterate();
}
}
/**
* @see javax.servlet.jsp.tagext.IterationTag#doAfterBody()
*/
public int doAfterBody() throws JspException {
if (extensions.hasNext()) {
// put the next extension in the request and reevaluate the body content
iterate();
return EVAL_BODY_AGAIN;
} else {
// no more extensions, do the end tag now
return SKIP_BODY;
}
}
/**
* Put the next extension into the request from the <code>extensions</code> iterator. If the
* current ext returns a non-null getBodyContentString(), print that to the request instead.
*/
private void iterate() {
Extension ext = extensions.next();
ext.initialize(parameterMap);
String overrideContent = ext.getOverrideContent(getBodyContentString());
if (overrideContent == null) {
log.debug("Adding ext: " + ext.getExtensionId() + " to pageContext class: " + ext.getClass());
pageContext.setAttribute("extension", ext);
// set up and apply the status variable
status.put(STATUS_FIRST, index == 0);
status.put(STATUS_LAST, extensions.hasNext() == false);
status.put(STATUS_INDEX, index++);
pageContext.setAttribute(varStatus, status);
} else {
try {
bodyContent.getEnclosingWriter().write(overrideContent);
}
catch (IOException io) {
log.warn("Cannot write override content of extension: " + ext.toString(), io);
}
}
}
/**
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException {
try {
if (getBodyContent() != null) {
if (log.isDebugEnabled())
log.debug("Ending tag: " + bodyContent.getString());
if (extensions != null)
getBodyContent().writeOut(bodyContent.getEnclosingWriter());
bodyContent.clearBody();
} else {
// the tag doesn't have a body, so initBody and doAfterBody have
// not been called. Do iterations now
while (extensions != null && extensions.hasNext()) {
Extension ext = extensions.next();
ext.initialize(parameterMap);
String overrideContent = ext.getOverrideContent("");
if (overrideContent != null)
pageContext.getOut().write(overrideContent);
}
}
}
catch (java.io.IOException e) {
throw new JspTagException("IO Error while ending tag for point: " + pointId, e);
}
release();
return EVAL_PAGE;
}
@Override
public void release() {
extensions = null;
pointId = null;
requiredClass = null;
type = null;
if (bodyContent != null)
bodyContent.clearBody();
bodyContent = null;
super.release();
}
public String getPointId() {
return pointId;
}
public void setPointId(String pointId) {
this.pointId = pointId;
}
public String getParameters() {
return parameters;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setBodyContent(BodyContent b) {
this.bodyContent = b;
}
public BodyContent getBodyContent() {
return bodyContent;
}
public String getBodyContentString() {
if (bodyContent == null)
return "";
else
return bodyContent.getString();
}
/**
* @return the varStatus
*/
public String getVarStatus() {
return varStatus;
}
/**
* @param varStatus the varStatus to set
*/
public void setVarStatus(String varStatus) {
this.varStatus = varStatus;
}
public String getRequiredClass() {
return requiredClass;
}
public void setRequiredClass(String requiredClass) {
this.requiredClass = requiredClass;
}
}
| true | true | public int doStartTag() {
log.debug("Starting tag for extension point: " + pointId);
// "zero out" the extension list and other variables
extensions = null;
parameterMap = OpenmrsUtil.parseParameterList(parameters);
status = new HashMap<String, Object>();
List<Extension> extensionList = null;
List<Extension> validExtensions = new ArrayList<Extension>();
if (type != null && type.length() > 0) {
try {
Extension.MEDIA_TYPE mediaType = Enum.valueOf(Extension.MEDIA_TYPE.class, type);
log.debug("Getting extensions: " + pointId + " : " + mediaType);
extensionList = ModuleFactory.getExtensions(pointId, mediaType);
}
catch (IllegalArgumentException e) {
log.warn("extension point type: '" + type + "' is invalid. Must be enum of Extension.MEDIA_TYPE", e);
}
} else {
log.debug("Getting extensions: " + pointId);
extensionList = ModuleFactory.getExtensions(pointId);
}
if (extensionList != null) {
log.debug("Found " + extensionList.size() + " extensions");
if (requiredClass != null) {
try {
Class<?> clazz = Class.forName(requiredClass);
for (Extension ext : extensionList) {
if (!clazz.isAssignableFrom(ext.getClass())) {
log.warn("Extensions at this point (" + pointId + ") are "
+ "required to be of " + clazz + " or a subclass. " + ext.getClass() + " is not.");
}
else
{
validExtensions.add(ext);
}
}
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(ex);
}
}
extensions = validExtensions.iterator();
}
if (extensions == null || extensions.hasNext() == false) {
extensions = null;
return SKIP_BODY;
} else {
return EVAL_BODY_BUFFERED;
}
}
| public int doStartTag() {
log.debug("Starting tag for extension point: " + pointId);
// "zero out" the extension list and other variables
extensions = null;
parameterMap = OpenmrsUtil.parseParameterList(parameters);
status = new HashMap<String, Object>();
List<Extension> extensionList = null;
List<Extension> validExtensions = new ArrayList<Extension>();
if (type != null && type.length() > 0) {
try {
Extension.MEDIA_TYPE mediaType = Enum.valueOf(Extension.MEDIA_TYPE.class, type);
log.debug("Getting extensions: " + pointId + " : " + mediaType);
extensionList = ModuleFactory.getExtensions(pointId, mediaType);
}
catch (IllegalArgumentException e) {
log.warn("extension point type: '" + type + "' is invalid. Must be enum of Extension.MEDIA_TYPE", e);
}
} else {
log.debug("Getting extensions: " + pointId);
extensionList = ModuleFactory.getExtensions(pointId);
}
if (extensionList != null) {
log.debug("Found " + extensionList.size() + " extensions");
if (requiredClass == null) {
validExtensions = extensionList;
} else {
try {
Class<?> clazz = Class.forName(requiredClass);
for (Extension ext : extensionList) {
if (!clazz.isAssignableFrom(ext.getClass())) {
log.warn("Extensions at this point (" + pointId + ") are "
+ "required to be of " + clazz + " or a subclass. " + ext.getClass() + " is not.");
}
else
{
validExtensions.add(ext);
}
}
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(ex);
}
}
extensions = validExtensions.iterator();
}
if (extensions == null || extensions.hasNext() == false) {
extensions = null;
return SKIP_BODY;
} else {
return EVAL_BODY_BUFFERED;
}
}
|
diff --git a/src/main/java/at/r7r/schemaInject/SchemaInject.java b/src/main/java/at/r7r/schemaInject/SchemaInject.java
index 282f958..7d30c67 100644
--- a/src/main/java/at/r7r/schemaInject/SchemaInject.java
+++ b/src/main/java/at/r7r/schemaInject/SchemaInject.java
@@ -1,75 +1,76 @@
package at.r7r.schemaInject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import at.r7r.schemaInject.dao.DatabaseHelper;
import at.r7r.schemaInject.dao.SqlBuilder;
import at.r7r.schemaInject.entity.Field;
import at.r7r.schemaInject.entity.PrimaryKey;
import at.r7r.schemaInject.entity.Schema;
import at.r7r.schemaInject.entity.Table;
public class SchemaInject {
private static Table createMetaTable(String tableName) {
List<Field> fields = new ArrayList<Field>();
List<String> pkeyFields = new LinkedList<String>();
fields.add(new Field(null, "revision", "INTEGER", false, null));
fields.add(new Field(null, "ts", "TIMESTAMP", false, null)); // not using a default value here as this is db-specific
pkeyFields.add("revision");
PrimaryKey pkey = new PrimaryKey(null, tableName+"_pkey", pkeyFields);
return new Table(null, tableName, fields, pkey, null, null);
}
static XStream getXStream() {
XStream xstream = new XStream();
xstream.processAnnotations(Schema.class);
return xstream;
}
public void inject(Connection conn, Schema schema) throws SQLException {
DatabaseHelper dh = new DatabaseHelper(conn);
// inject each table
for (Table table: schema.getTables()) {
dh.createTable(table);
}
Table metaTable = createMetaTable(schema.getMetaTable());
dh.createTable(metaTable);
SqlBuilder sql = new SqlBuilder(" ", false);
sql.append("INSERT INTO");
sql.appendIdentifier(schema.getMetaTable());
sql.append("(\"revision\", \"ts\") VALUES (?,?)");
PreparedStatement stmt = conn.prepareStatement(sql.join());
stmt.setInt(1, schema.getRevision());
stmt.setTimestamp(2, new Timestamp(Calendar.getInstance().getTimeInMillis()));
+ stmt.execute();
}
public Schema readSchema(InputStream is) {
XStream xstream = getXStream();
Schema rc = (Schema) xstream.fromXML(is);
rc.assignNamesToUnnamedIndices();
return rc;
}
public Schema readSchema(String filename) throws FileNotFoundException {
File file = new File(filename);
return readSchema(new FileInputStream(file));
}
}
| true | true | public void inject(Connection conn, Schema schema) throws SQLException {
DatabaseHelper dh = new DatabaseHelper(conn);
// inject each table
for (Table table: schema.getTables()) {
dh.createTable(table);
}
Table metaTable = createMetaTable(schema.getMetaTable());
dh.createTable(metaTable);
SqlBuilder sql = new SqlBuilder(" ", false);
sql.append("INSERT INTO");
sql.appendIdentifier(schema.getMetaTable());
sql.append("(\"revision\", \"ts\") VALUES (?,?)");
PreparedStatement stmt = conn.prepareStatement(sql.join());
stmt.setInt(1, schema.getRevision());
stmt.setTimestamp(2, new Timestamp(Calendar.getInstance().getTimeInMillis()));
}
| public void inject(Connection conn, Schema schema) throws SQLException {
DatabaseHelper dh = new DatabaseHelper(conn);
// inject each table
for (Table table: schema.getTables()) {
dh.createTable(table);
}
Table metaTable = createMetaTable(schema.getMetaTable());
dh.createTable(metaTable);
SqlBuilder sql = new SqlBuilder(" ", false);
sql.append("INSERT INTO");
sql.appendIdentifier(schema.getMetaTable());
sql.append("(\"revision\", \"ts\") VALUES (?,?)");
PreparedStatement stmt = conn.prepareStatement(sql.join());
stmt.setInt(1, schema.getRevision());
stmt.setTimestamp(2, new Timestamp(Calendar.getInstance().getTimeInMillis()));
stmt.execute();
}
|
diff --git a/src/com/js/interpreter/pascaltypes/JavaClassBasedType.java b/src/com/js/interpreter/pascaltypes/JavaClassBasedType.java
index 11cd0f2..d1c783a 100644
--- a/src/com/js/interpreter/pascaltypes/JavaClassBasedType.java
+++ b/src/com/js/interpreter/pascaltypes/JavaClassBasedType.java
@@ -1,171 +1,175 @@
package com.js.interpreter.pascaltypes;
import java.util.HashMap;
import ncsa.tools.common.util.TypeUtils;
import serp.bytecode.Code;
import com.js.interpreter.ast.ExpressionContext;
import com.js.interpreter.ast.instructions.returnsvalue.ReturnsValue;
import com.js.interpreter.ast.instructions.returnsvalue.boxing.CharacterBoxer;
import com.js.interpreter.ast.instructions.returnsvalue.boxing.StringBoxer;
import com.js.interpreter.ast.instructions.returnsvalue.boxing.StringBuilderBoxer;
import com.js.interpreter.exceptions.ParsingException;
import com.js.interpreter.pascaltypes.typeconversion.TypeConverter;
public class JavaClassBasedType extends DeclaredType {
Class c;
protected static HashMap<DeclaredType, Object> default_values = new HashMap<DeclaredType, Object>();
public static DeclaredType Boolean = new JavaClassBasedType(Boolean.class);
public static DeclaredType Character = new JavaClassBasedType(
Character.class);
public static DeclaredType StringBuilder = new JavaClassBasedType(
StringBuilder.class);
public static DeclaredType Long = new JavaClassBasedType(Long.class);
public static DeclaredType Double = new JavaClassBasedType(Double.class);
public static DeclaredType Integer = new JavaClassBasedType(Integer.class);
static {
default_values.put(JavaClassBasedType.Integer, 0);
default_values.put(JavaClassBasedType.StringBuilder, "");
default_values.put(JavaClassBasedType.Double, 0.0D);
default_values.put(JavaClassBasedType.Long, 0L);
default_values.put(JavaClassBasedType.Character, '\0');
default_values.put(JavaClassBasedType.Boolean, false);
}
private JavaClassBasedType(Class name) {
c = name;
}
@Override
public boolean isarray() {
return false;
}
@Override
public boolean equals(DeclaredType obj) {
if (this == obj) {
return true;
}
if (obj instanceof JavaClassBasedType) {
Class other = ((JavaClassBasedType) obj).c;
return c == other || c == Object.class || other == Object.class;
}
return false;
}
@Override
public int hashCode() {
return (TypeUtils.isPrimitiveWrapper(c) ? TypeUtils.getTypeForClass(c)
: c).getCanonicalName().hashCode();
}
@Override
public Object initialize() {
Object result;
if ((result = JavaClassBasedType.default_values.get(this)) != null) {
return result;
} else {
try {
return c.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
@Override
public Class toclass() {
return c;
}
@Override
public String toString() {
if (this == Boolean) {
return "Boolean";
} else if (this == Character) {
return "Character";
} else if (this == Integer) {
return "Integer";
} else if (this == Double) {
return "Double";
} else if (this == Long) {
return "Long";
} else if (this == StringBuilder) {
return "String";
}
return c.getCanonicalName();
}
public static DeclaredType anew(Class c) {
if (c == Integer.class) {
return JavaClassBasedType.Integer;
}
if (c == Double.class) {
return JavaClassBasedType.Double;
}
if (c == StringBuilder.class) {
return JavaClassBasedType.StringBuilder;
}
if (c == Long.class) {
return JavaClassBasedType.Long;
}
if (c == Character.class) {
return JavaClassBasedType.Character;
}
if (c == Boolean.class) {
return JavaClassBasedType.Boolean;
}
return new JavaClassBasedType(c);
}
@Override
public ReturnsValue convert(ReturnsValue value, ExpressionContext f)
throws ParsingException {
RuntimeType other_type = value.get_type(f);
if (other_type.declType instanceof JavaClassBasedType) {
if (this.equals(other_type.declType)) {
return value;
}
if (this == StringBuilder
&& other_type.declType == JavaClassBasedType.Character) {
return new CharacterBoxer(value);
}
if (this == StringBuilder
&& ((JavaClassBasedType) other_type.declType).c == String.class) {
return new StringBoxer(value);
}
if (this.c == String.class
&& other_type.declType == JavaClassBasedType.StringBuilder) {
return new StringBuilderBoxer(value);
}
+ if (this.c == String.class
+ && other_type.declType == JavaClassBasedType.Character) {
+ return new StringBuilderBoxer(new CharacterBoxer(value));
+ }
return TypeConverter.autoConvert(this, value,
(JavaClassBasedType) other_type.declType);
}
return null;
}
@Override
public void pushDefaultValue(Code constructor_code) {
// TODO Auto-generated method stub
}
}
| true | true | public ReturnsValue convert(ReturnsValue value, ExpressionContext f)
throws ParsingException {
RuntimeType other_type = value.get_type(f);
if (other_type.declType instanceof JavaClassBasedType) {
if (this.equals(other_type.declType)) {
return value;
}
if (this == StringBuilder
&& other_type.declType == JavaClassBasedType.Character) {
return new CharacterBoxer(value);
}
if (this == StringBuilder
&& ((JavaClassBasedType) other_type.declType).c == String.class) {
return new StringBoxer(value);
}
if (this.c == String.class
&& other_type.declType == JavaClassBasedType.StringBuilder) {
return new StringBuilderBoxer(value);
}
return TypeConverter.autoConvert(this, value,
(JavaClassBasedType) other_type.declType);
}
return null;
}
| public ReturnsValue convert(ReturnsValue value, ExpressionContext f)
throws ParsingException {
RuntimeType other_type = value.get_type(f);
if (other_type.declType instanceof JavaClassBasedType) {
if (this.equals(other_type.declType)) {
return value;
}
if (this == StringBuilder
&& other_type.declType == JavaClassBasedType.Character) {
return new CharacterBoxer(value);
}
if (this == StringBuilder
&& ((JavaClassBasedType) other_type.declType).c == String.class) {
return new StringBoxer(value);
}
if (this.c == String.class
&& other_type.declType == JavaClassBasedType.StringBuilder) {
return new StringBuilderBoxer(value);
}
if (this.c == String.class
&& other_type.declType == JavaClassBasedType.Character) {
return new StringBuilderBoxer(new CharacterBoxer(value));
}
return TypeConverter.autoConvert(this, value,
(JavaClassBasedType) other_type.declType);
}
return null;
}
|
diff --git a/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/visuals/RoomVisualWorld.java b/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/visuals/RoomVisualWorld.java
index 553f163ec..435682f18 100644
--- a/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/visuals/RoomVisualWorld.java
+++ b/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/visuals/RoomVisualWorld.java
@@ -1,164 +1,164 @@
package edu.umich.soar.gridmap2d.visuals;
import java.util.HashSet;
import java.util.List;
import lcmtypes.pose_t;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.widgets.Composite;
import edu.umich.soar.gridmap2d.Gridmap2D;
import edu.umich.soar.gridmap2d.Names;
import edu.umich.soar.gridmap2d.map.CellObject;
import edu.umich.soar.gridmap2d.players.Player;
import edu.umich.soar.gridmap2d.players.RoomPlayer;
import edu.umich.soar.gridmap2d.world.RoomWorld;
import edu.umich.soar.gridmap2d.world.World;
public class RoomVisualWorld extends VisualWorld {
private boolean colored_rooms = false;
RoomWorld world;
public RoomVisualWorld(Composite parent, int style, int cellSize, World world) {
super(parent, style, cellSize);
this.world = (RoomWorld)world;
}
public void paintControl(PaintEvent e) {
GC gc = e.gc;
gc.setFont(font);
gc.setForeground(WindowManager.black);
gc.setLineWidth(1);
if (!Gridmap2D.control.isRunning()) {
if (lastX != e.x || lastY != e.y || internalRepaint) {
lastX = e.x;
lastY = e.y;
painted = false;
}
if (disabled || !painted) {
gc.setBackground(WindowManager.widget_background);
gc.fillRectangle(0,0, this.getWidth(), this.getHeight());
if (disabled) {
painted = true;
return;
}
}
}
if (System.getProperty("os.name").contains("Mac OS X"))
painted = false;
// Draw world
int [] location = new int [2];
HashSet<Integer> roomIds = new HashSet<Integer>();
for(location[0] = 0; location[0] < map.size(); ++location[0]){
for(location[1] = 0; location[1] < map.size(); ++location[1]){
int [] drawLocation = new int [] { cellSize*location[0], cellSize*(map.size() - location[1] - 1) };
if (!this.map.getCell(location).checkAndResetRedraw() && painted) {
continue;
}
if (this.map.getCell(location).hasAnyWithProperty(Names.kPropertyBlock)) {
gc.setBackground(WindowManager.black);
gc.fillRectangle(drawLocation[0], drawLocation[1], cellSize, cellSize);
} else {
if (!map.getCell(location).hasAnyWithProperty(Names.kPropertyGatewayRender)) {
if (!colored_rooms) {
// normal:
gc.setBackground(WindowManager.widget_background);
} else {
// colored rooms:
CellObject roomObject = map.getCell(location).getObject(Names.kRoomID);
if (roomObject == null) {
gc.setBackground(WindowManager.widget_background);
} else {
int roomID = roomObject.getIntProperty(Names.kPropertyNumber, -1);
roomID %= Gridmap2D.simulation.kColors.length - 1; // the one off eliminates black
gc.setBackground(WindowManager.getColor(Gridmap2D.simulation.kColors[roomID]));
}
}
if (map.getCell(location).hasAnyWithProperty(Names.kRoomObjectName)) {
gc.setBackground(WindowManager.darkGray);
}
} else {
gc.setBackground(WindowManager.white);
}
gc.fillRectangle(drawLocation[0], drawLocation[1], cellSize, cellSize);
}
List<CellObject> objectIds = map.getCell(location).getAllWithProperty("object-id");
if (objectIds != null) {
gc.setForeground(WindowManager.white);
gc.drawString(objectIds.get(0).getProperty("object-id"), drawLocation[0], drawLocation[1]);
} else {
List<CellObject> numbers = map.getCell(location).getAllWithProperty("number");
if (numbers!= null) {
if (!roomIds.contains(numbers.get(0).getIntProperty("number", -1))) {
gc.setForeground(WindowManager.black);
- gc.drawString(numbers.get(0).getProperty("number"), drawLocation[0], drawLocation[1]);
+ gc.drawString(numbers.get(0).getProperty("number") + " ", drawLocation[0]+1, drawLocation[1]);
roomIds.add(numbers.get(0).getIntProperty("number", -1));
}
}
}
}
}
// draw entities now so they appear on top
for (Player p : world.getPlayers()) {
RoomPlayer player = (RoomPlayer)p;
pose_t pose = player.getState().getPose();
float [] center = new float [] { (float)pose.pos[0], (float)pose.pos[1] };
float [] offset = new float [] { 0, 0 };
Path path = new Path(gc.getDevice());
float heading = (float)player.getState().getYaw();
// first, move to the point representing the tip of the chevron
offset[1] = kDotSize * (float)Math.sin(heading);
offset[0] = kDotSize * (float)Math.cos(heading);
float [] original = new float [] { offset[0], offset[1] };
path.moveTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("First: " + offset);
// next draw a line to the corner
offset[1] = kDotSize/2.0f * (float)Math.sin(heading + (3*Math.PI)/4);
offset[0] = kDotSize/2.0f * (float)Math.cos(heading + (3*Math.PI)/4);
path.lineTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("Second: " + offset);
// next draw a line to the other corner
offset[1] = kDotSize/2.0f * (float)Math.sin(heading - (3*Math.PI)/4);
offset[0] = kDotSize/2.0f * (float)Math.cos(heading - (3*Math.PI)/4);
path.lineTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("Third: " + offset);
// finally a line back to the original
path.lineTo((center[0] + original[0]), map.size() * cellSize - (center[1] + original[1]));
gc.setForeground(WindowManager.getColor(player.getColor()));
gc.drawPath(path);
}
}
@Override
Player getPlayerAtPixel(int [] loc) {
loc[1] = map.size() * cellSize - loc[1];
int[] xy = getCellAtPixel(loc);
if (xy == null) {
return null;
}
return this.map.getCell(xy).getPlayer();
}
}
| true | true | public void paintControl(PaintEvent e) {
GC gc = e.gc;
gc.setFont(font);
gc.setForeground(WindowManager.black);
gc.setLineWidth(1);
if (!Gridmap2D.control.isRunning()) {
if (lastX != e.x || lastY != e.y || internalRepaint) {
lastX = e.x;
lastY = e.y;
painted = false;
}
if (disabled || !painted) {
gc.setBackground(WindowManager.widget_background);
gc.fillRectangle(0,0, this.getWidth(), this.getHeight());
if (disabled) {
painted = true;
return;
}
}
}
if (System.getProperty("os.name").contains("Mac OS X"))
painted = false;
// Draw world
int [] location = new int [2];
HashSet<Integer> roomIds = new HashSet<Integer>();
for(location[0] = 0; location[0] < map.size(); ++location[0]){
for(location[1] = 0; location[1] < map.size(); ++location[1]){
int [] drawLocation = new int [] { cellSize*location[0], cellSize*(map.size() - location[1] - 1) };
if (!this.map.getCell(location).checkAndResetRedraw() && painted) {
continue;
}
if (this.map.getCell(location).hasAnyWithProperty(Names.kPropertyBlock)) {
gc.setBackground(WindowManager.black);
gc.fillRectangle(drawLocation[0], drawLocation[1], cellSize, cellSize);
} else {
if (!map.getCell(location).hasAnyWithProperty(Names.kPropertyGatewayRender)) {
if (!colored_rooms) {
// normal:
gc.setBackground(WindowManager.widget_background);
} else {
// colored rooms:
CellObject roomObject = map.getCell(location).getObject(Names.kRoomID);
if (roomObject == null) {
gc.setBackground(WindowManager.widget_background);
} else {
int roomID = roomObject.getIntProperty(Names.kPropertyNumber, -1);
roomID %= Gridmap2D.simulation.kColors.length - 1; // the one off eliminates black
gc.setBackground(WindowManager.getColor(Gridmap2D.simulation.kColors[roomID]));
}
}
if (map.getCell(location).hasAnyWithProperty(Names.kRoomObjectName)) {
gc.setBackground(WindowManager.darkGray);
}
} else {
gc.setBackground(WindowManager.white);
}
gc.fillRectangle(drawLocation[0], drawLocation[1], cellSize, cellSize);
}
List<CellObject> objectIds = map.getCell(location).getAllWithProperty("object-id");
if (objectIds != null) {
gc.setForeground(WindowManager.white);
gc.drawString(objectIds.get(0).getProperty("object-id"), drawLocation[0], drawLocation[1]);
} else {
List<CellObject> numbers = map.getCell(location).getAllWithProperty("number");
if (numbers!= null) {
if (!roomIds.contains(numbers.get(0).getIntProperty("number", -1))) {
gc.setForeground(WindowManager.black);
gc.drawString(numbers.get(0).getProperty("number"), drawLocation[0], drawLocation[1]);
roomIds.add(numbers.get(0).getIntProperty("number", -1));
}
}
}
}
}
// draw entities now so they appear on top
for (Player p : world.getPlayers()) {
RoomPlayer player = (RoomPlayer)p;
pose_t pose = player.getState().getPose();
float [] center = new float [] { (float)pose.pos[0], (float)pose.pos[1] };
float [] offset = new float [] { 0, 0 };
Path path = new Path(gc.getDevice());
float heading = (float)player.getState().getYaw();
// first, move to the point representing the tip of the chevron
offset[1] = kDotSize * (float)Math.sin(heading);
offset[0] = kDotSize * (float)Math.cos(heading);
float [] original = new float [] { offset[0], offset[1] };
path.moveTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("First: " + offset);
// next draw a line to the corner
offset[1] = kDotSize/2.0f * (float)Math.sin(heading + (3*Math.PI)/4);
offset[0] = kDotSize/2.0f * (float)Math.cos(heading + (3*Math.PI)/4);
path.lineTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("Second: " + offset);
// next draw a line to the other corner
offset[1] = kDotSize/2.0f * (float)Math.sin(heading - (3*Math.PI)/4);
offset[0] = kDotSize/2.0f * (float)Math.cos(heading - (3*Math.PI)/4);
path.lineTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("Third: " + offset);
// finally a line back to the original
path.lineTo((center[0] + original[0]), map.size() * cellSize - (center[1] + original[1]));
gc.setForeground(WindowManager.getColor(player.getColor()));
gc.drawPath(path);
}
}
| public void paintControl(PaintEvent e) {
GC gc = e.gc;
gc.setFont(font);
gc.setForeground(WindowManager.black);
gc.setLineWidth(1);
if (!Gridmap2D.control.isRunning()) {
if (lastX != e.x || lastY != e.y || internalRepaint) {
lastX = e.x;
lastY = e.y;
painted = false;
}
if (disabled || !painted) {
gc.setBackground(WindowManager.widget_background);
gc.fillRectangle(0,0, this.getWidth(), this.getHeight());
if (disabled) {
painted = true;
return;
}
}
}
if (System.getProperty("os.name").contains("Mac OS X"))
painted = false;
// Draw world
int [] location = new int [2];
HashSet<Integer> roomIds = new HashSet<Integer>();
for(location[0] = 0; location[0] < map.size(); ++location[0]){
for(location[1] = 0; location[1] < map.size(); ++location[1]){
int [] drawLocation = new int [] { cellSize*location[0], cellSize*(map.size() - location[1] - 1) };
if (!this.map.getCell(location).checkAndResetRedraw() && painted) {
continue;
}
if (this.map.getCell(location).hasAnyWithProperty(Names.kPropertyBlock)) {
gc.setBackground(WindowManager.black);
gc.fillRectangle(drawLocation[0], drawLocation[1], cellSize, cellSize);
} else {
if (!map.getCell(location).hasAnyWithProperty(Names.kPropertyGatewayRender)) {
if (!colored_rooms) {
// normal:
gc.setBackground(WindowManager.widget_background);
} else {
// colored rooms:
CellObject roomObject = map.getCell(location).getObject(Names.kRoomID);
if (roomObject == null) {
gc.setBackground(WindowManager.widget_background);
} else {
int roomID = roomObject.getIntProperty(Names.kPropertyNumber, -1);
roomID %= Gridmap2D.simulation.kColors.length - 1; // the one off eliminates black
gc.setBackground(WindowManager.getColor(Gridmap2D.simulation.kColors[roomID]));
}
}
if (map.getCell(location).hasAnyWithProperty(Names.kRoomObjectName)) {
gc.setBackground(WindowManager.darkGray);
}
} else {
gc.setBackground(WindowManager.white);
}
gc.fillRectangle(drawLocation[0], drawLocation[1], cellSize, cellSize);
}
List<CellObject> objectIds = map.getCell(location).getAllWithProperty("object-id");
if (objectIds != null) {
gc.setForeground(WindowManager.white);
gc.drawString(objectIds.get(0).getProperty("object-id"), drawLocation[0], drawLocation[1]);
} else {
List<CellObject> numbers = map.getCell(location).getAllWithProperty("number");
if (numbers!= null) {
if (!roomIds.contains(numbers.get(0).getIntProperty("number", -1))) {
gc.setForeground(WindowManager.black);
gc.drawString(numbers.get(0).getProperty("number") + " ", drawLocation[0]+1, drawLocation[1]);
roomIds.add(numbers.get(0).getIntProperty("number", -1));
}
}
}
}
}
// draw entities now so they appear on top
for (Player p : world.getPlayers()) {
RoomPlayer player = (RoomPlayer)p;
pose_t pose = player.getState().getPose();
float [] center = new float [] { (float)pose.pos[0], (float)pose.pos[1] };
float [] offset = new float [] { 0, 0 };
Path path = new Path(gc.getDevice());
float heading = (float)player.getState().getYaw();
// first, move to the point representing the tip of the chevron
offset[1] = kDotSize * (float)Math.sin(heading);
offset[0] = kDotSize * (float)Math.cos(heading);
float [] original = new float [] { offset[0], offset[1] };
path.moveTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("First: " + offset);
// next draw a line to the corner
offset[1] = kDotSize/2.0f * (float)Math.sin(heading + (3*Math.PI)/4);
offset[0] = kDotSize/2.0f * (float)Math.cos(heading + (3*Math.PI)/4);
path.lineTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("Second: " + offset);
// next draw a line to the other corner
offset[1] = kDotSize/2.0f * (float)Math.sin(heading - (3*Math.PI)/4);
offset[0] = kDotSize/2.0f * (float)Math.cos(heading - (3*Math.PI)/4);
path.lineTo((center[0] + offset[0]), map.size() * cellSize - (center[1] + offset[1]));
//System.out.println("Third: " + offset);
// finally a line back to the original
path.lineTo((center[0] + original[0]), map.size() * cellSize - (center[1] + original[1]));
gc.setForeground(WindowManager.getColor(player.getColor()));
gc.drawPath(path);
}
}
|
diff --git a/extension/app-schema/app-schema-test/src/test/java/org/geoserver/test/ValidationTest.java b/extension/app-schema/app-schema-test/src/test/java/org/geoserver/test/ValidationTest.java
index e6de547ed..5f7126fba 100644
--- a/extension/app-schema/app-schema-test/src/test/java/org/geoserver/test/ValidationTest.java
+++ b/extension/app-schema/app-schema-test/src/test/java/org/geoserver/test/ValidationTest.java
@@ -1,163 +1,163 @@
/*
* Copyright (c) 2001 - 2009 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.test;
import junit.framework.Test;
import org.w3c.dom.Document;
/**
* Validation testing with GeoServer
*
* @author Victor Tey, CSIRO Exploration and Mining
*
*/
public class ValidationTest extends AbstractAppSchemaWfsTestSupport {
/**
* Read-only test so can use one-time setup.
*
* @return
*/
public static Test suite() {
return new OneTimeTestSetup(new ValidationTest());
}
@Override
protected NamespaceTestData buildTestData() {
return new ValidationTestMockData();
}
/**
* Test that when minOccur=0 the validation should let it pass
*/
public void testAttributeMinOccur0() {
Document doc = null;
doc = getAsDOM("wfs?request=GetFeature&typename=gsml:GeologicUnit");
LOGGER.info("WFS GetFeature&typename=gsml:GeologicUnit response:\n" + prettyString(doc));
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gml:name", doc);
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gml:name", doc);
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gml:name", doc);
assertXpathCount(
1,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"myBody1",
- "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
+ "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value[@codeSpace='myBodyCodespace1']",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:rank[@codeSpace='myBodyCodespace1']",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:rank[@codeSpace='myBodyCodespace2']",
doc);
assertXpathCount(
1,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"myBody3",
- "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
+ "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value[@codeSpace='myBodyCodespace3']",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:rank[@codeSpace='myBodyCodespace3']",
doc);
}
public void testSimpleContentInteger() {
Document doc = null;
doc = getAsDOM("wfs?request=GetFeature&typename=er:Commodity");
LOGGER.info("WFS GetFeature&typename=er:Commodity response:\n" + prettyString(doc));
assertXpathCount(1, "//er:Commodity[@gml:id='er.commodity.gu.1']/gml:name", doc);
assertXpathCount(1, "//er:Commodity[@gml:id='er.commodity.gu.1']/er:commodityRank", doc);
assertXpathEvaluatesTo("myName1", "//er:Commodity[@gml:id='er.commodity.gu.1']/gml:name",
doc);
assertXpathEvaluatesTo("1", "//er:Commodity[@gml:id='er.commodity.gu.1']/er:commodityRank",
doc);
assertXpathCount(1, "//er:Commodity[@gml:id='er.commodity.gu.2']/gml:name", doc);
assertXpathCount(0, "//er:Commodity[@gml:id='er.commodity.gu.2']/er:commodityRank", doc);
assertXpathEvaluatesTo("myName2", "//er:Commodity[@gml:id='er.commodity.gu.2']/gml:name",
doc);
assertXpathCount(1, "//er:Commodity[@gml:id='er.commodity.gu.3']/gml:name", doc);
assertXpathCount(1, "//er:Commodity[@gml:id='er.commodity.gu.3']/er:commodityRank", doc);
assertXpathEvaluatesTo("myName3", "//er:Commodity[@gml:id='er.commodity.gu.3']/gml:name",
doc);
assertXpathEvaluatesTo("3", "//er:Commodity[@gml:id='er.commodity.gu.3']/er:commodityRank",
doc);
}
/**
* Test minOccur=1 and the attribute should always be encoded even when empty.
*/
public void testAttributeMinOccur1() {
Document doc = getAsDOM("wfs?request=GetFeature&typename=gsml:MappedFeature");
LOGGER.info("WFS GetFeature&typename=gsml:gsml:MappedFeature response:\n"
+ prettyString(doc));
assertXpathCount(3, "//gsml:MappedFeature", doc);
// with minOccur = 1 and null value, an empty tag would be encoded
assertXpathCount(1, "//gsml:MappedFeature[@gml:id='gsml.mappedfeature.gu.1']", doc);
assertXpathCount(1,
"//gsml:MappedFeature[@gml:id='gsml.mappedfeature.gu.1']/gsml:observationMethod",
doc);
assertXpathCount(
0,
"//gsml:MappedFeature[@gml:id='gsml.mappedfeature.gu.1']/gsml:observationMethod/gsml:CGI_TermValue",
doc);
// the rest should be encoded as normal
assertXpathCount(1, "//gsml:MappedFeature[@gml:id='gsml.mappedfeature.gu.2']", doc);
assertXpathEvaluatesTo(
"observation2",
"//gsml:MappedFeature[@gml:id='gsml.mappedfeature.gu.2']/gsml:observationMethod/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathCount(1, "//gsml:MappedFeature[@gml:id='gsml.mappedfeature.gu.3']", doc);
assertXpathEvaluatesTo(
"observation3",
"//gsml:MappedFeature[@gml:id='gsml.mappedfeature.gu.3']/gsml:observationMethod/gsml:CGI_TermValue/gsml:value",
doc);
}
}
| false | true | public void testAttributeMinOccur0() {
Document doc = null;
doc = getAsDOM("wfs?request=GetFeature&typename=gsml:GeologicUnit");
LOGGER.info("WFS GetFeature&typename=gsml:GeologicUnit response:\n" + prettyString(doc));
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gml:name", doc);
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gml:name", doc);
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gml:name", doc);
assertXpathCount(
1,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:rank[@codeSpace='myBodyCodespace1']",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:rank[@codeSpace='myBodyCodespace2']",
doc);
assertXpathCount(
1,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:rank[@codeSpace='myBodyCodespace3']",
doc);
}
| public void testAttributeMinOccur0() {
Document doc = null;
doc = getAsDOM("wfs?request=GetFeature&typename=gsml:GeologicUnit");
LOGGER.info("WFS GetFeature&typename=gsml:GeologicUnit response:\n" + prettyString(doc));
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gml:name", doc);
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gml:name", doc);
assertXpathCount(1, "//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gml:name", doc);
assertXpathCount(
1,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value[@codeSpace='myBodyCodespace1']",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody1",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.1']/gsml:rank[@codeSpace='myBodyCodespace1']",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathCount(
0,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.2']/gsml:rank[@codeSpace='myBodyCodespace2']",
doc);
assertXpathCount(
1,
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:bodyMorphology/gsml:CGI_TermValue/gsml:value[@codeSpace='myBodyCodespace3']",
doc);
assertXpathEvaluatesTo(
"compositionName",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:composition/gsml:CompositionPart/gsml:lithology[1]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:composition/gsml:CompositionPart/gsml:lithology[2]/gsml:ControlledConcept/gml:name",
doc);
assertXpathEvaluatesTo(
"myBody3",
"//gsml:GeologicUnit[@gml:id='gsml.geologicunit.gu.3']/gsml:rank[@codeSpace='myBodyCodespace3']",
doc);
}
|
diff --git a/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/WidgetTypeTagHandler.java b/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/WidgetTypeTagHandler.java
index 9c2e3946..84c96a72 100644
--- a/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/WidgetTypeTagHandler.java
+++ b/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/WidgetTypeTagHandler.java
@@ -1,236 +1,236 @@
/*
* (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* 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.
*
* Contributors:
* <a href="mailto:[email protected]">Anahide Tchertchian</a>
*
* $Id: WidgetTypeTagHandler.java 26053 2007-10-16 01:45:43Z atchertchian $
*/
package org.nuxeo.ecm.platform.forms.layout.facelets;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELException;
import javax.el.ValueExpression;
import javax.el.VariableMapper;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.platform.forms.layout.api.FieldDefinition;
import org.nuxeo.ecm.platform.forms.layout.api.Widget;
import org.nuxeo.ecm.platform.forms.layout.api.impl.FieldDefinitionImpl;
import org.nuxeo.ecm.platform.forms.layout.facelets.plugins.TemplateWidgetTypeHandler;
import org.nuxeo.ecm.platform.forms.layout.service.WebLayoutManager;
import org.nuxeo.ecm.platform.ui.web.util.ComponentTagUtils;
import org.nuxeo.runtime.api.Framework;
import com.sun.facelets.FaceletContext;
import com.sun.facelets.el.VariableMapperWrapper;
import com.sun.facelets.tag.TagAttribute;
import com.sun.facelets.tag.TagConfig;
import com.sun.facelets.tag.TagHandler;
/**
* Widget type tag handler.
* <p>
* Applies a {@link WidgetTypeHandler} resolved from a widget created for given
* type name and mode, and uses other tag attributes to fill the widget
* properties.
* <p>
* Does not handle sub widgets.
*
* @author <a href="mailto:[email protected]">Anahide Tchertchian</a>
*/
public class WidgetTypeTagHandler extends TagHandler {
private static final Log log = LogFactory.getLog(WidgetTypeTagHandler.class);
protected final TagConfig config;
protected final TagAttribute name;
protected final TagAttribute mode;
protected final TagAttribute value;
protected final TagAttribute field;
protected final TagAttribute fields;
protected final TagAttribute label;
protected final TagAttribute helpLabel;
protected final TagAttribute translated;
protected final TagAttribute properties;
/**
* Convenient attribute to remove the "template" property from widget
* properties (and avoid stack overflow errors when using another widget
* type in a widget template, for compatibility code for instance).
*
* @since 5.6
*/
protected final TagAttribute ignoreTemplateProperty;
/**
* @since 5.6
*/
protected final TagAttribute subWidgets;
protected final TagAttribute[] vars;
protected final String[] reservedVarsArray = { "id", "mode", "type",
"properties", "ignoreTemplateProperty", "subWidgets" };
public WidgetTypeTagHandler(TagConfig config) {
super(config);
this.config = config;
name = getRequiredAttribute("name");
mode = getRequiredAttribute("mode");
value = getAttribute("value");
field = getAttribute("field");
fields = getAttribute("fields");
label = getAttribute("label");
helpLabel = getAttribute("helpLabel");
translated = getAttribute("translated");
properties = getAttribute("properties");
ignoreTemplateProperty = getAttribute("ignoreTemplateProperty");
subWidgets = getAttribute("subWidgets");
vars = tag.getAttributes().getAll();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public final void apply(FaceletContext ctx, UIComponent parent)
throws IOException, FacesException, ELException {
WebLayoutManager layoutService;
try {
layoutService = Framework.getService(WebLayoutManager.class);
} catch (Exception e) {
throw new FacesException(e);
}
if (layoutService == null) {
throw new FacesException("Layout service not found");
}
// build handler
List<String> reservedVars = Arrays.asList(reservedVarsArray);
Map<String, Serializable> widgetProps = new HashMap<String, Serializable>();
if (properties != null) {
Map<String, Serializable> propertiesValue = (Map<String, Serializable>) properties.getObject(
ctx, Map.class);
if (propertiesValue != null) {
widgetProps.putAll(propertiesValue);
}
}
for (TagAttribute var : vars) {
String localName = var.getLocalName();
if (!reservedVars.contains(localName)) {
widgetProps.put(localName, var.getValue());
}
}
boolean ignoreTemplatePropValue = false;
if (ignoreTemplateProperty != null) {
ignoreTemplatePropValue = ignoreTemplateProperty.getBoolean(ctx);
}
if (ignoreTemplatePropValue) {
widgetProps.remove(TemplateWidgetTypeHandler.TEMPLATE_PROPERTY_NAME);
}
String typeValue = name.getValue(ctx);
String modeValue = mode.getValue(ctx);
String valueName = null;
if (value != null) {
valueName = value.getValue();
if (ComponentTagUtils.isStrictValueReference(valueName)) {
valueName = ComponentTagUtils.getBareValueName(valueName);
}
}
List<FieldDefinition> fieldsValue = new ArrayList<FieldDefinition>();
if (field != null) {
Object fieldValue = field.getValue(ctx);
if (fieldValue instanceof FieldDefinition) {
fieldsValue.add((FieldDefinition) fieldValue);
} else if (fieldValue instanceof String) {
fieldsValue.add(new FieldDefinitionImpl(null,
(String) fieldValue));
} else {
log.error("Invalid field item => discard: " + fieldValue);
}
}
if (fields != null) {
List resolvedfields = (List) fields.getObject(ctx, List.class);
for (Object item : resolvedfields) {
if (item instanceof FieldDefinition) {
fieldsValue.add((FieldDefinition) item);
} else if (item instanceof String) {
fieldsValue.add(new FieldDefinitionImpl(null, (String) item));
} else {
log.error("Invalid field item => discard: " + item);
}
}
}
String labelValue = null;
if (label != null) {
- labelValue = label.getValue();
+ labelValue = label.getValue(ctx);
}
String helpLabelValue = null;
if (helpLabel != null) {
- helpLabelValue = helpLabel.getValue();
+ helpLabelValue = helpLabel.getValue(ctx);
}
Boolean translatedValue = Boolean.FALSE;
if (translated != null) {
translatedValue = Boolean.valueOf(translated.getBoolean(ctx));
}
Widget[] subWidgetsValue = null;
if (subWidgets != null) {
subWidgetsValue = (Widget[]) subWidgets.getObject(ctx,
Widget[].class);
}
Widget widget = layoutService.createWidget(ctx, typeValue, modeValue,
valueName, fieldsValue, labelValue, helpLabelValue,
translatedValue, widgetProps, subWidgetsValue);
// expose widget variable
VariableMapper orig = ctx.getVariableMapper();
VariableMapper vm = new VariableMapperWrapper(orig);
ctx.setVariableMapper(vm);
ValueExpression widgetVe = ctx.getExpressionFactory().createValueExpression(
widget, Widget.class);
vm.setVariable(RenderVariables.widgetVariables.widget.name(), widgetVe);
vm.setVariable(
String.format("%s_%s",
RenderVariables.widgetVariables.widget.name(),
Integer.valueOf(widget.getLevel())), widgetVe);
try {
WidgetTagHandler.applyWidgetHandler(ctx, parent, config, widget,
value, true, nextHandler);
} finally {
ctx.setVariableMapper(orig);
}
}
}
| false | true | public final void apply(FaceletContext ctx, UIComponent parent)
throws IOException, FacesException, ELException {
WebLayoutManager layoutService;
try {
layoutService = Framework.getService(WebLayoutManager.class);
} catch (Exception e) {
throw new FacesException(e);
}
if (layoutService == null) {
throw new FacesException("Layout service not found");
}
// build handler
List<String> reservedVars = Arrays.asList(reservedVarsArray);
Map<String, Serializable> widgetProps = new HashMap<String, Serializable>();
if (properties != null) {
Map<String, Serializable> propertiesValue = (Map<String, Serializable>) properties.getObject(
ctx, Map.class);
if (propertiesValue != null) {
widgetProps.putAll(propertiesValue);
}
}
for (TagAttribute var : vars) {
String localName = var.getLocalName();
if (!reservedVars.contains(localName)) {
widgetProps.put(localName, var.getValue());
}
}
boolean ignoreTemplatePropValue = false;
if (ignoreTemplateProperty != null) {
ignoreTemplatePropValue = ignoreTemplateProperty.getBoolean(ctx);
}
if (ignoreTemplatePropValue) {
widgetProps.remove(TemplateWidgetTypeHandler.TEMPLATE_PROPERTY_NAME);
}
String typeValue = name.getValue(ctx);
String modeValue = mode.getValue(ctx);
String valueName = null;
if (value != null) {
valueName = value.getValue();
if (ComponentTagUtils.isStrictValueReference(valueName)) {
valueName = ComponentTagUtils.getBareValueName(valueName);
}
}
List<FieldDefinition> fieldsValue = new ArrayList<FieldDefinition>();
if (field != null) {
Object fieldValue = field.getValue(ctx);
if (fieldValue instanceof FieldDefinition) {
fieldsValue.add((FieldDefinition) fieldValue);
} else if (fieldValue instanceof String) {
fieldsValue.add(new FieldDefinitionImpl(null,
(String) fieldValue));
} else {
log.error("Invalid field item => discard: " + fieldValue);
}
}
if (fields != null) {
List resolvedfields = (List) fields.getObject(ctx, List.class);
for (Object item : resolvedfields) {
if (item instanceof FieldDefinition) {
fieldsValue.add((FieldDefinition) item);
} else if (item instanceof String) {
fieldsValue.add(new FieldDefinitionImpl(null, (String) item));
} else {
log.error("Invalid field item => discard: " + item);
}
}
}
String labelValue = null;
if (label != null) {
labelValue = label.getValue();
}
String helpLabelValue = null;
if (helpLabel != null) {
helpLabelValue = helpLabel.getValue();
}
Boolean translatedValue = Boolean.FALSE;
if (translated != null) {
translatedValue = Boolean.valueOf(translated.getBoolean(ctx));
}
Widget[] subWidgetsValue = null;
if (subWidgets != null) {
subWidgetsValue = (Widget[]) subWidgets.getObject(ctx,
Widget[].class);
}
Widget widget = layoutService.createWidget(ctx, typeValue, modeValue,
valueName, fieldsValue, labelValue, helpLabelValue,
translatedValue, widgetProps, subWidgetsValue);
// expose widget variable
VariableMapper orig = ctx.getVariableMapper();
VariableMapper vm = new VariableMapperWrapper(orig);
ctx.setVariableMapper(vm);
ValueExpression widgetVe = ctx.getExpressionFactory().createValueExpression(
widget, Widget.class);
vm.setVariable(RenderVariables.widgetVariables.widget.name(), widgetVe);
vm.setVariable(
String.format("%s_%s",
RenderVariables.widgetVariables.widget.name(),
Integer.valueOf(widget.getLevel())), widgetVe);
try {
WidgetTagHandler.applyWidgetHandler(ctx, parent, config, widget,
value, true, nextHandler);
} finally {
ctx.setVariableMapper(orig);
}
}
| public final void apply(FaceletContext ctx, UIComponent parent)
throws IOException, FacesException, ELException {
WebLayoutManager layoutService;
try {
layoutService = Framework.getService(WebLayoutManager.class);
} catch (Exception e) {
throw new FacesException(e);
}
if (layoutService == null) {
throw new FacesException("Layout service not found");
}
// build handler
List<String> reservedVars = Arrays.asList(reservedVarsArray);
Map<String, Serializable> widgetProps = new HashMap<String, Serializable>();
if (properties != null) {
Map<String, Serializable> propertiesValue = (Map<String, Serializable>) properties.getObject(
ctx, Map.class);
if (propertiesValue != null) {
widgetProps.putAll(propertiesValue);
}
}
for (TagAttribute var : vars) {
String localName = var.getLocalName();
if (!reservedVars.contains(localName)) {
widgetProps.put(localName, var.getValue());
}
}
boolean ignoreTemplatePropValue = false;
if (ignoreTemplateProperty != null) {
ignoreTemplatePropValue = ignoreTemplateProperty.getBoolean(ctx);
}
if (ignoreTemplatePropValue) {
widgetProps.remove(TemplateWidgetTypeHandler.TEMPLATE_PROPERTY_NAME);
}
String typeValue = name.getValue(ctx);
String modeValue = mode.getValue(ctx);
String valueName = null;
if (value != null) {
valueName = value.getValue();
if (ComponentTagUtils.isStrictValueReference(valueName)) {
valueName = ComponentTagUtils.getBareValueName(valueName);
}
}
List<FieldDefinition> fieldsValue = new ArrayList<FieldDefinition>();
if (field != null) {
Object fieldValue = field.getValue(ctx);
if (fieldValue instanceof FieldDefinition) {
fieldsValue.add((FieldDefinition) fieldValue);
} else if (fieldValue instanceof String) {
fieldsValue.add(new FieldDefinitionImpl(null,
(String) fieldValue));
} else {
log.error("Invalid field item => discard: " + fieldValue);
}
}
if (fields != null) {
List resolvedfields = (List) fields.getObject(ctx, List.class);
for (Object item : resolvedfields) {
if (item instanceof FieldDefinition) {
fieldsValue.add((FieldDefinition) item);
} else if (item instanceof String) {
fieldsValue.add(new FieldDefinitionImpl(null, (String) item));
} else {
log.error("Invalid field item => discard: " + item);
}
}
}
String labelValue = null;
if (label != null) {
labelValue = label.getValue(ctx);
}
String helpLabelValue = null;
if (helpLabel != null) {
helpLabelValue = helpLabel.getValue(ctx);
}
Boolean translatedValue = Boolean.FALSE;
if (translated != null) {
translatedValue = Boolean.valueOf(translated.getBoolean(ctx));
}
Widget[] subWidgetsValue = null;
if (subWidgets != null) {
subWidgetsValue = (Widget[]) subWidgets.getObject(ctx,
Widget[].class);
}
Widget widget = layoutService.createWidget(ctx, typeValue, modeValue,
valueName, fieldsValue, labelValue, helpLabelValue,
translatedValue, widgetProps, subWidgetsValue);
// expose widget variable
VariableMapper orig = ctx.getVariableMapper();
VariableMapper vm = new VariableMapperWrapper(orig);
ctx.setVariableMapper(vm);
ValueExpression widgetVe = ctx.getExpressionFactory().createValueExpression(
widget, Widget.class);
vm.setVariable(RenderVariables.widgetVariables.widget.name(), widgetVe);
vm.setVariable(
String.format("%s_%s",
RenderVariables.widgetVariables.widget.name(),
Integer.valueOf(widget.getLevel())), widgetVe);
try {
WidgetTagHandler.applyWidgetHandler(ctx, parent, config, widget,
value, true, nextHandler);
} finally {
ctx.setVariableMapper(orig);
}
}
|
diff --git a/pmd-eclipse/src/net/sourceforge/pmd/eclipse/views/PriorityFilter.java b/pmd-eclipse/src/net/sourceforge/pmd/eclipse/views/PriorityFilter.java
index abe1dd64c..75ffd08ef 100644
--- a/pmd-eclipse/src/net/sourceforge/pmd/eclipse/views/PriorityFilter.java
+++ b/pmd-eclipse/src/net/sourceforge/pmd/eclipse/views/PriorityFilter.java
@@ -1,163 +1,166 @@
package net.sourceforge.pmd.eclipse.views;
import java.util.ArrayList;
import java.util.Arrays;
import net.sourceforge.pmd.eclipse.PMDConstants;
import net.sourceforge.pmd.eclipse.PMDPlugin;
import net.sourceforge.pmd.eclipse.model.FileRecord;
import net.sourceforge.pmd.eclipse.model.PackageRecord;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
/**
* The ViewerFilter for Priorities
*
* @author SebastianRaffel ( 17.05.2005 )
*/
public class PriorityFilter extends ViewerFilter {
private ArrayList priorityList;
/**
* Constructor
*
* @author SebastianRaffel ( 29.06.2005 )
*/
public PriorityFilter() {
priorityList = new ArrayList(Arrays.asList(
PMDPlugin.getDefault().getPriorityValues() ));
}
/* @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) */
public boolean select(Viewer viewer, Object parentElement, Object element) {
// the Element can be ...
if (element instanceof PackageRecord) {
// a Package (Overview)
PackageRecord packageRec = (PackageRecord) element;
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
if (packageRec.findMarkersByAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY, priority ) != null)
return true;
}
} else if (element instanceof FileRecord) {
// ... a File (Overview)
FileRecord fileRec = (FileRecord) element;
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
if (fileRec.findMarkersByAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY, priority ) != null)
return true;
}
} else if (element instanceof IMarker) {
// ... or a Marker (Outline)
try {
Integer markerPrio =
(Integer) ((IMarker) element).getAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY );
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
- for (int i=0; i<priorityList.size(); i++) {
- Integer priority = (Integer) priorityList.get(i);
- if (markerPrio.equals(priority))
- return true;
- }
+ // ** PHR note ** for unknown reason, markerPrio may be null
+ if (markerPrio != null) {
+ for (int i=0; i<priorityList.size(); i++) {
+ Integer priority = (Integer) priorityList.get(i);
+ if (markerPrio.equals(priority))
+ return true;
+ }
+ }
} catch (CoreException ce) {
PMDPlugin.getDefault().logError(
PMDConstants.MSGKEY_ERROR_CORE_EXCEPTION +
this.toString(), ce);
}
}
return false;
}
/**
* Sets the List of Priorities to filter
*
* @param newList, an ArrayLust of Integers
*/
public void setPriorityFilterList(ArrayList newList) {
priorityList = newList;
}
/**
* Gets the FilterList with the Priorities
*
* @return an ArrayList of Integers
*/
public ArrayList getPriorityFilterList() {
return priorityList;
}
/**
* Adds a Priority to The List
*
* @param priority
*/
public void addPriorityToList(Integer priority) {
priorityList.add(priority);
}
/**
* Removes a Priority From the List
*
* @param priority
*/
public void removePriorityFromList(Integer priority) {
priorityList.remove(priority);
}
/**
* Loads a Priorityist out of a String, e.g.
* from "1,2,3" it builds up the List {1,2,3}
* (for use with Mementos)
*
* @param newList, the List-String
* @param splitter, the List splitter (in general ",")
*/
public void setPriorityFilterListFromString(String newList, String splitter) {
if (newList == null)
return;
String[] newArray = newList.split(splitter);
ArrayList priorities = new ArrayList();
for (int i=0; i<newArray.length; i++) {
priorities.add(new Integer(newArray[i]));
}
priorityList = priorities;
}
/**
* Returns the FilterList as String with the given splitter,
* e.g. with "," the Priorities {1,4,5} would look like "1,4,5"
* (for use with Mementos)
*
* @param splitter, The String splitter (in general ",")
* @return the List-String
*/
public String getPriorityFilterListAsString(String splitter) {
String listString = "";
for (int i=0; i<priorityList.size(); i++) {
if (i > 0)
listString += splitter;
listString += priorityList.get(i).toString();
}
return listString;
}
}
| true | true | public boolean select(Viewer viewer, Object parentElement, Object element) {
// the Element can be ...
if (element instanceof PackageRecord) {
// a Package (Overview)
PackageRecord packageRec = (PackageRecord) element;
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
if (packageRec.findMarkersByAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY, priority ) != null)
return true;
}
} else if (element instanceof FileRecord) {
// ... a File (Overview)
FileRecord fileRec = (FileRecord) element;
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
if (fileRec.findMarkersByAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY, priority ) != null)
return true;
}
} else if (element instanceof IMarker) {
// ... or a Marker (Outline)
try {
Integer markerPrio =
(Integer) ((IMarker) element).getAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY );
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
if (markerPrio.equals(priority))
return true;
}
} catch (CoreException ce) {
PMDPlugin.getDefault().logError(
PMDConstants.MSGKEY_ERROR_CORE_EXCEPTION +
this.toString(), ce);
}
}
return false;
}
| public boolean select(Viewer viewer, Object parentElement, Object element) {
// the Element can be ...
if (element instanceof PackageRecord) {
// a Package (Overview)
PackageRecord packageRec = (PackageRecord) element;
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
if (packageRec.findMarkersByAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY, priority ) != null)
return true;
}
} else if (element instanceof FileRecord) {
// ... a File (Overview)
FileRecord fileRec = (FileRecord) element;
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
if (fileRec.findMarkersByAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY, priority ) != null)
return true;
}
} else if (element instanceof IMarker) {
// ... or a Marker (Outline)
try {
Integer markerPrio =
(Integer) ((IMarker) element).getAttribute(
PMDPlugin.KEY_MARKERATT_PRIORITY );
// go through the List and search for Markers with the
// given Priorities, if there is one, it is displayed
// ** PHR note ** for unknown reason, markerPrio may be null
if (markerPrio != null) {
for (int i=0; i<priorityList.size(); i++) {
Integer priority = (Integer) priorityList.get(i);
if (markerPrio.equals(priority))
return true;
}
}
} catch (CoreException ce) {
PMDPlugin.getDefault().logError(
PMDConstants.MSGKEY_ERROR_CORE_EXCEPTION +
this.toString(), ce);
}
}
return false;
}
|
diff --git a/src/server/src/main/java/org/apache/accumulo/server/test/TestIngest.java b/src/server/src/main/java/org/apache/accumulo/server/test/TestIngest.java
index 42be2a947..48e6bc082 100644
--- a/src/server/src/main/java/org/apache/accumulo/server/test/TestIngest.java
+++ b/src/server/src/main/java/org/apache/accumulo/server/test/TestIngest.java
@@ -1,418 +1,417 @@
/*
* 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.accumulo.server.test;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Random;
import java.util.TreeSet;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.impl.TabletServerBatchWriter;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.data.ConstraintViolationSummary;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.file.FileOperations;
import org.apache.accumulo.core.file.FileSKVWriter;
import org.apache.accumulo.core.file.rfile.RFile;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.accumulo.core.security.thrift.AuthInfo;
import org.apache.accumulo.core.trace.DistributedTrace;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.zookeeper.ZooReader;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.security.Authenticator;
import org.apache.accumulo.server.security.ZKAuthenticator;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import cloudtrace.instrument.Trace;
public class TestIngest {
public static final Authorizations AUTHS = new Authorizations("L1", "L2", "G1", "GROUP2");
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(TestIngest.class);
private static AuthInfo rootCredentials;
private static String username;
private static String passwd;
public static class CreateTable {
public static void main(String[] args) throws AccumuloException, AccumuloSecurityException, TableExistsException {
long start = Long.parseLong(args[0]);
long end = Long.parseLong(args[1]);
long numsplits = Long.parseLong(args[2]);
String username = args[3];
byte[] passwd = args[4].getBytes();
TreeSet<Text> splits = getSplitPoints(start, end, numsplits);
Connector conn = HdfsZooInstance.getInstance().getConnector(username, passwd);
conn.tableOperations().create("test_ingest");
try {
conn.tableOperations().addSplits("test_ingest", splits);
} catch (TableNotFoundException ex) {
// unlikely
throw new RuntimeException(ex);
}
}
public static TreeSet<Text> getSplitPoints(long start, long end, long numsplits) {
long splitSize = (end - start) / numsplits;
long pos = start + splitSize;
TreeSet<Text> splits = new TreeSet<Text>();
while (pos < end) {
splits.add(new Text(String.format("row_%010d", pos)));
pos += splitSize;
}
return splits;
}
}
public static class IngestArgs {
int rows;
int startRow;
int cols;
boolean random = false;
int seed = 0;
int dataSize = 1000;
boolean delete = false;
long timestamp = 0;
boolean hasTimestamp = false;
boolean useGet = false;
public boolean unique;
boolean outputToRFile = false;
String outputFile;
int stride;
public boolean useTsbw = false;
String columnFamily = "colf";
boolean trace = false;
}
public static Options getOptions() {
Options opts = new Options();
opts.addOption(new Option("size", "size", true, "size"));
opts.addOption(new Option("colf", "colf", true, "colf"));
opts.addOption(new Option("delete", "delete", false, "delete"));
opts.addOption(new Option("random", "random", true, "random"));
opts.addOption(new Option("timestamp", "timestamp", true, "timestamp"));
opts.addOption(new Option("stride", "stride", true, "stride"));
opts.addOption(new Option("useGet", "useGet", false, "use get"));
opts.addOption(new Option("tsbw", "tsbw", false, "tsbw"));
opts.addOption(new Option("username", "username", true, "username"));
opts.addOption(new Option("password", "password", true, "password"));
opts.addOption(new Option("trace", "trace", false, "turn on distributed tracing"));
opts.addOption(new Option("rFile", "rFile", true, "relative-key file"));
return opts;
}
public static IngestArgs parseArgs(String args[]) {
Parser p = new BasicParser();
Options opts = getOptions();
CommandLine cl;
try {
cl = p.parse(opts, args);
} catch (ParseException e) {
System.out.println("Parse Error, exiting.");
throw new RuntimeException(e);
}
if (cl.getArgs().length != 3) {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("test_ingest <rows> <start_row> <num_columns>", getOptions());
throw new RuntimeException();
}
IngestArgs ia = new IngestArgs();
if (cl.hasOption("size")) {
ia.dataSize = Integer.parseInt(cl.getOptionValue("size"));
}
if (cl.hasOption("colf")) {
ia.columnFamily = cl.getOptionValue("colf");
}
if (cl.hasOption("timestamp")) {
ia.timestamp = Long.parseLong(cl.getOptionValue("timestamp"));
ia.hasTimestamp = true;
}
if (cl.hasOption("rFile")) {
ia.outputToRFile = true;
ia.outputFile = cl.getOptionValue("rFile");
}
ia.delete = cl.hasOption("delete");
ia.useGet = cl.hasOption("useGet");
if (cl.hasOption("random")) {
ia.random = true;
ia.seed = Integer.parseInt(cl.getOptionValue("random"));
}
if (cl.hasOption("stride")) {
ia.stride = Integer.parseInt(cl.getOptionValue("stride"));
}
ia.useTsbw = cl.hasOption("tsbw");
username = cl.getOptionValue("username", "root");
passwd = cl.getOptionValue("password", "secret");
String[] requiredArgs = cl.getArgs();
ia.rows = Integer.parseInt(requiredArgs[0]);
ia.startRow = Integer.parseInt(requiredArgs[1]);
ia.cols = Integer.parseInt(requiredArgs[2]);
if (cl.hasOption("trace")) {
ia.trace = true;
}
return ia;
}
public static byte[][] generateValues(IngestArgs ingestArgs) {
byte[][] bytevals = new byte[10][];
byte[] letters = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
for (int i = 0; i < 10; i++) {
bytevals[i] = new byte[ingestArgs.dataSize];
for (int j = 0; j < ingestArgs.dataSize; j++)
bytevals[i][j] = letters[i];
}
return bytevals;
}
private static byte ROW_PREFIX[] = "row_".getBytes();
private static byte COL_PREFIX[] = "col_".getBytes();
public static Text generateRow(int rowid, int startRow) {
return new Text(FastFormat.toZeroPaddedString(rowid + startRow, 10, 10, ROW_PREFIX));
}
public static byte[] genRandomValue(Random random, byte dest[], int seed, int row, int col) {
random.setSeed((row ^ seed) ^ col);
random.nextBytes(dest);
toPrintableChars(dest);
return dest;
}
public static void toPrintableChars(byte[] dest) {
// transform to printable chars
for (int i = 0; i < dest.length; i++) {
dest[i] = (byte) (((0xff & dest[i]) % 92) + ' ');
}
}
public static void main(String[] args) {
// log.error("usage : test_ingest [-delete] [-size <value size>] [-random <seed>] [-timestamp <ts>] [-stride <size>] <rows> <start row> <# cols> ");
IngestArgs ingestArgs = parseArgs(args);
Instance instance = HdfsZooInstance.getInstance();
try {
if (ingestArgs.trace) {
String name = TestIngest.class.getSimpleName();
DistributedTrace.enable(instance, new ZooReader(instance), name, null);
Trace.on(name);
Trace.currentTrace().data("cmdLine", Arrays.asList(args).toString());
}
Logger.getLogger(TabletServerBatchWriter.class.getName()).setLevel(Level.TRACE);
// test batch update
long stopTime;
byte[][] bytevals = generateValues(ingestArgs);
byte randomValue[] = new byte[ingestArgs.dataSize];
Random random = new Random();
long bytesWritten = 0;
BatchWriter bw = null;
FileSKVWriter writer = null;
rootCredentials = new AuthInfo(username, ByteBuffer.wrap(passwd.getBytes()), instance.getInstanceID());
if (ingestArgs.outputToRFile) {
Configuration conf = CachedConfiguration.getInstance();
FileSystem fs = FileSystem.get(conf);
- System.out.println(ingestArgs.outputFile);
writer = FileOperations.getInstance().openWriter(ingestArgs.outputFile + "." + RFile.EXTENSION, fs, conf,
AccumuloConfiguration.getDefaultConfiguration());
writer.startDefaultLocalityGroup();
} else {
Connector connector = instance.getConnector(rootCredentials.user, rootCredentials.password);
bw = connector.createBatchWriter("test_ingest", 20000000l, 60000l, 10);
}
Authenticator authenticator = ZKAuthenticator.getInstance();
authenticator.changeAuthorizations(rootCredentials, rootCredentials.user, AUTHS);
ColumnVisibility le = new ColumnVisibility("L1&L2&G1&GROUP2");
Text labBA = new Text(le.getExpression());
// int step = 100;
long startTime = System.currentTimeMillis();
for (int i = 0; i < ingestArgs.rows; i++) {
int rowid;
if (ingestArgs.stride > 0) {
rowid = ((i % ingestArgs.stride) * (ingestArgs.rows / ingestArgs.stride)) + (i / ingestArgs.stride);
} else {
rowid = i;
}
Text row = generateRow(rowid, ingestArgs.startRow);
Mutation m = new Mutation(row);
for (int j = 0; j < ingestArgs.cols; j++) {
Text colf = new Text(ingestArgs.columnFamily);
Text colq = new Text(FastFormat.toZeroPaddedString(j, 5, 10, COL_PREFIX));
if (writer != null) {
Key key = new Key(row, colf, colq, labBA);
if (ingestArgs.hasTimestamp) {
key.setTimestamp(ingestArgs.timestamp);
} else {
key.setTimestamp(System.currentTimeMillis());
}
if (ingestArgs.delete) {
key.setDeleted(true);
} else {
key.setDeleted(false);
}
bytesWritten += key.getSize();
if (ingestArgs.delete) {
writer.append(key, new Value(new byte[0]));
} else {
byte value[];
if (ingestArgs.random) {
value = genRandomValue(random, randomValue, ingestArgs.seed, rowid + ingestArgs.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
Value v = new Value(value);
writer.append(key, v);
bytesWritten += v.getSize();
}
} else {
Key key = new Key(row, colf, colq, labBA);
bytesWritten += key.getSize();
if (ingestArgs.delete) {
if (ingestArgs.hasTimestamp)
m.putDelete(colf, colq, le, ingestArgs.timestamp);
else
m.putDelete(colf, colq, le);
} else {
byte value[];
if (ingestArgs.random) {
value = genRandomValue(random, randomValue, ingestArgs.seed, rowid + ingestArgs.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
bytesWritten += value.length;
if (ingestArgs.hasTimestamp) {
m.put(colf, colq, le, ingestArgs.timestamp, new Value(value, true));
} else {
m.put(colf, colq, le, new Value(value, true));
}
}
}
}
if (bw != null)
bw.addMutation(m);
}
if (writer != null) {
writer.close();
} else if (bw != null) {
try {
bw.close();
} catch (MutationsRejectedException e) {
if (e.getAuthorizationFailures().size() > 0) {
for (KeyExtent ke : e.getAuthorizationFailures()) {
System.err.println("ERROR : Not authorized to write to : " + ke);
}
}
if (e.getConstraintViolationSummaries().size() > 0) {
for (ConstraintViolationSummary cvs : e.getConstraintViolationSummaries()) {
System.err.println("ERROR : Constraint violates : " + cvs);
}
}
throw e;
}
}
stopTime = System.currentTimeMillis();
int totalValues = ingestArgs.rows * ingestArgs.cols;
double elapsed = (stopTime - startTime) / 1000.0;
System.out.printf("%,12d records written | %,8d records/sec | %,12d bytes written | %,8d bytes/sec | %6.3f secs \n", totalValues,
(int) (totalValues / elapsed), bytesWritten, (int) (bytesWritten / elapsed), elapsed);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Trace.off();
}
}
}
| true | true | public static void main(String[] args) {
// log.error("usage : test_ingest [-delete] [-size <value size>] [-random <seed>] [-timestamp <ts>] [-stride <size>] <rows> <start row> <# cols> ");
IngestArgs ingestArgs = parseArgs(args);
Instance instance = HdfsZooInstance.getInstance();
try {
if (ingestArgs.trace) {
String name = TestIngest.class.getSimpleName();
DistributedTrace.enable(instance, new ZooReader(instance), name, null);
Trace.on(name);
Trace.currentTrace().data("cmdLine", Arrays.asList(args).toString());
}
Logger.getLogger(TabletServerBatchWriter.class.getName()).setLevel(Level.TRACE);
// test batch update
long stopTime;
byte[][] bytevals = generateValues(ingestArgs);
byte randomValue[] = new byte[ingestArgs.dataSize];
Random random = new Random();
long bytesWritten = 0;
BatchWriter bw = null;
FileSKVWriter writer = null;
rootCredentials = new AuthInfo(username, ByteBuffer.wrap(passwd.getBytes()), instance.getInstanceID());
if (ingestArgs.outputToRFile) {
Configuration conf = CachedConfiguration.getInstance();
FileSystem fs = FileSystem.get(conf);
System.out.println(ingestArgs.outputFile);
writer = FileOperations.getInstance().openWriter(ingestArgs.outputFile + "." + RFile.EXTENSION, fs, conf,
AccumuloConfiguration.getDefaultConfiguration());
writer.startDefaultLocalityGroup();
} else {
Connector connector = instance.getConnector(rootCredentials.user, rootCredentials.password);
bw = connector.createBatchWriter("test_ingest", 20000000l, 60000l, 10);
}
Authenticator authenticator = ZKAuthenticator.getInstance();
authenticator.changeAuthorizations(rootCredentials, rootCredentials.user, AUTHS);
ColumnVisibility le = new ColumnVisibility("L1&L2&G1&GROUP2");
Text labBA = new Text(le.getExpression());
// int step = 100;
long startTime = System.currentTimeMillis();
for (int i = 0; i < ingestArgs.rows; i++) {
int rowid;
if (ingestArgs.stride > 0) {
rowid = ((i % ingestArgs.stride) * (ingestArgs.rows / ingestArgs.stride)) + (i / ingestArgs.stride);
} else {
rowid = i;
}
Text row = generateRow(rowid, ingestArgs.startRow);
Mutation m = new Mutation(row);
for (int j = 0; j < ingestArgs.cols; j++) {
Text colf = new Text(ingestArgs.columnFamily);
Text colq = new Text(FastFormat.toZeroPaddedString(j, 5, 10, COL_PREFIX));
if (writer != null) {
Key key = new Key(row, colf, colq, labBA);
if (ingestArgs.hasTimestamp) {
key.setTimestamp(ingestArgs.timestamp);
} else {
key.setTimestamp(System.currentTimeMillis());
}
if (ingestArgs.delete) {
key.setDeleted(true);
} else {
key.setDeleted(false);
}
bytesWritten += key.getSize();
if (ingestArgs.delete) {
writer.append(key, new Value(new byte[0]));
} else {
byte value[];
if (ingestArgs.random) {
value = genRandomValue(random, randomValue, ingestArgs.seed, rowid + ingestArgs.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
Value v = new Value(value);
writer.append(key, v);
bytesWritten += v.getSize();
}
} else {
Key key = new Key(row, colf, colq, labBA);
bytesWritten += key.getSize();
if (ingestArgs.delete) {
if (ingestArgs.hasTimestamp)
m.putDelete(colf, colq, le, ingestArgs.timestamp);
else
m.putDelete(colf, colq, le);
} else {
byte value[];
if (ingestArgs.random) {
value = genRandomValue(random, randomValue, ingestArgs.seed, rowid + ingestArgs.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
bytesWritten += value.length;
if (ingestArgs.hasTimestamp) {
m.put(colf, colq, le, ingestArgs.timestamp, new Value(value, true));
} else {
m.put(colf, colq, le, new Value(value, true));
}
}
}
}
if (bw != null)
bw.addMutation(m);
}
if (writer != null) {
writer.close();
} else if (bw != null) {
try {
bw.close();
} catch (MutationsRejectedException e) {
if (e.getAuthorizationFailures().size() > 0) {
for (KeyExtent ke : e.getAuthorizationFailures()) {
System.err.println("ERROR : Not authorized to write to : " + ke);
}
}
if (e.getConstraintViolationSummaries().size() > 0) {
for (ConstraintViolationSummary cvs : e.getConstraintViolationSummaries()) {
System.err.println("ERROR : Constraint violates : " + cvs);
}
}
throw e;
}
}
stopTime = System.currentTimeMillis();
int totalValues = ingestArgs.rows * ingestArgs.cols;
double elapsed = (stopTime - startTime) / 1000.0;
System.out.printf("%,12d records written | %,8d records/sec | %,12d bytes written | %,8d bytes/sec | %6.3f secs \n", totalValues,
(int) (totalValues / elapsed), bytesWritten, (int) (bytesWritten / elapsed), elapsed);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Trace.off();
}
}
| public static void main(String[] args) {
// log.error("usage : test_ingest [-delete] [-size <value size>] [-random <seed>] [-timestamp <ts>] [-stride <size>] <rows> <start row> <# cols> ");
IngestArgs ingestArgs = parseArgs(args);
Instance instance = HdfsZooInstance.getInstance();
try {
if (ingestArgs.trace) {
String name = TestIngest.class.getSimpleName();
DistributedTrace.enable(instance, new ZooReader(instance), name, null);
Trace.on(name);
Trace.currentTrace().data("cmdLine", Arrays.asList(args).toString());
}
Logger.getLogger(TabletServerBatchWriter.class.getName()).setLevel(Level.TRACE);
// test batch update
long stopTime;
byte[][] bytevals = generateValues(ingestArgs);
byte randomValue[] = new byte[ingestArgs.dataSize];
Random random = new Random();
long bytesWritten = 0;
BatchWriter bw = null;
FileSKVWriter writer = null;
rootCredentials = new AuthInfo(username, ByteBuffer.wrap(passwd.getBytes()), instance.getInstanceID());
if (ingestArgs.outputToRFile) {
Configuration conf = CachedConfiguration.getInstance();
FileSystem fs = FileSystem.get(conf);
writer = FileOperations.getInstance().openWriter(ingestArgs.outputFile + "." + RFile.EXTENSION, fs, conf,
AccumuloConfiguration.getDefaultConfiguration());
writer.startDefaultLocalityGroup();
} else {
Connector connector = instance.getConnector(rootCredentials.user, rootCredentials.password);
bw = connector.createBatchWriter("test_ingest", 20000000l, 60000l, 10);
}
Authenticator authenticator = ZKAuthenticator.getInstance();
authenticator.changeAuthorizations(rootCredentials, rootCredentials.user, AUTHS);
ColumnVisibility le = new ColumnVisibility("L1&L2&G1&GROUP2");
Text labBA = new Text(le.getExpression());
// int step = 100;
long startTime = System.currentTimeMillis();
for (int i = 0; i < ingestArgs.rows; i++) {
int rowid;
if (ingestArgs.stride > 0) {
rowid = ((i % ingestArgs.stride) * (ingestArgs.rows / ingestArgs.stride)) + (i / ingestArgs.stride);
} else {
rowid = i;
}
Text row = generateRow(rowid, ingestArgs.startRow);
Mutation m = new Mutation(row);
for (int j = 0; j < ingestArgs.cols; j++) {
Text colf = new Text(ingestArgs.columnFamily);
Text colq = new Text(FastFormat.toZeroPaddedString(j, 5, 10, COL_PREFIX));
if (writer != null) {
Key key = new Key(row, colf, colq, labBA);
if (ingestArgs.hasTimestamp) {
key.setTimestamp(ingestArgs.timestamp);
} else {
key.setTimestamp(System.currentTimeMillis());
}
if (ingestArgs.delete) {
key.setDeleted(true);
} else {
key.setDeleted(false);
}
bytesWritten += key.getSize();
if (ingestArgs.delete) {
writer.append(key, new Value(new byte[0]));
} else {
byte value[];
if (ingestArgs.random) {
value = genRandomValue(random, randomValue, ingestArgs.seed, rowid + ingestArgs.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
Value v = new Value(value);
writer.append(key, v);
bytesWritten += v.getSize();
}
} else {
Key key = new Key(row, colf, colq, labBA);
bytesWritten += key.getSize();
if (ingestArgs.delete) {
if (ingestArgs.hasTimestamp)
m.putDelete(colf, colq, le, ingestArgs.timestamp);
else
m.putDelete(colf, colq, le);
} else {
byte value[];
if (ingestArgs.random) {
value = genRandomValue(random, randomValue, ingestArgs.seed, rowid + ingestArgs.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
bytesWritten += value.length;
if (ingestArgs.hasTimestamp) {
m.put(colf, colq, le, ingestArgs.timestamp, new Value(value, true));
} else {
m.put(colf, colq, le, new Value(value, true));
}
}
}
}
if (bw != null)
bw.addMutation(m);
}
if (writer != null) {
writer.close();
} else if (bw != null) {
try {
bw.close();
} catch (MutationsRejectedException e) {
if (e.getAuthorizationFailures().size() > 0) {
for (KeyExtent ke : e.getAuthorizationFailures()) {
System.err.println("ERROR : Not authorized to write to : " + ke);
}
}
if (e.getConstraintViolationSummaries().size() > 0) {
for (ConstraintViolationSummary cvs : e.getConstraintViolationSummaries()) {
System.err.println("ERROR : Constraint violates : " + cvs);
}
}
throw e;
}
}
stopTime = System.currentTimeMillis();
int totalValues = ingestArgs.rows * ingestArgs.cols;
double elapsed = (stopTime - startTime) / 1000.0;
System.out.printf("%,12d records written | %,8d records/sec | %,12d bytes written | %,8d bytes/sec | %6.3f secs \n", totalValues,
(int) (totalValues / elapsed), bytesWritten, (int) (bytesWritten / elapsed), elapsed);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Trace.off();
}
}
|
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java
index 9052672d3..dce262288 100644
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java
+++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java
@@ -1,832 +1,832 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Eclipse 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://www.eclipse.org/org/documents/epl-v10.php
*
* 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.ide.eclipse.adt.internal.resources.manager;
import com.android.ide.eclipse.adt.internal.resources.IResourceRepository;
import com.android.ide.eclipse.adt.internal.resources.ResourceItem;
import com.android.ide.eclipse.adt.internal.resources.ResourceType;
import com.android.ide.eclipse.adt.internal.resources.configurations.FolderConfiguration;
import com.android.ide.eclipse.adt.internal.resources.configurations.LanguageQualifier;
import com.android.ide.eclipse.adt.internal.resources.configurations.RegionQualifier;
import com.android.ide.eclipse.adt.internal.resources.configurations.ResourceQualifier;
import com.android.ide.eclipse.adt.internal.resources.manager.files.IAbstractFolder;
import com.android.layoutlib.api.IResourceValue;
import com.android.layoutlib.utils.ResourceValue;
import org.eclipse.core.resources.IFolder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Represents the resources of a project. This is a file view of the resources, with handling
* for the alternate resource types. For a compiled view use CompiledResources.
*/
public class ProjectResources implements IResourceRepository {
private final HashMap<ResourceFolderType, List<ResourceFolder>> mFolderMap =
new HashMap<ResourceFolderType, List<ResourceFolder>>();
private final HashMap<ResourceType, List<ProjectResourceItem>> mResourceMap =
new HashMap<ResourceType, List<ProjectResourceItem>>();
/** Map of (name, id) for resources of type {@link ResourceType#ID} coming from R.java */
private Map<String, Map<String, Integer>> mResourceValueMap;
/** Map of (id, [name, resType]) for all resources coming from R.java */
private Map<Integer, String[]> mResIdValueToNameMap;
/** Map of (int[], name) for styleable resources coming from R.java */
private Map<IntArrayWrapper, String> mStyleableValueToNameMap;
/** Cached list of {@link IdResourceItem}. This is mix of IdResourceItem created by
* {@link MultiResourceFile} for ids coming from XML files under res/values and
* {@link IdResourceItem} created manually, from the list coming from R.java */
private final ArrayList<IdResourceItem> mIdResourceList = new ArrayList<IdResourceItem>();
private final boolean mIsFrameworkRepository;
private final IntArrayWrapper mWrapper = new IntArrayWrapper(null);
public ProjectResources(boolean isFrameworkRepository) {
mIsFrameworkRepository = isFrameworkRepository;
}
public boolean isSystemRepository() {
return mIsFrameworkRepository;
}
/**
* Adds a Folder Configuration to the project.
* @param type The resource type.
* @param config The resource configuration.
* @param folder The workspace folder object.
* @return the {@link ResourceFolder} object associated to this folder.
*/
protected ResourceFolder add(ResourceFolderType type, FolderConfiguration config,
IAbstractFolder folder) {
// get the list for the resource type
List<ResourceFolder> list = mFolderMap.get(type);
if (list == null) {
list = new ArrayList<ResourceFolder>();
ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository);
list.add(cf);
mFolderMap.put(type, list);
return cf;
}
// look for an already existing folder configuration.
for (ResourceFolder cFolder : list) {
if (cFolder.mConfiguration.equals(config)) {
// config already exist. Nothing to be done really, besides making sure
// the IFolder object is up to date.
cFolder.mFolder = folder;
return cFolder;
}
}
// If we arrive here, this means we didn't find a matching configuration.
// So we add one.
ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository);
list.add(cf);
return cf;
}
/**
* Removes a {@link ResourceFolder} associated with the specified {@link IAbstractFolder}.
* @param type The type of the folder
* @param folder the IFolder object.
*/
protected void removeFolder(ResourceFolderType type, IFolder folder) {
// get the list of folders for the resource type.
List<ResourceFolder> list = mFolderMap.get(type);
if (list != null) {
int count = list.size();
for (int i = 0 ; i < count ; i++) {
ResourceFolder resFolder = list.get(i);
if (resFolder.getFolder().getIFolder().equals(folder)) {
// we found the matching ResourceFolder. we need to remove it.
list.remove(i);
// we now need to invalidate this resource type.
// The easiest way is to touch one of the other folders of the same type.
if (list.size() > 0) {
list.get(0).touch();
} else {
// if the list is now empty, and we have a single ResouceType out of this
// ResourceFolderType, then we are done.
// However, if another ResourceFolderType can generate similar ResourceType
// than this, we need to update those ResourceTypes as well.
// For instance, if the last "drawable-*" folder is deleted, we need to
// refresh the ResourceItem associated with ResourceType.DRAWABLE.
// Those can be found in ResourceFolderType.DRAWABLE but also in
// ResourceFolderType.VALUES.
// If we don't find a single folder to touch, then it's fine, as the top
// level items (the list of generated resource types) is not cached
// (for now)
// get the lists of ResourceTypes generated by this ResourceFolderType
ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes(
type);
// for each of those, make sure to find one folder to touch so that the
// list of ResourceItem associated with the type is rebuilt.
for (ResourceType resType : resTypes) {
// get the list of folder that can generate this type
ResourceFolderType[] folderTypes =
FolderTypeRelationship.getRelatedFolders(resType);
// we only need to touch one folder in any of those (since it's one
// folder per type, not per folder type).
for (ResourceFolderType folderType : folderTypes) {
List<ResourceFolder> resFolders = mFolderMap.get(folderType);
if (resFolders != null && resFolders.size() > 0) {
resFolders.get(0).touch();
break;
}
}
}
}
// we're done updating/touching, we can stop
break;
}
}
}
}
/**
* Returns a list of {@link ResourceFolder} for a specific {@link ResourceFolderType}.
* @param type The {@link ResourceFolderType}
*/
public List<ResourceFolder> getFolders(ResourceFolderType type) {
return mFolderMap.get(type);
}
/* (non-Javadoc)
* @see com.android.ide.eclipse.editors.resources.IResourceRepository#getAvailableResourceTypes()
*/
public ResourceType[] getAvailableResourceTypes() {
ArrayList<ResourceType> list = new ArrayList<ResourceType>();
// For each key, we check if there's a single ResourceType match.
// If not, we look for the actual content to give us the resource type.
for (ResourceFolderType folderType : mFolderMap.keySet()) {
ResourceType types[] = FolderTypeRelationship.getRelatedResourceTypes(folderType);
if (types.length == 1) {
// before we add it we check if it's not already present, since a ResourceType
// could be created from multiple folders, even for the folders that only create
// one type of resource (drawable for instance, can be created from drawable/ and
// values/)
if (list.indexOf(types[0]) == -1) {
list.add(types[0]);
}
} else {
// there isn't a single resource type out of this folder, so we look for all
// content.
List<ResourceFolder> folders = mFolderMap.get(folderType);
if (folders != null) {
for (ResourceFolder folder : folders) {
Collection<ResourceType> folderContent = folder.getResourceTypes();
// then we add them, but only if they aren't already in the list.
for (ResourceType folderResType : folderContent) {
if (list.indexOf(folderResType) == -1) {
list.add(folderResType);
}
}
}
}
}
}
// in case ResourceType.ID haven't been added yet because there's no id defined
// in XML, we check on the list of compiled id resources.
if (list.indexOf(ResourceType.ID) == -1 && mResourceValueMap != null) {
Map<String, Integer> map = mResourceValueMap.get(ResourceType.ID.getName());
if (map != null && map.size() > 0) {
list.add(ResourceType.ID);
}
}
// at this point the list is full of ResourceType defined in the files.
// We need to sort it.
Collections.sort(list);
return list.toArray(new ResourceType[list.size()]);
}
/* (non-Javadoc)
* @see com.android.ide.eclipse.editors.resources.IResourceRepository#getResources(com.android.ide.eclipse.common.resources.ResourceType)
*/
public ProjectResourceItem[] getResources(ResourceType type) {
checkAndUpdate(type);
if (type == ResourceType.ID) {
synchronized (mIdResourceList) {
return mIdResourceList.toArray(new ProjectResourceItem[mIdResourceList.size()]);
}
}
List<ProjectResourceItem> items = mResourceMap.get(type);
return items.toArray(new ProjectResourceItem[items.size()]);
}
/* (non-Javadoc)
* @see com.android.ide.eclipse.editors.resources.IResourceRepository#hasResources(com.android.ide.eclipse.common.resources.ResourceType)
*/
public boolean hasResources(ResourceType type) {
checkAndUpdate(type);
if (type == ResourceType.ID) {
synchronized (mIdResourceList) {
return mIdResourceList.size() > 0;
}
}
List<ProjectResourceItem> items = mResourceMap.get(type);
return (items != null && items.size() > 0);
}
/**
* Returns the {@link ResourceFolder} associated with a {@link IFolder}.
* @param folder The {@link IFolder} object.
* @return the {@link ResourceFolder} or null if it was not found.
*/
public ResourceFolder getResourceFolder(IFolder folder) {
for (List<ResourceFolder> list : mFolderMap.values()) {
for (ResourceFolder resFolder : list) {
if (resFolder.getFolder().getIFolder().equals(folder)) {
return resFolder;
}
}
}
return null;
}
/**
* Returns the {@link ResourceFile} matching the given name, {@link ResourceFolderType} and
* configuration.
* <p/>This only works with files generating one resource named after the file (for instance,
* layouts, bitmap based drawable, xml, anims).
* @return the matching file or <code>null</code> if no match was found.
*/
public ResourceFile getMatchingFile(String name, ResourceFolderType type,
FolderConfiguration config) {
// get the folders for the given type
List<ResourceFolder> folders = mFolderMap.get(type);
// look for folders containing a file with the given name.
ArrayList<ResourceFolder> matchingFolders = new ArrayList<ResourceFolder>();
// remove the folders that do not have a file with the given name, or if their config
// is incompatible.
for (int i = 0 ; i < folders.size(); i++) {
ResourceFolder folder = folders.get(i);
if (folder.hasFile(name) == true) {
matchingFolders.add(folder);
}
}
// from those, get the folder with a config matching the given reference configuration.
Resource match = findMatchingConfiguredResource(matchingFolders, config);
// do we have a matching folder?
if (match instanceof ResourceFolder) {
// get the ResourceFile from the filename
return ((ResourceFolder)match).getFile(name);
}
return null;
}
/**
* Returns the resources values matching a given {@link FolderConfiguration}.
* @param referenceConfig the configuration that each value must match.
*/
public Map<String, Map<String, IResourceValue>> getConfiguredResources(
FolderConfiguration referenceConfig) {
Map<String, Map<String, IResourceValue>> map =
new HashMap<String, Map<String, IResourceValue>>();
// special case for Id since there's a mix of compiled id (declared inline) and id declared
// in the XML files.
if (mIdResourceList.size() > 0) {
Map<String, IResourceValue> idMap = new HashMap<String, IResourceValue>();
String idType = ResourceType.ID.getName();
for (IdResourceItem id : mIdResourceList) {
// FIXME: cache the ResourceValue!
idMap.put(id.getName(), new ResourceValue(idType, id.getName(),
mIsFrameworkRepository));
}
map.put(ResourceType.ID.getName(), idMap);
}
Set<ResourceType> keys = mResourceMap.keySet();
for (ResourceType key : keys) {
// we don't process ID resources since we already did it above.
if (key != ResourceType.ID) {
map.put(key.getName(), getConfiguredResource(key, referenceConfig));
}
}
return map;
}
/**
* Loads all the resources. Essentially this forces to load the values from the
* {@link ResourceFile} objects to make sure they are up to date and loaded
* in {@link #mResourceMap}.
*/
public void loadAll() {
// gets all the resource types available.
ResourceType[] types = getAvailableResourceTypes();
// loop on them and load them
for (ResourceType type: types) {
checkAndUpdate(type);
}
}
/**
* Resolves a compiled resource id into the resource name and type
* @param id
* @return an array of 2 strings { name, type } or null if the id could not be resolved
*/
public String[] resolveResourceValue(int id) {
if (mResIdValueToNameMap != null) {
return mResIdValueToNameMap.get(id);
}
return null;
}
/**
* Resolves a compiled resource id of type int[] into the resource name.
*/
public String resolveResourceValue(int[] id) {
if (mStyleableValueToNameMap != null) {
mWrapper.set(id);
return mStyleableValueToNameMap.get(mWrapper);
}
return null;
}
/**
* Returns the value of a resource by its type and name.
*/
public Integer getResourceValue(String type, String name) {
if (mResourceValueMap != null) {
Map<String, Integer> map = mResourceValueMap.get(type);
if (map != null) {
return map.get(name);
}
}
return null;
}
/**
* Returns the sorted list of languages used in the resources.
*/
public SortedSet<String> getLanguages() {
SortedSet<String> set = new TreeSet<String>();
Collection<List<ResourceFolder>> folderList = mFolderMap.values();
for (List<ResourceFolder> folderSubList : folderList) {
for (ResourceFolder folder : folderSubList) {
FolderConfiguration config = folder.getConfiguration();
LanguageQualifier lang = config.getLanguageQualifier();
if (lang != null) {
set.add(lang.getStringValue());
}
}
}
return set;
}
/**
* Returns the sorted list of regions used in the resources with the given language.
* @param currentLanguage the current language the region must be associated with.
*/
public SortedSet<String> getRegions(String currentLanguage) {
SortedSet<String> set = new TreeSet<String>();
Collection<List<ResourceFolder>> folderList = mFolderMap.values();
for (List<ResourceFolder> folderSubList : folderList) {
for (ResourceFolder folder : folderSubList) {
FolderConfiguration config = folder.getConfiguration();
// get the language
LanguageQualifier lang = config.getLanguageQualifier();
if (lang != null && lang.getStringValue().equals(currentLanguage)) {
RegionQualifier region = config.getRegionQualifier();
if (region != null) {
set.add(region.getStringValue());
}
}
}
}
return set;
}
/**
* Returns a map of (resource name, resource value) for the given {@link ResourceType}.
* <p/>The values returned are taken from the resource files best matching a given
* {@link FolderConfiguration}.
* @param type the type of the resources.
* @param referenceConfig the configuration to best match.
*/
private Map<String, IResourceValue> getConfiguredResource(ResourceType type,
FolderConfiguration referenceConfig) {
// get the resource item for the given type
List<ProjectResourceItem> items = mResourceMap.get(type);
// create the map
HashMap<String, IResourceValue> map = new HashMap<String, IResourceValue>();
for (ProjectResourceItem item : items) {
// get the source files generating this resource
List<ResourceFile> list = item.getSourceFileList();
// look for the best match for the given configuration
Resource match = findMatchingConfiguredResource(list, referenceConfig);
if (match instanceof ResourceFile) {
ResourceFile matchResFile = (ResourceFile)match;
// get the value of this configured resource.
IResourceValue value = matchResFile.getValue(type, item.getName());
if (value != null) {
map.put(item.getName(), value);
}
}
}
return map;
}
/**
* Returns the best matching {@link Resource}.
* @param resources the list of {@link Resource} to choose from.
* @param referenceConfig the {@link FolderConfiguration} to match.
* @see http://d.android.com/guide/topics/resources/resources-i18n.html#best-match
*/
private Resource findMatchingConfiguredResource(List<? extends Resource> resources,
FolderConfiguration referenceConfig) {
//
// 1: eliminate resources that contradict the reference configuration
// 2: pick next qualifier type
// 3: check if any resources use this qualifier, if no, back to 2, else move on to 4.
// 4: eliminate resources that don't use this qualifier.
// 5: if more than one resource left, go back to 2.
//
// The precedence of the qualifiers is more important than the number of qualifiers that
// exactly match the device.
// 1: eliminate resources that contradict
ArrayList<Resource> matchingResources = new ArrayList<Resource>();
for (int i = 0 ; i < resources.size(); i++) {
Resource res = resources.get(i);
if (res.getConfiguration().isMatchFor(referenceConfig)) {
matchingResources.add(res);
}
}
// if there is only one match, just take it
if (matchingResources.size() == 1) {
return matchingResources.get(0);
} else if (matchingResources.size() == 0) {
return null;
}
// 2. Loop on the qualifiers, and eliminate matches
final int count = FolderConfiguration.getQualifierCount();
for (int q = 0 ; q < count ; q++) {
// look to see if one resource has this qualifier.
// At the same time also record the best match value for the qualifier (if applicable).
// The reference value, to find the best match.
// Note that this qualifier could be null. In which case any qualifier found in the
// possible match, will all be considered best match.
ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q);
boolean found = false;
ResourceQualifier bestMatch = null; // this is to store the best match.
for (Resource res : matchingResources) {
ResourceQualifier qualifier = res.getConfiguration().getQualifier(q);
if (qualifier != null) {
// set the flag.
found = true;
// Now check for a best match. If the reference qualifier is null ,
// any qualifier is a "best" match (we don't need to record all of them.
// Instead the non compatible ones are removed below)
if (referenceQualifier != null) {
if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) {
bestMatch = qualifier;
}
}
}
}
// 4. If a resources has a qualifier at the current index, remove all the resources that
// do not have one, or whose qualifier value does not equal the best match found above
// unless there's no reference qualifier, in which case they are all considered
// "best" match.
if (found) {
for (int i = 0 ; i < matchingResources.size(); ) {
Resource res = matchingResources.get(i);
ResourceQualifier qualifier = res.getConfiguration().getQualifier(q);
if (qualifier == null) {
// this resources has no qualifier of this type: rejected.
matchingResources.remove(res);
} else if (referenceQualifier != null && bestMatch != null &&
bestMatch.equals(qualifier) == false) {
// there's a reference qualifier and there is a better match for it than
// this resource, so we reject it.
matchingResources.remove(res);
} else {
// looks like we keep this resource, move on to the next one.
i++;
}
}
// at this point we may have run out of matching resources before going
// through all the qualifiers.
if (matchingResources.size() < 2) {
break;
}
}
}
// Because we accept resources whose configuration have qualifiers where the reference
// configuration doesn't, we can end up with more than one match. In this case, we just
// take the first one.
if (matchingResources.size() == 0) {
return null;
}
- return matchingResources.get(1);
+ return matchingResources.get(0);
}
/**
* Checks if the list of {@link ResourceItem}s for the specified {@link ResourceType} needs
* to be updated.
* @param type the Resource Type.
*/
private void checkAndUpdate(ResourceType type) {
// get the list of folder that can output this type
ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type);
for (ResourceFolderType folderType : folderTypes) {
List<ResourceFolder> folders = mFolderMap.get(folderType);
if (folders != null) {
for (ResourceFolder folder : folders) {
if (folder.isTouched()) {
// if this folder is touched we need to update all the types that can
// be generated from a file in this folder.
// This will include 'type' obviously.
ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes(
folderType);
for (ResourceType resType : resTypes) {
update(resType);
}
return;
}
}
}
}
}
/**
* Updates the list of {@link ResourceItem} objects associated with a {@link ResourceType}.
* This will reset the touch status of all the folders that can generate this resource type.
* @param type the Resource Type.
*/
private void update(ResourceType type) {
// get the cache list, and lets make a backup
List<ProjectResourceItem> items = mResourceMap.get(type);
List<ProjectResourceItem> backup = new ArrayList<ProjectResourceItem>();
if (items == null) {
items = new ArrayList<ProjectResourceItem>();
mResourceMap.put(type, items);
} else {
// backup the list
backup.addAll(items);
// we reset the list itself.
items.clear();
}
// get the list of folder that can output this type
ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type);
for (ResourceFolderType folderType : folderTypes) {
List<ResourceFolder> folders = mFolderMap.get(folderType);
if (folders != null) {
for (ResourceFolder folder : folders) {
items.addAll(folder.getResources(type, this));
folder.resetTouch();
}
}
}
// now items contains the new list. We "merge" it with the backup list.
// Basically, we need to keep the old instances of ResourceItem (where applicable),
// but replace them by the content of the new items.
// This will let the resource explorer keep the expanded state of the nodes whose data
// is a ResourceItem object.
if (backup.size() > 0) {
// this is not going to change as we're only replacing instances.
int count = items.size();
for (int i = 0 ; i < count;) {
// get the "new" item
ProjectResourceItem item = items.get(i);
// look for a similar item in the old list.
ProjectResourceItem foundOldItem = null;
for (ProjectResourceItem oldItem : backup) {
if (oldItem.getName().equals(item.getName())) {
foundOldItem = oldItem;
break;
}
}
if (foundOldItem != null) {
// erase the data of the old item with the data from the new one.
foundOldItem.replaceWith(item);
// remove the old and new item from their respective lists
items.remove(i);
backup.remove(foundOldItem);
// add the old item to the new list
items.add(foundOldItem);
} else {
// this is a new item, we skip to the next object
i++;
}
}
}
// if this is the ResourceType.ID, we create the actual list, from this list and
// the compiled resource list.
if (type == ResourceType.ID) {
mergeIdResources();
} else {
// else this is the list that will actually be displayed, so we sort it.
Collections.sort(items);
}
}
/**
* Looks up an existing {@link ProjectResourceItem} by {@link ResourceType} and name.
* @param type the Resource Type.
* @param name the Resource name.
* @return the existing ResourceItem or null if no match was found.
*/
protected ProjectResourceItem findResourceItem(ResourceType type, String name) {
List<ProjectResourceItem> list = mResourceMap.get(type);
for (ProjectResourceItem item : list) {
if (name.equals(item.getName())) {
return item;
}
}
return null;
}
/**
* Sets compiled resource information.
* @param resIdValueToNameMap a map of compiled resource id to resource name.
* The map is acquired by the {@link ProjectResources} object.
* @param styleableValueMap
* @param resourceValueMap a map of (name, id) for resources of type {@link ResourceType#ID}.
* The list is acquired by the {@link ProjectResources} object.
*/
void setCompiledResources(Map<Integer, String[]> resIdValueToNameMap,
Map<IntArrayWrapper, String> styleableValueMap,
Map<String, Map<String, Integer>> resourceValueMap) {
mResourceValueMap = resourceValueMap;
mResIdValueToNameMap = resIdValueToNameMap;
mStyleableValueToNameMap = styleableValueMap;
mergeIdResources();
}
/**
* Merges the list of ID resource coming from R.java and the list of ID resources
* coming from XML declaration into the cached list {@link #mIdResourceList}.
*/
void mergeIdResources() {
// get the list of IDs coming from XML declaration. Those ids are present in
// mCompiledIdResources already, so we'll need to use those instead of creating
// new IdResourceItem
List<ProjectResourceItem> xmlIdResources = mResourceMap.get(ResourceType.ID);
synchronized (mIdResourceList) {
// copy the currently cached items.
ArrayList<IdResourceItem> oldItems = new ArrayList<IdResourceItem>();
oldItems.addAll(mIdResourceList);
// empty the current list
mIdResourceList.clear();
// get the list of compile id resources.
Map<String, Integer> idMap = null;
if (mResourceValueMap != null) {
idMap = mResourceValueMap.get(ResourceType.ID.getName());
}
if (idMap == null) {
if (xmlIdResources != null) {
for (ProjectResourceItem resourceItem : xmlIdResources) {
// check the actual class just for safety.
if (resourceItem instanceof IdResourceItem) {
mIdResourceList.add((IdResourceItem)resourceItem);
}
}
}
} else {
// loop on the full list of id, and look for a match in the old list,
// in the list coming from XML (in case a new XML item was created.)
Set<String> idSet = idMap.keySet();
idLoop: for (String idResource : idSet) {
// first look in the XML list in case an id went from inline to XML declared.
if (xmlIdResources != null) {
for (ProjectResourceItem resourceItem : xmlIdResources) {
if (resourceItem instanceof IdResourceItem &&
resourceItem.getName().equals(idResource)) {
mIdResourceList.add((IdResourceItem)resourceItem);
continue idLoop;
}
}
}
// if we haven't found it, look in the old items.
int count = oldItems.size();
for (int i = 0 ; i < count ; i++) {
IdResourceItem resourceItem = oldItems.get(i);
if (resourceItem.getName().equals(idResource)) {
oldItems.remove(i);
mIdResourceList.add(resourceItem);
continue idLoop;
}
}
// if we haven't found it, it looks like it's a new id that was
// declared inline.
mIdResourceList.add(new IdResourceItem(idResource,
true /* isDeclaredInline */));
}
}
// now we sort the list
Collections.sort(mIdResourceList);
}
}
}
| true | true | private Resource findMatchingConfiguredResource(List<? extends Resource> resources,
FolderConfiguration referenceConfig) {
//
// 1: eliminate resources that contradict the reference configuration
// 2: pick next qualifier type
// 3: check if any resources use this qualifier, if no, back to 2, else move on to 4.
// 4: eliminate resources that don't use this qualifier.
// 5: if more than one resource left, go back to 2.
//
// The precedence of the qualifiers is more important than the number of qualifiers that
// exactly match the device.
// 1: eliminate resources that contradict
ArrayList<Resource> matchingResources = new ArrayList<Resource>();
for (int i = 0 ; i < resources.size(); i++) {
Resource res = resources.get(i);
if (res.getConfiguration().isMatchFor(referenceConfig)) {
matchingResources.add(res);
}
}
// if there is only one match, just take it
if (matchingResources.size() == 1) {
return matchingResources.get(0);
} else if (matchingResources.size() == 0) {
return null;
}
// 2. Loop on the qualifiers, and eliminate matches
final int count = FolderConfiguration.getQualifierCount();
for (int q = 0 ; q < count ; q++) {
// look to see if one resource has this qualifier.
// At the same time also record the best match value for the qualifier (if applicable).
// The reference value, to find the best match.
// Note that this qualifier could be null. In which case any qualifier found in the
// possible match, will all be considered best match.
ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q);
boolean found = false;
ResourceQualifier bestMatch = null; // this is to store the best match.
for (Resource res : matchingResources) {
ResourceQualifier qualifier = res.getConfiguration().getQualifier(q);
if (qualifier != null) {
// set the flag.
found = true;
// Now check for a best match. If the reference qualifier is null ,
// any qualifier is a "best" match (we don't need to record all of them.
// Instead the non compatible ones are removed below)
if (referenceQualifier != null) {
if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) {
bestMatch = qualifier;
}
}
}
}
// 4. If a resources has a qualifier at the current index, remove all the resources that
// do not have one, or whose qualifier value does not equal the best match found above
// unless there's no reference qualifier, in which case they are all considered
// "best" match.
if (found) {
for (int i = 0 ; i < matchingResources.size(); ) {
Resource res = matchingResources.get(i);
ResourceQualifier qualifier = res.getConfiguration().getQualifier(q);
if (qualifier == null) {
// this resources has no qualifier of this type: rejected.
matchingResources.remove(res);
} else if (referenceQualifier != null && bestMatch != null &&
bestMatch.equals(qualifier) == false) {
// there's a reference qualifier and there is a better match for it than
// this resource, so we reject it.
matchingResources.remove(res);
} else {
// looks like we keep this resource, move on to the next one.
i++;
}
}
// at this point we may have run out of matching resources before going
// through all the qualifiers.
if (matchingResources.size() < 2) {
break;
}
}
}
// Because we accept resources whose configuration have qualifiers where the reference
// configuration doesn't, we can end up with more than one match. In this case, we just
// take the first one.
if (matchingResources.size() == 0) {
return null;
}
return matchingResources.get(1);
}
| private Resource findMatchingConfiguredResource(List<? extends Resource> resources,
FolderConfiguration referenceConfig) {
//
// 1: eliminate resources that contradict the reference configuration
// 2: pick next qualifier type
// 3: check if any resources use this qualifier, if no, back to 2, else move on to 4.
// 4: eliminate resources that don't use this qualifier.
// 5: if more than one resource left, go back to 2.
//
// The precedence of the qualifiers is more important than the number of qualifiers that
// exactly match the device.
// 1: eliminate resources that contradict
ArrayList<Resource> matchingResources = new ArrayList<Resource>();
for (int i = 0 ; i < resources.size(); i++) {
Resource res = resources.get(i);
if (res.getConfiguration().isMatchFor(referenceConfig)) {
matchingResources.add(res);
}
}
// if there is only one match, just take it
if (matchingResources.size() == 1) {
return matchingResources.get(0);
} else if (matchingResources.size() == 0) {
return null;
}
// 2. Loop on the qualifiers, and eliminate matches
final int count = FolderConfiguration.getQualifierCount();
for (int q = 0 ; q < count ; q++) {
// look to see if one resource has this qualifier.
// At the same time also record the best match value for the qualifier (if applicable).
// The reference value, to find the best match.
// Note that this qualifier could be null. In which case any qualifier found in the
// possible match, will all be considered best match.
ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q);
boolean found = false;
ResourceQualifier bestMatch = null; // this is to store the best match.
for (Resource res : matchingResources) {
ResourceQualifier qualifier = res.getConfiguration().getQualifier(q);
if (qualifier != null) {
// set the flag.
found = true;
// Now check for a best match. If the reference qualifier is null ,
// any qualifier is a "best" match (we don't need to record all of them.
// Instead the non compatible ones are removed below)
if (referenceQualifier != null) {
if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) {
bestMatch = qualifier;
}
}
}
}
// 4. If a resources has a qualifier at the current index, remove all the resources that
// do not have one, or whose qualifier value does not equal the best match found above
// unless there's no reference qualifier, in which case they are all considered
// "best" match.
if (found) {
for (int i = 0 ; i < matchingResources.size(); ) {
Resource res = matchingResources.get(i);
ResourceQualifier qualifier = res.getConfiguration().getQualifier(q);
if (qualifier == null) {
// this resources has no qualifier of this type: rejected.
matchingResources.remove(res);
} else if (referenceQualifier != null && bestMatch != null &&
bestMatch.equals(qualifier) == false) {
// there's a reference qualifier and there is a better match for it than
// this resource, so we reject it.
matchingResources.remove(res);
} else {
// looks like we keep this resource, move on to the next one.
i++;
}
}
// at this point we may have run out of matching resources before going
// through all the qualifiers.
if (matchingResources.size() < 2) {
break;
}
}
}
// Because we accept resources whose configuration have qualifiers where the reference
// configuration doesn't, we can end up with more than one match. In this case, we just
// take the first one.
if (matchingResources.size() == 0) {
return null;
}
return matchingResources.get(0);
}
|
diff --git a/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/manager/TargetsManager.java b/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/manager/TargetsManager.java
index 4121e0c5..42cfd5f8 100644
--- a/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/manager/TargetsManager.java
+++ b/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/manager/TargetsManager.java
@@ -1,252 +1,253 @@
/*******************************************************************************
* Copyright (c) May 18, 2011 Zend Technologies Ltd.
* 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.zend.sdklib.manager;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.zend.sdklib.internal.library.AbstractLibrary;
import org.zend.sdklib.internal.target.ZendTarget;
import org.zend.sdklib.internal.target.ZendTargetAutoDetect;
import org.zend.sdklib.target.ITargetLoader;
import org.zend.sdklib.target.IZendTarget;
import org.zend.webapi.core.WebApiException;
import org.zend.webapi.core.connection.response.ResponseCode;
/**
* Target environments manager for the This is a thread-safe class that can be
* used across threads
*
* @author Roy, 2011
*/
/**
* @author roy
*
*/
public class TargetsManager extends AbstractLibrary {
private static final String DEFAULT_KEY = "sdk";
/**
* All targets loaded in the manager
*/
private List<IZendTarget> all = new ArrayList<IZendTarget>(1);
/**
* The mechanism that is responsible to load the targets
*/
private final ITargetLoader loader;
public TargetsManager(ITargetLoader loader) {
this.loader = loader;
final IZendTarget[] loadAll = loader.loadAll();
for (IZendTarget zTarget : loadAll) {
if (!validTarget(zTarget)) {
log.error(new IllegalArgumentException(
"Conflict found when adding " + zTarget.getId()));
} else {
this.all.add(zTarget);
}
}
}
public synchronized IZendTarget add(IZendTarget target)
throws WebApiException {
if (!validTarget(target)) {
log.error(new IllegalArgumentException(
"Conflict found when adding " + target.getId()));
return null;
}
// try to connect to server
if (!target.connect()) {
return null;
}
// notify loader on addition
this.loader.add(target);
// adds the target to the list
final boolean added = this.all.add(target);
return added ? target : null;
}
public synchronized IZendTarget remove(IZendTarget target) {
if (target == null) {
throw new IllegalArgumentException("target cannot be null");
}
if (!this.all.contains(target)) {
throw new IllegalArgumentException("provided target not found");
}
this.loader.remove(target);
// remove the specified target
final boolean removed = this.all.remove(target);
return removed ? target : null;
}
/**
* Finds a target given target id
*
* @param i
* @return the specified target
*/
public synchronized IZendTarget getTargetById(String id) {
if (id == null) {
return null;
}
for (IZendTarget target : getTargets()) {
if (id.equals(target.getId())) {
return target;
}
}
return null;
}
/**
* Returns a target that represents the localhost zend server
*
* @return zend target for localhost
* @throws IOException
* @throws WebApiException
*/
public synchronized IZendTarget detectLocalhostTarget() throws IOException {
String targetId = Integer.toString(getTargets().length);
return detectLocalhostTarget(targetId, DEFAULT_KEY);
}
/**
* Returns a target that represents the localhost zend server
*
* @param key
* @return zend target for localhost
* @throws IOException
* @throws WebApiException
*/
public synchronized IZendTarget detectLocalhostTarget(String key)
throws IOException {
final String targetId = Integer.toString(getTargets().length);
return detectLocalhostTarget(targetId, key);
}
/**
* Returns a target that represents the localhost zend server
*
* @param targetId
* @param key
* @return zend target for localhost
* @throws IOException
* @throws WebApiException
*/
public synchronized IZendTarget detectLocalhostTarget(String targetId,
String key) throws IOException {
final IZendTarget[] list = getTargets();
targetId = targetId != null ? targetId : Integer
.toString(getTargets().length);
key = key != null ? key : DEFAULT_KEY;
for (IZendTarget t : list) {
if (ZendTargetAutoDetect.localhost.equals(t.getHost())) {
return t;
}
}
try {
// localhost not found - create one
final IZendTarget local = new ZendTargetAutoDetect()
.createLocalhostTarget(targetId, key);
return add(local);
} catch (IOException e) {
log.error(e.getMessage());
throw e;
} catch (WebApiException e) {
log.error("Coudn't connect to localhost server, please make "
- + "sure you the server is up and its version is 5.5 and up.");
+ + "sure your server is up and running. This tool works with "
+ + "version 5.5 and up.");
log.error("More information provided by localhost server:");
final ResponseCode responseCode = e.getResponseCode();
if (responseCode != null) {
log.error("\tError code: " + responseCode);
}
final String message = e.getMessage();
if (message != null) {
log.error("\tError message: " + message);
}
}
return null;
}
public synchronized IZendTarget[] getTargets() {
return (IZendTarget[]) this.all
.toArray(new ZendTarget[this.all.size()]);
}
/**
* Creates and adds new target based on provided parameters.
*
* @param host
* @param key
* @param secretKey
* @return
*/
public IZendTarget createTarget(String host, String key, String secretKey) {
final String targetId = Integer.toString(getTargets().length);
return createTarget(targetId, host, key, secretKey);
}
/**
* Creates and adds new target based on provided parameters.
*
* @param targetId
* @param host
* @param key
* @param secretKey
* @return
*/
public IZendTarget createTarget(String targetId, String host, String key,
String secretKey) {
try {
IZendTarget target = add(new ZendTarget(targetId, new URL(host),
key, secretKey));
if (target == null) {
log.error("Error adding Zend Target " + targetId);
return null;
}
return target;
} catch (MalformedURLException e) {
log.error("Error adding Zend Target " + targetId);
log.error("\tpossible error " + e.getMessage());
} catch (WebApiException e) {
log.error("Error adding Zend Target " + targetId);
log.error("\tpossible error " + e.getMessage());
}
return null;
}
/**
* Check for conflicts and errors in new target
*
* @param target
* @return
*/
private boolean validTarget(IZendTarget target) {
if (target == null) {
throw new IllegalArgumentException("target cannot be null");
}
if (target.getId() == null) {
return false;
}
return null == getTargetById(target.getId());
}
}
| true | true | public synchronized IZendTarget detectLocalhostTarget(String targetId,
String key) throws IOException {
final IZendTarget[] list = getTargets();
targetId = targetId != null ? targetId : Integer
.toString(getTargets().length);
key = key != null ? key : DEFAULT_KEY;
for (IZendTarget t : list) {
if (ZendTargetAutoDetect.localhost.equals(t.getHost())) {
return t;
}
}
try {
// localhost not found - create one
final IZendTarget local = new ZendTargetAutoDetect()
.createLocalhostTarget(targetId, key);
return add(local);
} catch (IOException e) {
log.error(e.getMessage());
throw e;
} catch (WebApiException e) {
log.error("Coudn't connect to localhost server, please make "
+ "sure you the server is up and its version is 5.5 and up.");
log.error("More information provided by localhost server:");
final ResponseCode responseCode = e.getResponseCode();
if (responseCode != null) {
log.error("\tError code: " + responseCode);
}
final String message = e.getMessage();
if (message != null) {
log.error("\tError message: " + message);
}
}
return null;
}
| public synchronized IZendTarget detectLocalhostTarget(String targetId,
String key) throws IOException {
final IZendTarget[] list = getTargets();
targetId = targetId != null ? targetId : Integer
.toString(getTargets().length);
key = key != null ? key : DEFAULT_KEY;
for (IZendTarget t : list) {
if (ZendTargetAutoDetect.localhost.equals(t.getHost())) {
return t;
}
}
try {
// localhost not found - create one
final IZendTarget local = new ZendTargetAutoDetect()
.createLocalhostTarget(targetId, key);
return add(local);
} catch (IOException e) {
log.error(e.getMessage());
throw e;
} catch (WebApiException e) {
log.error("Coudn't connect to localhost server, please make "
+ "sure your server is up and running. This tool works with "
+ "version 5.5 and up.");
log.error("More information provided by localhost server:");
final ResponseCode responseCode = e.getResponseCode();
if (responseCode != null) {
log.error("\tError code: " + responseCode);
}
final String message = e.getMessage();
if (message != null) {
log.error("\tError message: " + message);
}
}
return null;
}
|
diff --git a/src/edu/harvard/cs262/grading/StudentGetGradesServlet.java b/src/edu/harvard/cs262/grading/StudentGetGradesServlet.java
index b99493e..83d455a 100644
--- a/src/edu/harvard/cs262/grading/StudentGetGradesServlet.java
+++ b/src/edu/harvard/cs262/grading/StudentGetGradesServlet.java
@@ -1,126 +1,126 @@
package edu.harvard.cs262.grading;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
// Will return grades for all the submissions from given student
// not sure how to fix this serialization error
public class StudentGetGradesServlet extends AdminFrontEndServlet{
GradeStorageService gradeStorage;
SubmissionStorageService submissionStorage;
public void lookupServices() {
try {
// get reference to database service
// get reference to database service
Registry registry = LocateRegistry.getRegistry();
gradeStorage = (GradeStorageService) registry.lookup("GradeStorageService");
} catch (RemoteException e) {
System.err.println("AdminGetGradesServlet: Could not contact registry.");
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (NotBoundException e) {
System.err.println("AdminGetGradesServlet: Could not find GradeStorageService in registry.");
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
try {
// get reference to database service
Registry registry = LocateRegistry.getRegistry();
submissionStorage = (SubmissionStorageService) registry.lookup("SubmissionStorageService");
} catch (RemoteException e) {
System.err.println("AdminGetSubmissionsServlet: Could not contact registry.");
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (NotBoundException e) {
System.err.println("AdminGetSubmissionsServlet: Could not find SubmissionStorageService in registry.");
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
lookupServices();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get posted parameters
String rawStudent = request.getParameter("student");
// attempt to get corresponding grade
if(rawStudent == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"parameters not set");
} else {
// try to convert parameters into usable format
try{
Integer studentID = Integer.parseInt(rawStudent);
Student student = new StudentImpl(studentID);
Set<Submission> allSubmissions = submissionStorage.getStudentWork(student);
Set<Assignment> allAssignments = new HashSet<Assignment>();
for(Submission s : allSubmissions){
allAssignments.add(s.getAssignment());
}
// get all grades
Set<List<Grade>> allGradeLists = new HashSet<List<Grade>>();
for(Assignment assignment : allAssignments){
- allGradeLists.add(gradeStorage.getGrade(submissionStorage.getSubmission(student, assignment)));
+ allGradeLists.add(gradeStorage.getGrade(submissionStorage.getLatestSubmission(student, assignment)));
}
for(List<Grade> grades : allGradeLists){
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append("{grades:[");
if(grades != null) {
ListIterator<Grade> gradeIter = grades.listIterator();
while(gradeIter.hasNext()) {
Grade grade = gradeIter.next();
responseBuilder.append("score:");
responseBuilder.append(grade.getScore().getScore()+"/"+grade.getScore().maxScore());
responseBuilder.append("}");
}
}
responseBuilder.append("]}");
response.setContentType("text/Javascript");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(responseBuilder.toString());
}
} catch (NumberFormatException e){
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"invalid values given");
} catch (NullPointerException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"grade retrieval failed");
e.printStackTrace();
}
}
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get posted parameters
String rawStudent = request.getParameter("student");
// attempt to get corresponding grade
if(rawStudent == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"parameters not set");
} else {
// try to convert parameters into usable format
try{
Integer studentID = Integer.parseInt(rawStudent);
Student student = new StudentImpl(studentID);
Set<Submission> allSubmissions = submissionStorage.getStudentWork(student);
Set<Assignment> allAssignments = new HashSet<Assignment>();
for(Submission s : allSubmissions){
allAssignments.add(s.getAssignment());
}
// get all grades
Set<List<Grade>> allGradeLists = new HashSet<List<Grade>>();
for(Assignment assignment : allAssignments){
allGradeLists.add(gradeStorage.getGrade(submissionStorage.getSubmission(student, assignment)));
}
for(List<Grade> grades : allGradeLists){
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append("{grades:[");
if(grades != null) {
ListIterator<Grade> gradeIter = grades.listIterator();
while(gradeIter.hasNext()) {
Grade grade = gradeIter.next();
responseBuilder.append("score:");
responseBuilder.append(grade.getScore().getScore()+"/"+grade.getScore().maxScore());
responseBuilder.append("}");
}
}
responseBuilder.append("]}");
response.setContentType("text/Javascript");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(responseBuilder.toString());
}
} catch (NumberFormatException e){
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"invalid values given");
} catch (NullPointerException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"grade retrieval failed");
e.printStackTrace();
}
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get posted parameters
String rawStudent = request.getParameter("student");
// attempt to get corresponding grade
if(rawStudent == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"parameters not set");
} else {
// try to convert parameters into usable format
try{
Integer studentID = Integer.parseInt(rawStudent);
Student student = new StudentImpl(studentID);
Set<Submission> allSubmissions = submissionStorage.getStudentWork(student);
Set<Assignment> allAssignments = new HashSet<Assignment>();
for(Submission s : allSubmissions){
allAssignments.add(s.getAssignment());
}
// get all grades
Set<List<Grade>> allGradeLists = new HashSet<List<Grade>>();
for(Assignment assignment : allAssignments){
allGradeLists.add(gradeStorage.getGrade(submissionStorage.getLatestSubmission(student, assignment)));
}
for(List<Grade> grades : allGradeLists){
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append("{grades:[");
if(grades != null) {
ListIterator<Grade> gradeIter = grades.listIterator();
while(gradeIter.hasNext()) {
Grade grade = gradeIter.next();
responseBuilder.append("score:");
responseBuilder.append(grade.getScore().getScore()+"/"+grade.getScore().maxScore());
responseBuilder.append("}");
}
}
responseBuilder.append("]}");
response.setContentType("text/Javascript");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(responseBuilder.toString());
}
} catch (NumberFormatException e){
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"invalid values given");
} catch (NullPointerException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"grade retrieval failed");
e.printStackTrace();
}
}
}
|
diff --git a/smtp/src/org/subethamail/smtp/command/QuitCommand.java b/smtp/src/org/subethamail/smtp/command/QuitCommand.java
index 0dd5f95..61bdb59 100644
--- a/smtp/src/org/subethamail/smtp/command/QuitCommand.java
+++ b/smtp/src/org/subethamail/smtp/command/QuitCommand.java
@@ -1,25 +1,25 @@
package org.subethamail.smtp.command;
import java.io.IOException;
import org.subethamail.smtp.server.BaseCommand;
import org.subethamail.smtp.server.ConnectionContext;
/**
* @author Ian McFarland <[email protected]>
* @author Jon Stevens
*/
public class QuitCommand extends BaseCommand
{
public QuitCommand()
{
super("QUIT", "Exit the SMTP session.");
}
@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
- context.sendResponse("221 Bye");
context.getSession().quit();
+ context.sendResponse("221 Bye");
}
}
| false | true | public void execute(String commandString, ConnectionContext context) throws IOException
{
context.sendResponse("221 Bye");
context.getSession().quit();
}
| public void execute(String commandString, ConnectionContext context) throws IOException
{
context.getSession().quit();
context.sendResponse("221 Bye");
}
|
diff --git a/src/no/uninett/agora/AgoraMobile/ExternalFileUtil.java b/src/no/uninett/agora/AgoraMobile/ExternalFileUtil.java
index c3fdd57..b9505df 100644
--- a/src/no/uninett/agora/AgoraMobile/ExternalFileUtil.java
+++ b/src/no/uninett/agora/AgoraMobile/ExternalFileUtil.java
@@ -1,162 +1,166 @@
package no.uninett.agora.AgoraMobile;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
/**
* Created by Brian Chen on 7/9/13.
* Phonegap Plugin for Cookie Management
*/
public class ExternalFileUtil extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("openWith")) {
Log.v("AgoraMobilePlugin","external open file function");
String path = args.getString(0);
this.openWith(path,callbackContext);
return true;
}
return false;
}
private void openWith(final String path, final CallbackContext callbackContext){
try{
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
// Create URI
Uri uri = Uri.parse(path);
Intent intent = null;
// Check what kind of file you are trying to open, by comparing the url with extensions.
// When the if condition is matched, plugin sets the correct intent (mime) type,
// so Android knew what application to use to open the file
if (path.contains(".doc") || path.contains(".docx")) {
// Word document
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/msword");
} else if(path.contains(".pdf")) {
// PDF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
} else if(path.contains(".ppt") || path.contains(".pptx")) {
// Powerpoint file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if(path.contains(".xls") || path.contains(".xlsx")) {
// Excel file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if(path.contains(".rtf")) {
// RTF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/rtf");
} else if(path.contains(".wav")) {
// WAV audio file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "audio/x-wav");
} else if(path.contains(".gif")) {
// GIF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/gif");
} else if(path.contains(".jpg") || path.contains(".jpeg")) {
// JPG file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/jpeg");
} else if(path.contains(".txt")) {
// Text file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/plain");
} else if(path.contains(".mpg") || path.contains(".mpeg") || path.contains(".mpe") || path.contains(".mp4") || path.contains(".avi")) {
// Video files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/*");
}else if(path.contains(".sh")){
//script files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/plain");
}else if(path.contains(".html") || path.contains(".htm")){
//html files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/html");
}else if(path.contains(".xml") || path.contains(".rss")){
//xml files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/rss+xml");
}else if(path.contains(".js")){
//js files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/javascript");
}else if(path.contains(".json")){
//json files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/json");
}else if(path.contains(".png")){
//png files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/png");
}else if(path.contains(".class")){
//java class files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/java-vm");
}else if(path.contains(".jar")){
//jar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/java-archive");
}else if(path.contains(".gtar")){
//gtar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-gtar");
}else if(path.contains(".tar")){
//tar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-tar");
}else if(path.contains(".css")){
//css files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/css");
}else if(path.contains(".7z")){
//.7z files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-7z-compressed");
}else if(path.contains(".swf")){
//flash files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-shockwave-flash");
}else if(path.contains(".zip")){
//zip files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/zip");
+ }else if(path.contains(".csv")){
+ //csv files
+ intent = new Intent(Intent.ACTION_VIEW);
+ intent.setDataAndType(uri, "text/csv");
}
//if you want you can also define the intent type for any other file
//additionally use else clause below, to manage other unknown extensions
//in this case, Android will show all applications installed on the device
//so you can choose which application to use
else {
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "*/*");
}
try{
cordova.getActivity().startActivity(intent);
}catch (Exception ex){
callbackContext.error("external open file failed");
}
callbackContext.success("external open file success"); // Thread-safe.
}
});
}catch (Exception ex){
callbackContext.error("external open file failed");
}
}
}
| true | true | private void openWith(final String path, final CallbackContext callbackContext){
try{
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
// Create URI
Uri uri = Uri.parse(path);
Intent intent = null;
// Check what kind of file you are trying to open, by comparing the url with extensions.
// When the if condition is matched, plugin sets the correct intent (mime) type,
// so Android knew what application to use to open the file
if (path.contains(".doc") || path.contains(".docx")) {
// Word document
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/msword");
} else if(path.contains(".pdf")) {
// PDF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
} else if(path.contains(".ppt") || path.contains(".pptx")) {
// Powerpoint file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if(path.contains(".xls") || path.contains(".xlsx")) {
// Excel file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if(path.contains(".rtf")) {
// RTF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/rtf");
} else if(path.contains(".wav")) {
// WAV audio file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "audio/x-wav");
} else if(path.contains(".gif")) {
// GIF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/gif");
} else if(path.contains(".jpg") || path.contains(".jpeg")) {
// JPG file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/jpeg");
} else if(path.contains(".txt")) {
// Text file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/plain");
} else if(path.contains(".mpg") || path.contains(".mpeg") || path.contains(".mpe") || path.contains(".mp4") || path.contains(".avi")) {
// Video files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/*");
}else if(path.contains(".sh")){
//script files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/plain");
}else if(path.contains(".html") || path.contains(".htm")){
//html files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/html");
}else if(path.contains(".xml") || path.contains(".rss")){
//xml files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/rss+xml");
}else if(path.contains(".js")){
//js files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/javascript");
}else if(path.contains(".json")){
//json files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/json");
}else if(path.contains(".png")){
//png files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/png");
}else if(path.contains(".class")){
//java class files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/java-vm");
}else if(path.contains(".jar")){
//jar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/java-archive");
}else if(path.contains(".gtar")){
//gtar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-gtar");
}else if(path.contains(".tar")){
//tar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-tar");
}else if(path.contains(".css")){
//css files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/css");
}else if(path.contains(".7z")){
//.7z files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-7z-compressed");
}else if(path.contains(".swf")){
//flash files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-shockwave-flash");
}else if(path.contains(".zip")){
//zip files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/zip");
}
//if you want you can also define the intent type for any other file
//additionally use else clause below, to manage other unknown extensions
//in this case, Android will show all applications installed on the device
//so you can choose which application to use
else {
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "*/*");
}
try{
cordova.getActivity().startActivity(intent);
}catch (Exception ex){
callbackContext.error("external open file failed");
}
callbackContext.success("external open file success"); // Thread-safe.
}
});
}catch (Exception ex){
callbackContext.error("external open file failed");
}
}
| private void openWith(final String path, final CallbackContext callbackContext){
try{
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
// Create URI
Uri uri = Uri.parse(path);
Intent intent = null;
// Check what kind of file you are trying to open, by comparing the url with extensions.
// When the if condition is matched, plugin sets the correct intent (mime) type,
// so Android knew what application to use to open the file
if (path.contains(".doc") || path.contains(".docx")) {
// Word document
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/msword");
} else if(path.contains(".pdf")) {
// PDF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
} else if(path.contains(".ppt") || path.contains(".pptx")) {
// Powerpoint file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if(path.contains(".xls") || path.contains(".xlsx")) {
// Excel file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if(path.contains(".rtf")) {
// RTF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/rtf");
} else if(path.contains(".wav")) {
// WAV audio file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "audio/x-wav");
} else if(path.contains(".gif")) {
// GIF file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/gif");
} else if(path.contains(".jpg") || path.contains(".jpeg")) {
// JPG file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/jpeg");
} else if(path.contains(".txt")) {
// Text file
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/plain");
} else if(path.contains(".mpg") || path.contains(".mpeg") || path.contains(".mpe") || path.contains(".mp4") || path.contains(".avi")) {
// Video files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/*");
}else if(path.contains(".sh")){
//script files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/plain");
}else if(path.contains(".html") || path.contains(".htm")){
//html files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/html");
}else if(path.contains(".xml") || path.contains(".rss")){
//xml files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/rss+xml");
}else if(path.contains(".js")){
//js files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/javascript");
}else if(path.contains(".json")){
//json files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/json");
}else if(path.contains(".png")){
//png files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/png");
}else if(path.contains(".class")){
//java class files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/java-vm");
}else if(path.contains(".jar")){
//jar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/java-archive");
}else if(path.contains(".gtar")){
//gtar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-gtar");
}else if(path.contains(".tar")){
//tar files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-tar");
}else if(path.contains(".css")){
//css files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/css");
}else if(path.contains(".7z")){
//.7z files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-7z-compressed");
}else if(path.contains(".swf")){
//flash files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/x-shockwave-flash");
}else if(path.contains(".zip")){
//zip files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/zip");
}else if(path.contains(".csv")){
//csv files
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/csv");
}
//if you want you can also define the intent type for any other file
//additionally use else clause below, to manage other unknown extensions
//in this case, Android will show all applications installed on the device
//so you can choose which application to use
else {
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "*/*");
}
try{
cordova.getActivity().startActivity(intent);
}catch (Exception ex){
callbackContext.error("external open file failed");
}
callbackContext.success("external open file success"); // Thread-safe.
}
});
}catch (Exception ex){
callbackContext.error("external open file failed");
}
}
|
diff --git a/library/src/com/handmark/pulltorefresh/library/OverscrollHelper.java b/library/src/com/handmark/pulltorefresh/library/OverscrollHelper.java
index ef9602d..9818921 100644
--- a/library/src/com/handmark/pulltorefresh/library/OverscrollHelper.java
+++ b/library/src/com/handmark/pulltorefresh/library/OverscrollHelper.java
@@ -1,25 +1,25 @@
package com.handmark.pulltorefresh.library;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
final class OverscrollHelper {
static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
- final Mode mode = view.getCurrentMode();
+ final Mode mode = view.getMode();
if (mode != Mode.DISABLED && !isTouchEvent) {
final int newY = (deltaY + scrollY);
if (newY != 0) {
// Check the mode supports the overscroll direction, and
// then move scroll
if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
view.setHeaderScroll(view.getScrollY() + newY);
}
} else {
// Means we've stopped overscrolling, so scroll back to 0
view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
}
}
}
}
| true | true | static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
final Mode mode = view.getCurrentMode();
if (mode != Mode.DISABLED && !isTouchEvent) {
final int newY = (deltaY + scrollY);
if (newY != 0) {
// Check the mode supports the overscroll direction, and
// then move scroll
if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
view.setHeaderScroll(view.getScrollY() + newY);
}
} else {
// Means we've stopped overscrolling, so scroll back to 0
view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
}
}
}
| static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
final Mode mode = view.getMode();
if (mode != Mode.DISABLED && !isTouchEvent) {
final int newY = (deltaY + scrollY);
if (newY != 0) {
// Check the mode supports the overscroll direction, and
// then move scroll
if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
view.setHeaderScroll(view.getScrollY() + newY);
}
} else {
// Means we've stopped overscrolling, so scroll back to 0
view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
}
}
}
|
diff --git a/netbout/netbout-rest/src/main/java/com/netbout/rest/BoutRs.java b/netbout/netbout-rest/src/main/java/com/netbout/rest/BoutRs.java
index 447e1ae53..269c4a928 100644
--- a/netbout/netbout-rest/src/main/java/com/netbout/rest/BoutRs.java
+++ b/netbout/netbout-rest/src/main/java/com/netbout/rest/BoutRs.java
@@ -1,460 +1,460 @@
/**
* Copyright (c) 2009-2012, Netbout.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are PROHIBITED without prior written permission from
* the author. This product may NOT be used anywhere and on any computer
* except the server platform of netBout Inc. located at www.netbout.com.
* Federal copyright law prohibits unauthorized reproduction by any means
* and imposes fines up to $25,000 for violation. If you received
* this code accidentally and without intent to use it, please report this
* incident to the author by email.
*
* 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
* OWNER 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.netbout.rest;
import com.netbout.rest.jaxb.Invitee;
import com.netbout.rest.jaxb.LongBout;
import com.netbout.spi.Bout;
import com.netbout.spi.Friend;
import com.netbout.spi.Identity;
import com.netbout.spi.Message;
import com.netbout.spi.Urn;
import com.netbout.spi.client.RestSession;
import com.rexsl.page.CookieBuilder;
import com.rexsl.page.JaxbBundle;
import com.rexsl.page.JaxbGroup;
import com.rexsl.page.Link;
import com.rexsl.page.PageBuilder;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
/**
* RESTful front of one Bout.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @checkstyle ClassDataAbstractionCoupling (400 lines)
*/
@SuppressWarnings("PMD.TooManyMethods")
@Path("/{num : [0-9]+}")
public final class BoutRs extends BaseRs {
/**
* Threshold param.
*/
public static final String PERIOD_PARAM = "p";
/**
* Place changing param.
*/
public static final String PLACE_PARAM = "place";
/**
* Stage changing param.
*/
public static final String STAGE_PARAM = "stage";
/**
* Number of the bout.
*/
private transient Long number;
/**
* Query to filter messages with.
*/
private transient String query = "";
/**
* Mask for suggestions of invitees.
*/
private transient String mask;
/**
* Stage coordinates.
*/
private transient StageCoordinates coords = new StageCoordinates();
/**
* The period we're looking at.
*/
private transient String view = "";
/**
* Set number of bout.
* @param num The number
*/
@PathParam("num")
public void setNumber(final Long num) {
this.number = num;
}
/**
* Set period to view.
* @param name The name of it
*/
@QueryParam(BoutRs.PERIOD_PARAM)
public void setPeriod(final String name) {
if (name != null) {
this.view = name;
}
}
/**
* Set stage, if it's selected.
* @param name The name of it
*/
@QueryParam(BoutRs.STAGE_PARAM)
public void setStage(final Urn name) {
if (name != null) {
this.coords.setStage(name);
}
}
/**
* Set stage place.
* @param place The place name
*/
@QueryParam(BoutRs.PLACE_PARAM)
public void setPlace(final String place) {
if (place != null) {
this.coords.setPlace(place);
}
}
/**
* Set filtering keyword.
* @param keyword The query
*/
@QueryParam(RestSession.QUERY_PARAM)
public void setQuery(final String keyword) {
if (keyword != null) {
this.query = keyword;
}
}
/**
* Set suggestion keyword.
* @param msk The mask
*/
@QueryParam("mask")
public void setMask(final String msk) {
if (msk != null) {
this.mask = msk;
}
}
/**
* Set stage coordinates.
* @param cookie The information from cookie
*/
@CookieParam("netbout-stage")
public void setStageCoords(final String cookie) {
this.coords = StageCoordinates.valueOf(cookie);
}
/**
* Get bout front page.
* @return The JAX-RS response
*/
@GET
public Response front() {
final Response.ResponseBuilder resp =
this.page().render().authenticated(this.identity());
final String place = this.hub().make("post-render-change-place")
.inBout(this.bout())
.arg(this.bout().number())
.arg(this.identity().name())
.arg(this.coords.stage())
.arg(this.coords.place())
.noCache()
.asDefault(this.coords.place())
.exec();
return resp.cookie(
new CookieBuilder(this.self(""))
.name("netbout-stage")
.value(this.coords.copy().setPlace(place).toString())
.temporary()
.build()
).build();
}
/**
* Post new message to the bout.
* @param text Text of message just posted
* @return The JAX-RS response
*/
@Path("/p")
@POST
public Response post(@FormParam("text") final String text) {
final Bout bout = this.bout();
if (text == null) {
throw new ForwardException(
this,
this.self(""),
"Form param 'text' missed"
);
}
Message msg;
try {
msg = bout.post(text);
} catch (Bout.MessagePostException ex) {
throw new ForwardException(this, this.self(""), ex);
}
return new PageBuilder()
.build(NbPage.class)
.init(this)
.authenticated(this.identity())
.status(Response.Status.SEE_OTHER)
.location(this.self("").build())
.header("Message-number", msg.number())
.build();
}
/**
* Rename this bout.
* @param title New title to set
* @return The JAX-RS response
*/
@Path("/r")
@POST
public Response rename(@FormParam("title") final String title) {
final Bout bout = this.bout();
if (title == null) {
throw new ForwardException(
this,
this.self(""),
"Form param 'title' missed"
);
}
bout.rename(title);
return new PageBuilder()
.build(NbPage.class)
.init(this)
.authenticated(this.identity())
.status(Response.Status.SEE_OTHER)
.location(this.self("").build())
.build();
}
/**
* Invite new person.
* @param name Name of the invitee
* @return The JAX-RS response
*/
@Path("/i")
@GET
public Response invite(@QueryParam("name") final Urn name) {
final Bout bout = this.bout();
if (name == null) {
throw new ForwardException(
this,
this.self(""),
"Query param 'name' missed"
);
}
try {
bout.invite(this.identity().friend(name));
} catch (Identity.UnreachableUrnException ex) {
throw new ForwardException(this, this.self(""), ex);
} catch (Bout.DuplicateInvitationException ex) {
throw new ForwardException(this, this.self(""), ex);
}
return new PageBuilder()
.build(NbPage.class)
.init(this)
.authenticated(this.identity())
.status(Response.Status.SEE_OTHER)
.location(this.self("").build())
.header("Participant-name", name)
.build();
}
/**
* Confirm participation.
* @return The JAX-RS response
*/
@Path("/join")
@GET
public Response join() {
this.bout().confirm();
return new PageBuilder()
.build(NbPage.class)
.init(this)
.authenticated(this.identity())
.status(Response.Status.SEE_OTHER)
.location(this.self("").build())
.build();
}
/**
* Leave this bout.
* @return The JAX-RS response
*/
@Path("/leave")
@GET
public Response leave() {
this.bout().leave();
return new PageBuilder()
.build(NbPage.class)
.init(this)
.authenticated(this.identity())
.status(Response.Status.SEE_OTHER)
.location(this.base().build())
.build();
}
/**
* Kick-off somebody from the bout.
* @param name Who to kick off
* @return The JAX-RS response
*/
@Path("/kickoff")
@GET
public Response kickoff(@QueryParam("name") final Urn name) {
Friend friend;
try {
friend = this.identity().friend(name);
} catch (Identity.UnreachableUrnException ex) {
throw new ForwardException(this, this.base(), ex);
}
new Bout.Smart(this.bout()).participant(friend).kickOff();
return new PageBuilder()
.build(NbPage.class)
.init(this)
.authenticated(this.identity())
.status(Response.Status.SEE_OTHER)
.location(this.self("").build())
.build();
}
/**
* Stage dispatcher.
* @return The stage RS resource
*/
@Path("/s")
public StageRs stageDispatcher() {
return new StageRs(this.bout(), this.coords).duplicate(this);
}
/**
* Get bout.
* @return The bout
*/
private Bout bout() {
final Identity identity = this.identity();
Bout bout;
try {
bout = identity.bout(this.number);
} catch (Identity.BoutNotFoundException ex) {
throw new ForwardException(this, this.base(), ex);
}
return bout;
}
/**
* Main page.
* @return The page
*/
private NbPage page() {
final Identity myself = this.identity();
this.coords.normalize(this.hub(), this.bout());
final NbPage page = new PageBuilder()
.schema("")
.stylesheet(
- this.base().path("/{bout}/xsl/{stage}/wrapper.xsl")
+ UriBuilder.fromPath("/{bout}/xsl/{stage}/wrapper.xsl")
.build(this.bout().number(), this.coords.stage())
.toString()
)
.build(NbPage.class)
.init(this)
.searcheable(true)
.append(
new LongBout(
this.hub(),
this.bout(),
this.coords,
this.query,
this.self(""),
myself,
this.view
)
)
.append(new JaxbBundle("query", this.query))
.link(new Link("leave", "./leave"));
this.appendInvitees(page);
page.link(
new Link(
"top",
this.self("").replaceQueryParam(
BoutRs.PERIOD_PARAM,
new Object[0]
)
)
);
if (new Bout.Smart(this.bout()).participant(myself).confirmed()) {
page.link(new Link("post", "./p"));
} else {
page.link(new Link("join", "./join"));
}
if (new Bout.Smart(this.bout()).participant(myself).leader()) {
page.link(new Link("rename", "./r"));
}
return page;
}
/**
* Append invitees, if necessary.
* @param page The page to append to
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private void appendInvitees(final NbPage page) {
if (this.mask != null) {
final List<Invitee> invitees = new LinkedList<Invitee>();
for (Friend friend : this.identity().friends(this.mask)) {
invitees.add(new Invitee(friend, this.self("")));
}
page.append(new JaxbBundle("mask", this.mask))
.append(JaxbGroup.build(invitees, "invitees"));
}
}
/**
* Location of myself.
* @param path The path to add
* @return The location, its builder actually
*/
private UriBuilder self(final String path) {
return UriBuilder.fromUri(
this.base()
.path("/{bout}")
.path(path)
.replaceQueryParam(RestSession.QUERY_PARAM, "{query}")
.replaceQueryParam(BoutRs.PERIOD_PARAM, "{period}")
.build(this.bout().number(), this.query, this.view)
);
}
}
| true | true | private NbPage page() {
final Identity myself = this.identity();
this.coords.normalize(this.hub(), this.bout());
final NbPage page = new PageBuilder()
.schema("")
.stylesheet(
this.base().path("/{bout}/xsl/{stage}/wrapper.xsl")
.build(this.bout().number(), this.coords.stage())
.toString()
)
.build(NbPage.class)
.init(this)
.searcheable(true)
.append(
new LongBout(
this.hub(),
this.bout(),
this.coords,
this.query,
this.self(""),
myself,
this.view
)
)
.append(new JaxbBundle("query", this.query))
.link(new Link("leave", "./leave"));
this.appendInvitees(page);
page.link(
new Link(
"top",
this.self("").replaceQueryParam(
BoutRs.PERIOD_PARAM,
new Object[0]
)
)
);
if (new Bout.Smart(this.bout()).participant(myself).confirmed()) {
page.link(new Link("post", "./p"));
} else {
page.link(new Link("join", "./join"));
}
if (new Bout.Smart(this.bout()).participant(myself).leader()) {
page.link(new Link("rename", "./r"));
}
return page;
}
| private NbPage page() {
final Identity myself = this.identity();
this.coords.normalize(this.hub(), this.bout());
final NbPage page = new PageBuilder()
.schema("")
.stylesheet(
UriBuilder.fromPath("/{bout}/xsl/{stage}/wrapper.xsl")
.build(this.bout().number(), this.coords.stage())
.toString()
)
.build(NbPage.class)
.init(this)
.searcheable(true)
.append(
new LongBout(
this.hub(),
this.bout(),
this.coords,
this.query,
this.self(""),
myself,
this.view
)
)
.append(new JaxbBundle("query", this.query))
.link(new Link("leave", "./leave"));
this.appendInvitees(page);
page.link(
new Link(
"top",
this.self("").replaceQueryParam(
BoutRs.PERIOD_PARAM,
new Object[0]
)
)
);
if (new Bout.Smart(this.bout()).participant(myself).confirmed()) {
page.link(new Link("post", "./p"));
} else {
page.link(new Link("join", "./join"));
}
if (new Bout.Smart(this.bout()).participant(myself).leader()) {
page.link(new Link("rename", "./r"));
}
return page;
}
|
diff --git a/src/com/tomclaw/mandarin/core/QueryHelper.java b/src/com/tomclaw/mandarin/core/QueryHelper.java
index afe8cf9f..f18a6302 100644
--- a/src/com/tomclaw/mandarin/core/QueryHelper.java
+++ b/src/com/tomclaw/mandarin/core/QueryHelper.java
@@ -1,420 +1,421 @@
package com.tomclaw.mandarin.core;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.util.Log;
import com.google.gson.Gson;
import com.tomclaw.mandarin.R;
import com.tomclaw.mandarin.core.exceptions.AccountNotFoundException;
import com.tomclaw.mandarin.core.exceptions.BuddyNotFoundException;
import com.tomclaw.mandarin.im.AccountRoot;
import com.tomclaw.mandarin.im.icq.IcqStatusUtil;
import com.tomclaw.mandarin.util.StatusUtil;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: solkin
* Date: 5/9/13
* Time: 2:13 PM
*/
public class QueryHelper {
private static Gson gson;
static {
gson = new Gson();
}
public static List<AccountRoot> getAccounts(Context context, List<AccountRoot> accountRootList) {
// Clearing input list.
accountRootList.clear();
// Obtain specified account. If exist.
Cursor cursor = context.getContentResolver().query(Settings.ACCOUNT_RESOLVER_URI, null, null, null, null);
// Cursor may have more than only one entry.
if (cursor.moveToFirst()) {
// Obtain necessary column index.
int bundleColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_BUNDLE);
int typeColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_TYPE);
int dbIdColumnIndex = cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID);
// Iterate all accounts.
do {
accountRootList.add(createAccountRoot(context, cursor.getString(typeColumnIndex),
cursor.getString(bundleColumnIndex), cursor.getInt(dbIdColumnIndex)));
} while (cursor.moveToNext()); // Trying to move to position.
}
return accountRootList;
}
/*public static AccountRoot getAccount(ContentResolver contentResolver, int accountDbId) {
// Obtain specified account. If exist.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ROW_AUTO_ID + "='" + accountDbId + "'", null, null);
// Checking for there is at least one account and switching to it.
if (cursor.moveToFirst()) {
// Obtain necessary column index.
int bundleColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_BUNDLE);
int typeColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_TYPE);
return createAccountRoot(contentResolver, cursor.getString(typeColumnIndex),
cursor.getString(bundleColumnIndex));
}
return null;
}*/
public static int getAccountDbId(ContentResolver contentResolver, String accountType, String userId)
throws AccountNotFoundException {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountType + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + userId + "'", null, null);
// Cursor may have no more than only one entry. But lets check.
if (cursor.moveToFirst()) {
return cursor.getInt(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
}
throw new AccountNotFoundException();
}
private static AccountRoot createAccountRoot(Context context, String className,
String accountRootJson, int accountDbId) {
try {
// Creating account root from bundle.
AccountRoot accountRoot = (AccountRoot) gson.fromJson(accountRootJson,
Class.forName(className));
accountRoot.setContext(context);
accountRoot.setAccountDbId(accountDbId);
accountRoot.actualizeStatus();
return accountRoot;
} catch (ClassNotFoundException e) {
Log.d(Settings.LOG_TAG, "No such class found: " + e.getMessage());
}
return null;
}
public static boolean updateAccount(Context context, AccountRoot accountRoot) {
ContentResolver contentResolver = context.getContentResolver();
// Obtain specified account. If exist.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountRoot.getAccountType() + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + accountRoot.getUserId() + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.moveToFirst()) {
long accountDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// We must update account. Name, password, status, bundle.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ACCOUNT_NAME, accountRoot.getUserNick());
contentValues.put(GlobalProvider.ACCOUNT_USER_PASSWORD, accountRoot.getUserPassword());
contentValues.put(GlobalProvider.ACCOUNT_STATUS, accountRoot.getStatusIndex());
contentValues.put(GlobalProvider.ACCOUNT_CONNECTING, accountRoot.isConnecting() ? 1 : 0);
contentValues.put(GlobalProvider.ACCOUNT_BUNDLE, gson.toJson(accountRoot));
// Update query.
contentResolver.update(Settings.ACCOUNT_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + accountDbId + "'", null);
return false;
}
// No matching account. Creating new account.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ACCOUNT_TYPE, accountRoot.getAccountType());
contentValues.put(GlobalProvider.ACCOUNT_NAME, accountRoot.getUserNick());
contentValues.put(GlobalProvider.ACCOUNT_USER_ID, accountRoot.getUserId());
contentValues.put(GlobalProvider.ACCOUNT_USER_PASSWORD, accountRoot.getUserPassword());
contentValues.put(GlobalProvider.ACCOUNT_STATUS, accountRoot.getStatusIndex());
contentValues.put(GlobalProvider.ACCOUNT_CONNECTING, accountRoot.isConnecting() ? 1 : 0);
contentValues.put(GlobalProvider.ACCOUNT_BUNDLE, gson.toJson(accountRoot));
contentResolver.insert(Settings.ACCOUNT_RESOLVER_URI, contentValues);
// Setting up account db id.
try {
accountRoot.setAccountDbId(getAccountDbId(contentResolver, accountRoot.getAccountType(),
accountRoot.getUserId()));
accountRoot.setContext(context);
} catch (AccountNotFoundException e) {
// Hey, I'm inserted it 3 lines ago!
Log.d(Settings.LOG_TAG, "updateAccount method: no accounts after inserting.");
}
return true;
}
public static boolean updateAccountStatus(ContentResolver contentResolver, AccountRoot accountRoot,
int statusIndex, boolean isConnecting) {
// Obtain specified account. If exist.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountRoot.getAccountType() + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + accountRoot.getUserId() + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.moveToFirst()) {
long accountDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// We must update account. Status, connecting flag.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ACCOUNT_STATUS, accountRoot.getStatusIndex());
contentValues.put(GlobalProvider.ACCOUNT_BUNDLE, gson.toJson(accountRoot));
// Update query.
contentResolver.update(Settings.ACCOUNT_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + accountDbId + "'", null);
return true;
}
return false;
}
public static boolean removeAccount(ContentResolver contentResolver, String accountType, String userId) {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountType + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + userId + "'", null, null);
// Cursor may have no more than only one entry. But lets check.
if (cursor.moveToFirst()) {
do {
long accountDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// Removing roster groups.
contentResolver.delete(Settings.GROUP_RESOLVER_URI,
GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID + "=" + accountDbId, null);
// Removing roster buddies.
contentResolver.delete(Settings.BUDDY_RESOLVER_URI,
GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID + "=" + accountDbId, null);
// Removing all the history.
contentResolver.delete(Settings.HISTORY_RESOLVER_URI,
GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID + "=" + accountDbId, null);
} while (cursor.moveToNext());
}
// And remove account.
return contentResolver.delete(Settings.ACCOUNT_RESOLVER_URI, GlobalProvider.ACCOUNT_TYPE + "='"
+ accountType + "'" + " AND " + GlobalProvider.ACCOUNT_USER_ID + "='"
+ userId + "'", null) != 0;
}
public static void modifyDialog(ContentResolver contentResolver, int buddyDbId, boolean isOpened) {
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ROSTER_BUDDY_DIALOG, isOpened ? 1 : 0);
modifyBuddy(contentResolver, buddyDbId, contentValues);
}
public static void modifyFavorite(ContentResolver contentResolver, int buddyDbId, boolean isFavorite) {
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ROSTER_BUDDY_FAVORITE, isFavorite ? 1 : 0);
modifyBuddy(contentResolver, buddyDbId, contentValues);
}
public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, String messageText,
boolean activateDialog) {
insertMessage(contentResolver, appSession, accountDbId, buddyDbId, messageType, cookie, 0, messageText,
activateDialog);
}
public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog) {
Log.d(Settings.LOG_TAG, "insertMessage: type: " + messageType + " message = " + messageText);
// Checking for time specified.
if(messageTime == 0) {
messageTime = System.currentTimeMillis();
}
// Obtaining cursor with message to such buddy, of such type and not later, than two minutes.
Cursor cursor = contentResolver.query(Settings.HISTORY_RESOLVER_URI, null,
GlobalProvider.HISTORY_BUDDY_DB_ID + "='" + buddyDbId + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.getCount() >= 1) {
// Moving cursor to the last (and first) position and checking for operation success.
if (cursor.moveToLast()
&& cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TYPE)) == messageType
&& cursor.getLong(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TIME)) >=
(messageTime - Settings.MESSAGES_COLLAPSE_DELAY)) {
Log.d(Settings.LOG_TAG, "We have cookies!");
// We have cookies!
long messageDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
String cookies = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_COOKIE));
cookies += " " + cookie;
String messagesText = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TEXT));
messagesText += "\n" + messageText;
// Creating content values to update message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookies);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messagesText);
+ contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
// Update query.
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + messageDbId + "'", null);
cursor.close();
// Checking for dialog activate needed.
if(activateDialog) {
modifyDialog(contentResolver, buddyDbId, true);
}
return;
}
}
// No matching request message. Insert new message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID, accountDbId);
contentValues.put(GlobalProvider.HISTORY_BUDDY_DB_ID, buddyDbId);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TYPE, messageType);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookie);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TIME, messageTime);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messageText);
contentResolver.insert(Settings.HISTORY_RESOLVER_URI, contentValues);
cursor.close();
// Checking for dialog activate needed.
if(activateDialog) {
modifyDialog(contentResolver, buddyDbId, true);
}
}
public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
String userId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog)
throws BuddyNotFoundException {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID + "='" + accountDbId + "'" + " AND "
+ GlobalProvider.ROSTER_BUDDY_ID + "='" + userId + "'", null, null);
// Cursor may have more than only one entry.
// TODO: check for at least one buddy present.
if (cursor.moveToFirst()) {
final int BUDDY_DB_ID_COLUMN = cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID);
// Cycling all the identical buddies in different groups.
do {
int buddyDbId = cursor.getInt(BUDDY_DB_ID_COLUMN);
// Plain message query.
insertMessage(contentResolver, appSession, accountDbId,
buddyDbId, messageType, cookie, messageTime, messageText, activateDialog);
} while(cursor.moveToNext());
} else {
throw new BuddyNotFoundException();
}
}
public static void updateMessage(ContentResolver contentResolver, String cookie, int messageState) {
// Plain message modify by cookies.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, messageState);
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.HISTORY_MESSAGE_COOKIE + " LIKE '%" + cookie + "%'", null);
}
private static void modifyBuddy(ContentResolver contentResolver, int buddyDbId, ContentValues contentValues) {
contentResolver.update(Settings.BUDDY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + buddyDbId + "'", null);
}
public static void modifyBuddyStatus(ContentResolver contentResolver, int accountDbId, String buddyId,
int buddyStatusIndex) throws BuddyNotFoundException {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID + "='" + accountDbId + "'" + " AND "
+ GlobalProvider.ROSTER_BUDDY_ID + "='" + buddyId + "'", null, null);
// Cursor may have more than only one entry.
if (cursor.moveToFirst()) {
final int BUDDY_DB_ID_COLUMN = cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID);
// Cycling all the identical buddies in different groups.
do {
int buddyDbId = cursor.getInt(BUDDY_DB_ID_COLUMN);
// Plain buddy modify.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ROSTER_BUDDY_STATUS, buddyStatusIndex);
modifyBuddy(contentResolver, buddyDbId, contentValues);
} while(cursor.moveToNext());
} else {
throw new BuddyNotFoundException();
}
}
public static void updateOrCreateBuddy(ContentResolver contentResolver, int accountDbId, String accountType,
long updateTime, String groupName,
String buddyId, String buddyNick, String buddyStatus) {
ContentValues buddyValues = new ContentValues();
buddyValues.put(GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID, accountDbId);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_ACCOUNT_TYPE, accountType);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_ID, buddyId);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_NICK, buddyNick);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_GROUP, groupName);
// buddyValues.put(GlobalProvider.ROSTER_BUDDY_GROUP_ID, groupDbId);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_STATUS, IcqStatusUtil.getStatusIndex(buddyStatus));
buddyValues.put(GlobalProvider.ROSTER_BUDDY_DIALOG, 0);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_FAVORITE, 0);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_UPDATE_TIME, updateTime);
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append(GlobalProvider.ROSTER_BUDDY_ID).append("=='").append(buddyId).append("'")
.append(" AND ")
.append(GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID).append("==").append(accountDbId);
Cursor buddyCursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
queryBuilder.toString(), null,
GlobalProvider.ROW_AUTO_ID.concat(" ASC LIMIT 1"));
if (buddyCursor.moveToFirst()) {
long buddyDbId = buddyCursor.getLong(buddyCursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// Update this row.
queryBuilder.setLength(0);
queryBuilder.append(GlobalProvider.ROW_AUTO_ID).append("=='").append(buddyDbId).append("'");
contentResolver.update(Settings.BUDDY_RESOLVER_URI, buddyValues,
queryBuilder.toString(), null);
} else {
contentResolver.insert(Settings.BUDDY_RESOLVER_URI, buddyValues);
}
buddyCursor.close();
}
public static void updateOrCreateGroup(ContentResolver contentResolver, int accountDbId, long updateTime,
String groupName, int groupId) {
StringBuilder queryBuilder = new StringBuilder();
ContentValues groupValues = new ContentValues();
groupValues.put(GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID, accountDbId);
groupValues.put(GlobalProvider.ROSTER_GROUP_NAME, groupName);
groupValues.put(GlobalProvider.ROSTER_GROUP_ID, groupId);
groupValues.put(GlobalProvider.ROSTER_GROUP_TYPE, GlobalProvider.GROUP_TYPE_DEFAULT);
groupValues.put(GlobalProvider.ROSTER_GROUP_UPDATE_TIME, updateTime);
// Trying to update group
queryBuilder.append(GlobalProvider.ROSTER_GROUP_ID).append("=='").append(groupId).append("'")
.append(" AND ")
.append(GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID).append("==").append(accountDbId);
int groupsModified = contentResolver.update(Settings.GROUP_RESOLVER_URI, groupValues,
queryBuilder.toString(), null);
// Checking for there is no such group.
if (groupsModified == 0) {
contentResolver.insert(Settings.GROUP_RESOLVER_URI, groupValues);
}
}
public static void moveOutdatedBuddies(ContentResolver contentResolver, Resources resources,
int accountDbId, long updateTime) {
String recycleString = resources.getString(R.string.recycle);
StringBuilder queryBuilder = new StringBuilder();
// Move all deleted buddies to recycle.
queryBuilder.append(GlobalProvider.ROSTER_BUDDY_UPDATE_TIME).append("!=").append(updateTime)
.append(" AND ")
.append(GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID).append("==").append(accountDbId);
Cursor removedCursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
queryBuilder.toString(), null, null);
if(removedCursor.moveToFirst()) {
// Checking and creating recycle.
queryBuilder.setLength(0);
queryBuilder.append(GlobalProvider.ROSTER_GROUP_TYPE).append("=='")
.append(GlobalProvider.GROUP_TYPE_SYSTEM).append("'").append(" AND ")
.append(GlobalProvider.ROSTER_GROUP_ID).append("==").append(GlobalProvider.GROUP_ID_RECYCLE);
Cursor recycleCursor = contentResolver.query(Settings.GROUP_RESOLVER_URI, null,
queryBuilder.toString(), null, null);
if(!recycleCursor.moveToFirst()) {
ContentValues recycleValues = new ContentValues();
recycleValues.put(GlobalProvider.ROSTER_GROUP_NAME, recycleString);
recycleValues.put(GlobalProvider.ROSTER_GROUP_TYPE, GlobalProvider.GROUP_TYPE_SYSTEM);
recycleValues.put(GlobalProvider.ROSTER_GROUP_ID, GlobalProvider.GROUP_ID_RECYCLE);
recycleValues.put(GlobalProvider.ROSTER_GROUP_UPDATE_TIME, updateTime);
contentResolver.insert(Settings.GROUP_RESOLVER_URI, recycleValues);
}
recycleCursor.close();
// Move, move, move!
ContentValues moveValues = new ContentValues();
moveValues.put(GlobalProvider.ROSTER_BUDDY_GROUP, recycleString);
moveValues.put(GlobalProvider.ROSTER_BUDDY_GROUP_ID, GlobalProvider.GROUP_ID_RECYCLE);
moveValues.put(GlobalProvider.ROSTER_BUDDY_STATUS, StatusUtil.STATUS_OFFLINE);
queryBuilder.setLength(0);
queryBuilder.append(GlobalProvider.ROSTER_BUDDY_UPDATE_TIME).append("!=").append(updateTime)
.append(" AND ")
.append(GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID).append("==").append(accountDbId);
int movedBuddies = contentResolver.update(Settings.BUDDY_RESOLVER_URI, moveValues,
queryBuilder.toString(), null);
Log.d(Settings.LOG_TAG, "moved to recycle: " + movedBuddies);
}
removedCursor.close();
}
}
| true | true | public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog) {
Log.d(Settings.LOG_TAG, "insertMessage: type: " + messageType + " message = " + messageText);
// Checking for time specified.
if(messageTime == 0) {
messageTime = System.currentTimeMillis();
}
// Obtaining cursor with message to such buddy, of such type and not later, than two minutes.
Cursor cursor = contentResolver.query(Settings.HISTORY_RESOLVER_URI, null,
GlobalProvider.HISTORY_BUDDY_DB_ID + "='" + buddyDbId + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.getCount() >= 1) {
// Moving cursor to the last (and first) position and checking for operation success.
if (cursor.moveToLast()
&& cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TYPE)) == messageType
&& cursor.getLong(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TIME)) >=
(messageTime - Settings.MESSAGES_COLLAPSE_DELAY)) {
Log.d(Settings.LOG_TAG, "We have cookies!");
// We have cookies!
long messageDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
String cookies = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_COOKIE));
cookies += " " + cookie;
String messagesText = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TEXT));
messagesText += "\n" + messageText;
// Creating content values to update message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookies);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messagesText);
// Update query.
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + messageDbId + "'", null);
cursor.close();
// Checking for dialog activate needed.
if(activateDialog) {
modifyDialog(contentResolver, buddyDbId, true);
}
return;
}
}
// No matching request message. Insert new message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID, accountDbId);
contentValues.put(GlobalProvider.HISTORY_BUDDY_DB_ID, buddyDbId);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TYPE, messageType);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookie);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TIME, messageTime);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messageText);
contentResolver.insert(Settings.HISTORY_RESOLVER_URI, contentValues);
cursor.close();
// Checking for dialog activate needed.
if(activateDialog) {
modifyDialog(contentResolver, buddyDbId, true);
}
}
| public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog) {
Log.d(Settings.LOG_TAG, "insertMessage: type: " + messageType + " message = " + messageText);
// Checking for time specified.
if(messageTime == 0) {
messageTime = System.currentTimeMillis();
}
// Obtaining cursor with message to such buddy, of such type and not later, than two minutes.
Cursor cursor = contentResolver.query(Settings.HISTORY_RESOLVER_URI, null,
GlobalProvider.HISTORY_BUDDY_DB_ID + "='" + buddyDbId + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.getCount() >= 1) {
// Moving cursor to the last (and first) position and checking for operation success.
if (cursor.moveToLast()
&& cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TYPE)) == messageType
&& cursor.getLong(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TIME)) >=
(messageTime - Settings.MESSAGES_COLLAPSE_DELAY)) {
Log.d(Settings.LOG_TAG, "We have cookies!");
// We have cookies!
long messageDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
String cookies = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_COOKIE));
cookies += " " + cookie;
String messagesText = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TEXT));
messagesText += "\n" + messageText;
// Creating content values to update message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookies);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messagesText);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
// Update query.
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + messageDbId + "'", null);
cursor.close();
// Checking for dialog activate needed.
if(activateDialog) {
modifyDialog(contentResolver, buddyDbId, true);
}
return;
}
}
// No matching request message. Insert new message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID, accountDbId);
contentValues.put(GlobalProvider.HISTORY_BUDDY_DB_ID, buddyDbId);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TYPE, messageType);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookie);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TIME, messageTime);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messageText);
contentResolver.insert(Settings.HISTORY_RESOLVER_URI, contentValues);
cursor.close();
// Checking for dialog activate needed.
if(activateDialog) {
modifyDialog(contentResolver, buddyDbId, true);
}
}
|
diff --git a/src/qs/swornshop/Main.java b/src/qs/swornshop/Main.java
index b0ed691..b860cfd 100644
--- a/src/qs/swornshop/Main.java
+++ b/src/qs/swornshop/Main.java
@@ -1,280 +1,281 @@
package qs.swornshop;
import java.util.HashMap;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
private static final int SIGN = 63;
public static final HashMap<String, CommandHelp> help = new HashMap<String, CommandHelp>();
public static final CommandHelp cmdHelp = new CommandHelp("shop help", "h", "[action]", "show help with shops",
CommandHelp.arg("action", "get help on a /shop action, e.g. /shop h create"));
public static final CommandHelp cmdCreate = new CommandHelp("shop create", "c", "<owner>", "create a new shop",
CommandHelp.arg("owner", "the owner of the shop"));
public static final CommandHelp cmdRemove = new CommandHelp("shop remove", "rm", null, "removes this shop");
public static final CommandHelp cmdPending = new CommandHelp("shop pending", "p", null, "view pending shop requests",
"Shows a list of pending offers to sell items to your shops",
"Use /shop accept and /shop reject on these offers.");
public static final CommandHelp cmdBuy = new CommandHelp("shop buy", "b", "<item> <quantity>", "buy an item from this shop",
CommandHelp.args(
"item", "the name of the item",
"quantity", "the quantity you wish to buy"
));
public static final CommandHelp cmdSell = new CommandHelp("shop sell", "s", "<item> <quantity> [price=auto]", "request to sell an item to this shop",
CommandHelp.args(
"item", "the name of the item",
"quantity", "the quantity you wish to sell",
"price", "the price (for the entire quantity); defaults to the store's price times the quantity"
));
public static final CommandHelp cmdAdd = new CommandHelp("shop add", "a", "<buy-price> [sell-price=none]", "add your held item to this shop",
CommandHelp.args(
"buy-price", "the price of a single item in the stack",
"sell-price", "the selling price of a single item in the stack (by default the item cannot be sold)"
));
static {
help.put("help", cmdHelp);
help.put("h", cmdHelp);
help.put("create", cmdCreate);
help.put("c", cmdCreate);
help.put("remove", cmdRemove);
help.put("rm", cmdRemove);
help.put("pending", cmdPending);
help.put("p", cmdPending);
help.put("buy", cmdBuy);
help.put("b", cmdBuy);
help.put("sell", cmdSell);
help.put("s", cmdSell);
help.put("add", cmdAdd);
help.put("a", cmdAdd);
}
public static final String[] shopHelp = {
CommandHelp.header("Shop Help"),
cmdHelp.toIndexString(),
cmdPending.toIndexString()
};
public static final String[] shopSelectedHelp = { };
public static final String[] shopAdminHelp = {
cmdCreate.toIndexString()
};
public static final String[] shopSelectedAdminHelp = {
cmdRemove.toIndexString()
};
public static final String[] shopNotOwnerHelp = {
cmdBuy.toIndexString(),
cmdSell.toIndexString()
};
public static final String[] shopOwnerHelp = {
cmdAdd.toIndexString()
};
protected HashMap<Location, Shop> shops = new HashMap<Location, Shop>();
protected HashMap<Player, ShopSelection> selectedShops = new HashMap<Player, ShopSelection>();
protected Logger log;
public Main() {}
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
log = this.getLogger();
}
@Override
public void onDisable() {}
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (command.getName().equalsIgnoreCase("shop")) {
if (!(sender instanceof Player)) {
sendError(sender, "/shop can only be used by a player");
}
Player pl = (Player) sender;
ShopSelection selection = selectedShops.get(pl);
if (args.length == 0) {
showHelp(pl, selection);
return true;
}
String action = args[0];
if (action.equalsIgnoreCase("create") ||
action.equalsIgnoreCase("c")) {
if (args.length < 2) {
sendError(pl, cmdCreate.toUsageString());
return true;
}
if (!sender.hasPermission("shops.admin")) {
sendError(pl, "You cannot create shops");
return true;
}
Location loc = pl.getLocation();
Block b = loc.getBlock();
byte angle = (byte) ((((int) loc.getYaw() + 225) / 90) << 2);
b.setTypeIdAndData(SIGN, angle, false);
Sign sign = (Sign) b.getState();
String owner = args[1];
sign.setLine(1, (owner.length() < 13 ? owner : owner.substring(0, 12) + '…') + "'s");
sign.setLine(2, "shop");
sign.update();
Shop shop = new Shop();
shop.owner = owner;
shop.location = b.getLocation();
shops.put(shop.location, shop);
} else if (action.equalsIgnoreCase("remove") ||
action.equalsIgnoreCase("rm")) {
if (selection == null) {
sendError(pl, "You must select a shop to remove");
return true;
}
if (!pl.hasPermission("shop.admin") && !selection.isOwner) {
sendError(pl, "You cannot remove this shop");
return true;
}
Location loc = selection.shop.location;
Block b = loc.getBlock();
Sign sign = (Sign) b.getState();
sign.setLine(0, "This shop is");
sign.setLine(1, "out of");
sign.setLine(2, "business.");
sign.setLine(3, "Sorry! D:");
sign.update();
shops.remove(loc);
pl.sendMessage("§B" + selection.shop.owner + "§F's shop has been removed");
}
else if ((action.equalsIgnoreCase("add"))){
if(selection == null){
sender.sendMessage("you must have your shop selected");
}
else{
if(selection.isOwner){
if(args.length >= 2){
float sellAmmount = Integer.parseInt(args[1]);
float buyAmmount;
if(args.length == 3){
buyAmmount = Integer.parseInt(args[2]);
}
else{
buyAmmount = -1;
}
ItemStack stack = pl.getItemInHand().clone();
ShopEntry newEntry = new ShopEntry();
newEntry.buyPrice = buyAmmount;
newEntry.sellPrice = sellAmmount;
selection.shop.inventory.put(stack, newEntry);
+ pl.getItemInHand().setAmount(0);
}
else{
sender.sendMessage("Invalid arguments");
}
}
else{
sender.sendMessage("you are not the owner of this shop!");
}
}
}
else if ((action.equalsIgnoreCase("help") ||
action.equalsIgnoreCase("h")) &&
args.length > 1) {
String helpCmd = args[1];
CommandHelp h = help.get(helpCmd);
if (h != null)
pl.sendMessage(h.toHelpString());
else
sendError(pl, String.format("'/shop %s' is not an action", helpCmd));
} else {
showHelp(pl, selection);
}
return true;
}
return false;
}
/**
* Shows generic shop help to a player
* @param sender the player
*/
protected void showHelp(CommandSender sender) {
sender.sendMessage(shopHelp);
}
/**
* Shows context-sensitive help to a player based on that player's selection
* @param sender the player
* @param selection the player's shop selection, or null if the player has no selection
*/
protected void showHelp(CommandSender sender, ShopSelection selection) {
sender.sendMessage(shopHelp);
if (sender.hasPermission("shops.admin"))
sender.sendMessage(shopAdminHelp);
if (selection != null) {
sender.sendMessage(shopSelectedHelp);
if (sender.hasPermission("shops.admin"))
sender.sendMessage(shopSelectedAdminHelp);
if (selection.isOwner)
sender.sendMessage(shopOwnerHelp);
else
sender.sendMessage(shopNotOwnerHelp);
}
}
/**
* Informs a player of an error
* @param sender the player
* @param message the error message
*/
protected void sendError(CommandSender sender, String message) {
sender.sendMessage("§C" + message);
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Block b = event.getClickedBlock();
if (b != null && b.getTypeId() == SIGN) {
Shop shop = shops.get(b.getLocation());
if (shop != null) {
Player pl = event.getPlayer();
boolean isOwner = shop.owner.equals(pl.getName());
ShopSelection selection = selectedShops.get(pl);
if (selection == null) selection = new ShopSelection();
selection.isOwner = isOwner;
selection.shop = shop;
selection.page = 0;
selectedShops.put(pl, selection);
pl.sendMessage(new String[] {
isOwner ? "§FWelcome to your shop." :
String.format("§FWelcome to §B%s§F's shop.", shop.owner),
"§7For help with shops, type §3/shop help§7."
});
event.setCancelled(true);
if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
b.getState().update();
}
}
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (command.getName().equalsIgnoreCase("shop")) {
if (!(sender instanceof Player)) {
sendError(sender, "/shop can only be used by a player");
}
Player pl = (Player) sender;
ShopSelection selection = selectedShops.get(pl);
if (args.length == 0) {
showHelp(pl, selection);
return true;
}
String action = args[0];
if (action.equalsIgnoreCase("create") ||
action.equalsIgnoreCase("c")) {
if (args.length < 2) {
sendError(pl, cmdCreate.toUsageString());
return true;
}
if (!sender.hasPermission("shops.admin")) {
sendError(pl, "You cannot create shops");
return true;
}
Location loc = pl.getLocation();
Block b = loc.getBlock();
byte angle = (byte) ((((int) loc.getYaw() + 225) / 90) << 2);
b.setTypeIdAndData(SIGN, angle, false);
Sign sign = (Sign) b.getState();
String owner = args[1];
sign.setLine(1, (owner.length() < 13 ? owner : owner.substring(0, 12) + '…') + "'s");
sign.setLine(2, "shop");
sign.update();
Shop shop = new Shop();
shop.owner = owner;
shop.location = b.getLocation();
shops.put(shop.location, shop);
} else if (action.equalsIgnoreCase("remove") ||
action.equalsIgnoreCase("rm")) {
if (selection == null) {
sendError(pl, "You must select a shop to remove");
return true;
}
if (!pl.hasPermission("shop.admin") && !selection.isOwner) {
sendError(pl, "You cannot remove this shop");
return true;
}
Location loc = selection.shop.location;
Block b = loc.getBlock();
Sign sign = (Sign) b.getState();
sign.setLine(0, "This shop is");
sign.setLine(1, "out of");
sign.setLine(2, "business.");
sign.setLine(3, "Sorry! D:");
sign.update();
shops.remove(loc);
pl.sendMessage("§B" + selection.shop.owner + "§F's shop has been removed");
}
else if ((action.equalsIgnoreCase("add"))){
if(selection == null){
sender.sendMessage("you must have your shop selected");
}
else{
if(selection.isOwner){
if(args.length >= 2){
float sellAmmount = Integer.parseInt(args[1]);
float buyAmmount;
if(args.length == 3){
buyAmmount = Integer.parseInt(args[2]);
}
else{
buyAmmount = -1;
}
ItemStack stack = pl.getItemInHand().clone();
ShopEntry newEntry = new ShopEntry();
newEntry.buyPrice = buyAmmount;
newEntry.sellPrice = sellAmmount;
selection.shop.inventory.put(stack, newEntry);
}
else{
sender.sendMessage("Invalid arguments");
}
}
else{
sender.sendMessage("you are not the owner of this shop!");
}
}
}
else if ((action.equalsIgnoreCase("help") ||
action.equalsIgnoreCase("h")) &&
args.length > 1) {
String helpCmd = args[1];
CommandHelp h = help.get(helpCmd);
if (h != null)
pl.sendMessage(h.toHelpString());
else
sendError(pl, String.format("'/shop %s' is not an action", helpCmd));
} else {
showHelp(pl, selection);
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (command.getName().equalsIgnoreCase("shop")) {
if (!(sender instanceof Player)) {
sendError(sender, "/shop can only be used by a player");
}
Player pl = (Player) sender;
ShopSelection selection = selectedShops.get(pl);
if (args.length == 0) {
showHelp(pl, selection);
return true;
}
String action = args[0];
if (action.equalsIgnoreCase("create") ||
action.equalsIgnoreCase("c")) {
if (args.length < 2) {
sendError(pl, cmdCreate.toUsageString());
return true;
}
if (!sender.hasPermission("shops.admin")) {
sendError(pl, "You cannot create shops");
return true;
}
Location loc = pl.getLocation();
Block b = loc.getBlock();
byte angle = (byte) ((((int) loc.getYaw() + 225) / 90) << 2);
b.setTypeIdAndData(SIGN, angle, false);
Sign sign = (Sign) b.getState();
String owner = args[1];
sign.setLine(1, (owner.length() < 13 ? owner : owner.substring(0, 12) + '…') + "'s");
sign.setLine(2, "shop");
sign.update();
Shop shop = new Shop();
shop.owner = owner;
shop.location = b.getLocation();
shops.put(shop.location, shop);
} else if (action.equalsIgnoreCase("remove") ||
action.equalsIgnoreCase("rm")) {
if (selection == null) {
sendError(pl, "You must select a shop to remove");
return true;
}
if (!pl.hasPermission("shop.admin") && !selection.isOwner) {
sendError(pl, "You cannot remove this shop");
return true;
}
Location loc = selection.shop.location;
Block b = loc.getBlock();
Sign sign = (Sign) b.getState();
sign.setLine(0, "This shop is");
sign.setLine(1, "out of");
sign.setLine(2, "business.");
sign.setLine(3, "Sorry! D:");
sign.update();
shops.remove(loc);
pl.sendMessage("§B" + selection.shop.owner + "§F's shop has been removed");
}
else if ((action.equalsIgnoreCase("add"))){
if(selection == null){
sender.sendMessage("you must have your shop selected");
}
else{
if(selection.isOwner){
if(args.length >= 2){
float sellAmmount = Integer.parseInt(args[1]);
float buyAmmount;
if(args.length == 3){
buyAmmount = Integer.parseInt(args[2]);
}
else{
buyAmmount = -1;
}
ItemStack stack = pl.getItemInHand().clone();
ShopEntry newEntry = new ShopEntry();
newEntry.buyPrice = buyAmmount;
newEntry.sellPrice = sellAmmount;
selection.shop.inventory.put(stack, newEntry);
pl.getItemInHand().setAmount(0);
}
else{
sender.sendMessage("Invalid arguments");
}
}
else{
sender.sendMessage("you are not the owner of this shop!");
}
}
}
else if ((action.equalsIgnoreCase("help") ||
action.equalsIgnoreCase("h")) &&
args.length > 1) {
String helpCmd = args[1];
CommandHelp h = help.get(helpCmd);
if (h != null)
pl.sendMessage(h.toHelpString());
else
sendError(pl, String.format("'/shop %s' is not an action", helpCmd));
} else {
showHelp(pl, selection);
}
return true;
}
return false;
}
|
diff --git a/openFaces/source/org/openfaces/component/table/impl/InGroupHeaderOrFooterCell.java b/openFaces/source/org/openfaces/component/table/impl/InGroupHeaderOrFooterCell.java
index b06c83b12..bb7c4556a 100644
--- a/openFaces/source/org/openfaces/component/table/impl/InGroupHeaderOrFooterCell.java
+++ b/openFaces/source/org/openfaces/component/table/impl/InGroupHeaderOrFooterCell.java
@@ -1,98 +1,98 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2012, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* 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.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.openfaces.component.table.impl;
import org.openfaces.component.ContextDependentComponent;
import org.openfaces.component.table.BaseColumn;
import org.openfaces.component.table.DataTable;
import org.openfaces.renderkit.table.TableBody;
import org.openfaces.renderkit.table.TableStructure;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;
import java.util.Collections;
import java.util.List;
/**
* @author Dmitry Pikhulya
*/
public class InGroupHeaderOrFooterCell extends GroupHeaderOrFooterCell {
private static final ValueExpression ANY_COLUMN_VALUE_EXPRESSION = new AnyColumnValueExpression();
private static List<UIComponent> emptyTextChildList;
private static List<UIComponent> getEmptyTextChildList() {
if (emptyTextChildList == null) {
FacesContext context = FacesContext.getCurrentInstance();
HtmlOutputText outputText =
(HtmlOutputText) context.getApplication().createComponent(HtmlOutputText.COMPONENT_TYPE);
outputText.setValue("");
emptyTextChildList = Collections.singletonList((UIComponent) outputText);
}
return emptyTextChildList;
}
private TableBody tableBody;
public InGroupHeaderOrFooterCell(DataTable dataTable, String facetName) {
super(dataTable, getEmptyTextChildList(), facetName);
tableBody = TableStructure.getCurrentInstance(getDataTable()).getBody();
}
@Override
public ValueExpression getConditionExpression() {
return ANY_COLUMN_VALUE_EXPRESSION;
}
@Override
public List<UIComponent> getChildren() {
BaseColumn actualCol = getCurrentlyRenderedColumn();
if (actualCol instanceof ContextDependentComponent) {
if (!((ContextDependentComponent) actualCol).isComponentInContext()) {
// This method is expected to be called only from within the encodeAll method of this instance, and this
// method sets up column's context. If this check fails then it means that this method is invoked from
// somewhere else, and if that invocation is rightful then this cell's enterComponentContext method has
// to be invoked prior to this
- throw new IllegalStateException("Dynamic column is supposed to be in context when its children are retrieved");
+ throw new IllegalStateException("The current column is supposed to be in context when its children are retrieved");
}
}
UIComponent headerOrFooterComponentFromFacet = actualCol.getFacet(getFacetName());
if (headerOrFooterComponentFromFacet != null)
return Collections.singletonList(headerOrFooterComponentFromFacet);
else {
// Returning an empty string output-text here...
// A non-empty child list is required even when rendering a per-column group header cell for a column that
// doesn't have its inGroupHeader facet specified. The reason is that if we return an empty child list then
// the table rendering procedure will "think" that this cell doesn't want to override content rendering for
// this cell, and regular column's children will be rendered, which will cause an error because the
// currently rendered row is not a regular data row
return getDefaultChildList();
}
}
protected BaseColumn getCurrentlyRenderedColumn() {
BaseColumn currentlyRenderedColumn = tableBody.getCurrentlyRenderedColumn();
if (currentlyRenderedColumn == null)
throw new IllegalStateException("Couldn't retrieve tableBody.currentlyRenderedColumn property. It is " +
"expected that rendering for this cell is initiated only from the TableBody cell rendering " +
"procedure where currentRenderedColumn is set explicitly prior to rendering the cell contents " +
"container (this custom cell implementation)");
return currentlyRenderedColumn instanceof GroupingStructureColumn
? ((GroupingStructureColumn) currentlyRenderedColumn).getDelegate()
: currentlyRenderedColumn;
}
}
| true | true | public List<UIComponent> getChildren() {
BaseColumn actualCol = getCurrentlyRenderedColumn();
if (actualCol instanceof ContextDependentComponent) {
if (!((ContextDependentComponent) actualCol).isComponentInContext()) {
// This method is expected to be called only from within the encodeAll method of this instance, and this
// method sets up column's context. If this check fails then it means that this method is invoked from
// somewhere else, and if that invocation is rightful then this cell's enterComponentContext method has
// to be invoked prior to this
throw new IllegalStateException("Dynamic column is supposed to be in context when its children are retrieved");
}
}
UIComponent headerOrFooterComponentFromFacet = actualCol.getFacet(getFacetName());
if (headerOrFooterComponentFromFacet != null)
return Collections.singletonList(headerOrFooterComponentFromFacet);
else {
// Returning an empty string output-text here...
// A non-empty child list is required even when rendering a per-column group header cell for a column that
// doesn't have its inGroupHeader facet specified. The reason is that if we return an empty child list then
// the table rendering procedure will "think" that this cell doesn't want to override content rendering for
// this cell, and regular column's children will be rendered, which will cause an error because the
// currently rendered row is not a regular data row
return getDefaultChildList();
}
}
| public List<UIComponent> getChildren() {
BaseColumn actualCol = getCurrentlyRenderedColumn();
if (actualCol instanceof ContextDependentComponent) {
if (!((ContextDependentComponent) actualCol).isComponentInContext()) {
// This method is expected to be called only from within the encodeAll method of this instance, and this
// method sets up column's context. If this check fails then it means that this method is invoked from
// somewhere else, and if that invocation is rightful then this cell's enterComponentContext method has
// to be invoked prior to this
throw new IllegalStateException("The current column is supposed to be in context when its children are retrieved");
}
}
UIComponent headerOrFooterComponentFromFacet = actualCol.getFacet(getFacetName());
if (headerOrFooterComponentFromFacet != null)
return Collections.singletonList(headerOrFooterComponentFromFacet);
else {
// Returning an empty string output-text here...
// A non-empty child list is required even when rendering a per-column group header cell for a column that
// doesn't have its inGroupHeader facet specified. The reason is that if we return an empty child list then
// the table rendering procedure will "think" that this cell doesn't want to override content rendering for
// this cell, and regular column's children will be rendered, which will cause an error because the
// currently rendered row is not a regular data row
return getDefaultChildList();
}
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/part/EsbCreationWizard.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/part/EsbCreationWizard.java
index e94464557..b96aef24d 100644
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/part/EsbCreationWizard.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/part/EsbCreationWizard.java
@@ -1,427 +1,428 @@
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.part;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import org.apache.maven.project.MavenProject;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbDiagram;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbServer;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.Activator;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.EsbModelTransformer;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.wso2.developerstudio.eclipse.maven.util.MavenUtils;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;
import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EditorUtils.*;
/**
* @generated NOT
*/
public class EsbCreationWizard extends Wizard implements INewWizard,
IExecutableExtension {
/**
* @generated
*/
private IWorkbench workbench;
/**
* @generated
*/
protected IStructuredSelection selection;
/**
* @generated
*/
protected EsbCreationWizardPage diagramModelFilePage;
/**
* @generated NOT
*/
/*protected EsbCreationWizardPage domainModelFilePage;*/
/**
* @generated
*/
protected Resource diagram;
/**
* @generated
*/
private boolean openNewlyCreatedDiagramEditor = true;
private IProject esbProject;
private ESBProjectArtifact esbProjectArtifact;
private URI fileCreationLocationDiagram;
private URI fileCreationLocationDomain;
private IContainer location;
private WizardMode wizardMode = WizardMode.DEFAULT;
private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
/**
* @generated
*/
public IWorkbench getWorkbench() {
return workbench;
}
/**
* @generated
*/
public IStructuredSelection getSelection() {
return selection;
}
/**
* @generated
*/
public final Resource getDiagram() {
return diagram;
}
/**
* @generated
*/
public final boolean isOpenNewlyCreatedDiagramEditor() {
return openNewlyCreatedDiagramEditor;
}
/**
* @generated
*/
public void setOpenNewlyCreatedDiagramEditor(
boolean openNewlyCreatedDiagramEditor) {
this.openNewlyCreatedDiagramEditor = openNewlyCreatedDiagramEditor;
}
/**
* @generated
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.workbench = workbench;
this.selection = selection;
setWindowTitle(Messages.EsbCreationWizardTitle);
setDefaultPageImageDescriptor(EsbDiagramEditorPlugin
.getBundledImageDescriptor("icons/wizban/NewEsbWizard.gif")); //$NON-NLS-1$
setNeedsProgressMonitor(true);
}
/**
* @generated NOT
*/
public void addPages() {
diagramModelFilePage = new EsbCreationWizardPage(
"DiagramModelFile", getSelection(), null); //$NON-NLS-1$ //$NON-NLS-2$
diagramModelFilePage
.setTitle(Messages.EsbCreationWizard_DiagramModelFilePageTitle);
diagramModelFilePage
.setDescription(Messages.EsbCreationWizard_DiagramModelFilePageDescription);
addPage(diagramModelFilePage);
/* removed domainModelFilePage */
/* domainModelFilePage = new EsbCreationWizardPage(
"DomainModelFile", getSelection(), "esb") { //$NON-NLS-1$ //$NON-NLS-2$
public void setVisible(boolean visible) {
if (visible) {
String fileName = diagramModelFilePage.getFileName();
fileName = fileName.substring(0, fileName.length()
- ".esb_diagram".length()); //$NON-NLS-1$
setFileName(EsbDiagramEditorUtil.getUniqueFileName(
getContainerFullPath(), fileName, "esb")); //$NON-NLS-1$
}
super.setVisible(visible);
}
};
domainModelFilePage
.setTitle(Messages.EsbCreationWizard_DomainModelFilePageTitle);
domainModelFilePage
.setDescription(Messages.EsbCreationWizard_DomainModelFilePageDescription);
addPage(domainModelFilePage);*/
}
/**
* @generated NOT
*/
public boolean performFinish() {
try {
IRunnableWithProgress op = null;
IPath containerFullPath = diagramModelFilePage
.getContainerFullPath();
esbProject = ResourcesPlugin.getWorkspace().getRoot()
.getProject(containerFullPath.segment(0));
esbProjectArtifact = new ESBProjectArtifact();
esbProjectArtifact.fromFile(esbProject.getFile("artifact.xml")
.getLocation().toFile());
location = esbProject.getFolder(SYNAPSE_RESOURCE_DIR);
String type = null;
switch (wizardMode) {
case SEQUENCE:
location = esbProject.getFolder(SEQUENCE_RESOURCE_DIR);
op = createDiagram("sequence_", SEQUENCE_RESOURCE_DIR,
"sequence");
- type = "synapse/graphical-sequence";
+ type = "synapse/sequence";
break;
case PROXY:
location = esbProject.getFolder(PROXY_RESOURCE_DIR);
op = createDiagram("proxy_", PROXY_RESOURCE_DIR, "proxy");
- type = "synapse/graphical-proxy";
+ type = "synapse/proxy-service";
break;
case ENDPOINT:
location = esbProject.getFolder(ENDPOINT_RESOURCE_DIR);
op = createDiagram("endpoint_", ENDPOINT_RESOURCE_DIR,
"endpoint");
- type = "synapse/graphical-endpoint";
+ type = "synapse/endpoint";
break;
case LOCALENTRY:
location = esbProject.getFolder(LOCAL_ENTRY_RESOURCE_DIR);
op = createDiagram("localentry_", LOCAL_ENTRY_RESOURCE_DIR,
"localentry");
- type = "synapse/graphical-localentry";
+ type = "synapse/local-entry";
break;
default:
fileCreationLocationDiagram = URI.createPlatformResourceURI(
location.getFullPath().toString() + "/"
+ diagramModelFilePage.getFileName()
+ DIAGRAM_FILE_EXTENSION, false);
fileCreationLocationDomain = URI.createPlatformResourceURI(
location.getFullPath().toString() + "/"
+ diagramModelFilePage.getFileName()
+ DOMAIN_FILE_EXTENSION, false);
op = createSynapseDiagram();
- type = "synapse/graphical-configuration";
+ type = "synapse/configuration";
break;
}
String relativePathDiagram = FileUtils.getRelativePath(esbProject
.getLocation().toFile(), new File(location.getLocation()
.toFile(), diagramModelFilePage.getFileName()
- + DIAGRAM_FILE_EXTENSION));
+ + ".xml"));
+ relativePathDiagram = relativePathDiagram.replaceFirst("/graphical-synapse-config","/synapse-config");
esbProjectArtifact.addESBArtifact(createArtifact(
diagramModelFilePage.getFileName(),
getMavenGroupID(esbProject), "1.0.0", relativePathDiagram,
type));
esbProjectArtifact.toFile();
esbProject.refreshLocal(IResource.DEPTH_INFINITE,
new NullProgressMonitor());
try {
getContainer().run(false, true, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof CoreException) {
ErrorDialog.openError(getContainer().getShell(),
Messages.EsbCreationWizardCreationError, null,
((CoreException) e.getTargetException())
.getStatus());
} else {
EsbDiagramEditorPlugin.getInstance().logError(
"Error creating diagram", e.getTargetException()); //$NON-NLS-1$
}
return false;
}
return diagram != null;
} catch (Exception e) {
ErrorDialog.openError(getContainer().getShell(),
"Error creating diagram",
"An unexpected error has occurred while creating diagram",
Status.CANCEL_STATUS);
// TODO: log error
}
return true;
}
private IRunnableWithProgress createSynapseDiagram() {
IRunnableWithProgress op = new WorkspaceModifyOperation(null) {
protected void execute(IProgressMonitor monitor)
throws CoreException, InterruptedException {
/*diagram = EsbDiagramEditorUtil.createDiagram(
diagramModelFilePage.getURI(),
domainModelFilePage.getURI(), monitor); */
diagram = EsbDiagramEditorUtil.createDiagram(
fileCreationLocationDiagram,
fileCreationLocationDomain, monitor);
createXMLfile(diagramModelFilePage.getFileName(),diagram, SYNAPSE_RESOURCE_DIR);
if (isOpenNewlyCreatedDiagramEditor() && diagram != null) {
try {
EsbDiagramEditorUtil.openDiagram(diagram);
} catch (PartInitException e) {
ErrorDialog.openError(getContainer().getShell(),
Messages.EsbCreationWizardOpenEditorError,
null, e.getStatus());
}
}
}
};
return op;
}
private IRunnableWithProgress createDiagram(final String extentionPrefix,
final String dir, final String type) {
IRunnableWithProgress op = new WorkspaceModifyOperation(null) {
protected void execute(IProgressMonitor monitor)
throws CoreException, InterruptedException {
IPath fileLocation = new Path(location.getFullPath().toString()
+ "/" + extentionPrefix
+ diagramModelFilePage.getFileName()
+ DIAGRAM_FILE_EXTENSION);
IFile file = esbProject.getFile(dir + "/"
+ fileLocation.lastSegment());
if (!file.exists()) {
diagram = EsbDiagramEditorUtil.createDiagram(URI
.createPlatformResourceURI(location.getFullPath()
.toString()
+ "/"
+ extentionPrefix
+ diagramModelFilePage.getFileName()
+ DIAGRAM_FILE_EXTENSION, false), URI
.createPlatformResourceURI(location.getFullPath()
.toString()
+ "/"
+ extentionPrefix
+ diagramModelFilePage.getFileName()
+ DOMAIN_FILE_EXTENSION, false),
new NullProgressMonitor(), type,
diagramModelFilePage.getFileName());
createXMLfile(diagramModelFilePage.getFileName(),diagram,dir);
try {
EsbDiagramEditorUtil.openDiagram(diagram);
} catch (PartInitException e) {
ErrorDialog.openError(getContainer().getShell(),
Messages.EsbCreationWizardOpenEditorError,
null, e.getStatus());
}
}
}
};
return op;
}
protected void createXMLfile(String name, Resource resource, String dir) {
String xmlFilePath = dir.replaceAll("/graphical-synapse-config","/synapse-config") + "/"+ name + ".xml";
IFile xmlFile = esbProject.getFile(xmlFilePath);
EsbDiagram diagram = (EsbDiagram) ((org.eclipse.gmf.runtime.notation.impl.DiagramImpl) resource
.getContents().get(0)).getElement();
EsbServer server = diagram.getServer();
String newSource = null;
try {
newSource = EsbModelTransformer.instance
.designToSource(server);
InputStream is = new ByteArrayInputStream(newSource.getBytes());
xmlFile.create(is, true, null);
} catch (Exception e) {
log.warn("Could not create file " + xmlFile);
}
}
private ESBArtifact createArtifact(String name, String groupId,
String version, String path, String type) {
ESBArtifact artifact = new ESBArtifact();
artifact.setName(name);
artifact.setVersion(version);
artifact.setType(type);
artifact.setServerRole("EnterpriseServiceBus");
artifact.setGroupId(groupId);
artifact.setFile(path);
return artifact;
}
public void setInitializationData(IConfigurationElement config,
String propertyName, Object data) throws CoreException {
try {
if (propertyName != null) {
if ("class".equals(propertyName)) {
if (data instanceof Map) {
String type = (String) ((Map) data).get("mode");
wizardMode = WizardMode.valueOf(type.toUpperCase());
}
}
}
} catch (Exception e) {
//ignore. Then wizard mode would be default.
}
}
private String getMavenGroupID(IProject project) {
String groupID = "com.example";
try {
MavenProject mavenProject = MavenUtils.getMavenProject(project
.getFile("pom.xml").getLocation().toFile());
groupID = mavenProject.getGroupId();
} catch (Exception e) {
//ignore. Then group id would be default.
}
return groupID;
}
public enum WizardMode {
DEFAULT("DEFAULT"), PROXY("PROXY"), SEQUENCE("SEQUENCE"), ENDPOINT(
"ENDPOINT"),LOCALENTRY("LOCALENTRY");
private final String mode;
private WizardMode(final String text) {
this.mode = text;
}
@Override
public String toString() {
return mode;
}
}
}
| false | true | public boolean performFinish() {
try {
IRunnableWithProgress op = null;
IPath containerFullPath = diagramModelFilePage
.getContainerFullPath();
esbProject = ResourcesPlugin.getWorkspace().getRoot()
.getProject(containerFullPath.segment(0));
esbProjectArtifact = new ESBProjectArtifact();
esbProjectArtifact.fromFile(esbProject.getFile("artifact.xml")
.getLocation().toFile());
location = esbProject.getFolder(SYNAPSE_RESOURCE_DIR);
String type = null;
switch (wizardMode) {
case SEQUENCE:
location = esbProject.getFolder(SEQUENCE_RESOURCE_DIR);
op = createDiagram("sequence_", SEQUENCE_RESOURCE_DIR,
"sequence");
type = "synapse/graphical-sequence";
break;
case PROXY:
location = esbProject.getFolder(PROXY_RESOURCE_DIR);
op = createDiagram("proxy_", PROXY_RESOURCE_DIR, "proxy");
type = "synapse/graphical-proxy";
break;
case ENDPOINT:
location = esbProject.getFolder(ENDPOINT_RESOURCE_DIR);
op = createDiagram("endpoint_", ENDPOINT_RESOURCE_DIR,
"endpoint");
type = "synapse/graphical-endpoint";
break;
case LOCALENTRY:
location = esbProject.getFolder(LOCAL_ENTRY_RESOURCE_DIR);
op = createDiagram("localentry_", LOCAL_ENTRY_RESOURCE_DIR,
"localentry");
type = "synapse/graphical-localentry";
break;
default:
fileCreationLocationDiagram = URI.createPlatformResourceURI(
location.getFullPath().toString() + "/"
+ diagramModelFilePage.getFileName()
+ DIAGRAM_FILE_EXTENSION, false);
fileCreationLocationDomain = URI.createPlatformResourceURI(
location.getFullPath().toString() + "/"
+ diagramModelFilePage.getFileName()
+ DOMAIN_FILE_EXTENSION, false);
op = createSynapseDiagram();
type = "synapse/graphical-configuration";
break;
}
String relativePathDiagram = FileUtils.getRelativePath(esbProject
.getLocation().toFile(), new File(location.getLocation()
.toFile(), diagramModelFilePage.getFileName()
+ DIAGRAM_FILE_EXTENSION));
esbProjectArtifact.addESBArtifact(createArtifact(
diagramModelFilePage.getFileName(),
getMavenGroupID(esbProject), "1.0.0", relativePathDiagram,
type));
esbProjectArtifact.toFile();
esbProject.refreshLocal(IResource.DEPTH_INFINITE,
new NullProgressMonitor());
try {
getContainer().run(false, true, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof CoreException) {
ErrorDialog.openError(getContainer().getShell(),
Messages.EsbCreationWizardCreationError, null,
((CoreException) e.getTargetException())
.getStatus());
} else {
EsbDiagramEditorPlugin.getInstance().logError(
"Error creating diagram", e.getTargetException()); //$NON-NLS-1$
}
return false;
}
return diagram != null;
} catch (Exception e) {
ErrorDialog.openError(getContainer().getShell(),
"Error creating diagram",
"An unexpected error has occurred while creating diagram",
Status.CANCEL_STATUS);
// TODO: log error
}
return true;
}
| public boolean performFinish() {
try {
IRunnableWithProgress op = null;
IPath containerFullPath = diagramModelFilePage
.getContainerFullPath();
esbProject = ResourcesPlugin.getWorkspace().getRoot()
.getProject(containerFullPath.segment(0));
esbProjectArtifact = new ESBProjectArtifact();
esbProjectArtifact.fromFile(esbProject.getFile("artifact.xml")
.getLocation().toFile());
location = esbProject.getFolder(SYNAPSE_RESOURCE_DIR);
String type = null;
switch (wizardMode) {
case SEQUENCE:
location = esbProject.getFolder(SEQUENCE_RESOURCE_DIR);
op = createDiagram("sequence_", SEQUENCE_RESOURCE_DIR,
"sequence");
type = "synapse/sequence";
break;
case PROXY:
location = esbProject.getFolder(PROXY_RESOURCE_DIR);
op = createDiagram("proxy_", PROXY_RESOURCE_DIR, "proxy");
type = "synapse/proxy-service";
break;
case ENDPOINT:
location = esbProject.getFolder(ENDPOINT_RESOURCE_DIR);
op = createDiagram("endpoint_", ENDPOINT_RESOURCE_DIR,
"endpoint");
type = "synapse/endpoint";
break;
case LOCALENTRY:
location = esbProject.getFolder(LOCAL_ENTRY_RESOURCE_DIR);
op = createDiagram("localentry_", LOCAL_ENTRY_RESOURCE_DIR,
"localentry");
type = "synapse/local-entry";
break;
default:
fileCreationLocationDiagram = URI.createPlatformResourceURI(
location.getFullPath().toString() + "/"
+ diagramModelFilePage.getFileName()
+ DIAGRAM_FILE_EXTENSION, false);
fileCreationLocationDomain = URI.createPlatformResourceURI(
location.getFullPath().toString() + "/"
+ diagramModelFilePage.getFileName()
+ DOMAIN_FILE_EXTENSION, false);
op = createSynapseDiagram();
type = "synapse/configuration";
break;
}
String relativePathDiagram = FileUtils.getRelativePath(esbProject
.getLocation().toFile(), new File(location.getLocation()
.toFile(), diagramModelFilePage.getFileName()
+ ".xml"));
relativePathDiagram = relativePathDiagram.replaceFirst("/graphical-synapse-config","/synapse-config");
esbProjectArtifact.addESBArtifact(createArtifact(
diagramModelFilePage.getFileName(),
getMavenGroupID(esbProject), "1.0.0", relativePathDiagram,
type));
esbProjectArtifact.toFile();
esbProject.refreshLocal(IResource.DEPTH_INFINITE,
new NullProgressMonitor());
try {
getContainer().run(false, true, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof CoreException) {
ErrorDialog.openError(getContainer().getShell(),
Messages.EsbCreationWizardCreationError, null,
((CoreException) e.getTargetException())
.getStatus());
} else {
EsbDiagramEditorPlugin.getInstance().logError(
"Error creating diagram", e.getTargetException()); //$NON-NLS-1$
}
return false;
}
return diagram != null;
} catch (Exception e) {
ErrorDialog.openError(getContainer().getShell(),
"Error creating diagram",
"An unexpected error has occurred while creating diagram",
Status.CANCEL_STATUS);
// TODO: log error
}
return true;
}
|
diff --git a/MSC/src/AudioToFreq.java b/MSC/src/AudioToFreq.java
index fad013f..958a12f 100644
--- a/MSC/src/AudioToFreq.java
+++ b/MSC/src/AudioToFreq.java
@@ -1,172 +1,173 @@
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import javax.sound.sampled.*;
import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.transform.*;
/**
*
* @author Kevin
*/
public class AudioToFreq {
final static double INITIAL_THRESHHOLD = 450000.0;
final static int MIN_BIN = 50;
final static int MAX_BIN = 70;
public static boolean running = false;
private static boolean hasFired = false;
/**
* @param args the command line arguments
*/
public static void PlaySongAndTransform(String filename) {
// TODO code application logic here
running = true;
try {
File file = new File(filename);
try (AudioInputStream in = AudioSystem.getAudioInputStream(file)) {
AudioInputStream din;
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels()*2,
baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
rawplay(decodedFormat, din);
}
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
System.err.println("Something happened here.");
}
}
/**Provides a method to detect a beat given bin limits and a fourier
* transformed waveform
* @param minBin the minimum bin from which to detect a beat
* @param maxBin same, but maximum
* @param fourierTransformed a fourier transformed waveform
* @param difficulty A scale of difficulty. 0.5 being the hardest, 1 being the easiest
* @param spawnIndex Which speaker to send the messages to
*/
private static void minMaxBuffer(int minBin, int maxBin,
double initialThreshhold,
Complex[] fourierTransformed,
double difficulty,
int spawnIndex) {
double[] minmaxBuffer = new double[15];
double min;
double max;
boolean useRealValues = false;
double testMetric;
int nextWriteOver = 0;
boolean hasFired = false;
Arrays.fill(minmaxBuffer, 0.0);
double sum = 0;
for (int i = minBin; i < maxBin; ++i) {
sum += Math.sqrt(fourierTransformed[i].getReal()*
fourierTransformed[i].getReal() +
(fourierTransformed[i].getImaginary()*
fourierTransformed[i].getImaginary()));
} // This loop is for getting the average strength of a frequency range over the frame.
sum /= (maxBin - minBin);
minmaxBuffer[nextWriteOver] = sum; //This next block of code is for getting the min/max of the last 15 frames
++nextWriteOver;
if (nextWriteOver == minmaxBuffer.length) {nextWriteOver = 0; useRealValues = true;}
max = 0; min = 800000;
for (double i : minmaxBuffer) {
if (i > max) {max = i;}
if (i < min) {min = i;}
}
testMetric = (max - min)*.25 + min; // This is the number to test against to see if we are in a beat
if (useRealValues == true) {
if (sum > testMetric && hasFired == false) {
DrawPanel.spawn[spawnIndex] = true;
hasFired = true;
} else if (sum <= testMetric) {
DrawPanel.spawn[spawnIndex] = false;
hasFired = false;
}
}else {
if (sum > INITIAL_THRESHHOLD && hasFired == false) {
DrawPanel.spawn[spawnIndex] = true;
} else if (sum <= INITIAL_THRESHHOLD) {
DrawPanel.spawn[spawnIndex] = false;
hasFired = false;
}
}
}
//Given an audio format and an audio stream, plays audio and calculates fourier transforms
private static void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException
{
byte[] data = new byte[4096]; //Holds the current frame's data.
SourceDataLine line = getLine(targetFormat);
FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); //The class that performs fourier transforms
int[] volBuffer = new int[30]; //A buffer to hold the volume of the last 30 frames
int nextVol = 0; //To keep the position you are in. in the volume buffer
+ int curVolume;
Arrays.fill(volBuffer, 0);
if (line != null) {
line.start();
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1 && running) {
nBytesRead = din.read(data, 0, data.length); //Reads in 4096 bytes of data or 2048 samples
curVolume = 0;
ByteBuffer bb = ByteBuffer.allocate(2); //The data is actually 16 bits, so I need to transform it from 8
bb.order(ByteOrder.LITTLE_ENDIAN);
short[] shortVals = new short[2048];
for (int i = 0; i < 4096; i+=2) {
bb.put(data[i]);
bb.put(data[i+1]);
shortVals[i/2] = bb.getShort(0);
bb.clear();
curVolume += shortVals[i/2];//Add up all of the amplitudes
}
curVolume /= 2048; //The average volume of every sample in the frame
volBuffer[nextVol] = curVolume;//put it in the volume buffer
++nextVol; if (nextVol == volBuffer.length) { nextVol = 0; } //Fill the volBuffer
int volSum = 0;
for (int i : volBuffer) {
volSum+= Math.abs(i);
}
volSum/=50; //The average volume of the last 30 frames
double[] doubleData = new double[2048]; //The fourier transform requires a double array
for (int i = 0; i < shortVals.length; ++i) {
doubleData[i] = (double) shortVals[i];
}
Complex[] result = fft.transform(doubleData, TransformType.FORWARD); //Here's the star of the show
minMaxBuffer(MIN_BIN,MAX_BIN, INITIAL_THRESHHOLD, result, 0.85, 0);
minMaxBuffer(1200,1220, 400000, result, 0.5, 1);
minMaxBuffer(2000,2020, INITIAL_THRESHHOLD, result, 0.5, 2);
if (nBytesRead != -1) {
nBytesWritten = line.write(data, 0, nBytesRead);
}
}
line.drain(); //close the audio stream. Song's over
line.stop();
line.close();
din.close();
}
}
private static SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException
{
SourceDataLine res;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
}
| true | true | private static void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException
{
byte[] data = new byte[4096]; //Holds the current frame's data.
SourceDataLine line = getLine(targetFormat);
FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); //The class that performs fourier transforms
int[] volBuffer = new int[30]; //A buffer to hold the volume of the last 30 frames
int nextVol = 0; //To keep the position you are in. in the volume buffer
Arrays.fill(volBuffer, 0);
if (line != null) {
line.start();
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1 && running) {
nBytesRead = din.read(data, 0, data.length); //Reads in 4096 bytes of data or 2048 samples
curVolume = 0;
ByteBuffer bb = ByteBuffer.allocate(2); //The data is actually 16 bits, so I need to transform it from 8
bb.order(ByteOrder.LITTLE_ENDIAN);
short[] shortVals = new short[2048];
for (int i = 0; i < 4096; i+=2) {
bb.put(data[i]);
bb.put(data[i+1]);
shortVals[i/2] = bb.getShort(0);
bb.clear();
curVolume += shortVals[i/2];//Add up all of the amplitudes
}
curVolume /= 2048; //The average volume of every sample in the frame
volBuffer[nextVol] = curVolume;//put it in the volume buffer
++nextVol; if (nextVol == volBuffer.length) { nextVol = 0; } //Fill the volBuffer
int volSum = 0;
for (int i : volBuffer) {
volSum+= Math.abs(i);
}
volSum/=50; //The average volume of the last 30 frames
double[] doubleData = new double[2048]; //The fourier transform requires a double array
for (int i = 0; i < shortVals.length; ++i) {
doubleData[i] = (double) shortVals[i];
}
Complex[] result = fft.transform(doubleData, TransformType.FORWARD); //Here's the star of the show
minMaxBuffer(MIN_BIN,MAX_BIN, INITIAL_THRESHHOLD, result, 0.85, 0);
minMaxBuffer(1200,1220, 400000, result, 0.5, 1);
minMaxBuffer(2000,2020, INITIAL_THRESHHOLD, result, 0.5, 2);
if (nBytesRead != -1) {
nBytesWritten = line.write(data, 0, nBytesRead);
}
}
line.drain(); //close the audio stream. Song's over
line.stop();
line.close();
din.close();
}
}
| private static void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException
{
byte[] data = new byte[4096]; //Holds the current frame's data.
SourceDataLine line = getLine(targetFormat);
FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); //The class that performs fourier transforms
int[] volBuffer = new int[30]; //A buffer to hold the volume of the last 30 frames
int nextVol = 0; //To keep the position you are in. in the volume buffer
int curVolume;
Arrays.fill(volBuffer, 0);
if (line != null) {
line.start();
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1 && running) {
nBytesRead = din.read(data, 0, data.length); //Reads in 4096 bytes of data or 2048 samples
curVolume = 0;
ByteBuffer bb = ByteBuffer.allocate(2); //The data is actually 16 bits, so I need to transform it from 8
bb.order(ByteOrder.LITTLE_ENDIAN);
short[] shortVals = new short[2048];
for (int i = 0; i < 4096; i+=2) {
bb.put(data[i]);
bb.put(data[i+1]);
shortVals[i/2] = bb.getShort(0);
bb.clear();
curVolume += shortVals[i/2];//Add up all of the amplitudes
}
curVolume /= 2048; //The average volume of every sample in the frame
volBuffer[nextVol] = curVolume;//put it in the volume buffer
++nextVol; if (nextVol == volBuffer.length) { nextVol = 0; } //Fill the volBuffer
int volSum = 0;
for (int i : volBuffer) {
volSum+= Math.abs(i);
}
volSum/=50; //The average volume of the last 30 frames
double[] doubleData = new double[2048]; //The fourier transform requires a double array
for (int i = 0; i < shortVals.length; ++i) {
doubleData[i] = (double) shortVals[i];
}
Complex[] result = fft.transform(doubleData, TransformType.FORWARD); //Here's the star of the show
minMaxBuffer(MIN_BIN,MAX_BIN, INITIAL_THRESHHOLD, result, 0.85, 0);
minMaxBuffer(1200,1220, 400000, result, 0.5, 1);
minMaxBuffer(2000,2020, INITIAL_THRESHHOLD, result, 0.5, 2);
if (nBytesRead != -1) {
nBytesWritten = line.write(data, 0, nBytesRead);
}
}
line.drain(); //close the audio stream. Song's over
line.stop();
line.close();
din.close();
}
}
|
diff --git a/src/org/rsbot/gui/BotGUI.java b/src/org/rsbot/gui/BotGUI.java
index df3abcc9..883d9daa 100644
--- a/src/org/rsbot/gui/BotGUI.java
+++ b/src/org/rsbot/gui/BotGUI.java
@@ -1,656 +1,656 @@
package org.rsbot.gui;
import org.rsbot.Configuration;
import org.rsbot.Configuration.OperatingSystem;
import org.rsbot.bot.Bot;
import org.rsbot.log.TextAreaLogHandler;
import org.rsbot.script.Script;
import org.rsbot.script.ScriptManifest;
import org.rsbot.script.internal.ScriptHandler;
import org.rsbot.script.internal.event.ScriptListener;
import org.rsbot.script.methods.Environment;
import org.rsbot.script.provider.ScriptDeliveryNetwork;
import org.rsbot.script.provider.ScriptDownloader;
import org.rsbot.script.util.WindowUtil;
import org.rsbot.service.Monitoring;
import org.rsbot.service.Monitoring.Type;
import org.rsbot.service.TwitterUpdates;
import org.rsbot.service.WebQueue;
import org.rsbot.util.UpdateChecker;
import org.rsbot.util.io.ScreenshotUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import java.awt.event.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.List;
import java.util.logging.Logger;
/**
* @author Jacmob
*/
public class BotGUI extends JFrame implements ActionListener, ScriptListener {
public static final int PANEL_WIDTH = 765, PANEL_HEIGHT = 503, LOG_HEIGHT = 120;
public static final int MAX_BOTS = 6;
private static final long serialVersionUID = -5411033752001988794L;
private static final Logger log = Logger.getLogger(BotGUI.class.getName());
private BotPanel panel;
private JScrollPane scrollableBotPanel;
private BotToolBar toolBar;
private BotMenuBar menuBar;
private JScrollPane textScroll;
private BotHome home;
private final List<Bot> bots = new ArrayList<Bot>();
private boolean showAds = true;
private boolean disableConfirmations = false;
private TrayIcon tray = null;
private java.util.Timer shutdown = null;
private java.util.Timer clean = null;
public BotGUI() {
init();
pack();
setTitle(null);
setLocationRelativeTo(getOwner());
setMinimumSize(getSize());
setResizable(true);
menuBar.loadPrefs();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
if (showAds) {
new SplashAd(BotGUI.this).display();
}
UpdateChecker.notify(BotGUI.this);
if (Configuration.Twitter.ENABLED) {
TwitterUpdates.loadTweets(Configuration.Twitter.MESSAGES);
}
new Thread() {
@Override
public void run() {
ScriptDeliveryNetwork.getInstance().start();
}
}.start();
Monitoring.start();
addBot();
updateScriptControls();
System.gc();
}
});
clean = new java.util.Timer(true);
clean.schedule(new TimerTask() {
@Override
public void run() {
System.gc();
}
}, 1000 * 60 * 10, 1000 * 60 * 10);
}
@Override
public void setTitle(final String title) {
String t = Configuration.NAME + " v" + Configuration.getVersionFormatted();
final int v = Configuration.getVersion(), l = UpdateChecker.getLatestVersion();
if (v > l) {
t += " beta";
}
if (title != null) {
t = title + " - " + t;
}
super.setTitle(t);
}
public void actionPerformed(final ActionEvent evt) {
final String action = evt.getActionCommand();
final String menu, option;
final int z = action.indexOf('.');
if (z == -1) {
menu = action;
option = "";
} else {
menu = action.substring(0, z);
option = action.substring(z + 1);
}
if (menu.equals(Messages.CLOSEBOT)) {
if (confirmRemoveBot()) {
final int idx = Integer.parseInt(option);
removeBot(bots.get(idx));
}
} else if (menu.equals(Messages.FILE)) {
if (option.equals(Messages.NEWBOT)) {
addBot();
} else if (option.equals(Messages.CLOSEBOT)) {
if (confirmRemoveBot()) {
removeBot(getCurrentBot());
}
} else if (option.equals(Messages.ADDSCRIPT)) {
final String pretext = "";
final String key = (String) JOptionPane.showInputDialog(this, "Enter the script URL (e.g. pastebin link):",
option, JOptionPane.QUESTION_MESSAGE, null, null, pretext);
if (!(key == null || key.trim().isEmpty())) {
ScriptDownloader.save(key);
}
} else if (option.equals(Messages.RUNSCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
showScriptSelector(current);
}
} else if (option.equals(Messages.SERVICEKEY)) {
serviceKeyQuery(option);
} else if (option.equals(Messages.STOPSCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
showStopScript(current);
}
} else if (option.equals(Messages.PAUSESCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
pauseScript(current);
}
} else if (option.equals(Messages.SAVESCREENSHOT)) {
final Bot current = getCurrentBot();
if (current != null) {
ScreenshotUtil.saveScreenshot(current, current.getMethodContext().game.isLoggedIn());
}
} else if (option.equals(Messages.HIDEBOT)) {
setTray();
} else if (option.equals(Messages.EXIT)) {
cleanExit(false);
}
} else if (menu.equals(Messages.EDIT)) {
if (option.equals(Messages.ACCOUNTS)) {
AccountManager.getInstance().showGUI();
} else if (option.equals(Messages.DISABLEADS)) {
showAds = !((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.DISABLEMONITORING)) {
Monitoring.setEnabled(!((JCheckBoxMenuItem) evt.getSource()).isSelected());
if (!Monitoring.isEnabled()) {
log.info("Monitoring data is used to improve development, please enable it to help us");
}
} else if (option.equals(Messages.DISABLECONFIRMATIONS)) {
disableConfirmations = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.AUTOSHUTDOWN)) {
final boolean enabled = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
if (!enabled) {
if (shutdown != null) {
shutdown.cancel();
shutdown.purge();
}
shutdown = null;
} else {
final long interval = 10 * 60 * 1000; // 10mins
shutdown = new java.util.Timer(true);
shutdown.schedule(new TimerTask() {
@Override
public void run() {
for (final Bot bot : bots) {
if (bot.getScriptHandler().getRunningScripts().size() != 0) {
return;
}
}
final int delay = 3;
log.info("Shutdown pending in " + delay + " minutes...");
final Point[] mouse = new Point[]{MouseInfo.getPointerInfo().getLocation(), null};
try {
Thread.sleep(delay * 60 * 1000);
} catch (InterruptedException ignored) {
}
mouse[1] = MouseInfo.getPointerInfo().getLocation();
if (mouse[0].x != mouse[1].x || mouse[0].y != mouse[1].y) {
log.info("Mouse activity detected, delaying shutdown");
} else if (!menuBar.isTicked(option)) {
log.info("Shutdown cancelled");
} else if (Configuration.getCurrentOperatingSystem() == OperatingSystem.WINDOWS) {
try {
Runtime.getRuntime().exec("shutdown.exe", new String[]{"-s"});
cleanExit(true);
} catch (IOException ignored) {
log.severe("Could not shutdown system");
}
}
}
}, interval, interval);
}
} else {
final Bot current = getCurrentBot();
if (current != null) {
if (option.equals(Messages.FORCEINPUT)) {
final boolean selected = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
current.overrideInput = selected;
updateScriptControls();
} else if (option.equals(Messages.LESSCPU)) {
- lessCpu(true);
+ lessCpu(((JCheckBoxMenuItem) evt.getSource()).isSelected());
} else if (option.equals(Messages.DISABLEANTIRANDOMS)) {
current.disableRandoms = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.DISABLEAUTOLOGIN)) {
current.disableAutoLogin = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
}
}
}
} else if (menu.equals(Messages.VIEW)) {
final Bot current = getCurrentBot();
final boolean selected = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
if (option.equals(Messages.HIDETOOLBAR)) {
toggleViewState(toolBar, selected);
} else if (option.equals(Messages.HIDELOGPANE)) {
toggleViewState(textScroll, selected);
} else if (current != null) {
if (option.equals(Messages.ALLDEBUGGING)) {
for (final String key : BotMenuBar.DEBUG_MAP.keySet()) {
final Class<?> el = BotMenuBar.DEBUG_MAP.get(key);
if (menuBar.getCheckBox(key).isVisible()) {
final boolean wasSelected = menuBar.getCheckBox(key).isSelected();
menuBar.getCheckBox(key).setSelected(selected);
if (selected) {
if (!wasSelected) {
current.addListener(el);
}
} else {
if (wasSelected) {
current.removeListener(el);
}
}
}
}
} else {
final Class<?> el = BotMenuBar.DEBUG_MAP.get(option);
menuBar.getCheckBox(option).setSelected(selected);
if (selected) {
current.addListener(el);
} else {
menuBar.getCheckBox(Messages.ALLDEBUGGING).setSelected(false);
current.removeListener(el);
}
}
}
} else if (menu.equals(Messages.HELP)) {
if (option.equals(Messages.SITE)) {
openURL(Configuration.Paths.URLs.SITE);
} else if (option.equals(Messages.PROJECT)) {
openURL(Configuration.Paths.URLs.PROJECT);
} else if (option.equals(Messages.ABOUT)) {
JOptionPane.showMessageDialog(this, new String[]{"An open source bot developed by the community.", "Visit " + Configuration.Paths.URLs.SITE + "/ for more information."}, option, JOptionPane.INFORMATION_MESSAGE);
}
} else if (menu.equals("Tab")) {
final Bot curr = getCurrentBot();
menuBar.setBot(curr);
panel.setBot(curr);
panel.repaint();
toolBar.setHome(curr == null);
setTitle(curr == null ? null : curr.getAccountName());
updateScriptControls();
}
}
private void updateScriptControls() {
boolean idle = true, paused = false;
final Bot bot = getCurrentBot();
if (bot != null) {
final Map<Integer, Script> scriptMap = bot.getScriptHandler().getRunningScripts();
if (scriptMap.size() > 0) {
idle = false;
paused = scriptMap.values().iterator().next().isPaused();
} else {
idle = true;
}
}
menuBar.getMenuItem(Messages.RUNSCRIPT).setVisible(idle);
menuBar.getMenuItem(Messages.STOPSCRIPT).setVisible(!idle);
menuBar.getMenuItem(Messages.PAUSESCRIPT).setEnabled(!idle);
menuBar.setPauseScript(paused);
if (idle) {
toolBar.setOverrideInput(false);
menuBar.setOverrideInput(false);
toolBar.setInputState(Environment.INPUT_KEYBOARD | Environment.INPUT_MOUSE);
toolBar.setScriptButton(BotToolBar.RUN_SCRIPT);
menuBar.setEnabled(Messages.FORCEINPUT, false);
} else {
toolBar.setOverrideInput(bot.overrideInput);
toolBar.setOverrideInput(bot.overrideInput);
toolBar.setInputState(bot.inputFlags);
toolBar.setScriptButton(paused ? BotToolBar.RESUME_SCRIPT : BotToolBar.PAUSE_SCRIPT);
menuBar.setEnabled(Messages.FORCEINPUT, true);
}
toolBar.updateInputButton();
}
private void serviceKeyQuery(final String option) {
final String currentKey = ScriptDeliveryNetwork.getInstance().getKey();
final String key = (String) JOptionPane.showInputDialog(this, null, option, JOptionPane.QUESTION_MESSAGE, null, null, currentKey);
if (key == null || key.length() == 0) {
log.info("Services have been disabled");
} else if (key.length() != 40) {
log.warning("Invalid service key");
} else {
log.info("Services have been linked to {0}");
}
}
private void lessCpu(boolean on) {
disableRendering(on || menuBar.isTicked(Messages.LESSCPU));
}
public void disableRendering(final boolean mode) {
for (final Bot bot : bots) {
bot.disableRendering = mode;
}
}
public BotPanel getPanel() {
return panel;
}
public Bot getBot(final Object o) {
final ClassLoader cl = o.getClass().getClassLoader();
for (final Bot bot : bots) {
if (cl == bot.getLoader().getClient().getClass().getClassLoader()) {
panel.offset();
return bot;
}
}
return null;
}
public void addBot() {
if (bots.size() > MAX_BOTS) {
return;
}
final Bot bot = new Bot();
bots.add(bot);
toolBar.addTab();
toolBar.setAddTabVisible(bots.size() < MAX_BOTS);
bot.getScriptHandler().addScriptListener(this);
new Thread(new Runnable() {
public void run() {
bot.start();
home.setBots(bots);
}
}).start();
}
public void removeBot(final Bot bot) {
final int idx = bots.indexOf(bot);
bot.getScriptHandler().stopAllScripts();
bot.getScriptHandler().removeScriptListener(this);
bot.getBackgroundScriptHandler().stopAllScripts();
if (idx >= 0) {
toolBar.removeTab(idx);
}
bots.remove(idx);
home.setBots(bots);
toolBar.setAddTabVisible(bots.size() < MAX_BOTS);
new Thread(new Runnable() {
public void run() {
bot.stop();
System.gc();
}
}).start();
}
void pauseScript(final Bot bot) {
final ScriptHandler sh = bot.getScriptHandler();
final Map<Integer, Script> running = sh.getRunningScripts();
if (running.size() > 0) {
final int id = running.keySet().iterator().next();
sh.pauseScript(id);
}
}
private Bot getCurrentBot() {
final int idx = toolBar.getCurrentTab();
if (idx >= 0) {
return bots.get(idx);
}
return null;
}
private void showScriptSelector(final Bot bot) {
if (AccountManager.getAccountNames() == null || AccountManager.getAccountNames().length == 0) {
JOptionPane.showMessageDialog(this, "No accounts found! Please create one before using the bot.");
AccountManager.getInstance().showGUI();
} else if (bot.getMethodContext() == null) {
log.warning("The client is still loading");
} else {
new ScriptSelector(this, bot).showGUI();
}
}
private void showStopScript(final Bot bot) {
final ScriptHandler sh = bot.getScriptHandler();
final Map<Integer, Script> running = sh.getRunningScripts();
if (running.size() > 0) {
final int id = running.keySet().iterator().next();
final Script s = running.get(id);
final ScriptManifest prop = s.getClass().getAnnotation(ScriptManifest.class);
final int result = JOptionPane.showConfirmDialog(this, "Would you like to stop the script " + prop.name() + "?", "Script", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
sh.stopScript(id);
updateScriptControls();
}
}
}
private void toggleViewState(final Component component, final boolean visible) {
final Dimension size = getSize();
size.height += component.getSize().height * (visible ? -1 : 1);
component.setVisible(!visible);
setMinimumSize(size);
if ((getExtendedState() & Frame.MAXIMIZED_BOTH) != Frame.MAXIMIZED_BOTH) {
pack();
}
}
private void init() {
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
if (cleanExit(false)) {
dispose();
}
}
});
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(final WindowEvent arg0) {
switch (arg0.getID()) {
case WindowEvent.WINDOW_ICONIFIED:
lessCpu(true);
break;
case WindowEvent.WINDOW_DEICONIFIED:
lessCpu(false);
break;
}
}
});
setIconImage(Configuration.getImage(Configuration.Paths.Resources.ICON));
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (final Exception ignored) {
}
WindowUtil.setFrame(this);
home = new BotHome();
panel = new BotPanel(home);
menuBar = new BotMenuBar(this);
toolBar = new BotToolBar(this, menuBar);
panel.setFocusTraversalKeys(0, new HashSet<AWTKeyStroke>());
menuBar.setBot(null);
setJMenuBar(menuBar);
textScroll = new JScrollPane(TextAreaLogHandler.TEXT_AREA, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
textScroll.setBorder(null);
textScroll.setPreferredSize(new Dimension(PANEL_WIDTH, LOG_HEIGHT));
textScroll.setVisible(true);
scrollableBotPanel = new JScrollPane(panel);
add(toolBar, BorderLayout.NORTH);
add(scrollableBotPanel, BorderLayout.CENTER);
add(textScroll, BorderLayout.SOUTH);
}
public void scriptStarted(final ScriptHandler handler, final Script script) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
final Bot bot = handler.getBot();
if (bot == getCurrentBot()) {
bot.inputFlags = Environment.INPUT_KEYBOARD;
bot.overrideInput = false;
updateScriptControls();
final String acct = bot.getAccountName();
toolBar.setTabLabel(bots.indexOf(bot), acct == null ? Messages.TABDEFAULTTEXT : acct);
setTitle(acct);
}
}
});
}
public void scriptStopped(final ScriptHandler handler, final Script script) {
final Bot bot = handler.getBot();
if (bot == getCurrentBot()) {
bot.inputFlags = Environment.INPUT_KEYBOARD | Environment.INPUT_MOUSE;
bot.overrideInput = false;
updateScriptControls();
toolBar.setTabLabel(bots.indexOf(bot), Messages.TABDEFAULTTEXT);
setTitle(null);
}
}
public void scriptResumed(final ScriptHandler handler, final Script script) {
if (handler.getBot() == getCurrentBot()) {
updateScriptControls();
}
}
public void scriptPaused(final ScriptHandler handler, final Script script) {
if (handler.getBot() == getCurrentBot()) {
updateScriptControls();
}
}
public void inputChanged(final Bot bot, final int mask) {
bot.inputFlags = mask;
toolBar.setInputState(mask);
updateScriptControls();
}
public static void openURL(final String url) {
final Configuration.OperatingSystem os = Configuration.getCurrentOperatingSystem();
try {
if (os == Configuration.OperatingSystem.MAC) {
final Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
final Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class});
openURL.invoke(null, url);
} else if (os == Configuration.OperatingSystem.WINDOWS) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
} else {
final String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape", "google-chrome", "chromium-browser"};
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++) {
if (Runtime.getRuntime().exec(new String[]{"which", browsers[count]}).waitFor() == 0) {
browser = browsers[count];
}
}
if (browser == null) {
throw new Exception("Could not find web browser");
} else {
Runtime.getRuntime().exec(new String[]{browser, url});
}
}
} catch (final Exception e) {
log.warning("Unable to open " + url);
}
}
private boolean confirmRemoveBot() {
if (!disableConfirmations) {
final int result = JOptionPane.showConfirmDialog(this, "Are you sure you want to close this bot?", Messages.CLOSEBOT, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
return result == JOptionPane.OK_OPTION;
} else {
return true;
}
}
public boolean cleanExit(final boolean silent) {
if (silent) {
disableConfirmations = true;
}
if (!disableConfirmations) {
disableConfirmations = true;
for (final Bot bot : bots) {
if (bot.getAccountName() != null) {
disableConfirmations = true;
break;
}
}
}
boolean doExit = true;
if (!disableConfirmations) {
final String message = "Are you sure you want to exit?";
final int result = JOptionPane.showConfirmDialog(this, message, Messages.EXIT, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) {
doExit = false;
}
}
try {
WebQueue.Destroy();
} catch (NoClassDefFoundError ncdfe) {
}
setVisible(false);
try {
Monitoring.pushState(Type.ENVIRONMENT, "ADS", "SHOW", Boolean.toString(showAds));
} catch (NoClassDefFoundError ncdfe) {
}
if (doExit) {
menuBar.savePrefs();
try {
Monitoring.stop();
} catch (NoClassDefFoundError ncdfe) {
}
System.exit(0);
} else {
setVisible(true);
}
return doExit;
}
public void setTray() {
if (tray == null) {
final Image image = Configuration.getImage(Configuration.Paths.Resources.ICON);
tray = new TrayIcon(image, Configuration.NAME, null);
tray.setImageAutoSize(true);
tray.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
SystemTray.getSystemTray().remove(tray);
setVisible(true);
lessCpu(false);
}
});
}
try {
SystemTray.getSystemTray().add(tray);
final String msg = "Bots are still running in the background.\nClick this icon to restore the window.";
tray.displayMessage(Configuration.NAME + " Hidden", msg, MessageType.INFO);
} catch (Exception ignored) {
log.warning("Unable to hide window");
}
setVisible(false);
lessCpu(true);
}
}
| true | true | public void actionPerformed(final ActionEvent evt) {
final String action = evt.getActionCommand();
final String menu, option;
final int z = action.indexOf('.');
if (z == -1) {
menu = action;
option = "";
} else {
menu = action.substring(0, z);
option = action.substring(z + 1);
}
if (menu.equals(Messages.CLOSEBOT)) {
if (confirmRemoveBot()) {
final int idx = Integer.parseInt(option);
removeBot(bots.get(idx));
}
} else if (menu.equals(Messages.FILE)) {
if (option.equals(Messages.NEWBOT)) {
addBot();
} else if (option.equals(Messages.CLOSEBOT)) {
if (confirmRemoveBot()) {
removeBot(getCurrentBot());
}
} else if (option.equals(Messages.ADDSCRIPT)) {
final String pretext = "";
final String key = (String) JOptionPane.showInputDialog(this, "Enter the script URL (e.g. pastebin link):",
option, JOptionPane.QUESTION_MESSAGE, null, null, pretext);
if (!(key == null || key.trim().isEmpty())) {
ScriptDownloader.save(key);
}
} else if (option.equals(Messages.RUNSCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
showScriptSelector(current);
}
} else if (option.equals(Messages.SERVICEKEY)) {
serviceKeyQuery(option);
} else if (option.equals(Messages.STOPSCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
showStopScript(current);
}
} else if (option.equals(Messages.PAUSESCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
pauseScript(current);
}
} else if (option.equals(Messages.SAVESCREENSHOT)) {
final Bot current = getCurrentBot();
if (current != null) {
ScreenshotUtil.saveScreenshot(current, current.getMethodContext().game.isLoggedIn());
}
} else if (option.equals(Messages.HIDEBOT)) {
setTray();
} else if (option.equals(Messages.EXIT)) {
cleanExit(false);
}
} else if (menu.equals(Messages.EDIT)) {
if (option.equals(Messages.ACCOUNTS)) {
AccountManager.getInstance().showGUI();
} else if (option.equals(Messages.DISABLEADS)) {
showAds = !((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.DISABLEMONITORING)) {
Monitoring.setEnabled(!((JCheckBoxMenuItem) evt.getSource()).isSelected());
if (!Monitoring.isEnabled()) {
log.info("Monitoring data is used to improve development, please enable it to help us");
}
} else if (option.equals(Messages.DISABLECONFIRMATIONS)) {
disableConfirmations = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.AUTOSHUTDOWN)) {
final boolean enabled = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
if (!enabled) {
if (shutdown != null) {
shutdown.cancel();
shutdown.purge();
}
shutdown = null;
} else {
final long interval = 10 * 60 * 1000; // 10mins
shutdown = new java.util.Timer(true);
shutdown.schedule(new TimerTask() {
@Override
public void run() {
for (final Bot bot : bots) {
if (bot.getScriptHandler().getRunningScripts().size() != 0) {
return;
}
}
final int delay = 3;
log.info("Shutdown pending in " + delay + " minutes...");
final Point[] mouse = new Point[]{MouseInfo.getPointerInfo().getLocation(), null};
try {
Thread.sleep(delay * 60 * 1000);
} catch (InterruptedException ignored) {
}
mouse[1] = MouseInfo.getPointerInfo().getLocation();
if (mouse[0].x != mouse[1].x || mouse[0].y != mouse[1].y) {
log.info("Mouse activity detected, delaying shutdown");
} else if (!menuBar.isTicked(option)) {
log.info("Shutdown cancelled");
} else if (Configuration.getCurrentOperatingSystem() == OperatingSystem.WINDOWS) {
try {
Runtime.getRuntime().exec("shutdown.exe", new String[]{"-s"});
cleanExit(true);
} catch (IOException ignored) {
log.severe("Could not shutdown system");
}
}
}
}, interval, interval);
}
} else {
final Bot current = getCurrentBot();
if (current != null) {
if (option.equals(Messages.FORCEINPUT)) {
final boolean selected = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
current.overrideInput = selected;
updateScriptControls();
} else if (option.equals(Messages.LESSCPU)) {
lessCpu(true);
} else if (option.equals(Messages.DISABLEANTIRANDOMS)) {
current.disableRandoms = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.DISABLEAUTOLOGIN)) {
current.disableAutoLogin = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
}
}
}
} else if (menu.equals(Messages.VIEW)) {
| public void actionPerformed(final ActionEvent evt) {
final String action = evt.getActionCommand();
final String menu, option;
final int z = action.indexOf('.');
if (z == -1) {
menu = action;
option = "";
} else {
menu = action.substring(0, z);
option = action.substring(z + 1);
}
if (menu.equals(Messages.CLOSEBOT)) {
if (confirmRemoveBot()) {
final int idx = Integer.parseInt(option);
removeBot(bots.get(idx));
}
} else if (menu.equals(Messages.FILE)) {
if (option.equals(Messages.NEWBOT)) {
addBot();
} else if (option.equals(Messages.CLOSEBOT)) {
if (confirmRemoveBot()) {
removeBot(getCurrentBot());
}
} else if (option.equals(Messages.ADDSCRIPT)) {
final String pretext = "";
final String key = (String) JOptionPane.showInputDialog(this, "Enter the script URL (e.g. pastebin link):",
option, JOptionPane.QUESTION_MESSAGE, null, null, pretext);
if (!(key == null || key.trim().isEmpty())) {
ScriptDownloader.save(key);
}
} else if (option.equals(Messages.RUNSCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
showScriptSelector(current);
}
} else if (option.equals(Messages.SERVICEKEY)) {
serviceKeyQuery(option);
} else if (option.equals(Messages.STOPSCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
showStopScript(current);
}
} else if (option.equals(Messages.PAUSESCRIPT)) {
final Bot current = getCurrentBot();
if (current != null) {
pauseScript(current);
}
} else if (option.equals(Messages.SAVESCREENSHOT)) {
final Bot current = getCurrentBot();
if (current != null) {
ScreenshotUtil.saveScreenshot(current, current.getMethodContext().game.isLoggedIn());
}
} else if (option.equals(Messages.HIDEBOT)) {
setTray();
} else if (option.equals(Messages.EXIT)) {
cleanExit(false);
}
} else if (menu.equals(Messages.EDIT)) {
if (option.equals(Messages.ACCOUNTS)) {
AccountManager.getInstance().showGUI();
} else if (option.equals(Messages.DISABLEADS)) {
showAds = !((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.DISABLEMONITORING)) {
Monitoring.setEnabled(!((JCheckBoxMenuItem) evt.getSource()).isSelected());
if (!Monitoring.isEnabled()) {
log.info("Monitoring data is used to improve development, please enable it to help us");
}
} else if (option.equals(Messages.DISABLECONFIRMATIONS)) {
disableConfirmations = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.AUTOSHUTDOWN)) {
final boolean enabled = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
if (!enabled) {
if (shutdown != null) {
shutdown.cancel();
shutdown.purge();
}
shutdown = null;
} else {
final long interval = 10 * 60 * 1000; // 10mins
shutdown = new java.util.Timer(true);
shutdown.schedule(new TimerTask() {
@Override
public void run() {
for (final Bot bot : bots) {
if (bot.getScriptHandler().getRunningScripts().size() != 0) {
return;
}
}
final int delay = 3;
log.info("Shutdown pending in " + delay + " minutes...");
final Point[] mouse = new Point[]{MouseInfo.getPointerInfo().getLocation(), null};
try {
Thread.sleep(delay * 60 * 1000);
} catch (InterruptedException ignored) {
}
mouse[1] = MouseInfo.getPointerInfo().getLocation();
if (mouse[0].x != mouse[1].x || mouse[0].y != mouse[1].y) {
log.info("Mouse activity detected, delaying shutdown");
} else if (!menuBar.isTicked(option)) {
log.info("Shutdown cancelled");
} else if (Configuration.getCurrentOperatingSystem() == OperatingSystem.WINDOWS) {
try {
Runtime.getRuntime().exec("shutdown.exe", new String[]{"-s"});
cleanExit(true);
} catch (IOException ignored) {
log.severe("Could not shutdown system");
}
}
}
}, interval, interval);
}
} else {
final Bot current = getCurrentBot();
if (current != null) {
if (option.equals(Messages.FORCEINPUT)) {
final boolean selected = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
current.overrideInput = selected;
updateScriptControls();
} else if (option.equals(Messages.LESSCPU)) {
lessCpu(((JCheckBoxMenuItem) evt.getSource()).isSelected());
} else if (option.equals(Messages.DISABLEANTIRANDOMS)) {
current.disableRandoms = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
} else if (option.equals(Messages.DISABLEAUTOLOGIN)) {
current.disableAutoLogin = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
}
}
}
} else if (menu.equals(Messages.VIEW)) {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.