answer
stringlengths 17
10.2M
|
|---|
package eu.focusnet.app.ui.adapter;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import eu.focusnet.app.FocusApplication;
import eu.focusnet.app.R;
import eu.focusnet.app.exception.FocusMissingResourceException;
import eu.focusnet.app.model.json.Bookmark;
import eu.focusnet.app.model.json.BookmarkLink;
import eu.focusnet.app.model.json.Preference;
import eu.focusnet.app.service.DataManager;
import eu.focusnet.app.ui.activity.EntryPointActivity;
import eu.focusnet.app.ui.common.AbstractListItem;
import eu.focusnet.app.ui.common.HeaderListItem;
import eu.focusnet.app.ui.common.StandardListItem;
import eu.focusnet.app.ui.util.UiHelpers;
/**
* List Adapter, used for
*
* FIXME TODO JULIEN TO BE REVIEWED
*/
public class StandardListAdapter extends BaseAdapter
{
private Context context;
private LayoutInflater inflater;
private ArrayList<AbstractListItem> abstractListItems;
public StandardListAdapter(Context context, ArrayList<AbstractListItem> abstractListItems)
{
this.context = context;
this.inflater = android.view.LayoutInflater.from(this.context);
this.abstractListItems = abstractListItems;
}
@Override
public int getViewTypeCount()
{
return 2;
} //two types of views
@Override
public int getItemViewType(int position)
{
return abstractListItems.get(position).getType();
}
@Override
public int getCount()
{
return abstractListItems.size();
}
@Override
public Object getItem(int position)
{
return abstractListItems.get(position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(final int position, final View convertView, ViewGroup parent)
{
View row;
ViewHolder holder;
int itemViewType = getItemViewType(position);
//Test is the imageView is already created
if (convertView == null) {
holder = new ViewHolder();
//Find out the item imageView type and set the corresponding layout
if (itemViewType == HeaderListItem.TYPE_HEADER) {
row = inflater.inflate(R.layout.list_item_header, parent, false);
holder.leftIcon = (ImageView) row.findViewById(R.id.header_left_icon);
holder.title = (TextView) row.findViewById(R.id.header_title);
holder.rightIcon = (ImageView) row.findViewById(R.id.header_right_icon);
}
else {
row = inflater.inflate(R.layout.standard_list_item, parent, false);
holder.leftIcon = (ImageView) row.findViewById(R.id.icon);
holder.title = (TextView) row.findViewById(R.id.title);
holder.info = (TextView) row.findViewById(R.id.info);
holder.rightIcon = (ImageView) row.findViewById(R.id.right_icon);
holder.rightIcon.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
final StandardListItem standardListItem = (StandardListItem) abstractListItems.get(position);
if (standardListItem.getRightIcon() != null) {
final ImageView imageView = (ImageView) v;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View dialogView = inflater.inflate(R.layout.custom_alert_dialog_layout, null);
builder.setView(dialogView);
final Dialog dialog = builder.create();
TextView dialogTitle = ((TextView) dialogView.findViewById(R.id.dialog_title));
final EditText selectedContext = (EditText) dialogView.findViewById(R.id.edit_text_name);
selectedContext.setText(standardListItem.getTitle());
final boolean isRightIconActive = standardListItem.isRightIconActive();
if (isRightIconActive) {
dialogTitle.setText(R.string.focus_remove_bookmark_question);
}
else {
dialogTitle.setText(R.string.focus_add_bookmark_question);
}
Button ok = (Button) dialogView.findViewById(R.id.ok);
Button cancel = (Button) dialogView.findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
dialog.dismiss();
}
});
ok.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Preference userPreference = null;
try {
userPreference = FocusApplication.getInstance().getDataManager().getUserPreferences();
}
catch (FocusMissingResourceException ex) {
// FIXME FIXME TODO
// create a new one? or crash
}
if (isRightIconActive) {
standardListItem.setIsRightIconActive(false);
Bitmap rightIcon = UiHelpers.getBitmap(context, R.drawable.ic_star_o);
standardListItem.setRightIcon(rightIcon);
imageView.setImageBitmap(rightIcon);
userPreference.removeBookmarkLink(standardListItem.getPath(), standardListItem.getTitle(), standardListItem.getTypeOfBookmark());
}
else {
standardListItem.setIsRightIconActive(true);
Bitmap rightIcon = UiHelpers.getBitmap(context, R.drawable.ic_star);
standardListItem.setRightIcon(rightIcon);
imageView.setImageBitmap(rightIcon);
BookmarkLink bookmarkLink = new BookmarkLink(selectedContext.getText().toString(), standardListItem.getPath(), 0);
userPreference.addBookmarkLink(bookmarkLink, standardListItem.getTypeOfBookmark());
}
new SaveUserPreferencesTask(context).execute();
/*
// permanently save
final Thread save_user_preferences_thread = new Thread()
{
public void run()
{
UiHelpers.displayToast(context, "raaaaa");
FocusApplication.getInstance().getDataManager().saveUserPreferences();
}
};
save_user_preferences_thread.start();*/
dialog.dismiss();
}
});
dialog.show();
}
}
});
}
row.setTag(holder);
}
else {
row = convertView;
holder = (ViewHolder) row.getTag();
}
AbstractListItem abstractListItem = abstractListItems.get(position);
if (itemViewType == HeaderListItem.TYPE_HEADER) {
HeaderListItem headerListItem = (HeaderListItem) abstractListItem;
holder.rightIcon.setImageBitmap(headerListItem.getRightIcon());
}
else {
holder.info.setText(((StandardListItem) abstractListItem).getInfo());
holder.rightIcon.setImageBitmap(((StandardListItem) abstractListItem).getRightIcon());
}
//Present in all menu items
holder.leftIcon.setImageBitmap(abstractListItem.getIcon());
holder.title.setText(abstractListItem.getTitle());
return row;
}
private class ViewHolder
{
public ImageView leftIcon;
public TextView title;
public TextView info;
public ImageView rightIcon;
}
/**
* This class is used for testing if the given credential are correct
*/
private class SaveUserPreferencesTask extends AsyncTask<String, Void, Boolean>
{
private ProgressDialog progressDialog;
private Context context;
public SaveUserPreferencesTask(Context context)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
UiHelpers.displayToast(this.context, R.string.focus_save_user_pref_before);
}
@Override
protected Boolean doInBackground(String ... args)
{
FocusApplication.getInstance().getDataManager().saveUserPreferences();
return true;
}
@Override
protected void onPostExecute(Boolean result)
{
UiHelpers.displayToast(this.context, R.string.focus_save_user_pref_after);
}
}
}
|
package org.oakgp.function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Observable;
import java.util.Observer;
import org.junit.Test;
import org.oakgp.Assignments;
import org.oakgp.FunctionSet;
import org.oakgp.NodeSimplifier;
import org.oakgp.TestUtils;
import org.oakgp.Type;
import org.oakgp.VariableSet;
import org.oakgp.node.ConstantNode;
import org.oakgp.node.FunctionNode;
import org.oakgp.node.Node;
import org.oakgp.serialize.NodeReader;
public abstract class AbstractFunctionTest {
private static final Type[] DEFAULT_VARIABLE_TYPES = TestUtils.createIntegerTypeArray(100);
private final FunctionSet functionSet;
private final Observable observable = new Observable() {
@Override
public void notifyObservers(Object arg) {
super.setChanged();
super.notifyObservers(arg);
}
};
protected AbstractFunctionTest() {
functionSet = new FunctionSet(getFunctionSet());
}
protected abstract Function getFunction();
@Test
public abstract void testEvaluate();
@Test
public abstract void testCanSimplify();
@Test
public abstract void testCannotSimplify();
@Test
public void testSignatureReused() {
Function function = getFunction();
assertNotNull(function.getSignature());
assertSame(function.getSignature(), function.getSignature());
}
@Test
public void testDisplayNameValid() {
String displayName = getFunction().getDisplayName();
assertTrue(NodeReader.isValidDisplayName(displayName));
}
protected Function[] getFunctionSet() {
return new Function[] { getFunction() };
}
protected void cannotSimplify(String input, Type... variableTypes) {
FunctionNode node = readFunctionNode(input, variableTypes);
assertSame(node, NodeSimplifier.simplify(node));
}
void addObserver(Observer o) {
observable.addObserver(o);
}
private FunctionNode readFunctionNode(String input, Type... variableTypes) {
return readFunctionNode(input, VariableSet.createVariableSet(variableTypes));
}
private FunctionNode readFunctionNode(String input, VariableSet variableSet) {
FunctionNode functionNode = (FunctionNode) readNode(input, variableSet);
assertSame(getFunction().getClass(), functionNode.getFunction().getClass());
return functionNode;
}
private Node readNode(String input, VariableSet variableSet) {
try (NodeReader nodeReader = new NodeReader(input, functionSet, variableSet)) {
return nodeReader.readNode();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public EvaluateExpectation evaluate(String input) {
return new EvaluateExpectation(input);
}
protected class EvaluateExpectation {
private final String input;
private ConstantNode[] assignedValues = {};
private EvaluateExpectation(String input) {
this.input = input;
}
public EvaluateExpectation assigned(ConstantNode... assignedValues) {
this.assignedValues = assignedValues;
return this;
}
public void to(Object expectedResult) {
Type[] variableTypes = toVariableTypes(assignedValues);
FunctionNode functionNode = readFunctionNode(input, variableTypes);
Assignments assignments = toAssignments(assignedValues);
// assert evaluate consistently returns the expected result
assertEquals(expectedResult, functionNode.evaluate(assignments));
assertEquals(expectedResult, functionNode.evaluate(assignments));
observable.notifyObservers(new Notification(functionNode, assignedValues, expectedResult));
}
private Assignments toAssignments(ConstantNode[] constants) {
Object[] values = new Object[constants.length];
for (int i = 0; i < constants.length; i++) {
values[i] = constants[i].evaluate(null);
}
return Assignments.createAssignments(values);
}
private Type[] toVariableTypes(ConstantNode[] constants) {
Type[] types = new Type[constants.length];
for (int i = 0; i < constants.length; i++) {
types[i] = constants[i].getType();
}
return types;
}
}
static class Notification {
final FunctionNode input;
final ConstantNode[] assignedValues;
final Object output;
private Notification(FunctionNode input, ConstantNode[] assignedValues, Object output) {
this.input = input;
this.assignedValues = assignedValues;
this.output = output;
}
}
public SimplifyExpectation simplify(String input) {
return new SimplifyExpectation(input);
}
protected class SimplifyExpectation {
private final String input;
private Type[] variableTypes = DEFAULT_VARIABLE_TYPES;
private FunctionNode inputNode;
private Node simplifiedNode;
public SimplifyExpectation(String input) {
this.input = input;
}
public SimplifyExpectation with(Type... variableTypes) {
this.variableTypes = variableTypes;
return this;
}
public SimplifyExpectation to(String expected) {
VariableSet variableSet = VariableSet.createVariableSet(variableTypes);
Node expectedNode = readNode(expected, variableSet);
inputNode = readFunctionNode(input, variableSet);
simplifiedNode = NodeSimplifier.simplify(inputNode);
assertEquals(expectedNode, simplifiedNode);
return this;
}
public SimplifyExpectation verify(Object... values) {
Assignments assignments = Assignments.createAssignments(values);
Object expectedOutcome = inputNode.evaluate(assignments);
Object actualOutcome = simplifiedNode.evaluate(assignments);
assertEquals(expectedOutcome, actualOutcome);
return this;
}
public void verifyAll(Object[][] values) {
for (Object[] a : values) {
verify(a);
}
}
}
}
|
package eu.kanade.mangafeed.data.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import eu.kanade.mangafeed.data.database.tables.ChapterSyncTable;
import eu.kanade.mangafeed.data.database.tables.ChapterTable;
import eu.kanade.mangafeed.data.database.tables.MangaTable;
public class DbOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mangafeed.db";
public static final int DATABASE_VERSION = 2;
public DbOpenHelper(@NonNull Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(@NonNull SQLiteDatabase db) {
db.execSQL(MangaTable.getCreateTableQuery());
db.execSQL(ChapterTable.getCreateTableQuery());
db.execSQL(ChapterSyncTable.getCreateTableQuery());
}
@Override
public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1)
db.execSQL(ChapterSyncTable.getCreateTableQuery());
}
@Override
public void onConfigure(SQLiteDatabase db){
db.setForeignKeyConstraintsEnabled(true);
}
}
|
package org.owasp.esapi.reference;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.owasp.esapi.*;
import org.owasp.esapi.errors.ValidationException;
import org.owasp.esapi.filters.SecurityWrapperRequest;
import org.owasp.esapi.http.MockHttpServletRequest;
import org.owasp.esapi.http.MockHttpServletResponse;
import org.owasp.esapi.reference.validation.HTMLValidationRule;
import org.owasp.esapi.reference.validation.StringValidationRule;
import javax.servlet.http.Cookie;
/**
* The Class ValidatorTest.
*
* @author Mike Fauzy (mike.fauzy@aspectsecurity.com)
* @author Jeff Williams (jeff.williams@aspectsecurity.com)
*/
public class ValidatorTest extends TestCase {
private static final String PREFERRED_ENCODING = "UTF-8";
public static Test suite() {
return new TestSuite(ValidatorTest.class);
}
/**
* Instantiates a new HTTP utilities test.
*
* @param testName the test name
*/
public ValidatorTest(String testName) {
super(testName);
}
/**
* {@inheritDoc}
*
* @throws Exception
*/
protected void setUp() throws Exception {
// none
}
/**
* {@inheritDoc}
*
* @throws Exception
*/
protected void tearDown() throws Exception {
// none
}
public void testAddRule() {
Validator validator = ESAPI.validator();
ValidationRule rule = new StringValidationRule("ridiculous");
validator.addRule(rule);
assertEquals(rule, validator.getRule("ridiculous"));
}
public void testAssertValidFileUpload() {
// assertValidFileUpload(String, String, String, byte[], int, boolean, ValidationErrorList)
}
public void testGetPrintable1() {
// getValidPrintable(String, char[], int, boolean, ValidationErrorList)
}
public void testGetPrintable2() {
// getValidPrintable(String, String, int, boolean, ValidationErrorList)
}
public void testGetRule() {
Validator validator = ESAPI.validator();
ValidationRule rule = new StringValidationRule("rule");
validator.addRule(rule);
assertEquals(rule, validator.getRule("rule"));
assertFalse(rule == validator.getRule("ridiculous"));
}
public void testGetValidCreditCard() {
System.out.println("getValidCreditCard");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.isValidCreditCard("cctest1", "1234 9876 0000 0008", false));
assertTrue(instance.isValidCreditCard("cctest2", "1234987600000008", false));
assertFalse(instance.isValidCreditCard("cctest3", "12349876000000081", false));
assertFalse(instance.isValidCreditCard("cctest4", "4417 1234 5678 9112", false));
instance.getValidCreditCard("cctest5", "1234 9876 0000 0008", false, errors);
assertEquals(0, errors.size());
instance.getValidCreditCard("cctest6", "1234987600000008", false, errors);
assertEquals(0, errors.size());
instance.getValidCreditCard("cctest7", "12349876000000081", false, errors);
assertEquals(1, errors.size());
instance.getValidCreditCard("cctest8", "4417 1234 5678 9112", false, errors);
assertEquals(2, errors.size());
assertTrue(instance.isValidCreditCard("cctest1", "1234 9876 0000 0008", false, errors));
assertTrue(errors.size()==2);
assertTrue(instance.isValidCreditCard("cctest2", "1234987600000008", false, errors));
assertTrue(errors.size()==2);
assertFalse(instance.isValidCreditCard("cctest3", "12349876000000081", false, errors));
assertTrue(errors.size()==3);
assertFalse(instance.isValidCreditCard("cctest4", "4417 1234 5678 9112", false, errors));
assertTrue(errors.size()==4);
}
public void testGetValidDate() throws Exception {
System.out.println("getValidDate");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.getValidDate("datetest1", "June 23, 1967", DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US), false) != null);
instance.getValidDate("datetest2", "freakshow", DateFormat.getDateInstance(), false, errors);
assertEquals(1, errors.size());
// TODO: This test case fails due to an apparent bug in SimpleDateFormat
// Note: This seems to be fixed in JDK 6. Will leave it commented out since
// we only require JDK 5. -kww
instance.getValidDate("test", "June 32, 2008", DateFormat.getDateInstance(), false, errors);
// assertEquals( 2, errors.size() );
}
// FIXME: Should probably use SecurityConfigurationWrapper and force
// Validator.AcceptLenientDates to be false.
public void testLenientDate() {
System.out.println("testLenientDate");
boolean acceptLenientDates = ESAPI.securityConfiguration().getLenientDatesAccepted();
if ( acceptLenientDates ) {
assertTrue("Lenient date test skipped because Validator.AcceptLenientDates set to true", true);
return;
}
Date lenientDateTest = null;
try {
// lenientDateTest will be null when Validator.AcceptLenientDates
// is set to false (the default).
Validator instance = ESAPI.validator();
lenientDateTest = instance.getValidDate("datatest3-lenient", "15/2/2009 11:83:00",
DateFormat.getDateInstance(DateFormat.SHORT, Locale.US),
false);
fail("Failed to throw expected ValidationException when Validator.AcceptLenientDates set to false.");
} catch (ValidationException ve) {
assertNull( lenientDateTest );
Throwable cause = ve.getCause();
assertTrue( cause.getClass().getName().equals("java.text.ParseException") );
} catch (Exception e) {
fail("Caught unexpected exception: " + e.getClass().getName() + "; msg: " + e);
}
}
public void testGetValidDirectoryPath() throws Exception {
System.out.println("getValidDirectoryPath");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
// find a directory that exists
File parent = new File("/");
String path = ESAPI.securityConfiguration().getResourceFile("ESAPI.properties").getParentFile().getCanonicalPath();
instance.getValidDirectoryPath("dirtest1", path, parent, true, errors);
assertEquals(0, errors.size());
instance.getValidDirectoryPath("dirtest2", null, parent, false, errors);
assertEquals(1, errors.size());
instance.getValidDirectoryPath("dirtest3", "ridicul%00ous", parent, false, errors);
assertEquals(2, errors.size());
}
public void testGetValidDouble() {
System.out.println("getValidDouble");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
instance.getValidDouble("dtest1", "1.0", 0, 20, true, errors);
assertEquals(0, errors.size());
instance.getValidDouble("dtest2", null, 0, 20, true, errors);
assertEquals(0, errors.size());
instance.getValidDouble("dtest3", null, 0, 20, false, errors);
assertEquals(1, errors.size());
instance.getValidDouble("dtest4", "ridiculous", 0, 20, true, errors);
assertEquals(2, errors.size());
instance.getValidDouble("dtest5", "" + (Double.MAX_VALUE), 0, 20, true, errors);
assertEquals(3, errors.size());
instance.getValidDouble("dtest6", "" + (Double.MAX_VALUE + .00001), 0, 20, true, errors);
assertEquals(4, errors.size());
}
public void testGetValidFileContent() {
System.out.println("getValidFileContent");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
byte[] bytes = null;
try {
bytes = "12345".getBytes(PREFERRED_ENCODING);
}
catch (UnsupportedEncodingException e) {
fail(PREFERRED_ENCODING + " not a supported encoding?!?!!");
}
instance.getValidFileContent("test", bytes, 5, true, errors);
assertEquals(0, errors.size());
instance.getValidFileContent("test", bytes, 4, true, errors);
assertEquals(1, errors.size());
}
public void testGetValidFileName() throws Exception {
System.out.println("getValidFileName");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
String testName = "aspe%20ct.jar";
assertEquals("Percent encoding is not changed", testName, instance.getValidFileName("test", testName, ESAPI.securityConfiguration().getAllowedFileExtensions(), false, errors));
}
public void testGetValidInput() {
System.out.println("getValidInput");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
// instance.getValidInput(String, String, String, int, boolean, ValidationErrorList)
}
public void testGetValidInteger() {
System.out.println("getValidInteger");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
// instance.getValidInteger(String, String, int, int, boolean, ValidationErrorList)
}
public void testGetValidListItem() {
System.out.println("getValidListItem");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
// instance.getValidListItem(String, String, List, ValidationErrorList)
}
public void testGetValidNumber() {
System.out.println("getValidNumber");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
// instance.getValidNumber(String, String, long, long, boolean, ValidationErrorList)
}
public void testGetValidRedirectLocation() {
System.out.println("getValidRedirectLocation");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
// instance.getValidRedirectLocation(String, String, boolean, ValidationErrorList)
}
public void testGetValidSafeHTML() throws Exception {
System.out.println("getValidSafeHTML");
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
// new school test case setup
HTMLValidationRule rule = new HTMLValidationRule("test");
ESAPI.validator().addRule(rule);
assertEquals("Test.", ESAPI.validator().getRule("test").getValid("test", "Test. <script>alert(document.cookie)</script>"));
String test1 = "<b>Jeff</b>";
String result1 = instance.getValidSafeHTML("test", test1, 100, false, errors);
assertEquals(test1, result1);
String test2 = "<a href=\"http:
String result2 = instance.getValidSafeHTML("test", test2, 100, false, errors);
assertEquals(test2, result2);
String test3 = "Test. <script>alert(document.cookie)</script>";
assertEquals("Test.", rule.getSafe("test", test3));
assertEquals("Test. <<div>load=alert()</div>", rule.getSafe("test", "Test. <<div on<script></script>load=alert()"));
assertEquals("Test. <div>b</div>", rule.getSafe("test", "Test. <div style={xss:expression(xss)}>b</div>"));
assertEquals("Test.", rule.getSafe("test", "Test. <s%00cript>alert(document.cookie)</script>"));
assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>"));
assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>"));
// TODO: ENHANCE waiting for a way to validate text headed for an attribute for scripts
// This would be nice to catch, but just looks like text to AntiSamy
// assertFalse(instance.isValidSafeHTML("test", "\" onload=\"alert(document.cookie)\" "));
// String result4 = instance.getValidSafeHTML("test", test4);
// assertEquals("", result4);
}
public void testIsInvalidFilename() {
System.out.println("testIsInvalidFilename");
Validator instance = ESAPI.validator();
char invalidChars[] = "/\\:*?\"<>|".toCharArray();
for (int i = 0; i < invalidChars.length; i++) {
assertFalse(invalidChars[i] + " is an invalid character for a filename",
instance.isValidFileName("test", "as" + invalidChars[i] + "pect.jar", false));
}
assertFalse("Files must have an extension", instance.isValidFileName("test", "", false));
assertFalse("Files must have a valid extension", instance.isValidFileName("test.invalidExtension", "", false));
assertFalse("Filennames cannot be the empty string", instance.isValidFileName("test", "", false));
}
public void testIsValidDate() {
System.out.println("isValidDate");
Validator instance = ESAPI.validator();
DateFormat format = SimpleDateFormat.getDateInstance();
assertTrue(instance.isValidDate("datetest1", "September 11, 2001", format, true));
assertFalse(instance.isValidDate("datetest2", null, format, false));
assertFalse(instance.isValidDate("datetest3", "", format, false));
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.isValidDate("datetest1", "September 11, 2001", format, true, errors));
assertTrue(errors.size()==0);
assertFalse(instance.isValidDate("datetest2", null, format, false, errors));
assertTrue(errors.size()==1);
assertFalse(instance.isValidDate("datetest3", "", format, false, errors));
assertTrue(errors.size()==2);
}
public void testIsValidDirectoryPath() throws IOException {
System.out.println("isValidDirectoryPath");
// get an encoder with a special list of codecs and make a validator out of it
List list = new ArrayList();
list.add("HTMLEntityCodec");
Encoder encoder = new DefaultEncoder(list);
Validator instance = new DefaultValidator(encoder);
boolean isWindows = (System.getProperty("os.name").indexOf("Windows") != -1) ? true : false;
File parent = new File("/");
ValidationErrorList errors = new ValidationErrorList();
if (isWindows) {
String sysRoot = new File(System.getenv("SystemRoot")).getCanonicalPath();
// Windows paths that don't exist and thus should fail
assertFalse(instance.isValidDirectoryPath("test", "c:\\ridiculous", parent, false));
assertFalse(instance.isValidDirectoryPath("test", "c:\\jeff", parent, false));
assertFalse(instance.isValidDirectoryPath("test", "c:\\temp\\..\\etc", parent, false));
// Windows paths
assertTrue(instance.isValidDirectoryPath("test", "C:\\", parent, false)); // Windows root directory
assertTrue(instance.isValidDirectoryPath("test", sysRoot, parent, false)); // Windows always exist directory
assertFalse(instance.isValidDirectoryPath("test", sysRoot + "\\System32\\cmd.exe", parent, false)); // Windows command shell
// Unix specific paths should not pass
assertFalse(instance.isValidDirectoryPath("test", "/tmp", parent, false)); // Unix Temporary directory
assertFalse(instance.isValidDirectoryPath("test", "/bin/sh", parent, false)); // Unix Standard shell
assertFalse(instance.isValidDirectoryPath("test", "/etc/config", parent, false));
// Unix specific paths that should not exist or work
assertFalse(instance.isValidDirectoryPath("test", "/etc/ridiculous", parent, false));
assertFalse(instance.isValidDirectoryPath("test", "/tmp/../etc", parent, false));
assertFalse(instance.isValidDirectoryPath("test1", "c:\\ridiculous", parent, false, errors));
assertTrue(errors.size()==1);
assertFalse(instance.isValidDirectoryPath("test2", "c:\\jeff", parent, false, errors));
assertTrue(errors.size()==2);
assertFalse(instance.isValidDirectoryPath("test3", "c:\\temp\\..\\etc", parent, false, errors));
assertTrue(errors.size()==3);
// Windows paths
assertTrue(instance.isValidDirectoryPath("test4", "C:\\", parent, false, errors)); // Windows root directory
assertTrue(errors.size()==3);
assertTrue(instance.isValidDirectoryPath("test5", sysRoot, parent, false, errors)); // Windows always exist directory
assertTrue(errors.size()==3);
assertFalse(instance.isValidDirectoryPath("test6", sysRoot + "\\System32\\cmd.exe", parent, false, errors)); // Windows command shell
assertTrue(errors.size()==4);
// Unix specific paths should not pass
assertFalse(instance.isValidDirectoryPath("test7", "/tmp", parent, false, errors)); // Unix Temporary directory
assertTrue(errors.size()==5);
assertFalse(instance.isValidDirectoryPath("test8", "/bin/sh", parent, false, errors)); // Unix Standard shell
assertTrue(errors.size()==6);
assertFalse(instance.isValidDirectoryPath("test9", "/etc/config", parent, false, errors));
assertTrue(errors.size()==7);
// Unix specific paths that should not exist or work
assertFalse(instance.isValidDirectoryPath("test10", "/etc/ridiculous", parent, false, errors));
assertTrue(errors.size()==8);
assertFalse(instance.isValidDirectoryPath("test11", "/tmp/../etc", parent, false, errors));
assertTrue(errors.size()==9);
} else {
// Windows paths should fail
assertFalse(instance.isValidDirectoryPath("test", "c:\\ridiculous", parent, false));
assertFalse(instance.isValidDirectoryPath("test", "c:\\temp\\..\\etc", parent, false));
// Standard Windows locations should fail
assertFalse(instance.isValidDirectoryPath("test", "c:\\", parent, false)); // Windows root directory
assertFalse(instance.isValidDirectoryPath("test", "c:\\Windows\\temp", parent, false)); // Windows temporary directory
assertFalse(instance.isValidDirectoryPath("test", "c:\\Windows\\System32\\cmd.exe", parent, false)); // Windows command shell
// Unix specific paths should pass
assertTrue(instance.isValidDirectoryPath("test", "/", parent, false)); // Root directory
assertTrue(instance.isValidDirectoryPath("test", "/bin", parent, false)); // Always exist directory
// Unix specific paths that should not exist or work
assertFalse(instance.isValidDirectoryPath("test", "/bin/sh", parent, false)); // Standard shell, not dir
assertFalse(instance.isValidDirectoryPath("test", "/etc/ridiculous", parent, false));
assertFalse(instance.isValidDirectoryPath("test", "/tmp/../etc", parent, false));
// Windows paths should fail
assertFalse(instance.isValidDirectoryPath("test1", "c:\\ridiculous", parent, false, errors));
assertTrue(errors.size()==1);
assertFalse(instance.isValidDirectoryPath("test2", "c:\\temp\\..\\etc", parent, false, errors));
assertTrue(errors.size()==2);
// Standard Windows locations should fail
assertFalse(instance.isValidDirectoryPath("test3", "c:\\", parent, false, errors)); // Windows root directory
assertTrue(errors.size()==3);
assertFalse(instance.isValidDirectoryPath("test4", "c:\\Windows\\temp", parent, false, errors)); // Windows temporary directory
assertTrue(errors.size()==4);
assertFalse(instance.isValidDirectoryPath("test5", "c:\\Windows\\System32\\cmd.exe", parent, false, errors)); // Windows command shell
assertTrue(errors.size()==5);
// Unix specific paths should pass
assertTrue(instance.isValidDirectoryPath("test6", "/", parent, false, errors)); // Root directory
assertTrue(errors.size()==5);
assertTrue(instance.isValidDirectoryPath("test7", "/bin", parent, false, errors)); // Always exist directory
assertTrue(errors.size()==5);
// Unix specific paths that should not exist or work
assertFalse(instance.isValidDirectoryPath("test8", "/bin/sh", parent, false, errors)); // Standard shell, not dir
assertTrue(errors.size()==6);
assertFalse(instance.isValidDirectoryPath("test9", "/etc/ridiculous", parent, false, errors));
assertTrue(errors.size()==7);
assertFalse(instance.isValidDirectoryPath("test10", "/tmp/../etc", parent, false, errors));
assertTrue(errors.size()==8);
}
}
public void TestIsValidDirectoryPath() {
// isValidDirectoryPath(String, String, boolean)
}
public void testIsValidDouble() {
// isValidDouble(String, String, double, double, boolean)
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
//testing negative range
assertFalse(instance.isValidDouble("test1", "-4", 1, 10, false, errors));
assertTrue(errors.size() == 1);
assertTrue(instance.isValidDouble("test2", "-4", -10, 10, false, errors));
assertTrue(errors.size() == 1);
//testing null value
assertTrue(instance.isValidDouble("test3", null, -10, 10, true, errors));
assertTrue(errors.size() == 1);
assertFalse(instance.isValidDouble("test4", null, -10, 10, false, errors));
assertTrue(errors.size() == 2);
//testing empty string
assertTrue(instance.isValidDouble("test5", "", -10, 10, true, errors));
assertTrue(errors.size() == 2);
assertFalse(instance.isValidDouble("test6", "", -10, 10, false, errors));
assertTrue(errors.size() == 3);
//testing improper range
assertFalse(instance.isValidDouble("test7", "50.0", 10, -10, false, errors));
assertTrue(errors.size() == 4);
//testing non-integers
assertTrue(instance.isValidDouble("test8", "4.3214", -10, 10, true, errors));
assertTrue(errors.size() == 4);
assertTrue(instance.isValidDouble("test9", "-1.65", -10, 10, true, errors));
assertTrue(errors.size() == 4);
//other testing
assertTrue(instance.isValidDouble("test10", "4", 1, 10, false, errors));
assertTrue(errors.size() == 4);
assertTrue(instance.isValidDouble("test11", "400", 1, 10000, false, errors));
assertTrue(errors.size() == 4);
assertTrue(instance.isValidDouble("test12", "400000000", 1, 400000000, false, errors));
assertTrue(errors.size() == 4);
assertFalse(instance.isValidDouble("test13", "4000000000000", 1, 10000, false, errors));
assertTrue(errors.size() == 5);
assertFalse(instance.isValidDouble("test14", "alsdkf", 10, 10000, false, errors));
assertTrue(errors.size() == 6);
assertFalse(instance.isValidDouble("test15", "--10", 10, 10000, false, errors));
assertTrue(errors.size() == 7);
assertFalse(instance.isValidDouble("test16", "14.1414234x", 10, 10000, false, errors));
assertTrue(errors.size() == 8);
assertFalse(instance.isValidDouble("test17", "Infinity", 10, 10000, false, errors));
assertTrue(errors.size() == 9);
assertFalse(instance.isValidDouble("test18", "-Infinity", 10, 10000, false, errors));
assertTrue(errors.size() == 10);
assertFalse(instance.isValidDouble("test19", "NaN", 10, 10000, false, errors));
assertTrue(errors.size() == 11);
assertFalse(instance.isValidDouble("test20", "-NaN", 10, 10000, false, errors));
assertTrue(errors.size() == 12);
assertFalse(instance.isValidDouble("test21", "+NaN", 10, 10000, false, errors));
assertTrue(errors.size() == 13);
assertTrue(instance.isValidDouble("test22", "1e-6", -999999999, 999999999, false, errors));
assertTrue(errors.size() == 13);
assertTrue(instance.isValidDouble("test23", "-1e-6", -999999999, 999999999, false, errors));
assertTrue(errors.size() == 13);
}
public void testIsValidFileContent() {
System.out.println("isValidFileContent");
byte[] content = null;
try {
content = "This is some file content".getBytes(PREFERRED_ENCODING);
}
catch (UnsupportedEncodingException e) {
fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!");
}
Validator instance = ESAPI.validator();
assertTrue(instance.isValidFileContent("test", content, 100, false));
}
public void testIsValidFileName() {
System.out.println("isValidFileName");
Validator instance = ESAPI.validator();
assertTrue("Simple valid filename with a valid extension", instance.isValidFileName("test", "aspect.jar", false));
assertTrue("All valid filename characters are accepted", instance.isValidFileName("test", "!@#$%^&{}[]()_+-=,.~'` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.jar", false));
assertTrue("Legal filenames that decode to legal filenames are accepted", instance.isValidFileName("test", "aspe%20ct.jar", false));
ValidationErrorList errors = new ValidationErrorList();
assertTrue("Simple valid filename with a valid extension", instance.isValidFileName("test", "aspect.jar", false, errors));
assertTrue("All valid filename characters are accepted", instance.isValidFileName("test", "!@#$%^&{}[]()_+-=,.~'` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.jar", false, errors));
assertTrue("Legal filenames that decode to legal filenames are accepted", instance.isValidFileName("test", "aspe%20ct.jar", false, errors));
assertTrue(errors.size() == 0);
}
public void testIsValidFileUpload() throws IOException {
System.out.println("isValidFileUpload");
String filepath = new File(System.getProperty("user.dir")).getCanonicalPath();
String filename = "aspect.jar";
File parent = new File("/").getCanonicalFile();
ValidationErrorList errors = new ValidationErrorList();
byte[] content = null;
try {
content = "This is some file content".getBytes(PREFERRED_ENCODING);
}
catch (UnsupportedEncodingException e) {
fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!");
}
Validator instance = ESAPI.validator();
assertTrue(instance.isValidFileUpload("test", filepath, filename, parent, content, 100, false));
assertTrue(instance.isValidFileUpload("test", filepath, filename, parent, content, 100, false, errors));
assertTrue(errors.size() == 0);
filepath = "/ridiculous";
filename = "aspect.jar";
try {
content = "This is some file content".getBytes(PREFERRED_ENCODING);
}
catch (UnsupportedEncodingException e) {
fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!");
}
assertFalse(instance.isValidFileUpload("test", filepath, filename, parent, content, 100, false));
assertFalse(instance.isValidFileUpload("test", filepath, filename, parent, content, 100, false, errors));
assertTrue(errors.size() == 1);
}
public void testIsValidHTTPRequestParameterSet() {
// isValidHTTPRequestParameterSet(String, Set, Set)
}
public void testisValidInput() {
System.out.println("isValidInput");
Validator instance = ESAPI.validator();
assertTrue(instance.isValidInput("test", "jeff.williams@aspectsecurity.com", "Email", 100, false));
assertFalse(instance.isValidInput("test", "jeff.williams@@aspectsecurity.com", "Email", 100, false));
assertFalse(instance.isValidInput("test", "jeff.williams@aspectsecurity", "Email", 100, false));
assertTrue(instance.isValidInput("test", "jeff.wil'liams@aspectsecurity.com", "Email", 100, false));
assertTrue(instance.isValidInput("test", "jeff.wil''liams@aspectsecurity.com", "Email", 100, false));
assertTrue(instance.isValidInput("test", "123.168.100.234", "IPAddress", 100, false));
assertTrue(instance.isValidInput("test", "192.168.1.234", "IPAddress", 100, false));
assertFalse(instance.isValidInput("test", "..168.1.234", "IPAddress", 100, false));
assertFalse(instance.isValidInput("test", "10.x.1.234", "IPAddress", 100, false));
assertTrue(instance.isValidInput("test", "http:
assertFalse(instance.isValidInput("test", "http:
assertFalse(instance.isValidInput("test", "http:
assertTrue(instance.isValidInput("test", "078-05-1120", "SSN", 100, false));
assertTrue(instance.isValidInput("test", "078 05 1120", "SSN", 100, false));
assertTrue(instance.isValidInput("test", "078051120", "SSN", 100, false));
assertFalse(instance.isValidInput("test", "987-65-4320", "SSN", 100, false));
assertFalse(instance.isValidInput("test", "000-00-0000", "SSN", 100, false));
assertFalse(instance.isValidInput("test", "(555) 555-5555", "SSN", 100, false));
assertFalse(instance.isValidInput("test", "test", "SSN", 100, false));
assertTrue(instance.isValidInput("test", "jeffWILLIAMS123", "HTTPParameterValue", 100, false));
assertTrue(instance.isValidInput("test", "jeff .-/+=@_ WILLIAMS", "HTTPParameterValue", 100, false));
// Removed per Issue 116 - The '*' character is valid as a parameter character
// assertFalse(instance.isValidInput("test", "jeff*WILLIAMS", "HTTPParameterValue", 100, false));
assertFalse(instance.isValidInput("test", "jeff^WILLIAMS", "HTTPParameterValue", 100, false));
assertFalse(instance.isValidInput("test", "jeff\\WILLIAMS", "HTTPParameterValue", 100, false));
assertTrue(instance.isValidInput("test", null, "Email", 100, true));
assertFalse(instance.isValidInput("test", null, "Email", 100, false));
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.isValidInput("test1", "jeff.williams@aspectsecurity.com", "Email", 100, false, errors));
assertTrue(errors.size()==0);
assertFalse(instance.isValidInput("test2", "jeff.williams@@aspectsecurity.com", "Email", 100, false, errors));
assertTrue(errors.size()==1);
assertFalse(instance.isValidInput("test3", "jeff.williams@aspectsecurity", "Email", 100, false, errors));
assertTrue(errors.size()==2);
assertTrue(instance.isValidInput("test4", "jeff.wil'liams@aspectsecurity.com", "Email", 100, false, errors));
assertTrue(errors.size()==2);
assertTrue(instance.isValidInput("test5", "jeff.wil''liams@aspectsecurity.com", "Email", 100, false, errors));
assertTrue(errors.size()==2);
assertTrue(instance.isValidInput("test6", "123.168.100.234", "IPAddress", 100, false, errors));
assertTrue(errors.size()==2);
assertTrue(instance.isValidInput("test7", "192.168.1.234", "IPAddress", 100, false, errors));
assertTrue(errors.size()==2);
assertFalse(instance.isValidInput("test8", "..168.1.234", "IPAddress", 100, false, errors));
assertTrue(errors.size()==3);
assertFalse(instance.isValidInput("test9", "10.x.1.234", "IPAddress", 100, false, errors));
assertTrue(errors.size()==4);
assertTrue(instance.isValidInput("test10", "http:
assertTrue(errors.size()==4);
assertFalse(instance.isValidInput("test11", "http:
assertTrue(errors.size()==5);
assertFalse(instance.isValidInput("test12", "http:
assertTrue(errors.size()==6);
assertTrue(instance.isValidInput("test13", "078-05-1120", "SSN", 100, false, errors));
assertTrue(errors.size()==6);
assertTrue(instance.isValidInput("test14", "078 05 1120", "SSN", 100, false, errors));
assertTrue(errors.size()==6);
assertTrue(instance.isValidInput("test15", "078051120", "SSN", 100, false, errors));
assertTrue(errors.size()==6);
assertFalse(instance.isValidInput("test16", "987-65-4320", "SSN", 100, false, errors));
assertTrue(errors.size()==7);
assertFalse(instance.isValidInput("test17", "000-00-0000", "SSN", 100, false, errors));
assertTrue(errors.size()==8);
assertFalse(instance.isValidInput("test18", "(555) 555-5555", "SSN", 100, false, errors));
assertTrue(errors.size()==9);
assertFalse(instance.isValidInput("test19", "test", "SSN", 100, false, errors));
assertTrue(errors.size()==10);
assertTrue(instance.isValidInput("test20", "jeffWILLIAMS123", "HTTPParameterValue", 100, false, errors));
assertTrue(errors.size()==10);
assertTrue(instance.isValidInput("test21", "jeff .-/+=@_ WILLIAMS", "HTTPParameterValue", 100, false, errors));
assertTrue(errors.size()==10);
// Removed per Issue 116 - The '*' character is valid as a parameter character
// assertFalse(instance.isValidInput("test", "jeff*WILLIAMS", "HTTPParameterValue", 100, false));
assertFalse(instance.isValidInput("test22", "jeff^WILLIAMS", "HTTPParameterValue", 100, false, errors));
assertTrue(errors.size()==11);
assertFalse(instance.isValidInput("test23", "jeff\\WILLIAMS", "HTTPParameterValue", 100, false, errors));
assertTrue(errors.size()==12);
assertTrue(instance.isValidInput("test", null, "Email", 100, true, errors));
assertFalse(instance.isValidInput("test", null, "Email", 100, false, errors));
}
public void testIsValidInteger() {
System.out.println("isValidInteger");
Validator instance = ESAPI.validator();
//testing negative range
assertFalse(instance.isValidInteger("test", "-4", 1, 10, false));
assertTrue(instance.isValidInteger("test", "-4", -10, 10, false));
//testing null value
assertTrue(instance.isValidInteger("test", null, -10, 10, true));
assertFalse(instance.isValidInteger("test", null, -10, 10, false));
//testing empty string
assertTrue(instance.isValidInteger("test", "", -10, 10, true));
assertFalse(instance.isValidInteger("test", "", -10, 10, false));
//testing improper range
assertFalse(instance.isValidInteger("test", "50", 10, -10, false));
//testing non-integers
assertFalse(instance.isValidInteger("test", "4.3214", -10, 10, true));
assertFalse(instance.isValidInteger("test", "-1.65", -10, 10, true));
//other testing
assertTrue(instance.isValidInteger("test", "4", 1, 10, false));
assertTrue(instance.isValidInteger("test", "400", 1, 10000, false));
assertTrue(instance.isValidInteger("test", "400000000", 1, 400000000, false));
assertFalse(instance.isValidInteger("test", "4000000000000", 1, 10000, false));
assertFalse(instance.isValidInteger("test", "alsdkf", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "--10", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "14.1414234x", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "Infinity", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "-Infinity", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "NaN", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "-NaN", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "+NaN", 10, 10000, false));
assertFalse(instance.isValidInteger("test", "1e-6", -999999999, 999999999, false));
assertFalse(instance.isValidInteger("test", "-1e-6", -999999999, 999999999, false));
ValidationErrorList errors = new ValidationErrorList();
//testing negative range
assertFalse(instance.isValidInteger("test1", "-4", 1, 10, false, errors));
assertTrue(errors.size() == 1);
assertTrue(instance.isValidInteger("test2", "-4", -10, 10, false, errors));
assertTrue(errors.size() == 1);
//testing null value
assertTrue(instance.isValidInteger("test3", null, -10, 10, true, errors));
assertTrue(errors.size() == 1);
assertFalse(instance.isValidInteger("test4", null, -10, 10, false, errors));
assertTrue(errors.size() == 2);
//testing empty string
assertTrue(instance.isValidInteger("test5", "", -10, 10, true, errors));
assertTrue(errors.size() == 2);
assertFalse(instance.isValidInteger("test6", "", -10, 10, false, errors));
assertTrue(errors.size() == 3);
//testing improper range
assertFalse(instance.isValidInteger("test7", "50", 10, -10, false, errors));
assertTrue(errors.size() == 4);
//testing non-integers
assertFalse(instance.isValidInteger("test8", "4.3214", -10, 10, true, errors));
assertTrue(errors.size() == 5);
assertFalse(instance.isValidInteger("test9", "-1.65", -10, 10, true, errors));
assertTrue(errors.size() == 6);
//other testing
assertTrue(instance.isValidInteger("test10", "4", 1, 10, false, errors));
assertTrue(errors.size() == 6);
assertTrue(instance.isValidInteger("test11", "400", 1, 10000, false, errors));
assertTrue(errors.size() == 6);
assertTrue(instance.isValidInteger("test12", "400000000", 1, 400000000, false, errors));
assertTrue(errors.size() == 6);
assertFalse(instance.isValidInteger("test13", "4000000000000", 1, 10000, false, errors));
assertTrue(errors.size() == 7);
assertFalse(instance.isValidInteger("test14", "alsdkf", 10, 10000, false, errors));
assertTrue(errors.size() == 8);
assertFalse(instance.isValidInteger("test15", "--10", 10, 10000, false, errors));
assertTrue(errors.size() == 9);
assertFalse(instance.isValidInteger("test16", "14.1414234x", 10, 10000, false, errors));
assertTrue(errors.size() == 10);
assertFalse(instance.isValidInteger("test17", "Infinity", 10, 10000, false, errors));
assertTrue(errors.size() == 11);
assertFalse(instance.isValidInteger("test18", "-Infinity", 10, 10000, false, errors));
assertTrue(errors.size() == 12);
assertFalse(instance.isValidInteger("test19", "NaN", 10, 10000, false, errors));
assertTrue(errors.size() == 13);
assertFalse(instance.isValidInteger("test20", "-NaN", 10, 10000, false, errors));
assertTrue(errors.size() == 14);
assertFalse(instance.isValidInteger("test21", "+NaN", 10, 10000, false, errors));
assertTrue(errors.size() == 15);
assertFalse(instance.isValidInteger("test22", "1e-6", -999999999, 999999999, false, errors));
assertTrue(errors.size() == 16);
assertFalse(instance.isValidInteger("test23", "-1e-6", -999999999, 999999999, false, errors));
assertTrue(errors.size() == 17);
}
public void testIsValidListItem() {
System.out.println("isValidListItem");
Validator instance = ESAPI.validator();
List list = new ArrayList();
list.add("one");
list.add("two");
assertTrue(instance.isValidListItem("test", "one", list));
assertFalse(instance.isValidListItem("test", "three", list));
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.isValidListItem("test1", "one", list, errors));
assertTrue(errors.size()==0);
assertFalse(instance.isValidListItem("test2", "three", list, errors));
assertTrue(errors.size()==1);
}
public void testIsValidNumber() {
System.out.println("isValidNumber");
Validator instance = ESAPI.validator();
//testing negative range
assertFalse(instance.isValidNumber("test", "-4", 1, 10, false));
assertTrue(instance.isValidNumber("test", "-4", -10, 10, false));
//testing null value
assertTrue(instance.isValidNumber("test", null, -10, 10, true));
assertFalse(instance.isValidNumber("test", null, -10, 10, false));
//testing empty string
assertTrue(instance.isValidNumber("test", "", -10, 10, true));
assertFalse(instance.isValidNumber("test", "", -10, 10, false));
//testing improper range
assertFalse(instance.isValidNumber("test", "5", 10, -10, false));
//testing non-integers
assertTrue(instance.isValidNumber("test", "4.3214", -10, 10, true));
assertTrue(instance.isValidNumber("test", "-1.65", -10, 10, true));
//other testing
assertTrue(instance.isValidNumber("test", "4", 1, 10, false));
assertTrue(instance.isValidNumber("test", "400", 1, 10000, false));
assertTrue(instance.isValidNumber("test", "400000000", 1, 400000000, false));
assertFalse(instance.isValidNumber("test", "4000000000000", 1, 10000, false));
assertFalse(instance.isValidNumber("test", "alsdkf", 10, 10000, false));
assertFalse(instance.isValidNumber("test", "--10", 10, 10000, false));
assertFalse(instance.isValidNumber("test", "14.1414234x", 10, 10000, false));
assertFalse(instance.isValidNumber("test", "Infinity", 10, 10000, false));
assertFalse(instance.isValidNumber("test", "-Infinity", 10, 10000, false));
assertFalse(instance.isValidNumber("test", "NaN", 10, 10000, false));
assertFalse(instance.isValidNumber("test", "-NaN", 10, 10000, false));
assertFalse(instance.isValidNumber("test", "+NaN", 10, 10000, false));
assertTrue(instance.isValidNumber("test", "1e-6", -999999999, 999999999, false));
assertTrue(instance.isValidNumber("test", "-1e-6", -999999999, 999999999, false));
ValidationErrorList errors = new ValidationErrorList();
//testing negative range
assertFalse(instance.isValidNumber("test1", "-4", 1, 10, false, errors));
assertTrue(errors.size()==1);
assertTrue(instance.isValidNumber("test2", "-4", -10, 10, false, errors));
assertTrue(errors.size()==1);
//testing null value
assertTrue(instance.isValidNumber("test3", null, -10, 10, true, errors));
assertTrue(errors.size()==1);
assertFalse(instance.isValidNumber("test4", null, -10, 10, false, errors));
assertTrue(errors.size()==2);
//testing empty string
assertTrue(instance.isValidNumber("test5", "", -10, 10, true, errors));
assertTrue(errors.size()==2);
assertFalse(instance.isValidNumber("test6", "", -10, 10, false, errors));
assertTrue(errors.size()==3);
//testing improper range
assertFalse(instance.isValidNumber("test7", "5", 10, -10, false, errors));
assertTrue(errors.size()==4);
//testing non-integers
assertTrue(instance.isValidNumber("test8", "4.3214", -10, 10, true, errors));
assertTrue(errors.size()==4);
assertTrue(instance.isValidNumber("test9", "-1.65", -10, 10, true, errors));
assertTrue(errors.size()==4);
//other testing
assertTrue(instance.isValidNumber("test10", "4", 1, 10, false, errors));
assertTrue(errors.size()==4);
assertTrue(instance.isValidNumber("test11", "400", 1, 10000, false, errors));
assertTrue(errors.size()==4);
assertTrue(instance.isValidNumber("test12", "400000000", 1, 400000000, false, errors));
assertTrue(errors.size()==4);
assertFalse(instance.isValidNumber("test13", "4000000000000", 1, 10000, false, errors));
assertTrue(errors.size()==5);
assertFalse(instance.isValidNumber("test14", "alsdkf", 10, 10000, false, errors));
assertTrue(errors.size()==6);
assertFalse(instance.isValidNumber("test15", "--10", 10, 10000, false, errors));
assertTrue(errors.size()==7);
assertFalse(instance.isValidNumber("test16", "14.1414234x", 10, 10000, false, errors));
assertTrue(errors.size()==8);
assertFalse(instance.isValidNumber("test17", "Infinity", 10, 10000, false, errors));
assertTrue(errors.size()==9);
assertFalse(instance.isValidNumber("test18", "-Infinity", 10, 10000, false, errors));
assertTrue(errors.size()==10);
assertFalse(instance.isValidNumber("test19", "NaN", 10, 10000, false, errors));
assertTrue(errors.size()==11);
assertFalse(instance.isValidNumber("test20", "-NaN", 10, 10000, false, errors));
assertTrue(errors.size()==12);
assertFalse(instance.isValidNumber("test21", "+NaN", 10, 10000, false, errors));
assertTrue(errors.size()==13);
assertTrue(instance.isValidNumber("test22", "1e-6", -999999999, 999999999, false, errors));
assertTrue(errors.size()==13);
assertTrue(instance.isValidNumber("test23", "-1e-6", -999999999, 999999999, false, errors));
assertTrue(errors.size()==13);
}
public void testIsValidParameterSet() {
System.out.println("isValidParameterSet");
Set requiredNames = new HashSet();
requiredNames.add("p1");
requiredNames.add("p2");
requiredNames.add("p3");
Set optionalNames = new HashSet();
optionalNames.add("p4");
optionalNames.add("p5");
optionalNames.add("p6");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("p1", "value");
request.addParameter("p2", "value");
request.addParameter("p3", "value");
ESAPI.httpUtilities().setCurrentHTTP(request, response);
Validator instance = ESAPI.validator();
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames));
assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames,errors));
assertTrue(errors.size()==0);
request.addParameter("p4", "value");
request.addParameter("p5", "value");
request.addParameter("p6", "value");
assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames));
assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames, errors));
assertTrue(errors.size()==0);
request.removeParameter("p1");
assertFalse(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames));
assertFalse(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames, errors));
assertTrue(errors.size() ==1);
}
public void testIsValidPrintable() {
System.out.println("isValidPrintable");
Validator instance = ESAPI.validator();
assertTrue(instance.isValidPrintable("name", "abcDEF", 100, false));
assertTrue(instance.isValidPrintable("name", "!@#R()*$;><()", 100, false));
char[] chars = {0x60, (char) 0xFF, 0x10, 0x25};
assertFalse(instance.isValidPrintable("name", chars, 100, false));
assertFalse(instance.isValidPrintable("name", "%08", 100, false));
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.isValidPrintable("name1", "abcDEF", 100, false, errors));
assertTrue(errors.size()==0);
assertTrue(instance.isValidPrintable("name2", "!@#R()*$;><()", 100, false, errors));
assertTrue(errors.size()==0);
assertFalse(instance.isValidPrintable("name3", chars, 100, false, errors));
assertTrue(errors.size()==1);
assertFalse(instance.isValidPrintable("name4", "%08", 100, false, errors));
assertTrue(errors.size()==2);
}
public void testIsValidRedirectLocation() {
// isValidRedirectLocation(String, String, boolean)
}
public void testIsValidSafeHTML() {
System.out.println("isValidSafeHTML");
Validator instance = ESAPI.validator();
assertTrue(instance.isValidSafeHTML("test", "<b>Jeff</b>", 100, false));
assertTrue(instance.isValidSafeHTML("test", "<a href=\"http:
assertTrue(instance.isValidSafeHTML("test", "Test. <script>alert(document.cookie)</script>", 100, false));
assertTrue(instance.isValidSafeHTML("test", "Test. <div style={xss:expression(xss)}>", 100, false));
assertTrue(instance.isValidSafeHTML("test", "Test. <s%00cript>alert(document.cookie)</script>", 100, false));
assertTrue(instance.isValidSafeHTML("test", "Test. <s\tcript>alert(document.cookie)</script>", 100, false));
assertTrue(instance.isValidSafeHTML("test", "Test. <s\r\n\0cript>alert(document.cookie)</script>", 100, false));
// TODO: waiting for a way to validate text headed for an attribute for scripts
// This would be nice to catch, but just looks like text to AntiSamy
// assertFalse(instance.isValidSafeHTML("test", "\" onload=\"alert(document.cookie)\" "));
ValidationErrorList errors = new ValidationErrorList();
assertTrue(instance.isValidSafeHTML("test1", "<b>Jeff</b>", 100, false, errors));
assertTrue(instance.isValidSafeHTML("test2", "<a href=\"http:
assertTrue(instance.isValidSafeHTML("test3", "Test. <script>alert(document.cookie)</script>", 100, false, errors));
assertTrue(instance.isValidSafeHTML("test4", "Test. <div style={xss:expression(xss)}>", 100, false, errors));
assertTrue(instance.isValidSafeHTML("test5", "Test. <s%00cript>alert(document.cookie)</script>", 100, false, errors));
assertTrue(instance.isValidSafeHTML("test6", "Test. <s\tcript>alert(document.cookie)</script>", 100, false, errors));
assertTrue(instance.isValidSafeHTML("test7", "Test. <s\r\n\0cript>alert(document.cookie)</script>", 100, false, errors));
assertTrue(errors.size() == 0);
}
public void testSafeReadLine() {
System.out.println("safeReadLine");
byte[] bytes = null;
try {
bytes = "testString".getBytes(PREFERRED_ENCODING);
}
catch (UnsupportedEncodingException e1) {
fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!");
}
ByteArrayInputStream s = new ByteArrayInputStream(bytes);
Validator instance = ESAPI.validator();
try {
instance.safeReadLine(s, -1);
fail();
}
catch (ValidationException e) {
// Expected
}
s.reset();
try {
instance.safeReadLine(s, 4);
fail();
}
catch (ValidationException e) {
// Expected
}
s.reset();
try {
String u = instance.safeReadLine(s, 20);
assertEquals("testString", u);
}
catch (ValidationException e) {
fail();
}
// This sub-test attempts to validate that BufferedReader.readLine() and safeReadLine() are similar in operation
// for the nominal case
try {
s.reset();
InputStreamReader isr = new InputStreamReader(s);
BufferedReader br = new BufferedReader(isr);
String u = br.readLine();
s.reset();
String v = instance.safeReadLine(s, 20);
assertEquals(u, v);
}
catch (IOException e) {
fail();
}
catch (ValidationException e) {
fail();
}
}
public void testIssue82_SafeString_Bad_Regex() {
Validator instance = ESAPI.validator();
try {
instance.getValidInput("address", "55 main st. pasadena ak", "SafeString", 512, false);
}
catch (ValidationException e) {
fail(e.getLogMessage());
}
}
public void testGetParameterMap() {
//testing Validator.HTTPParameterName and Validator.HTTPParameterValue
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
//an example of a parameter from displaytag, should pass
request.addParameter("d-49653-p", "pass");
request.addParameter("<img ", "fail");
request.addParameter(generateStringOfLength(32), "pass");
request.addParameter(generateStringOfLength(33), "fail");
assertEquals(safeRequest.getParameterMap().size(), 2);
assertNull(safeRequest.getParameterMap().get("<img"));
assertNull(safeRequest.getParameterMap().get(generateStringOfLength(33)));
}
public void testGetParameterNames() {
//testing Validator.HTTPParameterName
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
//an example of a parameter from displaytag, should pass
request.addParameter("d-49653-p", "pass");
request.addParameter("<img ", "fail");
request.addParameter(generateStringOfLength(32), "pass");
request.addParameter(generateStringOfLength(33), "fail");
assertEquals(Collections.list(safeRequest.getParameterNames()).size(), 2);
}
public void testGetParameter() {
//testing Validator.HTTPParameterValue
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
request.addParameter("p1", "Alice");
request.addParameter("p2", "bob@alice.com");//mail-address from a submit-form
request.addParameter("p3", ESAPI.authenticator().generateStrongPassword());
request.addParameter("p4", new String(EncoderConstants.CHAR_PASSWORD_SPECIALS));
//TODO - I think this should fair request.addParameter("p5", "?"); //some special characters from european languages;
request.addParameter("f1", "<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>");
request.addParameter("f2", "<IMG SRC=javascript:alert('XSS')>");
request.addParameter("f3", "<IMG SRC=javascript:alert('XSS')>");
for (int i = 1; i <= 4; i++) {
assertTrue(safeRequest.getParameter("p" + i).equals(request.getParameter("p" + i)));
}
for (int i = 1; i <= 2; i++) {
boolean testResult = false;
try {
testResult = safeRequest.getParameter("f" + i).equals(request.getParameter("f" + i));
} catch (NullPointerException npe) {
//the test is this block SHOULD fail. a NPE is an acceptable failure state
testResult = false; //redundant, just being descriptive here
}
assertFalse(testResult);
}
assertNull(safeRequest.getParameter("e1"));
//This is revealing problems with Jeff's original SafeRequest
//mishandling of the AllowNull parameter. I'm adding a new Google code
//bug to track this.
//assertNotNull(safeRequest.getParameter("e1", false));
}
public void testGetCookies() {
//testing Validator.HTTPCookieName and Validator.HTTPCookieValue
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
//should support a base64-encode value
request.setCookie("p1", "34=VJhjv7jiDu7tsdLrQQ2KcUwpfWUM2_mBae6UA8ttk4wBHdxxQ-1IBxyCOn3LWE08SDhpnBcJ7N5Vze48F2t8a1R_hXt7PX1BvgTM0pn-T4JkqGTm_tlmV4RmU3GT-dgn");
request.setCookie("f1", "<A HREF=\"http://66.102.7.147/\">XSS</A>");
request.setCookie("load-balancing", "pass");
request.setCookie("'bypass", "fail");
Cookie[] cookies = safeRequest.getCookies();
assertEquals(cookies[0].getValue(), request.getCookies()[0].getValue());
assertEquals(cookies[1].getName(), request.getCookies()[2].getName());
assertTrue(cookies.length == 2);
}
public void testGetHeader() {
//testing Validator.HTTPHeaderValue
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
request.addHeader("p1", "login");
request.addHeader("f1", "<A HREF=\"http://0x42.0x0000066.0x7.0x93/\">XSS</A>");
request.addHeader("p2", generateStringOfLength(150));
request.addHeader("f2", generateStringOfLength(151));
assertEquals(safeRequest.getHeader("p1"), request.getHeader("p1"));
assertEquals(safeRequest.getHeader("p2"), request.getHeader("p2"));
assertFalse(safeRequest.getHeader("f1").equals(request.getHeader("f1")));
assertFalse(safeRequest.getHeader("f2").equals(request.getHeader("f2")));
assertNull(safeRequest.getHeader("p3"));
}
public void testGetHeaderNames() {
//testing Validator.HTTPHeaderName
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
request.addHeader("d-49653-p", "pass");
request.addHeader("<img ", "fail");
request.addHeader(generateStringOfLength(32), "pass");
request.addHeader(generateStringOfLength(33), "fail");
assertEquals(Collections.list(safeRequest.getHeaderNames()).size(), 2);
}
public void testGetQueryString() {
//testing Validator.HTTPQueryString
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
request.setQueryString("mail=bob@alice.com&passwd=" + new String(EncoderConstants.CHAR_PASSWORD_SPECIALS));// TODO, fix this + "&special=");
assertEquals(safeRequest.getQueryString(), request.getQueryString());
request.setQueryString("mail=<IMG SRC=\"jav\tascript:alert('XSS');\">");
assertFalse(safeRequest.getQueryString().equals(request.getQueryString()));
request.setQueryString("mail=bob@alice.com-passwd=johny");
assertTrue(safeRequest.getQueryString().equals(request.getQueryString()));
request.setQueryString("mail=bob@alice.com-passwd=johny&special"); //= is missing!
assertFalse(safeRequest.getQueryString().equals(request.getQueryString()));
}
public void testGetRequestURI() {
//testing Validator.HTTPURI
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request);
try {
request.setRequestURI("/app/page.jsp");
} catch (UnsupportedEncodingException ignored) {
}
assertEquals(safeRequest.getRequestURI(), request.getRequestURI());
}
private String generateStringOfLength(int length) {
StringBuilder longString = new StringBuilder();
for (int i = 0; i < length; i++) {
longString.append("a");
}
return longString.toString();
}
}
|
package im.tny.segvault.disturbances;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.jgrapht.alg.BellmanFordShortestPath;
import org.jgrapht.alg.DijkstraShortestPath;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import im.tny.segvault.disturbances.model.StationUse;
import im.tny.segvault.subway.Connection;
import im.tny.segvault.subway.Line;
import im.tny.segvault.subway.Network;
import im.tny.segvault.subway.Station;
import im.tny.segvault.subway.Stop;
import info.debatty.java.stringsimilarity.experimental.Sift4;
import io.realm.Realm;
public class StationPickerView extends LinearLayout {
private InstantAutoComplete textView;
private ImageButton clearButton;
private AutoCompleteStationsAdapter adapter = null;
private OnStationSelectedListener onStationSelectedListener = null;
private OnSelectionLostListener onSelectionLostListener = null;
private AllStationsSortStrategy allStationsSortStrategy = new AZSortStrategy();
private Station selection = null;
// weakSelection: if true, selection should clear once the textbox gets focus
private boolean weakSelection = false;
public Station getSelection() {
return selection;
}
public void setSelection(Station station) {
if (adapter.stations.contains(station)) {
textView.setText(station.getName());
selection = station;
weakSelection = false;
if (onStationSelectedListener != null) {
onStationSelectedListener.onStationSelected(selection);
}
}
}
public void setWeakSelection(Station station) {
setSelection(station);
weakSelection = true;
}
public void setSelectionById(String id) {
if (adapter == null) {
return;
}
for (Station s : adapter.stations) {
if (s.getId().equals(id)) {
setSelection(s);
break;
}
}
}
public void setWeakSelectionById(String id) {
setSelectionById(id);
weakSelection = true;
}
public StationPickerView(Context context) {
super(context);
initializeViews(context);
}
public StationPickerView(Context context, AttributeSet attrs) {
super(context, attrs);
initializeViews(context);
setHintFromAttrs(attrs);
}
public StationPickerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initializeViews(context);
setHintFromAttrs(attrs);
}
public void setStations(List<Station> stations) {
adapter = new AutoCompleteStationsAdapter(getContext(), stations, R.id.text_station);
textView.setAdapter(adapter);
}
public void setHint(@Nullable CharSequence hint) {
((TextInputLayout) findViewById(R.id.input_station)).setHint(hint);
}
/**
* Inflates the views in the layout.
*
* @param context the current context for the view.
*/
private void initializeViews(Context context) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.station_picker_view, this);
textView = (InstantAutoComplete) findViewById(R.id.text_station);
clearButton = (ImageButton) findViewById(R.id.button_clear);
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos,
long id) {
selection = (Station) parent.getItemAtPosition(pos);
weakSelection = false;
if (onStationSelectedListener != null) {
onStationSelectedListener.onStationSelected(selection);
}
}
});
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
textView.showDropDown();
}
});
clearButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
textView.setText("");
focusOnEntry();
}
});
textView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
selection = null;
if (onSelectionLostListener != null) {
onSelectionLostListener.onSelectionLost();
}
weakSelection = false;
showHideClearButton();
}
});
textView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (weakSelection && hasFocus) {
textView.setText("");
}
showHideClearButton();
}
});
}
private void showHideClearButton() {
if (textView.getEditableText().length() > 0 && textView.isFocused()) {
clearButton.setVisibility(VISIBLE);
} else {
clearButton.setVisibility(GONE);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
}
private void setHintFromAttrs(AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.StationPickerView);
String hint = ta.getString(R.styleable.StationPickerView_hint);
setHint(hint);
ta.recycle();
}
class StationsFilter extends Filter {
AutoCompleteStationsAdapter adapter;
List<Station> originalList;
Sift4 sift4 = new Sift4();
public StationsFilter(AutoCompleteStationsAdapter adapter, List<Station> originalList) {
super();
this.adapter = adapter;
this.originalList = originalList;
sift4.setMaxOffset(5);
}
@Override
@WorkerThread
protected FilterResults performFiltering(CharSequence constraint) {
List<Station> filteredList = new ArrayList<>();
final FilterResults results = new FilterResults();
final Map<Station, Double> distances = new HashMap<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(originalList);
allStationsSortStrategy.sortStations(filteredList);
} else {
final String filterPattern = Normalizer
.normalize(constraint.toString().toLowerCase().trim(), Normalizer.Form.NFD)
.replaceAll("[^\\p{ASCII}]", "");
for (final Station station : originalList) {
String norm = Normalizer
.normalize(station.getName(), Normalizer.Form.NFD)
.replaceAll("[^\\p{ASCII}]", "").toLowerCase();
int indexOf = norm.indexOf(filterPattern);
if (indexOf >= 0) {
filteredList.add(station);
distances.put(station, -1000.0 + indexOf);
continue;
}
norm = norm.substring(0, Math.min(filterPattern.length(), norm.length()));
double distance = sift4.distance(norm, filterPattern);
if (distance < 3.0) {
filteredList.add(station);
distances.put(station, distance);
continue;
}
for (String altName : station.getAltNames()) {
norm = Normalizer
.normalize(altName, Normalizer.Form.NFD)
.replaceAll("[^\\p{ASCII}]", "").toLowerCase();
indexOf = norm.indexOf(filterPattern);
if (indexOf >= 0) {
filteredList.add(station);
// add 1000 to make matches with alternative names go to the bottom
distances.put(station, 1000.0 + indexOf);
break;
}
norm = norm.substring(0, Math.min(filterPattern.length(), norm.length()));
distance = sift4.distance(norm, filterPattern);
if (distance < 2.0) {
filteredList.add(station);
distances.put(station, 2000.0 + distance);
break;
}
}
}
Collections.sort(filteredList, new Comparator<Station>() {
@Override
public int compare(Station station, Station t1) {
return distances.get(station).compareTo(distances.get(t1));
}
});
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.values != null) {
adapter.filteredStations = (ArrayList<Station>) results.values;
adapter.notifyDataSetChanged();
}
}
@Override
public CharSequence convertResultToString(Object resultValue) {
return ((Station) resultValue).getName();
}
}
class AutoCompleteStationsAdapter extends ArrayAdapter<Station> {
private final List<Station> stations;
private List<Station> filteredStations = new ArrayList<>();
public AutoCompleteStationsAdapter(Context context, List<Station> stations, int textViewResourceId) {
super(context, 0, textViewResourceId);
this.stations = stations;
}
@Override
public int getCount() {
return filteredStations.size();
}
@Override
public Filter getFilter() {
return new StationsFilter(this, stations);
}
@Override
public Station getItem(int index) {
return filteredStations.get(index);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item from filtered list.
Station station = filteredStations.get(position);
List<Line> lines = new ArrayList<>(station.getLines());
Collections.sort(lines, Collections.reverseOrder(new Comparator<Line>() {
@Override
public int compare(Line l1, Line l2) {
return l1.getName().compareTo(l2.getName());
}
}));
Line line = lines.get(0);
int color = line.getColor();
// Inflate your custom row layout as usual.
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_station, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.text_name);
name.setText(station.getName());
Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.circle);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
FrameLayout icon = (FrameLayout) convertView.findViewById(R.id.frame_circle);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
icon.setBackgroundDrawable(drawable);
} else {
icon.setBackground(drawable);
}
ImageView subicon = (ImageView) convertView.findViewById(R.id.image_icon);
Drawable mWrappedDrawable = ContextCompat.getDrawable(getContext(), Util.getDrawableResourceIdForLine(line)).mutate();
mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
DrawableCompat.setTint(mWrappedDrawable, Color.WHITE);
DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);
subicon.setImageDrawable(mWrappedDrawable);
if (station.getLines().size() > 1) {
line = lines.get(1);
color = line.getColor();
drawable = ContextCompat.getDrawable(getContext(), R.drawable.circle);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
Bitmap bmp = getBitmapFromVectorDrawable(getContext(), drawable, 2, 1);
icon = (FrameLayout) convertView.findViewById(R.id.frame_half_circle);
icon.setVisibility(VISIBLE);
if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
icon.setBackgroundDrawable(new BitmapDrawable(getResources(), bmp));
} else {
icon.setBackground(new BitmapDrawable(getResources(), bmp));
}
subicon = (ImageView) convertView.findViewById(R.id.image_half_icon);
mWrappedDrawable = ContextCompat.getDrawable(getContext(), Util.getDrawableResourceIdForLine(line)).mutate();
mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
DrawableCompat.setTint(mWrappedDrawable, Color.WHITE);
DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);
bmp = getBitmapFromVectorDrawable(getContext(), mWrappedDrawable, 2, 1);
subicon.setImageBitmap(bmp);
}
return convertView;
}
}
public static Bitmap getBitmapFromVectorDrawable(Context context, Drawable drawable, int widthDiv, int heightDiv) {
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
} catch (Exception e) {
bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
canvas.clipRect(0, 0, canvas.getWidth() / widthDiv, canvas.getHeight() / heightDiv);
drawable.draw(canvas);
return bitmap;
}
@Override
public boolean isFocused() {
return textView.isFocused();
}
public boolean focusOnEntry() {
textView.setFocusableInTouchMode(true);
return textView.requestFocus();
}
@Override
public Parcelable onSaveInstanceState() {
String stationId = "";
if (selection != null) {
stationId = selection.getId();
}
return new SavedState(super.onSaveInstanceState(), stationId, textView.getText().toString());
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
textView.setText(savedState.getInput());
if (!savedState.getStationId().isEmpty()) {
setSelectionById(savedState.getStationId());
}
}
@Override
protected void dispatchSaveInstanceState(SparseArray container) {
super.dispatchFreezeSelfOnly(container);
}
@Override
protected void dispatchRestoreInstanceState(SparseArray container) {
super.dispatchThawSelfOnly(container);
}
protected static class SavedState extends BaseSavedState {
private final String stationId;
private final String input;
private SavedState(Parcelable superState, String stationId, String input) {
super(superState);
this.stationId = stationId;
this.input = input;
}
private SavedState(Parcel in) {
super(in);
stationId = in.readString();
input = in.readString();
}
public String getStationId() {
return stationId;
}
public String getInput() {
return input;
}
@Override
public void writeToParcel(Parcel destination, int flags) {
super.writeToParcel(destination, flags);
destination.writeString(stationId);
destination.writeString(input);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
public void setOnStationSelectedListener(OnStationSelectedListener listener) {
onStationSelectedListener = listener;
}
public void setOnSelectionLostListener(OnSelectionLostListener listener) {
onSelectionLostListener = listener;
}
public void setAllStationsSortStrategy(AllStationsSortStrategy strategy) {
allStationsSortStrategy = strategy;
}
public interface OnStationSelectedListener {
void onStationSelected(Station station);
}
public interface OnSelectionLostListener {
void onSelectionLost();
}
public interface AllStationsSortStrategy {
void sortStations(List<Station> stations);
}
public static class AZSortStrategy implements AllStationsSortStrategy {
@Override
public void sortStations(List<Station> stations) {
Collections.sort(stations, new Comparator<Station>() {
@Override
public int compare(Station station, Station t1) {
return station.getName().compareTo(t1.getName());
}
});
}
}
private static abstract class RealmBasedSortStrategy implements AllStationsSortStrategy {
protected Realm realm = null;
protected Map<String, Double> scores = new HashMap<>();
@Override
public void sortStations(List<Station> stations) {
// ensure this is created in the right thread
realm = Realm.getDefaultInstance();
Collections.sort(stations, new Comparator<Station>() {
@Override
public int compare(Station station, Station t1) {
// order by decreasing score, then A-Z
int result = Double.compare(getScore(t1), getScore(station));
if (result == 0) {
return station.getName().compareTo(t1.getName());
}
return result;
}
});
realm.close();
}
abstract protected double getScore(Station station);
}
public static class EnterFrequencySortStrategy extends RealmBasedSortStrategy {
protected double getScore(Station station) {
Double score = scores.get(station.getId());
if (score == null) {
long entryCount = realm.where(StationUse.class).equalTo("station.id", station.getId()).equalTo("type", StationUse.UseType.NETWORK_ENTRY.name()).count();
score = new Double(entryCount);
scores.put(station.getId(), score);
}
return score;
}
}
public static class ExitFrequencySortStrategy extends RealmBasedSortStrategy {
protected double getScore(Station station) {
Double score = scores.get(station.getId());
if (score == null) {
long exitCount = realm.where(StationUse.class).equalTo("station.id", station.getId()).equalTo("type", StationUse.UseType.NETWORK_EXIT.name()).count();
score = new Double(exitCount);
scores.put(station.getId(), score);
}
return score;
}
}
public static class DistanceSortStrategy implements AllStationsSortStrategy {
private Network network;
private Stop startVertex;
public DistanceSortStrategy(Network network, Stop startVertex) {
this.network = network;
this.startVertex = startVertex;
}
@Override
public void sortStations(List<Station> stations) {
final BellmanFordShortestPath<Stop, Connection> bfsp = new BellmanFordShortestPath<Stop, Connection>(network, startVertex);
Collections.sort(stations, new Comparator<Station>() {
@Override
public int compare(Station station, Station t1) {
return Double.compare(getStationWeight(station, bfsp), getStationWeight(t1, bfsp));
}
});
}
private double getStationWeight(Station station, BellmanFordShortestPath<Stop, Connection> bfsp) {
Set<Stop> stops = station.getStops();
double weight = Double.MAX_VALUE;
for (Stop s : stops) {
weight = Math.min(s == startVertex ? 0 : bfsp.getCost(s), weight);
}
return weight;
}
}
}
|
package org.secureauth.restapi.test;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.secureauth.sarestapi.ISAAccess;
import org.secureauth.sarestapi.SAAccess;
import org.secureauth.sarestapi.data.PushAcceptStatus;
import org.secureauth.sarestapi.data.Response.*;
import org.secureauth.sarestapi.data.SAAuth;
import org.secureauth.sarestapi.data.SABaseURL;
import org.secureauth.sarestapi.data.UserProfile.NewUserProfile;
import org.secureauth.sarestapi.data.UserProfile.NewUserProfileProperties;
import org.secureauth.sarestapi.data.UserProfile.UserProfileKB;
import org.secureauth.sarestapi.exception.SARestAPIException;
import org.secureauth.sarestapi.guid.GUIDStrategy;
import org.secureauth.sarestapi.resources.SAExecuter;
import org.secureauth.sarestapi.util.Property;
import org.secureauth.sarestapi.util.RetrievePropertiesUtils;
import org.secureauth.sarestapi.util.SAFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class SAAccessTDD {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
private static SAAuth saAuth;
private static ISAAccess saAccess;
private static SABaseURL saBaseURL;
private static SAExecuter saExecuter;
private static String realm;
private static String apiApplicationId;
private static String apiApplicationKey;
private static String host;
private static String port;
private static Boolean ssl;
//User
private static String validUsername;
private static String validPin;
private static String validPassword;
private static String userDomain;
private static String newUserPin;
private final static String NEW_USERNAME = "new-user";
private final static String NEW_USER_PASSWORD = "password";
private final static String NEW_USERNAME_QP = "new-user" + "+~.!@$%^&*'_";
private final static String UNEXISTING_USERNAME = "unexisting-user";
private final static String UNEXISTING_USERNAME_QP = UNEXISTING_USERNAME + "+~.!@$%^&*'_";
//DFP
private static String validFingerprintId;
private static String validHostAddress;
//Response messages
private static final String FOUND_MESSAGE = "found";
private static final String NOT_FOUND_MESSAGE = "not_found";
private static final String VALID_MESSAGE = "valid";
private static final String INVALID_MESSAGE = "invalid";
private static final String OK_MESSAGE = "OK";
private static final String INVALID_OTP_MESSAGE = "OTP is invalid.";
private static final String ID_FOUND_MESSAGE = "User Id found";
private static final String ID_NOT_FOUND_MESSAGE = "User Id was not found.";
private static final String SUCCESS_MESSAGE = "success";
private static final String PROCESSED_REQUEST_MESSAGE = "Request has been processed.";
//User OATH-OTP
private static String validFactorIdForOathOtp;
private static String validUserOtp;
private static String validUserOtpOath;
private static RetrievePropertiesUtils retrievePropertiesUtils;
private static Boolean assumeTest;
@Before
public void setup() {
setupStrings();
Assume.assumeTrue(assumeTest);
saAuth = new SAAuth(apiApplicationId, apiApplicationKey, realm);
saBaseURL = new SABaseURL(host, port, ssl, true);
saExecuter = new SAExecuter(saBaseURL);
saAccess = SAFactory.of(saBaseURL, saAuth, saExecuter);
}
private void setupStrings(){
retrievePropertiesUtils = new RetrievePropertiesUtils();
apiApplicationId = getValue(Property.API_APPLICATION_ID);
apiApplicationKey = getValue(Property.API_APPLICATION_KEY);
realm = getValue(Property.REALM);
host = getValue(Property.HOST);
port = getValue(Property.PORT);
ssl = Boolean.valueOf(getValue(Property.SSL));
validUsername = getValue(Property.VALID_USERNAME);
validPin = getValue(Property.VALID_PIN);
validPassword = getValue(Property.VALID_PASSWORD);
userDomain = getValue(Property.USER_DOMAIN);
validFactorIdForOathOtp = getValue(Property.VALID_FACTOR_ID_FOR_OATH_OTP);
validUserOtp = getValue(Property.VALID_OTP_PIN_CODE);
validUserOtpOath = getValue(Property.VALID_OTP_OATH_CODE);
validHostAddress = getValue(Property.VALID_HOST_ADDRESS);
validFingerprintId = getValue(Property.VALID_FINGERPRINT_ID);
assumeTest = Boolean.valueOf(getValue(Property.ASSUME_TEST));
}
private String getValue(Property property){
return retrievePropertiesUtils.getValueFromProperty(property);
}
@Test
public void testUserPINWithValidValues() throws Exception {
/*
* Response would return:
{
"status" : "valid",
"message" : ""
}
*/
BaseResponse response = saAccess.validateUserPin(validUsername, validPin);
assertNotNull(response);
assertEquals(VALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testUserPINWithValidValuesIncludingAXRequestID() throws Exception {
/*
* Response would return:
{
"status" : "valid",
"message" : ""
}
*/
final GUIDStrategy guidStrategy = UUID::randomUUID;
SAAccess saAccessWithXRequestID = new SAAccess( saBaseURL, saAuth, new SAExecuter( saBaseURL, guidStrategy) );
BaseResponse response = saAccessWithXRequestID.validateUserPin(validUsername, validPin);
assertNotNull(response);
assertEquals(VALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testGetPropertiesWithValidUser() throws Exception {
/*
* Response would return:
{
"status" : "found",
"message" : "",
"userId" : "jsmith",
"properties" : {
"firstName" : {
"value" : "John",
"isWritable" : "false"
},
"lastName" : {
"value" : "Smith",
"isWritable" : "false"
},
"email1" : {
"value" : "jsmith@secureauth.com",
"isWritable" : "false"
}
},
"knowledgeBase" : { },
"groups" : [ ],
"accessHistories" : [ {
"userAgent" : "Jersey/2.5.1 (HttpUrlConnection 1.8.0_202)",
"ipAddress" : "11.1.1.2",
"timeStamp" : "2019-07-12T18:13:17.921501Z",
"authState" : "Success"
},
{...} ]
}
*/
UserProfileResponse response = saAccess.getUserProfile(validUsername);
assertNotNull(response);
assertEquals(FOUND_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testGetPropertiesWithValidUserQP() throws Exception {
/*
* Response would return:
{
"status" : "found",
"message" : "",
"userId" : "jsmith",
"properties" : {
"firstName" : {
"value" : "John",
"isWritable" : "false"
},
"lastName" : {
"value" : "Smith",
"isWritable" : "false"
},
"email1" : {
"value" : "jsmith@secureauth.com",
"isWritable" : "false"
}
},
"knowledgeBase" : { },
"groups" : [ ],
"accessHistories" : [ {
"userAgent" : "Jersey/2.5.1 (HttpUrlConnection 1.8.0_202)",
"ipAddress" : "11.1.1.2",
"timeStamp" : "2019-07-12T18:13:17.921501Z",
"authState" : "Success"
},
{...} ]
}
*/
UserProfileResponse response = saAccess.getUserProfileQP(validUsername);
assertNotNull(response);
assertEquals(FOUND_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testGetPropertiesWithUnexistingUser() throws Exception {
/*
* Response would return:
{
"status" : "not_found",
"message" : "User Id was not found.",
"user_id" : "unexisting-user",
"properties" : { },
"knowledgeBase" : { },
"groups" : [ ],
"accessHistories" : [ ]
}
*/
UserProfileResponse response = saAccess.getUserProfile(UNEXISTING_USERNAME);
assertNotNull(response);
assertEquals( NOT_FOUND_MESSAGE, response.getStatus() );
assertEquals( ID_NOT_FOUND_MESSAGE, response.getMessage());
}
@Test
public void testGetPropertiesWithUnexistingUserQP() throws Exception {
/*
* Response would return:
{
"status" : "not_found",
"message" : "User Id was not found.",
"user_id" : "unexisting-user",
"properties" : { },
"knowledgeBase" : { },
"groups" : [ ],
"accessHistories" : [ ]
}
*/
UserProfileResponse response = saAccess.getUserProfileQP(UNEXISTING_USERNAME_QP);
assertNotNull(response);
// If the special characters are not being recognised then we should get some sort of reject instead of a NOT_FOUND_MESSAGE here
assertEquals( NOT_FOUND_MESSAGE, response.getStatus() );
assertEquals( ID_NOT_FOUND_MESSAGE, response.getMessage() );
}
@Test
public void testValidateOathOTPWithValidCode() throws Exception {
/*
* Response would return:
{
"status" : "valid",
"message" : ""
}
*/
BaseResponse response = saAccess.validateOath(validUsername, validUserOtpOath, validFactorIdForOathOtp);
assertNotNull(response);
assertEquals(VALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testValidateOathOTPWithInvalidFactorId() throws Exception {
/*
* Response would return:
{
"status" : "invalid",
"message" : "Request validation failed with: Unknown factor id 'zzzz0000b4504a15acec016d7ef9f42b'."
}
*/
String invalidFactorId = "zzzz0000z0000a00zzzz000z0zz0z00z";
BaseResponse response = saAccess.validateOath(validUsername, validUserOtp, invalidFactorId);
String expectedResponse = String.format("Request validation failed with: Unknown factor id %s", invalidFactorId);
assertNotNull(response);
assertEquals(INVALID_MESSAGE, response.getStatus());
assertEquals(expectedResponse, response.getMessage());
}
@Test
public void testValidateOathOTPWithInvalidCode() throws Exception {
/*
* Response would return:
{
"status" : "invalid",
"message" : "OTP is invalid."
}
*/
BaseResponse response = saAccess.validateOath(validUsername, validUserOtp, validFactorIdForOathOtp);
assertNotNull(response);
assertEquals(INVALID_MESSAGE, response.getStatus());
assertEquals(INVALID_OTP_MESSAGE, response.getMessage());
}
@Test
public void testValidatePasswordWithValidCredentials() throws Exception {
/*
* Response would return:
{
"status" : "valid",
"message" : ""
}
*/
BaseResponse response = saAccess.validateUserPassword(validUsername, validPassword);
assertNotNull(response);
assertEquals(VALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testValidatePasswordWithInvalidPassword() throws Exception {
/*
* Response would return:
{
"status" : "invalid",
"message" : "User Id or password is invalid."
}
*/
String invalidPassword = "invalidPassword";
BaseResponse response = saAccess.validateUserPassword(validUsername, invalidPassword);
assertNotNull(response);
assertEquals(INVALID_MESSAGE, response.getStatus());
assertEquals("User Id or password is invalid.", response.getMessage());
}
@Test
public void testValidatePasswordFromUnexistingUser() throws Exception {
String somePassword = "password";
BaseResponse response = saAccess.validateUserPassword(UNEXISTING_USERNAME, somePassword);
assertNotNull(response);
assertEquals(NOT_FOUND_MESSAGE, response.getStatus());
assertEquals(ID_NOT_FOUND_MESSAGE, response.getMessage());
}
@Test
public void testGetFactorsFromValidUser() throws Exception {
/*
* Response would return:
{
"status" : "found",
"message" : "",
"user_id" : "jsmith",
"factors" : [ {
"type" : "email",
"id" : "Email1",
"value" : "jsmith@secureauth.com"
}, {
"type" : "push",
"id" : "8020890sxt414974b2235e31f4192785",
"value" : "SM-J7",
"capabilities" : [ "push", "push_accept" ]
}, {
"type" : "oath",
"id" : "7edec5b5e3f553150f1e90261a03b8fd",
"value" : "Windows"
}, {
"type" : "oath",
"id" : "6f669edbb4504a15acec016d7ef9f42b",
"value" : "SM-J7"
} ]
}
*/
FactorsResponse response = saAccess.factorsByUser(validUsername);
assertNotNull(response);
assertEquals(FOUND_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testGetFactorsFromValidUserQP() throws Exception {
/*
* Response would return:
{
"status" : "found",
"message" : "",
"user_id" : "jsmith",
"factors" : [ {
"type" : "email",
"id" : "Email1",
"value" : "jsmith@secureauth.com"
}, {
"type" : "push",
"id" : "8020890sxt414974b2235e31f4192785",
"value" : "SM-J7",
"capabilities" : [ "push", "push_accept" ]
}, {
"type" : "oath",
"id" : "7edec5b5e3f553150f1e90261a03b8fd",
"value" : "Windows"
}, {
"type" : "oath",
"id" : "6f669edbb4504a15acec016d7ef9f42b",
"value" : "SM-J7"
} ]
}
*/
FactorsResponse response = saAccess.factorsByUserQP(validUsername);
assertNotNull(response);
assertEquals(FOUND_MESSAGE, response.getStatus());
assertTrue(response.getMessage().isEmpty());
}
@Test
public void testGetFactorsFromUnexistingUser() throws Exception {
/*
* Response would return:
{
"status" : "not_found",
"message" : "User Id was not found.",
"user_id" : "unexisting-user",
"factors" : [ ]
}
*/
FactorsResponse response = saAccess.factorsByUser(UNEXISTING_USERNAME);
assertNotNull(response);
assertEquals(NOT_FOUND_MESSAGE, response.getStatus());
assertEquals(ID_NOT_FOUND_MESSAGE, response.getMessage());
}
@Test
public void testGetFactorsFromUnexistingUserQP() throws Exception {
/*
* Response would return:
{
"status" : "not_found",
"message" : "User Id was not found.",
"user_id" : "unexisting-user",
"factors" : [ ]
}
*/
FactorsResponse response = saAccess.factorsByUserQP(UNEXISTING_USERNAME_QP);
assertNotNull(response);
assertEquals(NOT_FOUND_MESSAGE, response.getStatus());
assertEquals(ID_NOT_FOUND_MESSAGE, response.getMessage());
}
@Test
public void testUserPINWithInvalidNumbers() throws Exception {
/*
* Response would return:
{
"status" : "invalid",
"message" : "PIN is invalid."
}
*/
String invalidNumbersForPin = "000000";
BaseResponse response = saAccess.validateUserPin(validUsername, invalidNumbersForPin);
assertNotNull(response);
assertEquals(INVALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().contains("PIN is invalid."));
}
@Test
public void testValidateUserWithValidInfo() throws Exception {
/*
* Response would return:
{
"status" : "found",
"message" : "User Id found"
}
*/
BaseResponse response = saAccess.validateUser(validUsername);
assertNotNull(response);
assertEquals(FOUND_MESSAGE, response.getStatus());
assertEquals(ID_FOUND_MESSAGE, response.getMessage());
}
@Test
public void testValidateUserNotFound() throws Exception {
/*
* Response would return:
{
"status" : "not_found",
"message" : "User Id was not found.",
"user_id" : "unexisting-user"
}
*/
BaseResponse response = saAccess.validateUser(UNEXISTING_USERNAME_QP);
assertNotNull(response);
assertEquals(NOT_FOUND_MESSAGE, response.getStatus());
assertEquals(ID_NOT_FOUND_MESSAGE, response.getMessage());
}
@Test
public void testValidateUserWithInvalidKey() throws Exception{
/*
* Response would return:
{
"status" : "not_found",
"message" : "The requested resource cannot be found."
}
*/
SAAuth invalidAuth = new SAAuth(apiApplicationId, "de141d3f532be6035c3206083df96c8d1b645220094705aaa3ff9765b0a1a81e", realm);
SAAccess invalidAuthAccess = new SAAccess(saBaseURL, invalidAuth, saExecuter);
BaseResponse response = invalidAuthAccess.validateUser(validUsername);
assertNotNull(response);
assertEquals(INVALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().contains("Invalid credentials."));
}
@Test
public void testValidateUserWithValidID() throws Exception {
/*
* Response would return:
{
"status" : "not_found",
"message" : "The requested resource cannot be found."
}
*/
SAAuth invalidAuth = new SAAuth("invalidID", apiApplicationKey, realm);
SAAccess invalidAuthAccess = new SAAccess(saBaseURL, invalidAuth, saExecuter);
BaseResponse response = invalidAuthAccess.validateUser(validUsername);
assertNotNull(response);
assertEquals(INVALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().contains("AppId is unknown."));
}
@Test
//("Slow test")
//@Ignore
public void testValidateUserWithInvalidHost() throws Exception {
SABaseURL invalidBase = new SABaseURL("invalidHost", port, ssl, true);
SAAccess invalidAuthAccess = new SAAccess(invalidBase, saAuth, saExecuter);
BaseResponse response = invalidAuthAccess.validateUser(validUsername);
assertNull("Already connected", response);
}
@Test
public void testUserPINWithInvalidStrings() throws Exception {
/*
* Response would return:
{
"status" : "invalid",
"message" : "PIN is invalid."
}
*/
BaseResponse response = saAccess.validateUserPin(validUsername, INVALID_MESSAGE);
assertNotNull(response);
assertEquals(INVALID_MESSAGE, response.getStatus());
assertTrue(response.getMessage().contains("PIN is invalid."));
}
@Test
public void testUpdateUserProfileKBQKBAOrderedValid() throws Exception {
NewUserProfile newUserProfile = new NewUserProfile();
newUserProfile.getKnowledgeBase().put("nonFormated1", new UserProfileKB("kbq1", "kba1"));
newUserProfile.getKnowledgeBase().put("nonFormated3", new UserProfileKB("kbq3", "kba3"));
newUserProfile.getKnowledgeBase().put("nonFormated2", new UserProfileKB("kbq2", "kba2"));
newUserProfile.setPassword(validPassword);
NewUserProfileProperties newUserProfileProperties = new NewUserProfileProperties();
newUserProfileProperties.setEmail4("email@email.com");
newUserProfileProperties.setAuxId10("aux10");
newUserProfileProperties.setPhone4("123-456-7890");
newUserProfile.setProperties(newUserProfileProperties);
ResponseObject responseObj = saAccess.updateUser(validUsername, newUserProfile);
assertNotNull(responseObj);
assertEquals(SUCCESS_MESSAGE, responseObj.getStatus());
assertEquals("", responseObj.getMessage());
}
@Test
public void testCreateUserProfileKBQKBAOrderedValid() throws Exception {
NewUserProfile newUserProfile = new NewUserProfile();
newUserProfile.getKnowledgeBase().put("NonFormated2", new UserProfileKB("Kbq2", "kba2"));
newUserProfile.getKnowledgeBase().put("nOnFormated3", new UserProfileKB("kbq3", "kba3"));
newUserProfile.getKnowledgeBase().put("nonFormated1", new UserProfileKB("kBq1", "kba1"));
newUserProfile.setPassword(validPassword);
newUserProfile.setUserId(String.valueOf(randomNumberBetween(1, 1000)));
NewUserProfileProperties newUserProfileProperties = new NewUserProfileProperties();
newUserProfileProperties.setEmail1("email@email.com");
newUserProfileProperties.setAuxId10("aux10");
newUserProfileProperties.setPhone4("123-456-7890");
newUserProfileProperties.setFirstName("foo");
newUserProfileProperties.setLastName("foo");
newUserProfile.setProperties(newUserProfileProperties);
ResponseObject responseObj = saAccess.createUser(newUserProfile);
assertNotNull(responseObj);
assertEquals(SUCCESS_MESSAGE, responseObj.getStatus());
assertEquals("", responseObj.getMessage());
}
@Test(expected = SARestAPIException.class)
public void testCreateUserProfileKBQKBAOrderedInValid() throws Exception {
NewUserProfile newUserProfile = new NewUserProfile();
newUserProfile.getKnowledgeBase().put("nonFormated1", new UserProfileKB("kbq1", "kba1"));
newUserProfile.getKnowledgeBase().put("nonFormated2", new UserProfileKB("kbq2", "kba2"));
newUserProfile.getKnowledgeBase().put("nonFormated3", new UserProfileKB("kbq3", "kba3"));
newUserProfile.setPassword("");
newUserProfile.setUserId("");
NewUserProfileProperties newUserProfileProperties = new NewUserProfileProperties();
newUserProfileProperties.setEmail1("email@email.com");
newUserProfileProperties.setAuxId10("aux10");
newUserProfileProperties.setPhone4("123-456-7890");
newUserProfileProperties.setFirstName("foo");
newUserProfileProperties.setLastName("foo");
newUserProfile.setProperties(newUserProfileProperties);
ResponseObject responseObj = saAccess.createUser(newUserProfile);
exceptionRule.expect(SARestAPIException.class);
exceptionRule.expectMessage("User and password are required to create a new user");
assertEquals(null, responseObj);
}
private double randomNumberBetween(int min, int max){
return (Math.random() * ((max - min) + 1)) + min;
}
@Test
public void testDFPScoreWithValidNotFound() throws Exception {
/*
* Response would return:
{
"fingerprint_id": "",
"fingerprint_name": "",
"score": "0.00",
"match_score": "0.00",
"update_score": "0.00",
"status": "not_found",
"message": ""
}
*/
String emptyFingerprintJSON = "{}";
DFPValidateResponse response = saAccess.DFPScoreFingerprint(validUsername, validHostAddress, validFingerprintId, emptyFingerprintJSON);
assertNotNull(response);
assertEquals(NOT_FOUND_MESSAGE, response.getStatus());
assertEquals(0.0, response.getScore(), 0.1);
assertEquals(0.0, response.getUpdate_score(), 0.1);
}
@Test
public void testDeleteUserValid() throws Exception {
//when
BaseResponse responseObj = saAccess.deleteUser(NEW_USERNAME, userDomain, Boolean.FALSE );
//then
assertNotNull(responseObj);
assertEquals(SUCCESS_MESSAGE, responseObj.getStatus());
assertEquals("User delete complete", responseObj.getMessage());
assertEquals(userDomain + "\\" +NEW_USERNAME, responseObj.getUser_id());
}
@Test
public void testDeleteUserInvalidUser() throws Exception {
//when
BaseResponse responseObj = saAccess.deleteUser(UNEXISTING_USERNAME, userDomain, Boolean.FALSE );
//then
assertNotNull(responseObj);
assertEquals("failed", responseObj.getStatus());
assertEquals("user_id does not exist", responseObj.getMessage());
String domainAndUser = userDomain.isEmpty() ? UNEXISTING_USERNAME : userDomain + "\\" + UNEXISTING_USERNAME;
assertEquals(domainAndUser, responseObj.getUser_id());
}
@Test
public void testDFPScoreWithValidFoundData() throws Exception {
/*
* Response would return:
{
"fingerprint_id": "",
"fingerprint_name": "",
"score": "0.00",
"match_score": "0.00",
"update_score": "0.00",
"status": "not_found",
"message": ""
}
*/
String fingerprintJSON = "{\n" +
" \"fingerprint\" : {\"uaString\" : \"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0\",\n" +
" \"uaBrowser\" : {\n" +
" \"name\" : \"Firefox\",\n" +
" \"version\" : \"52.0\",\n" +
" \"major\" : \"52\"\n" +
" },\n" +
" \"uaDevice\" : {\n" +
" \"model\" : \"testmodel\",\n" +
" \"type\" : \"testtype\",\n" +
" \"vendor\" : \"testvendor\"\n" +
" },\n" +
" \"uaEngine\" : {\n" +
" \"name\" : \"Gecko\",\n" +
" \"version\" : \"52.0\"\n" +
" },\n" +
" \"uaOS\" : {\n" +
" \"name\" : \"Windows\",\n" +
" \"version\" : \"8.1\"\n" +
" },\n" +
" \"uaCPU\" : {\n" +
" \"architecture\" : \"amd64\"\n" +
" },\n" +
" \"uaPlatform\" : \"Win32\",\n" +
" \"language\" : \"en-US\",\n" +
" \"colorDepth\" : 24,\n" +
" \"pixelRatio\" : 1.0,\n" +
" \"screenResolution\" : \"2560x1440\",\n" +
" \"availableScreenResolution\" : \"2560x1400\",\n" +
" \"timezone\" : \"America/Los_Angeles\",\n" +
" \"timezoneOffset\" : 420,\n" +
" \"localStorage\" : true,\n" +
" \"sessionStorage\" : true,\n" +
" \"indexedDb\" : true,\n" +
" \"addBehavior\" : false,\n" +
" \"openDatabase\" : false,\n" +
" \"cpuClass\" : null,\n" +
" \"platform\" : \"Win32\",\n" +
" \"doNotTrack\" : \"unspecified\",\n" +
" \"plugins\" : \"\",\n" +
" \"canvas\" : \"812446969\",\n" +
" \"webGl\" : \"-1928114666\",\n" +
" \"adBlock\" : false,\n" +
" \"userTamperLanguage\" : false,\n" +
" \"userTamperScreenResolution\" : false,\n" +
" \"userTamperOS\" : false,\n" +
" \"userTamperBrowser\" : false,\n" +
" \"touchSupport\" : {\n" +
" \"maxTouchPoints\" : 0,\n" +
" \"touchEvent\" : false,\n" +
" \"touchStart\" : false\n" +
" },\n" +
" \"cookieSupport\" : true,\n" +
" \"fonts\" : \"Aharoni,Andalus,Angsana New,AngsanaUPC,Aparajita,Arabic Typesetting,Arial,Batang,BatangChe,Bauhaus 93,Bodoni 72,Bodoni 72 Oldstyle,Bodoni 72 Smallcaps,Bookshelf Symbol 7,Browallia New,BrowalliaUPC,Calibri,Cambria,Cambria Math,Candara,Comic Sans MS,Consolas,Constantia,Corbel,Cordia New,CordiaUPC,DaunPenh,David,DFKai-SB,DilleniaUPC,DokChampa,Dotum,DotumChe,Ebrima,English 111 Vivace BT,Estrangelo Edessa,EucrosiaUPC,Euphemia,FangSong,Franklin Gothic,FrankRuehl,FreesiaUPC,Gabriola,Gautami,Georgia,GeoSlab 703 Lt BT,GeoSlab 703 XBd BT,Gisha,Gulim,GulimChe,Gungsuh,GungsuhChe,Helvetica,Humanst 521 Cn BT,Impact,IrisUPC,Iskoola Pota,JasmineUPC,KaiTi,Kalinga,Kartika,Khmer UI,KodchiangUPC,Kokila,Lao UI,Latha,Leelawadee,Levenim MT,LilyUPC,Lucida Console,Lucida Sans Unicode,Malgun Gothic,Mangal,Marlett,Meiryo,Meiryo UI,Microsoft Himalaya,Microsoft JhengHei,Microsoft New Tai Lue,Microsoft PhagsPa,Microsoft Sans Serif,Microsoft Tai Le,Microsoft Uighur,Microsoft YaHei,Microsoft Yi Baiti,MingLiU,MingLiU_HKSCS,MingLiU_HKSCS-ExtB,MingLiU-ExtB,Miriam,Miriam Fixed,Modern No. 20,Mongolian Baiti,MoolBoran,MS Gothic,MS Mincho,MS PGothic,MS PMincho,MS Sans Serif,MS Serif,MS UI Gothic,MV Boli,Narkisim,NSimSun,Nyala,Palatino Linotype,Plantagenet Cherokee,PMingLiU,PMingLiU-ExtB,Raavi,Rod,Roman,Sakkal Majalla,Segoe Print,Segoe Script,Segoe UI,Segoe UI Symbol,Shonar Bangla,Shruti,SimHei,Simplified Arabic,Simplified Arabic Fixed,SimSun,SimSun-ExtB,Small Fonts,Sylfaen,Tahoma,Times,Times New Roman,Traditional Arabic,Trebuchet MS,Tunga,Univers CE 55 Medium,Utsaah,Vani,Verdana,Vijaya,Vrinda,Wingdings,Wingdings 2,Wingdings 3\",\n" +
" \"id\" : \"a31332450f284e9bbb1572e7c1c4927a\",\n" +
" \"userId\" : \"atest\",\n" +
" \"displayName\" : \"Windows - 8.1 - Firefox\",\n" +
" \"httpHeaders\" : {\n" +
" \"Accept\" : \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n" +
" \"AcceptCharSet\" : \"\",\n" +
" \"AcceptEncoding\" : \"gzip, deflate, br\",\n" +
" \"AcceptLanguage\" : \"en-US,en;q=0.5\"\n" +
" },\n" +
" \"hostAddress\" : \"172.16.17.171\",\n" +
" \"mobileDeviceId\" : \"\",\n" +
" \"mobileDeviceName\" : \"\",\n" +
" \"mobileDeviceComment\" : \"\",\n" +
" \"lastAccess\" : \"2017-05-08T20:28:18.4333144+00:00\",\n" +
" \"createdOn\" : \"2017-05-08T20:28:18.4333144+00:00\"},\n" +
" \"accept\" : \"asdasdf\",\n" +
" \"acceptCharset\" : \"bbbbbb\",\n" +
" \"acceptEncoding\" : \"cccc\",\n" +
" \"acceptLanguage\" : \"eeee\",\n" +
" \"deviceId\" : \"aaa\",\n" +
" \"deviceName\" : \"asdf\",\n" +
" \"deviceComment\" : \"\"\n" +
" }";
DFPValidateResponse response = saAccess.DFPScoreFingerprint(validUsername, validHostAddress, validFingerprintId, fingerprintJSON);
assertNotNull(response);
assertEquals(FOUND_MESSAGE, response.getStatus());
assertEquals(100.0, response.getScore(), 1);
assertEquals(90.0, response.getUpdate_score(), 1);
assertEquals(89.0, response.getMatch_score(), 1);
}
@Test
public void testDFPSaveWithValidFound() throws Exception {
/*
* Response would return:
{
"fingerprint_id": "",
"fingerprint_name": "",
"score": "0.00",
"match_score": "0.00",
"update_score": "0.00",
"status": "not_found",
"message": ""
}
*/
String fingerprintJSON = "{\n" +
" \"fingerprint\" : {\"uaString\" : \"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0\",\n" +
" \"uaBrowser\" : {\n" +
" \"name\" : \"Firefox\",\n" +
" \"version\" : \"52.0\",\n" +
" \"major\" : \"52\"\n" +
" },\n" +
" \"uaDevice\" : {\n" +
" \"model\" : \"testmodel\",\n" +
" \"type\" : \"testtype\",\n" +
" \"vendor\" : \"testvendor\"\n" +
" },\n" +
" \"uaEngine\" : {\n" +
" \"name\" : \"Gecko\",\n" +
" \"version\" : \"52.0\"\n" +
" },\n" +
" \"uaOS\" : {\n" +
" \"name\" : \"Windows\",\n" +
" \"version\" : \"8.1\"\n" +
" },\n" +
" \"uaCPU\" : {\n" +
" \"architecture\" : \"amd64\"\n" +
" },\n" +
" \"uaPlatform\" : \"Win32\",\n" +
" \"language\" : \"en-US\",\n" +
" \"colorDepth\" : 24,\n" +
" \"pixelRatio\" : 1.0,\n" +
" \"screenResolution\" : \"2560x1440\",\n" +
" \"availableScreenResolution\" : \"2560x1400\",\n" +
" \"timezone\" : \"America/Los_Angeles\",\n" +
" \"timezoneOffset\" : 420,\n" +
" \"localStorage\" : true,\n" +
" \"sessionStorage\" : true,\n" +
" \"indexedDb\" : true,\n" +
" \"addBehavior\" : false,\n" +
" \"openDatabase\" : false,\n" +
" \"cpuClass\" : null,\n" +
" \"platform\" : \"Win32\",\n" +
" \"doNotTrack\" : \"unspecified\",\n" +
" \"plugins\" : \"\",\n" +
" \"canvas\" : \"812446969\",\n" +
" \"webGl\" : \"-1928114666\",\n" +
" \"adBlock\" : false,\n" +
" \"userTamperLanguage\" : false,\n" +
" \"userTamperScreenResolution\" : false,\n" +
" \"userTamperOS\" : false,\n" +
" \"userTamperBrowser\" : false,\n" +
" \"touchSupport\" : {\n" +
" \"maxTouchPoints\" : 0,\n" +
" \"touchEvent\" : false,\n" +
" \"touchStart\" : false\n" +
" },\n" +
" \"cookieSupport\" : true,\n" +
" \"fonts\" : \"Aharoni,Andalus,Angsana New,AngsanaUPC,Aparajita,Arabic Typesetting,Arial,Batang,BatangChe,Bauhaus 93,Bodoni 72,Bodoni 72 Oldstyle,Bodoni 72 Smallcaps,Bookshelf Symbol 7,Browallia New,BrowalliaUPC,Calibri,Cambria,Cambria Math,Candara,Comic Sans MS,Consolas,Constantia,Corbel,Cordia New,CordiaUPC,DaunPenh,David,DFKai-SB,DilleniaUPC,DokChampa,Dotum,DotumChe,Ebrima,English 111 Vivace BT,Estrangelo Edessa,EucrosiaUPC,Euphemia,FangSong,Franklin Gothic,FrankRuehl,FreesiaUPC,Gabriola,Gautami,Georgia,GeoSlab 703 Lt BT,GeoSlab 703 XBd BT,Gisha,Gulim,GulimChe,Gungsuh,GungsuhChe,Helvetica,Humanst 521 Cn BT,Impact,IrisUPC,Iskoola Pota,JasmineUPC,KaiTi,Kalinga,Kartika,Khmer UI,KodchiangUPC,Kokila,Lao UI,Latha,Leelawadee,Levenim MT,LilyUPC,Lucida Console,Lucida Sans Unicode,Malgun Gothic,Mangal,Marlett,Meiryo,Meiryo UI,Microsoft Himalaya,Microsoft JhengHei,Microsoft New Tai Lue,Microsoft PhagsPa,Microsoft Sans Serif,Microsoft Tai Le,Microsoft Uighur,Microsoft YaHei,Microsoft Yi Baiti,MingLiU,MingLiU_HKSCS,MingLiU_HKSCS-ExtB,MingLiU-ExtB,Miriam,Miriam Fixed,Modern No. 20,Mongolian Baiti,MoolBoran,MS Gothic,MS Mincho,MS PGothic,MS PMincho,MS Sans Serif,MS Serif,MS UI Gothic,MV Boli,Narkisim,NSimSun,Nyala,Palatino Linotype,Plantagenet Cherokee,PMingLiU,PMingLiU-ExtB,Raavi,Rod,Roman,Sakkal Majalla,Segoe Print,Segoe Script,Segoe UI,Segoe UI Symbol,Shonar Bangla,Shruti,SimHei,Simplified Arabic,Simplified Arabic Fixed,SimSun,SimSun-ExtB,Small Fonts,Sylfaen,Tahoma,Times,Times New Roman,Traditional Arabic,Trebuchet MS,Tunga,Univers CE 55 Medium,Utsaah,Vani,Verdana,Vijaya,Vrinda,Wingdings,Wingdings 2,Wingdings 3\",\n" +
" \"id\" : \"a31332450f284e9bbb1572e7c1c4927a\",\n" +
" \"userId\" : \"atest\",\n" +
" \"displayName\" : \"Windows - 8.1 - Firefox\",\n" +
" \"httpHeaders\" : {\n" +
" \"Accept\" : \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n" +
" \"AcceptCharSet\" : \"\",\n" +
" \"AcceptEncoding\" : \"gzip, deflate, br\",\n" +
" \"AcceptLanguage\" : \"en-US,en;q=0.5\"\n" +
" },\n" +
" \"hostAddress\" : \"172.16.17.171\",\n" +
" \"mobileDeviceId\" : \"\",\n" +
" \"mobileDeviceName\" : \"\",\n" +
" \"mobileDeviceComment\" : \"\",\n" +
" \"lastAccess\" : \"2017-05-08T20:28:18.4333144+00:00\",\n" +
" \"createdOn\" : \"2017-05-08T20:28:18.4333144+00:00\"},\n" +
" \"accept\" : \"asdasdf\",\n" +
" \"acceptCharset\" : \"bbbbbb\",\n" +
" \"acceptEncoding\" : \"cccc\",\n" +
" \"acceptLanguage\" : \"eeee\",\n" +
" \"deviceId\" : \"aaa\",\n" +
" \"deviceName\" : \"asdf\",\n" +
" \"deviceComment\" : \"\"\n" +
" }";
DFPValidateResponse response = saAccess.DFPSaveFingerprint(validUsername, validHostAddress, validFingerprintId, fingerprintJSON);
assertNotNull(response);
assertEquals(FOUND_MESSAGE, response.getStatus());
assertEquals(100.0, response.getScore(), 1);
assertEquals(89.0, response.getUpdate_score(), 1);
assertEquals(90.0, response.getMatch_score(), 1);
assertEquals(validFingerprintId, response.getFingerprintId());
assertEquals("Windows - 8.1 - Firefox", response.getFingerprintName());
}
@Test
public void testDFPSaveWithValidNotFound() throws Exception {
/*
* Response would return:
{
"fingerprint_id": "",
"fingerprint_name": "",
"score": "0.00",
"match_score": "0.00",
"update_score": "0.00",
"status": "not_found",
"message": ""
}
*/
String emptyFingerprintJSON = "{}";
DFPValidateResponse response = saAccess.DFPSaveFingerprint(validUsername, validHostAddress, validFingerprintId, emptyFingerprintJSON);
assertNotNull(response);
assertEquals(NOT_FOUND_MESSAGE, response.getStatus());
assertEquals(0.0, response.getScore(), 0.1);
assertEquals(0.0, response.getUpdate_score(), 0.1);
assertEquals("", response.getFingerprintId());
assertEquals("", response.getFingerprintName());
}
@Test
public void testNotifySuccessAuthenticatedResult() {
BaseResponse response = saAccess.notifyAuthenticated( validUsername, "success", "EMAIL" );
assertEquals( PROCESSED_REQUEST_MESSAGE, response.getMessage() );
}
@Test
public void testNotifyAbortedAuthenticatedResult() {
BaseResponse response = saAccess.notifyAuthenticated( validUsername, "aborted", "EMAIL" );
assertEquals( PROCESSED_REQUEST_MESSAGE, response.getMessage() );
}
@Test
public void testNotifyCancelledAuthenticatedResult() {
BaseResponse response = saAccess.notifyAuthenticated( validUsername, "cancelled", "EMAIL" );
assertEquals( PROCESSED_REQUEST_MESSAGE, response.getMessage() );
}
@Test
public void testNotifyWrongAuthenticatedResult() {
BaseResponse response = saAccess.notifyAuthenticated( validUsername, "wrong", "NONE" );
assertEquals( PROCESSED_REQUEST_MESSAGE, response.getMessage() );
}
@Test
public void testWhenUserIdIsNotValidThenNotifyAuthenticatedResultFail() {
BaseResponse response = saAccess.notifyAuthenticated( UNEXISTING_USERNAME, "success", "NONE" );
assertEquals( ID_NOT_FOUND_MESSAGE, response.getMessage() );
}
// This tests the creation of a real user
@Test
public void testCreateUserWithSpecialCharacters() {
NewUserProfile userProfile = new NewUserProfile();
userProfile.setUserId(NEW_USERNAME_QP);
userProfile.setPassword(NEW_USER_PASSWORD);
BaseResponse response = saAccess.createUser(userProfile);
assertEquals(OK_MESSAGE, response.getStatus());
}
@Test
public void testGetCreatedUserWithSpecialCharacters() {
String userName = validUsername;
BaseResponse response = saAccess.getUserProfileQP(userName);
assertEquals(FOUND_MESSAGE, response.getStatus());
}
@Test
public void testGetCreatedFactorsUserWithSpecialCharacters() {
String userName = validUsername;
BaseResponse response = saAccess.factorsByUserQP(userName);
assertEquals(FOUND_MESSAGE, response.getStatus());
}
@Test
public void testGetCreatedThrottleUserWithSpecialCharacters() {
String userName = validUsername;
BaseResponse response = saAccess.getThrottleReqQP(userName);
assertEquals(FOUND_MESSAGE, response.getStatus());
}
@Test
public void testLinkToAcceptEmail() {
StatefulResponseObject response = saAccess.emailLink(validUsername, "Email1");
assertEquals(VALID_MESSAGE, response.getStatus());
}
@Test
public void testLinkToAcceptSMS() {
StatefulResponseObject response = saAccess.smsLink(validUsername, "Phone1");
assertEquals(VALID_MESSAGE, response.getStatus());
}
@Test
public void testLinkToAcceptVerify() {
StatefulResponseObject linkResponse = saAccess.smsLink(validUsername, "Phone1");
PushAcceptStatus response = saAccess.verifyLinkToAcceptStatus(linkResponse.getReference_id(), linkResponse.getSessionAffinityCookie());
assertEquals(FOUND_MESSAGE, response.getStatus());
}
}
|
package pl.codecouple.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(pl.codecouple.Runner.class)
@WebAppConfiguration
public class CIWorkshopTest {
@Autowired
WebApplicationContext webCtx;
MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webCtx).build();
}
@Test
public void shouldReturn200() throws Exception {
// Then
mockMvc.perform(get("/")).andExpect(status().is(200));
// mockMvc.perform(get("/books")).andExpect(status().is(200));
}
}
|
package seedu.todo.guitests;
import static org.junit.Assert.*;
import java.time.LocalDateTime;
import org.junit.Test;
import seedu.todo.commons.util.DateUtil;
import seedu.todo.models.Event;
// @@author A0139812A
public class AddEventCommandTest extends GuiTest {
@Test
public void addEvent_eventSameDateInFuture_isVisible() {
// Get formatted string for two days from now, e.g. 17 Oct 2016
LocalDateTime twoDaysFromNow = LocalDateTime.now().plusDays(2);
String twoDaysFromNowString = DateUtil.formatDate(twoDaysFromNow);
String twoDaysFromNowIsoString = DateUtil.formatIsoDate(twoDaysFromNow);
String command = String.format("add event Presentation in the Future from %s 2pm to %s 9pm", twoDaysFromNowString, twoDaysFromNowString);
Event event = new Event();
event.setName("Presentation in the Future");
event.setStartDate(DateUtil.parseDateTime(String.format("%s 14:00:00", twoDaysFromNowIsoString)));
event.setEndDate(DateUtil.parseDateTime(String.format("%s 19:00:00", twoDaysFromNowIsoString)));
assertEventVisibleAfterCmd(command, event);
}
@Test
public void addEvent_eventSameDateInPast_isNotVisible() {
// Get formatted string for two days before now, e.g. 13 Oct 2016
LocalDateTime twoDaysBeforeNow = LocalDateTime.now().minusDays(2);
String twoDaysBeforeNowString = DateUtil.formatDate(twoDaysBeforeNow);
String twoDaysBeforeNowIsoString = DateUtil.formatIsoDate(twoDaysBeforeNow);
// Creates a task in the same date to make sure that a DateItem is created but not a EventItem
console.runCommand("add Task in the same day by " + twoDaysBeforeNowString);
String command = String.format("add event Presentation in the Past from %s 2pm to %s 9pm", twoDaysBeforeNowString, twoDaysBeforeNowString);
Event event = new Event();
event.setName("Presentation in the Past");
event.setStartDate(DateUtil.parseDateTime(String.format("%s 14:00:00", twoDaysBeforeNowIsoString)));
event.setEndDate(DateUtil.parseDateTime(String.format("%s 19:00:00", twoDaysBeforeNowIsoString)));
assertEventNotVisibleAfterCmd(command, event);
}
@Test
public void addEvent_missingStartDate_disambiguate() {
String command = "add event Presentation that never starts to 9pm";
console.runCommand(command);
String expectedDisambiguation = "add event \"Presentation that never starts\" from \"<start time>\" to \"9pm\"";
assertEquals(console.getConsoleInputText(), expectedDisambiguation);
}
@Test
public void addEvent_missingEndDate_disambiguate() {
String command = "add event Presentation that never ends from 2pm";
console.runCommand(command);
String expectedDisambiguation = "add event \"Presentation that never ends\" from \"2pm\" to \"<end time>\"";
assertEquals(console.getConsoleInputText(), expectedDisambiguation);
}
@Test
public void addEvent_missingStartEndDate_disambiguate() {
String command = "add event Presentation that does not take place";
console.runCommand(command);
String expectedDisambiguation = "add event \"Presentation that does not take place\" from \"<start time>\" to \"<end time>\"";
assertEquals(console.getConsoleInputText(), expectedDisambiguation);
}
@Test
public void addEvent_missingStartBeforeEnd_disambiguate() {
String command = "add event Presentation from 9pm to 2pm";
console.runCommand(command);
String expectedDisambiguation = "add event \"Presentation\" from \"9pm\" to \"2pm\"";
assertEquals(console.getConsoleInputText(), expectedDisambiguation);
}
@Test
public void addEvent_missingName_disambiguate() {
String command = "add event from 2pm to 9pm";
console.runCommand(command);
String expectedDisambiguation = "add event \"<name>\" from \"2pm\" to \"9pm\"";
assertEquals(console.getConsoleInputText(), expectedDisambiguation);
}
@Test
public void addEvent_unmatchedQuotes_commandRemains() {
String command = "add event \"Presentation from 2pm to 9pm";
console.runCommand(command);
assertEquals(console.getConsoleInputText(), command);
}
}
|
package com.crawljax.core;
import junit.framework.Assert;
import org.apache.commons.configuration.ConfigurationException;
import org.junit.Ignore;
import org.junit.Test;
import com.crawljax.core.configuration.CrawlSpecification;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.core.configuration.ThreadConfiguration;
/**
* Test the CrawlerExecutor ThreadPoolExecutor. Basically it test only the correct naming.
*
* @author Stefan Lenselink <S.R.Lenselink@student.tudelft.nl>
* @version $Id$
*/
public class CrawlerExecutorTest {
private CrawlerExecutor excutor = new CrawlerExecutor(1);
/**
* Test for single thread setup.
*
* @throws InterruptedException
* the the waitForTermination fails.
*/
@Test
public void testCorrectNamesSingleThread() throws InterruptedException {
TestThread t1 = new TestThread("Thread 1 Crawler 1");
TestThread t2 = new TestThread("Thread 1 Crawler 2 (Automatic)", "Automatic");
// First to start
excutor.execute(t1);
excutor.execute(t2);
excutor.waitForTermination();
Assert.assertTrue("Thread 1 ok", t1.success);
Assert.assertTrue("Thread 2 ok", t2.success);
}
/**
* Test for multi-thread setup. TODO Stefan; Enable this test when concurrent crawling is done.
* Now It would not run because there is only one thread at the time active.
*
* @throws InterruptedException
* the the waitForTermination fails.
* @throws ConfigurationException
* when config fails TODO Stefan check why this method failes in combination with
* mvn install
*/
@Ignore
@Test
public void testCorrectNamesMultiThread() throws InterruptedException, ConfigurationException {
CrawlSpecification spec = new CrawlSpecification("about:plugins");
CrawljaxConfiguration cfg = new CrawljaxConfiguration();
cfg.setCrawlSpecification(spec);
cfg.setThreadConfiguration(new ThreadConfiguration()); // TODO Stefan after 1.9 release set
// to 2
excutor = new CrawlerExecutor(2);
TestThread t1 = new TestThread("Thread 1 Crawler 1");
TestThread t2 = new TestThread("Thread 2 Crawler 2 (Automatic)", "Automatic");
excutor.execute(t1);
excutor.execute(t2);
excutor.waitForTermination();
Assert.assertTrue("Thread 1 ok", t1.success);
Assert.assertTrue("Thread 2 ok", t2.success);
}
/**
* Internal class used to 'emulate' a Crawler and do the actual unit-check.
*
* @author Stefan Lenselink <S.R.Lenselink@student.tudelft.nl>
*/
private class TestThread implements Runnable {
private final String compare;
private final String name;
private boolean success = false;
public TestThread(String c, String n) {
compare = c;
name = n;
}
public TestThread(String string) {
this(string, "");
}
@Override
public void run() {
try {
Thread.sleep(500);
String tName = Thread.currentThread().getName();
if (tName.equals(compare)) {
success = true;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return name;
}
}
}
|
package org.worshipsongs.activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import org.worshipsongs.CommonConstants;
import org.worshipsongs.adapter.ServiceSongAdapter;
import org.worshipsongs.dao.SongDao;
import org.worshipsongs.domain.ServiceSong;
import org.worshipsongs.domain.Song;
import org.worshipsongs.fragment.HomeTabFragment;
import org.worshipsongs.fragment.ServiceSongsFragment;
import org.worshipsongs.fragment.SongContentPortraitViewFragment;
import org.worshipsongs.listener.SongContentViewListener;
import org.worshipsongs.service.PresentationScreenService;
import org.worshipsongs.utils.PropertyUtils;
import org.worshipsongs.worship.R;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ServiceSongsActivity extends AppCompatActivity implements SongContentViewListener
{
private FrameLayout songContentFrameLayout;
private PresentationScreenService presentationScreenService;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
presentationScreenService = new PresentationScreenService(ServiceSongsActivity.this);
setActionBar();
setContentViewFragment();
setTabsFragment();
}
private void setActionBar()
{
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(getIntent().getStringExtra(CommonConstants.SERVICE_NAME_KEY));
}
private void setContentViewFragment()
{
songContentFrameLayout = (FrameLayout) findViewById(R.id.song_content_fragment);
}
private void setTabsFragment()
{
FragmentManager fragmentManager = getSupportFragmentManager();
ServiceSongsFragment exisitingServiceSongsFragment = (ServiceSongsFragment) fragmentManager.findFragmentByTag(ServiceSongsFragment.class.getSimpleName());
if (exisitingServiceSongsFragment == null) {
Bundle bundle = new Bundle();
bundle.putString(CommonConstants.SERVICE_NAME_KEY, getIntent().getStringExtra(CommonConstants.SERVICE_NAME_KEY));
ServiceSongsFragment serviceSongsFragment = ServiceSongsFragment.newInstance(bundle);
serviceSongsFragment.setSongContentViewListener(this);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.tabs_fragment, serviceSongsFragment, HomeTabFragment.class.getSimpleName());
transaction.addToBackStack(null);
transaction.commit();
}
}
@Override
public void displayContent(String title, List<String> titleList, int position)
{
if (songContentFrameLayout != null) {
SongContentPortraitViewFragment songContentPortraitViewFragment = SongContentPortraitViewFragment.newInstance(title, new ArrayList<String>(titleList));
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.song_content_fragment, songContentPortraitViewFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
public void onResume()
{
super.onResume();
presentationScreenService.onResume();
}
@Override
protected void onStop()
{
super.onStop();
presentationScreenService.onStop();
}
@Override
protected void onPause()
{
super.onPause();
presentationScreenService.onPause();
}
@Override
public void onBackPressed()
{
super.onBackPressed();
finish();
}
}
|
package com.github.davidmoten.rtree;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.github.davidmoten.rtree.geometry.Rectangle;
public class RTreeTest {
private static final double PRECISION = 0.000001;
@Test
public void testInstantiation() {
RTree<Object> tree = new RTree<Object>();
assertTrue(tree.entries().isEmpty().toBlocking().single());
}
@Test
public void testSearchEmptyTree() {
RTree<Object> tree = new RTree<Object>();
assertTrue(tree.search(r(1)).isEmpty().toBlocking().single());
}
@SuppressWarnings("unchecked")
@Test
public void testSearchOnOneItem() {
RTree<Object> tree = new RTree<Object>();
Entry<Object> entry = new Entry<Object>(new Object(), r(1));
tree = tree.add(entry);
assertEquals(Arrays.asList(entry), tree.search(r(1)).toList()
.toBlocking().single());
System.out.println("entries="
+ tree.entries().toList().toBlocking().single());
}
@Test
public void testPerformanceAndEntriesCount() {
long t = System.currentTimeMillis();
int n = 10000;
RTree<Object> tree = createRandomRTree(n);
long diff = System.currentTimeMillis() - t;
System.out.println("inserts/second = " + ((double) n / diff * 1000));
assertEquals(n, (int) tree.entries().count().toBlocking().single());
t = System.currentTimeMillis();
Entry<Object> entry = tree.search(Rectangle.create(0, 0, 500, 500))
.first().toBlocking().single();
diff = System.currentTimeMillis() - t;
System.out.println("found " + entry);
System.out
.println("time to get nearest with " + n + " entries=" + diff);
}
private static RTree<Object> createRandomRTree(int n) {
RTree<Object> tree = RTree.builder().maxChildren(4).build();
for (int i = 0; i < n; i++) {
Entry<Object> entry = new Entry<Object>(new Object(), random());
tree = tree.add(entry);
}
return tree;
}
@Test
public void testNearest() {
RTree<Object> tree = RTree.builder().maxChildren(4).build().add(e(1))
.add(e(2)).add(e(10)).add(e(11));
List<Entry<Object>> list = tree.nearest(r(9), 10, 2).toList()
.toBlocking().single();
assertEquals(2, list.size());
assertEquals(10, list.get(0).mbr().x1(), PRECISION);
assertEquals(11, list.get(1).mbr().x1(), PRECISION);
}
@Test
public void testVisualizer() {
RTree<Object> tree = createRandomRTree(100);
tree.visualize(600, 600, new Rectangle(-20, -20, 1100, 1100), 5).save(
new File("target/tree.png"), "PNG");
}
@Test
public void testDeleteOneFromOne() {
Entry<Object> e1 = e(1);
RTree<Object> tree = RTree.builder().maxChildren(4).build().add(e1)
.delete(e1);
assertEquals(0, (int) tree.entries().count().toBlocking().single());
}
@Test
public void testDeleteOneFromTreeWithDepthGreaterThanOne() {
Entry<Object> e1 = e(1);
RTree<Object> tree = RTree.builder().maxChildren(4).build().add(e1)
.add(e(2)).add(e(3)).add(e(4)).add(e(5)).add(e(6)).add(e(7))
.add(e(8)).add(e(9)).add(e(10)).delete(e1);
assertEquals(9, (int) tree.entries().count().toBlocking().single());
assertFalse(tree.entries().contains(e1).toBlocking().single());
}
@Test
public void testDeleteOneFromLargeTree() {
Entry<Object> e1 = e(1);
Entry<Object> e2 = e(2);
int n = 10000;
RTree<Object> tree = createRandomRTree(n).add(e1).add(e2).delete(e1);
assertEquals(n + 1, (int) tree.entries().count().toBlocking().single());
assertFalse(tree.entries().contains(e1).toBlocking().single());
assertTrue(tree.entries().contains(e2).toBlocking().single());
}
@Test
public void testDeleteItemThatIsNotPresentDoesNothing() {
Entry<Object> e1 = e(1);
Entry<Object> e2 = e(2);
RTree<Object> tree = RTree.builder().build().add(e1);
assertTrue(tree == tree.delete(e2));
}
private static Entry<Object> e(int n) {
return new Entry<Object>(new Object(), r(n));
}
private static Rectangle r(int n) {
return Rectangle.create(n, n, n + 1, n + 1);
}
private static Rectangle r(int n, int m) {
return Rectangle.create(n, m, n + 1, m + 1);
}
private static Rectangle random() {
return r((int) Math.round(Math.sqrt(Math.random()) * 1000),
(int) Math.round(Math.sqrt(Math.random()) * 1000));
}
}
|
package tonivade.db.replication;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static tonivade.db.persistence.HexUtil.toHexString;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import tonivade.db.TinyDB;
import tonivade.db.command.IServerContext;
@RunWith(MockitoJUnitRunner.class)
public class SlaveReplicationTest {
private TinyDB server;
@Mock
private IServerContext context;
@Captor
private ArgumentCaptor<InputStream> captor;
@Before
public void setUp() throws Exception {
server = new TinyDB();
server.start();
}
@Test
public void testReplication() throws Exception {
SlaveReplication slave = new SlaveReplication(context, "localhost", 7081);
slave.start();
verify(context, timeout(2000)).importRDB(captor.capture());
InputStream stream = captor.getValue();
byte[] buffer = new byte[stream.available()];
int readed = stream.read(buffer);
assertThat(readed, is(buffer.length));
assertThat(toHexString(buffer), is("524544495330303036FF224AF218835A1E69"));
}
}
|
package ve.com.abicelis.chefbuddy.ui.home;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ve.com.abicelis.chefbuddy.R;
import ve.com.abicelis.chefbuddy.app.ChefBuddyApplication;
import ve.com.abicelis.chefbuddy.model.RecipeSource;
import ve.com.abicelis.chefbuddy.ui.about.AboutActivity;
import ve.com.abicelis.chefbuddy.ui.addEditRecipe.AddEditRecipeActivity;
import ve.com.abicelis.chefbuddy.ui.home_history.HistoryFragment;
import ve.com.abicelis.chefbuddy.ui.home_recipeList.RecipeListFragment;
import ve.com.abicelis.chefbuddy.ui.home_spinWheel.SpinWheelFragment;
import ve.com.abicelis.chefbuddy.ui.home.presenter.HomePresenter;
import ve.com.abicelis.chefbuddy.ui.home.view.HomeView;
import ve.com.abicelis.chefbuddy.ui.searchOnlineRecipe.SearchOnlineRecipeActivity;
public class HomeActivity extends AppCompatActivity implements HomeView, SearchViewListener {
//CONST
private static final String TAG = HomeActivity.class.getSimpleName();
private static final int RECIPE_TAB_POSITION = 0;
private static final int SPINWHEEL_TAB_POSITION = 1;
//DATA
@Inject
HomePresenter presenter;
@BindView(R.id.activity_home_viewpager)
ViewPager mViewpager;
@BindView(R.id.activity_home_tab_layout)
TabLayout mTabLayout;
@BindView(R.id.activity_home_search_view)
MaterialSearchView mSearchView;
@BindView(R.id.activity_home_appbar)
AppBarLayout mAppBarLayout;
@BindView(R.id.activity_home_toolbar)
Toolbar mToolbar;
@BindView(R.id.activity_home_fab_add_recipe)
FloatingActionButton mFabAdd;
private HomeViewPagerAdapter mHomeViewPagerAdapter;
private RecipeListFragment mRecipeListFragment;
private SpinWheelFragment mSpinWheelFragment;
private HistoryFragment mHistoryFragment;
//DATA
private List<String> titleList = new ArrayList<>();
private List<Fragment> fragmentList = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
((ChefBuddyApplication)getApplication()).getAppComponent().inject(this);
presenter.attachView(this);
//Setup toolbar
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setLogo(R.drawable.ic_toolbar_home);
setupViewPagerAndTabLayout();
setupSearchView();
setupFab();
}
private void setupViewPagerAndTabLayout() {
//Clear lists
titleList.clear();
fragmentList.clear();
//Populate title list
titleList.add(getResources().getString(R.string.activity_home_tab_recipe_title));
titleList.add(getResources().getString(R.string.activity_home_tab_spin_wheel_title));
titleList.add(getResources().getString(R.string.activity_home_tab_history_title));
//Populate fragment list
mRecipeListFragment = new RecipeListFragment();
fragmentList.add(mRecipeListFragment);
mSpinWheelFragment = new SpinWheelFragment();
fragmentList.add(mSpinWheelFragment);
mHistoryFragment = new HistoryFragment();
fragmentList.add(mHistoryFragment);
//Setup adapter, viewpager and tabLayout
mHomeViewPagerAdapter = new HomeViewPagerAdapter(getSupportFragmentManager(), titleList, fragmentList);
mViewpager.setAdapter(mHomeViewPagerAdapter);
mViewpager.setCurrentItem(0); //Start at page 1
mViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
if (position != 0 && mSearchView.isSearchOpen())
mSearchView.closeSearch();
if(position == RECIPE_TAB_POSITION)
mFabAdd.show();
else
mFabAdd.hide();
//Expand appBar when not in recipe tab
if(position != RECIPE_TAB_POSITION)
mAppBarLayout.setExpanded(true, true);
if(position == SPINWHEEL_TAB_POSITION) {
//Notify fragment
((SpinWheelFragment)mHomeViewPagerAdapter.getRegisteredFragment(SPINWHEEL_TAB_POSITION)).refreshWheel();
}
}
@Override
public void onPageScrollStateChanged(int state) {}
});
mTabLayout.setupWithViewPager(mViewpager);
}
private void setupSearchView() {
mSearchView.setVoiceSearch(true);
mSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if(mHomeViewPagerAdapter.getRegisteredFragment(0) != null) {
if (query.isEmpty())
((RecipeListFragment) mHomeViewPagerAdapter.getRegisteredFragment(0)).cancelFilterRecipes();
else
((RecipeListFragment) mHomeViewPagerAdapter.getRegisteredFragment(0)).filterRecipes(query);
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(mHomeViewPagerAdapter.getRegisteredFragment(0) != null) {
if (newText.isEmpty())
((RecipeListFragment) mHomeViewPagerAdapter.getRegisteredFragment(0)).cancelFilterRecipes();
else
((RecipeListFragment) mHomeViewPagerAdapter.getRegisteredFragment(0)).filterRecipes(newText);
}
return false;
}
});
mSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
//mAppBarLayout.setExpanded(false, true);
mTabLayout.setVisibility(View.GONE);
}
@Override
public void onSearchViewClosed() {
//mAppBarLayout.setExpanded(true, true);
mTabLayout.setVisibility(View.VISIBLE);
((RecipeListFragment) mHomeViewPagerAdapter.getRegisteredFragment(0)).cancelFilterRecipes();
}
});
}
private void setupFab() {
mFabAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
SelectRecipeSourceDialogFragment dialog = SelectRecipeSourceDialogFragment.newInstance();
dialog.setListener(new SelectRecipeSourceDialogFragment.RecipeSourceSelectedListener() {
@Override
public void onSourceSelected(RecipeSource recipeSource) {
switch (recipeSource) {
case DATABASE:
Intent addRecipeIntent = new Intent(HomeActivity.this, AddEditRecipeActivity.class);
startActivity(addRecipeIntent);
break;
case ONLINE:
Intent goToSearchIntent = new Intent(HomeActivity.this, SearchOnlineRecipeActivity.class);
startActivity(goToSearchIntent);
break;
}
}
});
dialog.show(fm, "dialog");
}
});
}
// @Override
// protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) {
// ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// if (matches != null && matches.size() > 0) {
// String searchWrd = matches.get(0);
// if (!TextUtils.isEmpty(searchWrd)) {
// mSearchView.setQuery(searchWrd, false);
// return;
// super.onActivityResult(requestCode, resultCode, data);
@Override
protected void onDestroy() {
super.onDestroy();
presenter.detachView();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
MenuItem item = menu.findItem(R.id.menu_home_search);
mSearchView.setMenuItem(item);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu_home_about:
Intent goToAboutPage = new Intent(this, AboutActivity.class);
startActivity(goToAboutPage);
break;
case R.id.menu_home_settings:
Toast.makeText(this, "Settings screen under construction", Toast.LENGTH_SHORT).show();
break;
case R.id.menu_home_search:
Toast.makeText(this, "Search under construction", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
/* SearchViewListener interface implementation */
@Override
public void closeSearchView(){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mSearchView.closeSearch();
}
}, 500);
}
}
|
package com.lfkdsk.justel.lexer;
import com.lfkdsk.justel.utils.logger.Logger;
import org.junit.jupiter.api.Test;
import java.io.StringReader;
import static org.junit.jupiter.api.Assertions.*;
class JustLexerTest {
@Test
void testLexer() {
String lfkdsk = " 12 13.2222 \"lfkdsk\" lfkdsk 1200000000000 || &&";
// String lfkdsk = "|| &&";
JustLexer lexer = new JustLexer(new StringReader(lfkdsk));
Logger.init("logger test");
Logger.d(lexer.read().toString());
Logger.d(lexer.read().toString());
Logger.d(lexer.read().toString());
Logger.d(lexer.read().toString());
Logger.d(lexer.read().toString());
Logger.d(lexer.read().toString());
Logger.d(lexer.read().toString());
}
}
|
package com.messners.gitlab.api;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.messners.gitlab.api.models.Branch;
import com.messners.gitlab.api.models.Project;
public class TestGitLabApi {
// The following needs to be set to your test repository
private static final String TEST_PROJECT_NAME;
private static final String TEST_NAMESPACE;
private static final String TEST_HOST_URL;
private static final String TEST_PRIVATE_TOKEN;
static {
TEST_NAMESPACE = System.getProperty("TEST_NAMESPACE");
TEST_PROJECT_NAME = System.getProperty("TEST_PROJECT_NAME");
TEST_HOST_URL = System.getProperty("TEST_HOST_URL");
TEST_PRIVATE_TOKEN = System.getProperty("TEST_PRIVATE_TOKEN");
}
private static final String TEST_BRANCH_NAME = "feature/test_branch";
private static GitLabApi gitLabApi;
public TestGitLabApi() {
super();
}
@BeforeClass
public static void setup() {
String problems = "";
if (TEST_NAMESPACE == null || TEST_NAMESPACE.trim().length() == 0) {
problems += "TEST_NAMESPACE cannot be empty\n";
}
if (TEST_PROJECT_NAME == null || TEST_PROJECT_NAME.trim().length() == 0) {
problems += "TEST_PROJECT_NAME cannot be empty\n";
}
if (TEST_HOST_URL == null || TEST_HOST_URL.trim().length() == 0) {
problems += "TEST_HOST_URL cannot be empty\n";
}
if (TEST_PRIVATE_TOKEN == null || TEST_PRIVATE_TOKEN.trim().length() == 0) {
problems += "TEST_PRIVATE_TOKEN cannot be empty\n";
}
if (problems.isEmpty()) {
gitLabApi = new GitLabApi(TEST_HOST_URL, TEST_PRIVATE_TOKEN);
} else {
System.err.print(problems);
}
}
@AfterClass
public static void teardown() throws GitLabApiException {
if (gitLabApi != null) {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
gitLabApi.getRepositoryApi().deleteBranch(project.getId(), TEST_BRANCH_NAME);
}
}
@Before
public void beforeMethod() {
assumeTrue(gitLabApi != null);
}
@Test
public void testProjects() throws GitLabApiException {
List<Project> projects = gitLabApi.getProjectApi().getProjects();
assertTrue(projects != null);
}
@Test
public void testOwnedProjects() throws GitLabApiException {
List<Project> projects = gitLabApi.getProjectApi().getOwnedProjects();
assertTrue(projects != null);
}
@Test
public void testCreateBranch() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
Branch branch = gitLabApi.getRepositoryApi().createBranch(project.getId(), TEST_BRANCH_NAME, "master");
assertNotNull(branch);
}
}
|
package org.openlmis.core.presenter;
import com.google.inject.AbstractModule;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import org.openlmis.core.LMISApp;
import org.openlmis.core.LMISTestApp;
import org.openlmis.core.LMISTestRunner;
import org.openlmis.core.R;
import org.openlmis.core.exceptions.LMISException;
import org.openlmis.core.exceptions.NoFacilityForUserException;
import org.openlmis.core.manager.UserInfoMgr;
import org.openlmis.core.model.User;
import org.openlmis.core.model.repository.UserRepository;
import org.openlmis.core.model.repository.UserRepository.NewCallback;
import org.openlmis.core.network.model.SyncBackProductsResponse;
import org.openlmis.core.service.SyncManager;
import org.openlmis.core.service.SyncSubscriber;
import org.openlmis.core.view.activity.LoginActivity;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowToast;
import roboguice.RoboGuice;
import rx.Observer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(LMISTestRunner.class)
public class LoginPresenterTest {
UserRepository userRepository;
LoginActivity mockActivity;
LoginPresenter presenter;
SyncBackProductsResponse mockSyncBackProductsResponse;
SyncManager syncManager;
@Captor
private ArgumentCaptor<NewCallback<User>> loginCB;
@Captor
private ArgumentCaptor<Observer<Void>> getProductsCB;
private LMISTestApp appInject;
private SyncSubscriber<Void> syncProductSubscriber;
private SyncSubscriber<Void> syncRequisitionDataSubscriber;
@Before
public void setup() {
appInject = (LMISTestApp) RuntimeEnvironment.application;
userRepository = mock(UserRepository.class);
mockActivity = mock(LoginActivity.class);
mockSyncBackProductsResponse = mock(SyncBackProductsResponse.class);
syncManager = mock(SyncManager.class);
RoboGuice.overrideApplicationInjector(RuntimeEnvironment.application, new MyTestModule());
MockitoAnnotations.initMocks(this);
presenter = RoboGuice.getInjector(RuntimeEnvironment.application).getInstance(LoginPresenter.class);
presenter.attachView(mockActivity);
syncProductSubscriber = presenter.getSyncProductSubscriber();
syncRequisitionDataSubscriber = presenter.getSyncRequisitionDataSubscriber();
}
@After
public void teardown() {
RoboGuice.Util.reset();
}
@Test
public void shouldSaveUserToLocalDBWhenSuccess() throws InterruptedException {
appInject.setNetworkConnection(true);
presenter.startLogin("user", "password");
verify(mockActivity).loading();
verify(userRepository).authorizeUser(any(User.class), loginCB.capture());
loginCB.getValue().success(new User("user", "password"));
verify(userRepository).save(any(User.class));
}
@Test
public void shouldCreateSyncAccountWhenLoginSuccess() {
appInject.setNetworkConnection(true);
when(mockActivity.hasGetProducts()).thenReturn(false);
presenter.startLogin("user", "password");
User user = new User("user", "password");
verify(userRepository).authorizeUser(any(User.class), loginCB.capture());
loginCB.getValue().success(user);
verify(syncManager).createSyncAccount(user);
verify(syncManager).kickOff();
}
@Test
public void shouldSaveUserInfoWhenLoginSuccess() {
appInject.setNetworkConnection(true);
when(mockActivity.hasGetProducts()).thenReturn(false);
presenter.startLogin("user", "password");
User user = new User("user", "password");
verify(userRepository).authorizeUser(any(User.class), loginCB.capture());
loginCB.getValue().success(user);
verify(userRepository).save(user);
assertThat(UserInfoMgr.getInstance().getUser()).isEqualTo(user);
verify(mockActivity).clearErrorAlerts();
}
@Test
public void shouldGetProductsWhenLoginSuccessFromNet() {
appInject.setNetworkConnection(true);
when(mockActivity.hasGetProducts()).thenReturn(false);
presenter.startLogin("user", "password");
verify(userRepository).authorizeUser(any(User.class), loginCB.capture());
loginCB.getValue().success(new User("user", "password"));
verify(syncManager).syncProductsWithProgramAsync(getProductsCB.capture());
getProductsCB.getValue().onCompleted();
}
@Test
public void shouldGoToInventoryPageIfGetProductsSuccess() throws InterruptedException {
when(mockActivity.needInitInventory()).thenReturn(true);
appInject.setNetworkConnection(true);
when(mockActivity.hasGetProducts()).thenReturn(false);
presenter.startLogin("user", "password");
verify(userRepository).authorizeUser(any(User.class), loginCB.capture());
loginCB.getValue().success(new User("user", "password"));
verify(syncManager).syncProductsWithProgramAsync(getProductsCB.capture());
getProductsCB.getValue().onCompleted();
if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_sync_back_rnr_186)){
verify(mockActivity).loaded();
}else {
verify(mockActivity, times(2)).loaded();
}
}
@Test
public void shouldDoOfflineLoginWhenNoConnectionAndHasLocalCacheAndSynedData() {
appInject.setNetworkConnection(false);
when(userRepository.getUserFromLocal(any(User.class))).thenReturn(new User("user", "password"));
when(mockActivity.needInitInventory()).thenReturn(false);
when(mockActivity.hasGetProducts()).thenReturn(true);
when(mockActivity.isStockDataSynced()).thenReturn(true);
when(mockActivity.isRequisitionDataSynced()).thenReturn(true);
presenter.startLogin("user", "password");
verify(userRepository).getUserFromLocal(any(User.class));
assertThat(UserInfoMgr.getInstance().getUser().getUsername()).isEqualTo("user");
verify(mockActivity).loaded();
verify(mockActivity).goToHomePage();
}
@Test
public void shouldShowMessageWhenNoConnectionAndHasNotGetProducts() {
appInject.setNetworkConnection(false);
when(userRepository.getUserFromLocal(any(User.class))).thenReturn(new User("user", "password"));
when(mockActivity.needInitInventory()).thenReturn(false);
when(mockActivity.hasGetProducts()).thenReturn(false);
presenter.startLogin("user", "password");
verify(userRepository).getUserFromLocal(any(User.class));
assertThat(UserInfoMgr.getInstance().getUser().getUsername()).isEqualTo("user");
verify(mockActivity).loaded();
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(RuntimeEnvironment.application.getString(R.string.msg_sync_products_list_failed));
}
@Test
public void shouldShowLoginFailErrorMsgWhenNoConnectionAndNoLocalCache() {
appInject.setNetworkConnection(false);
when(userRepository.getUserFromLocal(any(User.class))).thenReturn(null);
presenter.startLogin("user", "password");
verify(userRepository).getUserFromLocal(any(User.class));
verify(mockActivity).loaded();
verify(mockActivity).showInvalidAlert();
verify(mockActivity).clearPassword();
}
@Test
public void shouldCallGetProductOnlyOnceWhenClickLoginButtonTwice() {
appInject.setNetworkConnection(true);
when(mockActivity.hasGetProducts()).thenReturn(false);
presenter.startLogin("user", "password");
presenter.startLogin("user", "password");
verify(userRepository, times(2)).authorizeUser(any(User.class), loginCB.capture());
loginCB.getValue().success(new User("user", "password"));
verify(syncManager, times(1)).syncProductsWithProgramAsync(any(Observer.class));
}
@Test
public void shouldShowUserNameEmptyErrorMessage() {
presenter.startLogin("", "password1");
verify(mockActivity).showUserNameEmpty();
}
@Test
public void shouldShowPasswordEmptyErrorMessage() {
presenter.startLogin("user", "");
verify(mockActivity).showPasswordEmpty();
}
@Test
public void shouldSyncDataBackWhenProductSyncCompleted() {
if (!LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_sync_back_rnr_186)) {
return;
}
syncProductSubscriber.onCompleted();
verify(mockActivity).setHasGetProducts(true);
verify(mockActivity).loading(RuntimeEnvironment.application.getString(R.string.msg_sync_requisition_data));
verify(syncManager).syncBackRnr(any(rx.Observer.class));
}
@Test
public void shouldShowErrorMessageWhenProductSyncFailed() {
syncProductSubscriber.onError(new LMISException("Products save failed"));
String message = RuntimeEnvironment.application.getString(R.string.msg_save_products_failed);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(message);
verify(mockActivity).loaded();
syncProductSubscriber.onError(new NoFacilityForUserException("No Facility"));
message = RuntimeEnvironment.application.getString(R.string.msg_user_not_facility);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(message);
syncProductSubscriber.onError(new Exception("Sync products failed"));
message = RuntimeEnvironment.application.getString(R.string.msg_sync_products_list_failed);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(message);
}
@Test
public void shouldGoToInitInventoryWhenDataBackCompleted() {
when(mockActivity.needInitInventory()).thenReturn(true);
syncRequisitionDataSubscriber.onCompleted();
verify(mockActivity).loaded();
verify(mockActivity).goToInitInventory();
}
@Test
public void shouldLoginFailedWhenSyncProductSucceedAndSyncRequisitionFailed() {
when(mockActivity.needInitInventory()).thenReturn(true);
syncRequisitionDataSubscriber.onError(new Exception("error"));
verify(mockActivity, times(1)).loaded();
verify(mockActivity, times(0)).goToInitInventory();
verify(mockActivity, times(0)).goToHomePage();
}
@Test
public void shouldNotGoToNextPageWhenSyncProductFailed() {
syncProductSubscriber.onError(new Exception("error"));
verify(mockActivity, times(1)).loaded();
verify(mockActivity, times(0)).goToInitInventory();
verify(mockActivity, times(0)).goToHomePage();
}
@Test
public void shouldSyncRequisitionDataIfProductSyncExistButRequisitionDataNonExist() {
if (!LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_sync_back_rnr_186)) {
return;
}
when(mockActivity.hasGetProducts()).thenReturn(true);
when(mockActivity.isRequisitionDataSynced()).thenReturn(false);
presenter.onLoginSuccess(any(User.class));
verify(mockActivity).loading(RuntimeEnvironment.application.getString(R.string.msg_sync_requisition_data));
verify(syncManager).syncBackRnr(syncRequisitionDataSubscriber);
}
@Test
public void shouldSetRequisitionDataSharedPreference() {
syncRequisitionDataSubscriber.onCompleted();
verify(mockActivity).setRequisitionDataSynced(true);
}
public class MyTestModule extends AbstractModule {
@Override
protected void configure() {
bind(UserRepository.class).toInstance(userRepository);
bind(SyncManager.class).toInstance(syncManager);
}
}
}
|
package com.thankjava.wqq.test.qq;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thankjava.wqq.SmartQQClient;
import com.thankjava.wqq.WQQClient;
import com.thankjava.wqq.entity.msg.PollMsg;
import com.thankjava.wqq.extend.CallBackListener;
import com.thankjava.wqq.extend.ListenerAction;
import com.thankjava.wqq.extend.NotifyListener;
public class TestSmartQQ {
private static final Logger logger = LoggerFactory.getLogger(TestSmartQQ.class);
// SmartQQClient
// NotifyListener SmartQQClient
static final SmartQQClient smartQQClient = new WQQClient(new NotifyListener() {
@Override
public void hander(PollMsg pollMsg) {
// NotifyListener.hander,NotifyHander.hander
// NotifyHander
notifyHander.hander(pollMsg);
}
});
static final NotifyHander notifyHander = new NotifyHander(smartQQClient);
public static void main(String[] args) {
logger.debug("smartqq");
smartQQClient.login(true, new CallBackListener() {
// login CallBackListener
// byte[] ListenerAction.data
@Override
public void onListener(ListenerAction listenerAction) {
try {
// byte[]iopng
// log/qrcode.png
ImageIO.write(
(BufferedImage)listenerAction.data, "png",
new File("./log/qrcode.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
// QQ,smartqq-agreement-core
// SmartQQClient.sendMsg
// smartqq-agreement-core||NotifyListener.hander
}
}
|
package org.commcare.utils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.util.List;
import java.util.ArrayList;
import org.commcare.CommCareApplication;
import org.commcare.android.CommCareTestRunner;
import org.commcare.android.util.TestUtils;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.InFormCacheableExpr;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.parser.XPathSyntaxException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@Config(application = CommCareApplication.class)
@RunWith(CommCareTestRunner.class)
public class FormCacheEligibilityTester {
private static final String PATH_TO_CCZ_RESOURCES = "/commcare-apps/cache_eligibility_testing";
private static void categorizeAndPrintExpressions(String resourcePath) throws IOException {
List<XPathExpression> allExpressions = getXPathExpressions(resourcePath);
Map<XPathExpression, Integer> cacheable = new HashMap<>();
Map<XPathExpression, Integer> notCacheable = new HashMap<>();
FormInstance instance = new FormInstance(new TreeElement("data"));
EvaluationContext ec = TestUtils.getEvaluationContextWithoutSession(instance);
for (XPathExpression expr : allExpressions) {
boolean isCacheable = false;
try {
isCacheable = !InFormCacheableExpr.referencesMainFormInstance(expr, instance, ec) &&
!InFormCacheableExpr.containsUncacheableSubExpression(expr, ec);
} catch (Exception e) {
System.out.println("Error computing cacheability of expression: " + expr.toPrettyString());
}
if (isCacheable) {
int count = cacheable.containsKey(expr) ? cacheable.get(expr) : 0;
cacheable.put(expr, count+1);
} else {
int count = notCacheable.containsKey(expr) ? notCacheable.get(expr) : 0;
notCacheable.put(expr, count+1);
}
}
System.out.println();
System.out.println("# of cacheable expressions: " + cacheable.size());
for (XPathExpression expr : cacheable.keySet()) {
System.out.println(cacheable.get(expr) + ": " + expr.toPrettyString());
}
System.out.println();
System.out.println("# of un-cacheable expressions: " + notCacheable.size());
for (XPathExpression expr : notCacheable.keySet()) {
System.out.println(notCacheable.get(expr) + ": " + expr.toPrettyString());
}
}
private static List<XPathExpression> getXPathExpressions(String resourcePath) throws IOException {
InputStream is = System.class.getResourceAsStream(resourcePath);
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
List<XPathExpression> expressions = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
addExpressions(sanitize(line), expressions);
}
return expressions;
}
private static String sanitize(String formLine) {
return formLine.replace("<", "<")
.replace(">", ">")
.replace(""", "'");
}
private static void addExpressions(String line, List<XPathExpression> expressions) {
Pattern relevant = Pattern.compile("(?:relevant=)\"(.*?)(?:\")");
Pattern calculate = Pattern.compile("(?:calculate=)\"(.*?)(?:\")");
Matcher m = relevant.matcher(line);
String currentString = null;
try {
while (m.find()) {
currentString = m.group(1);
expressions.add(XPathParseTool.parseXPath(currentString));
}
m = calculate.matcher(line);
while (m.find()) {
currentString = m.group(1);
expressions.add(XPathParseTool.parseXPath(currentString));
}
} catch (XPathSyntaxException e) {
System.out.println("Error parsing string as XPathExpression: " + currentString);
}
}
private static List<String> getAllFormsToTest() {
URL path = System.class.getResource(PATH_TO_CCZ_RESOURCES);
File f = new File(path);
}
@Test //Keep this commented out for normal test runs because it will be slow and it's not a real test
public void run() {
try {
List<String> formPaths = getAllFormsToTest();
for (String path : formPaths) {
categorizeAndPrintExpressions(path);
}
} catch (IOException e) {
System.out.println("IO error with file");
e.printStackTrace();
}
}
// to avoid test file initialization error due to not having any runnable test methods
@Test
public void dummy() {
}
}
|
package edu.mayo.ve.VCFParser;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mongodb.*;
import com.mongodb.util.JSON;
import com.tinkerpop.pipes.util.Pipeline;
import edu.mayo.TypeAhead.TypeAhead;
import edu.mayo.concurrency.exceptions.ProcessTerminatedException;
import edu.mayo.pipes.PrintPipe;
import edu.mayo.pipes.UNIX.CatPipe;
import edu.mayo.util.Tokens;
import edu.mayo.ve.resources.*;
import edu.mayo.util.MongoConnection;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.*;
public class VCFParserITCase {
boolean reporting = false;
List<String> known = Arrays.asList(
"{\"CHROM\":\"chr1\",\"POS\":\"13656\",\"ID\":\".\",\"REF\":\"CAG\",\"ALT\":\"C\",\"QUAL\":\".\",\"FILTER\":\"PASS\",\"INFO\":{\"AC\":[2],\"AF\":[0.5],\"AN\":4,\"Cases_AC\":\"2\",\"Cases_AF\":\"0.500\",\"Cases_AN\":\"4\",\"FS\":0.0,\"Genotyper\":\"Pindel\",\"Group\":\"Cases\",\"HRun\":0,\"SNPEFF_EFFECT\":\"DOWNSTREAM\",\"SNPEFF_FUNCTIONAL_CLASS\":\"NONE\",\"SNPEFF_GENE_NAME\":\"WASH7P\",\"SNPEFF_IMPACT\":\"MODIFIER\",\"SNPEFF_TRANSCRIPT_ID\":\"NR_024540\",\"set\":\"variant\"},\"_ident\":\".\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"CAG\",\"_altAlleles\":[\"C\"],\"_minBP\":13656,\"_maxBP\":13658,\"samples\":[{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_175\"},{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_365\"}],\"FORMAT\":{\"max\":{\"AD\":3.0},\"min\":{\"AD\":3.0},\"GenotypePostitiveCount\":2,\"GenotypePositiveList\":[\"s_Mayo_TN_CC_175\",\"s_Mayo_TN_CC_365\"],\"HeterozygousList\":[\"s_Mayo_TN_CC_175\",\"s_Mayo_TN_CC_365\"],\"HomozygousList\":[]},\"CUSTOM\":{\"max\":{\"AD\":4.9E-324},\"min\":{\"AD\":1.7976931348623157E308}}}"
//"{\"CHROM\":\"chr1\",\"POS\":\"13656\",\"ID\":\".\",\"REF\":\"CAG\",\"ALT\":\"C\",\"QUAL\":\".\",\"FILTER\":\"PASS\",\"INFO\":{\"AC\":[2],\"AF\":[0.5],\"AN\":4,\"Cases_AC\":\"2\",\"Cases_AF\":\"0.500\",\"Cases_AN\":\"4\",\"FS\":0.0,\"Genotyper\":\"Pindel\",\"Group\":\"Cases\",\"HRun\":0,\"SNPEFF_EFFECT\":\"DOWNSTREAM\",\"SNPEFF_FUNCTIONAL_CLASS\":\"NONE\",\"SNPEFF_GENE_NAME\":\"WASH7P\",\"SNPEFF_IMPACT\":\"MODIFIER\",\"SNPEFF_TRANSCRIPT_ID\":\"NR_024540\",\"set\":\"variant\"},\"_ident\":\".\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"CAG\",\"_altAlleles\":[\"C\"],\"_minBP\":13656,\"_maxBP\":13658,\"samples\":[{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_175\"},{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_365\"}],\"FORMAT\":{\"max\":{\"AD\":3.0},\"min\":{\"AD\":3.0},\"GenotypePostitiveCount\":2,\"GenotypePositiveList\":[\"s_Mayo_TN_CC_175\",\"s_Mayo_TN_CC_365\"],\"HeterozygousList\":[\"s_Mayo_TN_CC_175\",\"s_Mayo_TN_CC_365\"],\"HomozygousList\":[]}}"
//"{\"CHROM\":\"chr1\",\"POS\":\"13656\",\"ID\":\".\",\"REF\":\"CAG\",\"ALT\":\"C\",\"QUAL\":\".\",\"FILTER\":\"PASS\",\"INFO\":{\"AC\":[2],\"AF\":[0.5],\"AN\":4,\"Cases_AC\":\"2\",\"Cases_AF\":\"0.500\",\"Cases_AN\":\"4\",\"FS\":0.0,\"Genotyper\":\"Pindel\",\"Group\":\"Cases\",\"HRun\":0,\"SNPEFF_EFFECT\":\"DOWNSTREAM\",\"SNPEFF_FUNCTIONAL_CLASS\":\"NONE\",\"SNPEFF_GENE_NAME\":\"WASH7P\",\"SNPEFF_IMPACT\":\"MODIFIER\",\"SNPEFF_TRANSCRIPT_ID\":\"NR_024540\",\"set\":\"variant\"},\"_ident\":\".\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"CAG\",\"_altAlleles\":[\"C\"],\"_minBP\":13656,\"_maxBP\":13658,\"samples\":[{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_175\"},{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_365\"}],\"FORMAT\":{\"max\":{\"AD\":3.0},\"min\":{\"AD\":3.0},\"GenotypePostitiveCount\":2,\"GenotypePositiveList\":[\"s_Mayo_TN_CC_175\",\"s_Mayo_TN_CC_365\"]}}"
//"{\"CHROM\":\"chr1\",\"POS\":\"13656\",\"ID\":\".\",\"REF\":\"CAG\",\"ALT\":\"C\",\"QUAL\":\".\",\"FILTER\":\"PASS\",\"INFO\":{\"AC\":[2],\"AF\":[0.5],\"AN\":4,\"Cases_AC\":\"2\",\"Cases_AF\":\"0.500\",\"Cases_AN\":\"4\",\"FS\":0.0,\"Genotyper\":\"Pindel\",\"Group\":\"Cases\",\"HRun\":0,\"SNPEFF_EFFECT\":\"DOWNSTREAM\",\"SNPEFF_FUNCTIONAL_CLASS\":\"NONE\",\"SNPEFF_GENE_NAME\":\"WASH7P\",\"SNPEFF_IMPACT\":\"MODIFIER\",\"SNPEFF_TRANSCRIPT_ID\":\"NR_024540\",\"set\":\"variant\"},\"_ident\":\".\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"CAG\",\"_altAlleles\":[\"C\"],\"_minBP\":13656,\"_maxBP\":13658,\"samples\":[{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_175\"},{\"GT\":\"0/1\",\"AD\":3.0,\"GenotypePositive\":1,\"sampleID\":\"s_Mayo_TN_CC_365\"}],\"GenotypePostitiveCount\":2,\"GenotypePositiveList\":[\"s_Mayo_TN_CC_175\",\"s_Mayo_TN_CC_365\"],\"PLIntervalMin\":1.7976931348623157E308,\"PLIntervalMax\":-2147483648,\"PLAverage\":NaN,\"ADIntervalMin\":1.7976931348623157E308,\"ADIntervalMax\":-2147483648,\"ADAverage\":NaN}"
);
List<String> metadata = Arrays.asList(
"{\"HEADER\":{\"FORMAT\":{\"PL\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\",\"EntryType\":\"FORMAT\"},\"AD\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"Allelic depths for the ref and alt alleles in the order listed\",\"EntryType\":\"FORMAT\"},\"GT\":{\"number\":1,\"type\":\"String\",\"Description\":\"Genotype\",\"EntryType\":\"FORMAT\"},\"GQ\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Genotype Quality\",\"EntryType\":\"FORMAT\"},\"DP\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Approximate read depth (reads with MQ=255 or with bad mates are filtered)\",\"EntryType\":\"FORMAT\"},\"MLPSAF\":{\"number\":\".\",\"type\":\"Float\",\"Description\":\"Maximum likelihood expectation (MLE) for the alternate allele fraction, in the same order as listed, for each individual sample\",\"EntryType\":\"FORMAT\"},\"DP4\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"The number of high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\",\"EntryType\":\"FORMAT\"},\"MLPSAC\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"Maximum likelihood expectation (MLE) for the alternate allele count, in the same order as listed, for each individual sample\",\"EntryType\":\"FORMAT\"},\"GL\":{\"number\":3,\"type\":\"Float\",\"Description\":\"Likelihoods for RR,RA,AA genotypes (R=ref,A=alt)\",\"EntryType\":\"FORMAT\"},\"SP\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Phred-scaled strand bias P-value\",\"EntryType\":\"FORMAT\"}},\"INFO\":{\"Controls_AN\":{\"number\":1,\"type\":\"String\",\"Description\":\"Original AN for Controls\",\"EntryType\":\"INFO\"},\"SNPEFF_AMINO_ACID_LENGTH\":{\"number\":1,\"type\":\"String\",\"Description\":\"Length of protein in amino acids (actually, transcription length divided by 3)\",\"EntryType\":\"INFO\"},\"SNPEFF_TRANSCRIPT_ID\":{\"number\":1,\"type\":\"String\",\"Description\":\"Transcript ID for the highest-impact effect resulting from the current variant\",\"EntryType\":\"INFO\"},\"UGT\":{\"number\":1,\"type\":\"String\",\"Description\":\"The most probable unconstrained genotype configuration in the trio\",\"EntryType\":\"INFO\"},\"InbreedingCoeff\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Inbreeding coefficient as estimated from the genotype likelihoods per-sample when compared against the Hardy-Weinberg expectation\",\"EntryType\":\"INFO\"},\"Group\":{\"number\":1,\"type\":\"String\",\"Description\":\"Source VCF for the merged record in CombineVariants\",\"EntryType\":\"INFO\"},\"SNPEFF_CODON_CHANGE\":{\"number\":1,\"type\":\"String\",\"Description\":\"Old/New codon for the highest-impact effect resulting from the current variant\",\"EntryType\":\"INFO\"},\"AF1\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Max-likelihood estimate of the first ALT allele frequency (assuming HWE)\",\"EntryType\":\"INFO\"},\"Cases_AF\":{\"number\":1,\"type\":\"String\",\"Description\":\"Original AF for Cases\",\"EntryType\":\"INFO\"},\"ReadPosRankSum\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Z-score from Wilcoxon rank sum test of Alt vs. Ref read position bias\",\"EntryType\":\"INFO\"},\"DP\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Approximate read depth; some reads may have been filtered\",\"EntryType\":\"INFO\"},\"DS\":{\"number\":0,\"type\":\"Flag\",\"Description\":\"Were any of the samples downsampled?\",\"EntryType\":\"INFO\"},\"Controls_AF\":{\"number\":1,\"type\":\"String\",\"Description\":\"Original AF for Controls\",\"EntryType\":\"INFO\"},\"Cases_AN\":{\"number\":1,\"type\":\"String\",\"Description\":\"Original AN for Cases\",\"EntryType\":\"INFO\"},\"Controls_AC\":{\"number\":1,\"type\":\"String\",\"Description\":\"Original AC for Controls\",\"EntryType\":\"INFO\"},\"STR\":{\"number\":0,\"type\":\"Flag\",\"Description\":\"Variant is a short tandem repeat\",\"EntryType\":\"INFO\"},\"BaseQRankSum\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Z-score from Wilcoxon rank sum test of Alt Vs. Ref base qualities\",\"EntryType\":\"INFO\"},\"HWE\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Chi^2 based HWE test P-value based on G3\",\"EntryType\":\"INFO\"},\"QD\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Variant Confidence/Quality by Depth\",\"EntryType\":\"INFO\"},\"MQ\":{\"number\":1,\"type\":\"Float\",\"Description\":\"RMS Mapping Quality\",\"EntryType\":\"INFO\"},\"PC2\":{\"number\":2,\"type\":\"Integer\",\"Description\":\"Phred probability of the nonRef allele frequency in group1 samples being larger (,smaller) than in group2.\",\"EntryType\":\"INFO\"},\"CGT\":{\"number\":1,\"type\":\"String\",\"Description\":\"The most probable constrained genotype configuration in the trio\",\"EntryType\":\"INFO\"},\"AC\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"Allele count in genotypes, for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"HRun\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Largest Contiguous Homopolymer Run of Variant Allele In Either Direction\",\"EntryType\":\"INFO\"},\"QCHI2\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Phred scaled PCHI2.\",\"EntryType\":\"INFO\"},\"SNPEFF_IMPACT\":{\"number\":1,\"type\":\"String\",\"Description\":\"Impact of the highest-impact effect resulting from the current variant [MODIFIER, LOW, MODERATE, HIGH]\",\"EntryType\":\"INFO\"},\"Dels\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Fraction of Reads Containing Spanning Deletions\",\"EntryType\":\"INFO\"},\"INDEL\":{\"number\":0,\"type\":\"Flag\",\"Description\":\"Indicates that the variant is an INDEL.\",\"EntryType\":\"INFO\"},\"PR\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"# permutations yielding a smaller PCHI2.\",\"EntryType\":\"INFO\"},\"AF\":{\"number\":\".\",\"type\":\"Float\",\"Description\":\"Allele Frequency, for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"DP4\":{\"number\":4,\"type\":\"Integer\",\"Description\":\"# high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\",\"EntryType\":\"INFO\"},\"SVLEN\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Difference in length between REF and ALT alleles\",\"EntryType\":\"INFO\"},\"AN\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Total number of alleles in called genotypes\",\"EntryType\":\"INFO\"},\"CLR\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Log ratio of genotype likelihoods with and without the constraint\",\"EntryType\":\"INFO\"},\"HaplotypeScore\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Consistency of the site with at most two segregating haplotypes\",\"EntryType\":\"INFO\"},\"PCHI2\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Posterior weighted chi^2 P-value for testing the association between group1 and group2 samples.\",\"EntryType\":\"INFO\"},\"set\":{\"number\":1,\"type\":\"String\",\"Description\":\"Source VCF for the merged record in CombineVariants\",\"EntryType\":\"INFO\"},\"Genotyper\":{\"number\":1,\"type\":\"String\",\"Description\":\"Source VCF for the merged record in CombineVariants\",\"EntryType\":\"INFO\"},\"SNPEFF_EXON_ID\":{\"number\":1,\"type\":\"String\",\"Description\":\"Exon ID for the highest-impact effect resulting from the current variant\",\"EntryType\":\"INFO\"},\"MLEAC\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"Maximum likelihood expectation (MLE) for the allele counts (not necessarily the same as the AC), for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"SNPEFF_GENE_NAME\":{\"number\":1,\"type\":\"String\",\"Description\":\"Gene name for the highest-impact effect resulting from the current variant\",\"EntryType\":\"INFO\"},\"MLEAF\":{\"number\":\".\",\"type\":\"Float\",\"Description\":\"Maximum likelihood expectation (MLE) for the allele frequency (not necessarily the same as the AF), for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"FS\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Phred-scaled p-value using Fisher's exact test to detect strand bias\",\"EntryType\":\"INFO\"},\"G3\":{\"number\":3,\"type\":\"Float\",\"Description\":\"ML estimate of genotype frequencies\",\"EntryType\":\"INFO\"},\"FQ\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Phred probability of all samples being the same\",\"EntryType\":\"INFO\"},\"SNPEFF_AMINO_ACID_CHANGE\":{\"number\":1,\"type\":\"String\",\"Description\":\"Old/New amino acid for the highest-impact effect resulting from the current variant (in HGVS style)\",\"EntryType\":\"INFO\"},\"GenotyperControls\":{\"number\":1,\"type\":\"String\",\"Description\":\"Source VCF for the merged record in CombineVariants\",\"EntryType\":\"INFO\"},\"VDB\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Variant Distance Bias\",\"EntryType\":\"INFO\"},\"SNPEFF_FUNCTIONAL_CLASS\":{\"number\":1,\"type\":\"String\",\"Description\":\"Functional class of the highest-impact effect resulting from the current variant: [NONE, SILENT, MISSENSE, NONSENSE]\",\"EntryType\":\"INFO\"},\"SNPEFF_EFFECT\":{\"number\":1,\"type\":\"String\",\"Description\":\"The highest-impact effect resulting from the current variant (or one of the highest-impact effects, if there is a tie)\",\"EntryType\":\"INFO\"},\"Cases_AC\":{\"number\":1,\"type\":\"String\",\"Description\":\"Original AC for Cases\",\"EntryType\":\"INFO\"},\"DB\":{\"number\":0,\"type\":\"Flag\",\"Description\":\"dbSNP Membership\",\"EntryType\":\"INFO\"},\"SVTYPE\":{\"number\":1,\"type\":\"String\",\"Description\":\"Type of structural variant\",\"EntryType\":\"INFO\"},\"SNPEFF_GENE_BIOTYPE\":{\"number\":1,\"type\":\"String\",\"Description\":\"Gene biotype for the highest-impact effect resulting from the current variant\",\"EntryType\":\"INFO\"},\"NTLEN\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"Number of bases inserted in place of deleted code\",\"EntryType\":\"INFO\"},\"HOMSEQ\":{\"number\":\".\",\"type\":\"String\",\"Description\":\"Sequence of base pair identical micro-homology at event breakpoints\",\"EntryType\":\"INFO\"},\"MQRankSum\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Z-score From Wilcoxon rank sum test of Alt vs. Ref read mapping qualities\",\"EntryType\":\"INFO\"},\"RU\":{\"number\":1,\"type\":\"String\",\"Description\":\"Tandem repeat unit (bases)\",\"EntryType\":\"INFO\"},\"HOMLEN\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Length of base pair identical micro-homology at event breakpoints\",\"EntryType\":\"INFO\"},\"RPA\":{\"number\":\".\",\"type\":\"Integer\",\"Description\":\"Number of times tandem repeat unit is repeated, for each allele (including reference)\",\"EntryType\":\"INFO\"},\"END\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"End position of the variant described in this record\",\"EntryType\":\"INFO\"},\"MQ0\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Total Mapping Quality Zero Reads\",\"EntryType\":\"INFO\"},\"AC1\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Max-likelihood estimate of the first ALT allele count (no HWE assumption)\",\"EntryType\":\"INFO\"},\"PV4\":{\"number\":4,\"type\":\"Float\",\"Description\":\"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\",\"EntryType\":\"INFO\"}}},\"FORMAT\":{\"PL\":1,\"AD\":1,\"GT\":1,\"GQ\":1},\"SAMPLES\":{\"s_Mayo_TN_CC_254\":189,\"s_Mayo_TN_CC_255\":190,\"s_Mayo_TN_CC_252\":187,\"s_Mayo_TN_CC_253\":188,\"s_Mayo_TN_CC_250\":185,\"s_Mayo_TN_CC_251\":186,\"s_Mayo_TN_CC_530\":493,\"s_Mayo_TN_CC_537\":500,\"s_Mayo_TN_CC_538\":501,\"s_Mayo_TN_CC_535\":498,\"s_Mayo_TN_CC_536\":499,\"s_Mayo_TN_CC_533\":496,\"s_Mayo_TN_CC_534\":497,\"s_Mayo_TN_CC_531\":494,\"s_Mayo_TN_CC_532\":495,\"s_Mayo_TN_CC_259\":194,\"s_Mayo_TN_CC_258\":193,\"s_Mayo_TN_CC_257\":192,\"s_Mayo_TN_CC_539\":502,\"s_Mayo_TN_CC_256\":191,\"s_Mayo_TN_CC_241\":175,\"s_Mayo_TN_CC_242\":176,\"s_Mayo_TN_CC_243\":177,\"s_Mayo_TN_CC_244\":178,\"s_Mayo_TN_CC_240\":174,\"s_Mayo_TN_CC_524\":486,\"s_Mayo_TN_CC_525\":487,\"s_Mayo_TN_CC_526\":488,\"s_Mayo_TN_CC_527\":489,\"s_Mayo_TN_CC_520\":482,\"s_Mayo_TN_CC_521\":483,\"s_Mayo_TN_CC_522\":484,\"s_Mayo_TN_CC_523\":485,\"s_Mayo_TN_CC_249\":183,\"s_Mayo_TN_CC_246\":180,\"s_Mayo_TN_CC_528\":490,\"s_Mayo_TN_CC_245\":179,\"s_Mayo_TN_CC_529\":491,\"s_Mayo_TN_CC_248\":182,\"s_Mayo_TN_CC_247\":181,\"s_Mayo_TN_CC_232\":165,\"s_Mayo_TN_CC_233\":166,\"s_Mayo_TN_CC_230\":163,\"s_Mayo_TN_CC_231\":164,\"s_Mayo_TN_CC_798\":787,\"s_Mayo_TN_CC_797\":786,\"s_Mayo_TN_CC_796\":785,\"s_Mayo_TN_CC_795\":784,\"s_Mayo_TN_CC_799\":788,\"s_Mayo_TN_CC_511\":472,\"s_Mayo_TN_CC_790\":779,\"s_Mayo_TN_CC_512\":473,\"s_Mayo_TN_CC_510\":471,\"s_Mayo_TN_CC_793\":782,\"s_Mayo_TN_CC_515\":476,\"s_Mayo_TN_CC_794\":783,\"s_Mayo_TN_CC_516\":477,\"s_Mayo_TN_CC_791\":780,\"s_Mayo_TN_CC_513\":474,\"s_Mayo_TN_CC_792\":781,\"s_Mayo_TN_CC_514\":475,\"s_Mayo_TN_CC_237\":170,\"s_Mayo_TN_CC_519\":480,\"s_Mayo_TN_CC_236\":169,\"s_Mayo_TN_CC_235\":168,\"s_Mayo_TN_CC_517\":478,\"s_Mayo_TN_CC_234\":167,\"s_Mayo_TN_CC_518\":479,\"s_Mayo_TN_CC_239\":172,\"s_Mayo_TN_CC_238\":171,\"s_Mayo_TN_CC_220\":152,\"s_Mayo_TN_CC_221\":153,\"s_Mayo_TN_CC_222\":154,\"s_Mayo_TN_CC_785\":773,\"s_Mayo_TN_CC_784\":772,\"s_Mayo_TN_CC_787\":775,\"s_Mayo_TN_CC_786\":774,\"s_Mayo_TN_CC_789\":777,\"s_Mayo_TN_CC_788\":776,\"s_Mayo_TN_CC_500\":460,\"s_Mayo_TN_CC_501\":461,\"s_Mayo_TN_CC_502\":462,\"s_Mayo_TN_CC_780\":768,\"s_Mayo_TN_CC_503\":463,\"s_Mayo_TN_CC_781\":769,\"s_Mayo_TN_CC_504\":464,\"s_Mayo_TN_CC_782\":770,\"s_Mayo_TN_CC_505\":465,\"s_Mayo_TN_CC_783\":771,\"s_Mayo_TN_CC_224\":156,\"s_Mayo_TN_CC_506\":466,\"s_Mayo_TN_CC_223\":155,\"s_Mayo_TN_CC_507\":467,\"s_Mayo_TN_CC_226\":158,\"s_Mayo_TN_CC_508\":468,\"s_Mayo_TN_CC_225\":157,\"s_Mayo_TN_CC_509\":469,\"s_Mayo_TN_CC_228\":160,\"s_Mayo_TN_CC_227\":159,\"s_Mayo_TN_CC_229\":161,\"s_Mayo_TN_CC_291\":230,\"s_Mayo_TN_CC_573\":540,\"s_Mayo_TN_CC_779\":766,\"s_Mayo_TN_CC_290\":229,\"s_Mayo_TN_CC_574\":541,\"s_Mayo_TN_CC_571\":538,\"s_Mayo_TN_CC_777\":764,\"s_Mayo_TN_CC_572\":539,\"s_Mayo_TN_CC_778\":765,\"s_Mayo_TN_CC_775\":762,\"s_Mayo_TN_CC_570\":537,\"s_Mayo_TN_CC_776\":763,\"s_Mayo_TN_CC_773\":760,\"s_Mayo_TN_CC_774\":761,\"s_Mayo_TN_CC_299\":238,\"s_Mayo_TN_CC_298\":237,\"s_Mayo_TN_CC_297\":236,\"s_Mayo_TN_CC_296\":235,\"s_Mayo_TN_CC_295\":234,\"s_Mayo_TN_CC_294\":233,\"s_Mayo_TN_CC_293\":232,\"s_Mayo_TN_CC_292\":231,\"s_Mayo_TN_CC_772\":759,\"s_Mayo_TN_CC_771\":758,\"s_Mayo_TN_CC_770\":757,\"s_Mayo_TN_CC_579\":546,\"s_Mayo_TN_CC_578\":545,\"s_Mayo_TN_CC_577\":544,\"s_Mayo_TN_CC_576\":543,\"s_Mayo_TN_CC_575\":542,\"s_Mayo_TN_CC_560\":526,\"s_Mayo_TN_CC_766\":752,\"s_Mayo_TN_CC_561\":527,\"s_Mayo_TN_CC_767\":753,\"s_Mayo_TN_CC_280\":218,\"s_Mayo_TN_CC_562\":528,\"s_Mayo_TN_CC_768\":754,\"s_Mayo_TN_CC_563\":529,\"s_Mayo_TN_CC_769\":755,\"s_Mayo_TN_CC_762\":748,\"s_Mayo_TN_CC_763\":749,\"s_Mayo_TN_CC_764\":750,\"s_Mayo_TN_CC_765\":751,\"s_Mayo_TN_CC_286\":224,\"s_Mayo_TN_CC_285\":223,\"s_Mayo_TN_CC_288\":226,\"s_Mayo_TN_CC_287\":225,\"s_Mayo_TN_CC_282\":220,\"s_Mayo_TN_CC_281\":219,\"s_Mayo_TN_CC_284\":222,\"s_Mayo_TN_CC_283\":221,\"s_Mayo_TN_CC_289\":227,\"s_Mayo_TN_CC_569\":535,\"s_Mayo_TN_CC_568\":534,\"s_Mayo_TN_CC_761\":747,\"s_Mayo_TN_CC_760\":746,\"s_Mayo_TN_CC_565\":531,\"s_Mayo_TN_CC_564\":530,\"s_Mayo_TN_CC_567\":533,\"s_Mayo_TN_CC_566\":532,\"s_Mayo_TN_CC_753\":738,\"s_Mayo_TN_CC_754\":739,\"s_Mayo_TN_CC_751\":736,\"s_Mayo_TN_CC_752\":737,\"s_Mayo_TN_CC_551\":516,\"s_Mayo_TN_CC_757\":742,\"s_Mayo_TN_CC_552\":517,\"s_Mayo_TN_CC_758\":743,\"s_Mayo_TN_CC_755\":740,\"s_Mayo_TN_CC_550\":515,\"s_Mayo_TN_CC_756\":741,\"s_Mayo_TN_CC_273\":210,\"s_Mayo_TN_CC_272\":209,\"s_Mayo_TN_CC_271\":208,\"s_Mayo_TN_CC_759\":744,\"s_Mayo_TN_CC_270\":207,\"s_Mayo_TN_CC_277\":214,\"s_Mayo_TN_CC_276\":213,\"s_Mayo_TN_CC_275\":212,\"s_Mayo_TN_CC_274\":211,\"s_Mayo_TN_CC_278\":215,\"s_Mayo_TN_CC_279\":216,\"s_Mayo_TN_CC_556\":521,\"s_Mayo_TN_CC_555\":520,\"s_Mayo_TN_CC_554\":519,\"s_Mayo_TN_CC_553\":518,\"s_Mayo_TN_CC_750\":735,\"s_Mayo_TN_CC_559\":524,\"s_Mayo_TN_CC_558\":523,\"s_Mayo_TN_CC_557\":522,\"s_Mayo_TN_CC_740\":724,\"s_Mayo_TN_CC_741\":725,\"s_Mayo_TN_CC_742\":726,\"s_Mayo_TN_CC_743\":727,\"s_Mayo_TN_CC_744\":728,\"s_Mayo_TN_CC_745\":729,\"s_Mayo_TN_CC_540\":504,\"s_Mayo_TN_CC_746\":730,\"s_Mayo_TN_CC_541\":505,\"s_Mayo_TN_CC_747\":731,\"s_Mayo_TN_CC_260\":196,\"s_Mayo_TN_CC_748\":732,\"s_Mayo_TN_CC_749\":733,\"s_Mayo_TN_CC_262\":198,\"s_Mayo_TN_CC_261\":197,\"s_Mayo_TN_CC_264\":200,\"s_Mayo_TN_CC_263\":199,\"s_Mayo_TN_CC_266\":202,\"s_Mayo_TN_CC_265\":201,\"s_Mayo_TN_CC_267\":203,\"s_Mayo_TN_CC_268\":204,\"s_Mayo_TN_CC_269\":205,\"s_Mayo_TN_CC_543\":507,\"s_Mayo_TN_CC_542\":506,\"s_Mayo_TN_CC_545\":509,\"s_Mayo_TN_CC_544\":508,\"s_Mayo_TN_CC_547\":511,\"s_Mayo_TN_CC_546\":510,\"s_Mayo_TN_CC_549\":513,\"s_Mayo_TN_CC_548\":512,\"s_Mayo_TN_CC_738\":721,\"s_Mayo_TN_CC_737\":720,\"s_Mayo_TN_CC_739\":722,\"s_Mayo_TN_CC_734\":717,\"s_Mayo_TN_CC_733\":716,\"s_Mayo_TN_CC_736\":719,\"s_Mayo_TN_CC_735\":718,\"s_Mayo_TN_CC_730\":713,\"s_Mayo_TN_CC_732\":715,\"s_Mayo_TN_CC_731\":714,\"s_Mayo_TN_CC_729\":711,\"s_Mayo_TN_CC_728\":710,\"s_Mayo_TN_CC_727\":709,\"s_Mayo_TN_CC_726\":708,\"s_Mayo_TN_CC_725\":707,\"s_Mayo_TN_CC_724\":706,\"s_Mayo_TN_CC_723\":705,\"s_Mayo_TN_CC_722\":704,\"s_Mayo_TN_CC_721\":703,\"s_Mayo_TN_CC_720\":702,\"s_Mayo_TN_CC_716\":697,\"s_Mayo_TN_CC_715\":696,\"s_Mayo_TN_CC_718\":699,\"s_Mayo_TN_CC_717\":698,\"s_Mayo_TN_CC_719\":700,\"s_Mayo_TN_CC_710\":691,\"s_Mayo_TN_CC_712\":693,\"s_Mayo_TN_CC_711\":692,\"s_Mayo_TN_CC_714\":695,\"s_Mayo_TN_CC_713\":694,\"s_Mayo_TN_CC_707\":687,\"s_Mayo_TN_CC_706\":686,\"s_Mayo_TN_CC_705\":685,\"s_Mayo_TN_CC_704\":684,\"s_Mayo_TN_CC_709\":689,\"s_Mayo_TN_CC_708\":688,\"s_Mayo_TN_CC_703\":683,\"s_Mayo_TN_CC_702\":682,\"s_Mayo_TN_CC_701\":681,\"s_Mayo_TN_CC_700\":680,\"s_Mayo_TN_CC_588\":556,\"s_Mayo_TN_CC_589\":557,\"s_Mayo_TN_CC_586\":554,\"s_Mayo_TN_CC_587\":555,\"s_Mayo_TN_CC_585\":553,\"s_Mayo_TN_CC_584\":552,\"s_Mayo_TN_CC_583\":551,\"s_Mayo_TN_CC_582\":550,\"s_Mayo_TN_CC_581\":549,\"s_Mayo_TN_CC_580\":548,\"s_Mayo_TN_CC_597\":566,\"s_Mayo_TN_CC_598\":567,\"s_Mayo_TN_CC_599\":568,\"s_Mayo_TN_CC_594\":563,\"s_Mayo_TN_CC_593\":562,\"s_Mayo_TN_CC_596\":565,\"s_Mayo_TN_CC_595\":564,\"s_Mayo_TN_CC_590\":559,\"s_Mayo_TN_CC_592\":561,\"s_Mayo_TN_CC_591\":560,\"s_Mayo_TN_CC_203\":133,\"s_Mayo_TN_CC_204\":134,\"s_Mayo_TN_CC_201\":131,\"s_Mayo_TN_CC_202\":132,\"s_Mayo_TN_CC_207\":137,\"s_Mayo_TN_CC_208\":138,\"s_Mayo_TN_CC_205\":135,\"s_Mayo_TN_CC_206\":136,\"s_Mayo_TN_CC_209\":139,\"s_Mayo_TN_CC_200\":130,\"s_Mayo_TN_CC_212\":143,\"s_Mayo_TN_CC_213\":144,\"s_Mayo_TN_CC_214\":145,\"s_Mayo_TN_CC_215\":146,\"s_Mayo_TN_CC_216\":147,\"s_Mayo_TN_CC_217\":148,\"s_Mayo_TN_CC_218\":149,\"s_Mayo_TN_CC_219\":150,\"s_Mayo_TN_CC_211\":142,\"s_Mayo_TN_CC_210\":141,\"s_Mayo_TN_CC_37\":316,\"s_Mayo_TN_CC_677\":654,\"s_Mayo_TN_CC_36\":305,\"s_Mayo_TN_CC_676\":653,\"s_Mayo_TN_CC_35\":294,\"s_Mayo_TN_CC_675\":652,\"s_Mayo_TN_CC_34\":283,\"s_Mayo_TN_CC_674\":651,\"s_Mayo_TN_CC_33\":272,\"s_Mayo_TN_CC_32\":261,\"s_Mayo_TN_CC_31\":250,\"s_Mayo_TN_CC_679\":656,\"s_Mayo_TN_CC_30\":239,\"s_Mayo_TN_CC_678\":655,\"s_Mayo_TN_CC_159\":84,\"s_Mayo_TN_CC_350\":295,\"s_Mayo_TN_CC_157\":82,\"s_Mayo_TN_CC_158\":83,\"s_Mayo_TN_CC_353\":298,\"s_Mayo_TN_CC_354\":299,\"s_Mayo_TN_CC_39\":338,\"s_Mayo_TN_CC_351\":296,\"s_Mayo_TN_CC_38\":327,\"s_Mayo_TN_CC_352\":297,\"s_Mayo_TN_CC_358\":303,\"s_Mayo_TN_CC_152\":77,\"s_Mayo_TN_CC_357\":302,\"s_Mayo_TN_CC_151\":76,\"s_Mayo_TN_CC_356\":301,\"s_Mayo_TN_CC_150\":75,\"s_Mayo_TN_CC_355\":300,\"s_Mayo_TN_CC_156\":81,\"s_Mayo_TN_CC_155\":80,\"s_Mayo_TN_CC_154\":79,\"s_Mayo_TN_CC_359\":304,\"s_Mayo_TN_CC_153\":78,\"s_Mayo_TN_CC_40\":349,\"s_Mayo_TN_CC_672\":649,\"s_Mayo_TN_CC_673\":650,\"s_Mayo_TN_CC_670\":647,\"s_Mayo_TN_CC_671\":648,\"s_Mayo_TN_CC_24\":173,\"s_Mayo_TN_CC_664\":640,\"s_Mayo_TN_CC_23\":162,\"s_Mayo_TN_CC_663\":639,\"s_Mayo_TN_CC_26\":195,\"s_Mayo_TN_CC_666\":642,\"s_Mayo_TN_CC_25\":184,\"s_Mayo_TN_CC_665\":641,\"s_Mayo_TN_CC_20\":129,\"s_Mayo_TN_CC_668\":644,\"s_Mayo_TN_CC_667\":643,\"s_Mayo_TN_CC_22\":151,\"s_Mayo_TN_CC_21\":140,\"s_Mayo_TN_CC_669\":645,\"s_Mayo_TN_CC_146\":70,\"s_Mayo_TN_CC_147\":71,\"s_Mayo_TN_CC_148\":72,\"s_Mayo_TN_CC_149\":73,\"s_Mayo_TN_CC_340\":284,\"s_Mayo_TN_CC_28\":217,\"s_Mayo_TN_CC_341\":285,\"s_Mayo_TN_CC_27\":206,\"s_Mayo_TN_CC_342\":286,\"s_Mayo_TN_CC_343\":287,\"s_Mayo_TN_CC_29\":228,\"s_Mayo_TN_CC_345\":289,\"s_Mayo_TN_CC_344\":288,\"s_Mayo_TN_CC_347\":291,\"s_Mayo_TN_CC_141\":65,\"s_Mayo_TN_CC_346\":290,\"s_Mayo_TN_CC_140\":64,\"s_Mayo_TN_CC_349\":293,\"s_Mayo_TN_CC_143\":67,\"s_Mayo_TN_CC_348\":292,\"s_Mayo_TN_CC_142\":66,\"s_Mayo_TN_CC_145\":69,\"s_Mayo_TN_CC_144\":68,\"s_Mayo_TN_CC_660\":636,\"s_Mayo_TN_CC_661\":637,\"s_Mayo_TN_CC_662\":638,\"s_Mayo_TN_CC_55\":514,\"s_Mayo_TN_CC_809\":799,\"s_Mayo_TN_CC_54\":503,\"s_Mayo_TN_CC_808\":798,\"s_Mayo_TN_CC_53\":492,\"s_Mayo_TN_CC_807\":797,\"s_Mayo_TN_CC_52\":481,\"s_Mayo_TN_CC_806\":796,\"s_Mayo_TN_CC_59\":558,\"s_Mayo_TN_CC_699\":678,\"s_Mayo_TN_CC_805\":795,\"s_Mayo_TN_CC_58\":547,\"s_Mayo_TN_CC_698\":677,\"s_Mayo_TN_CC_804\":794,\"s_Mayo_TN_CC_57\":536,\"s_Mayo_TN_CC_697\":676,\"s_Mayo_TN_CC_803\":793,\"s_Mayo_TN_CC_56\":525,\"s_Mayo_TN_CC_696\":675,\"s_Mayo_TN_CC_802\":792,\"s_Mayo_TN_CC_375\":322,\"s_Mayo_TN_CC_801\":791,\"s_Mayo_TN_CC_376\":323,\"s_Mayo_TN_CC_800\":790,\"s_Mayo_TN_CC_373\":320,\"s_Mayo_TN_CC_374\":321,\"s_Mayo_TN_CC_371\":318,\"s_Mayo_TN_CC_372\":319,\"s_Mayo_TN_CC_179\":106,\"s_Mayo_TN_CC_370\":317,\"s_Mayo_TN_CC_178\":105,\"s_Mayo_TN_CC_177\":104,\"s_Mayo_TN_CC_176\":103,\"s_Mayo_TN_CC_175\":102,\"s_Mayo_TN_CC_174\":101,\"s_Mayo_TN_CC_379\":326,\"s_Mayo_TN_CC_173\":100,\"s_Mayo_TN_CC_418\":369,\"s_Mayo_TN_CC_378\":325,\"s_Mayo_TN_CC_172\":99,\"s_Mayo_TN_CC_419\":370,\"s_Mayo_TN_CC_377\":324,\"s_Mayo_TN_CC_171\":98,\"s_Mayo_TN_CC_416\":367,\"s_Mayo_TN_CC_170\":97,\"s_Mayo_TN_CC_694\":673,\"s_Mayo_TN_CC_417\":368,\"s_Mayo_TN_CC_695\":674,\"s_Mayo_TN_CC_414\":365,\"s_Mayo_TN_CC_692\":671,\"s_Mayo_TN_CC_415\":366,\"s_Mayo_TN_CC_693\":672,\"s_Mayo_TN_CC_412\":363,\"s_Mayo_TN_CC_61\":580,\"s_Mayo_TN_CC_690\":669,\"s_Mayo_TN_CC_413\":364,\"s_Mayo_TN_CC_62\":591,\"s_Mayo_TN_CC_691\":670,\"s_Mayo_TN_CC_410\":361,\"s_Mayo_TN_CC_411\":362,\"s_Mayo_TN_CC_60\":569,\"s_Mayo_TN_CC_819\":810,\"s_Mayo_TN_CC_42\":371,\"s_Mayo_TN_CC_818\":809,\"s_Mayo_TN_CC_41\":360,\"s_Mayo_TN_CC_689\":667,\"s_Mayo_TN_CC_44\":393,\"s_Mayo_TN_CC_43\":382,\"s_Mayo_TN_CC_815\":806,\"s_Mayo_TN_CC_46\":415,\"s_Mayo_TN_CC_686\":664,\"s_Mayo_TN_CC_814\":805,\"s_Mayo_TN_CC_45\":404,\"s_Mayo_TN_CC_685\":663,\"s_Mayo_TN_CC_817\":808,\"s_Mayo_TN_CC_48\":437,\"s_Mayo_TN_CC_688\":666,\"s_Mayo_TN_CC_816\":807,\"s_Mayo_TN_CC_47\":426,\"s_Mayo_TN_CC_687\":665,\"s_Mayo_TN_CC_811\":802,\"s_Mayo_TN_CC_362\":308,\"s_Mayo_TN_CC_810\":801,\"s_Mayo_TN_CC_363\":309,\"s_Mayo_TN_CC_49\":448,\"s_Mayo_TN_CC_813\":804,\"s_Mayo_TN_CC_364\":310,\"s_Mayo_TN_CC_812\":803,\"s_Mayo_TN_CC_365\":311,\"s_Mayo_TN_CC_168\":94,\"s_Mayo_TN_CC_169\":95,\"s_Mayo_TN_CC_360\":306,\"s_Mayo_TN_CC_361\":307,\"s_Mayo_TN_CC_165\":91,\"s_Mayo_TN_CC_164\":90,\"s_Mayo_TN_CC_167\":93,\"s_Mayo_TN_CC_166\":92,\"s_Mayo_TN_CC_407\":357,\"s_Mayo_TN_CC_367\":313,\"s_Mayo_TN_CC_161\":87,\"s_Mayo_TN_CC_408\":358,\"s_Mayo_TN_CC_366\":312,\"s_Mayo_TN_CC_160\":86,\"s_Mayo_TN_CC_409\":359,\"s_Mayo_TN_CC_369\":315,\"s_Mayo_TN_CC_163\":89,\"s_Mayo_TN_CC_368\":314,\"s_Mayo_TN_CC_162\":88,\"s_Mayo_TN_CC_403\":353,\"s_Mayo_TN_CC_681\":659,\"s_Mayo_TN_CC_404\":354,\"s_Mayo_TN_CC_682\":660,\"s_Mayo_TN_CC_405\":355,\"s_Mayo_TN_CC_683\":661,\"s_Mayo_TN_CC_406\":356,\"s_Mayo_TN_CC_684\":662,\"s_Mayo_TN_CC_400\":350,\"s_Mayo_TN_CC_401\":351,\"s_Mayo_TN_CC_50\":459,\"s_Mayo_TN_CC_402\":352,\"s_Mayo_TN_CC_51\":470,\"s_Mayo_TN_CC_680\":658,\"s_Mayo_TN_CC_394\":343,\"s_Mayo_TN_CC_116\":37,\"s_Mayo_TN_CC_820\":812,\"s_Mayo_TN_CC_393\":342,\"s_Mayo_TN_CC_115\":36,\"s_Mayo_TN_CC_392\":341,\"s_Mayo_TN_CC_114\":35,\"s_Mayo_TN_CC_638\":611,\"s_Mayo_TN_CC_391\":340,\"s_Mayo_TN_CC_113\":34,\"s_Mayo_TN_CC_639\":612,\"s_Mayo_TN_CC_823\":815,\"s_Mayo_TN_CC_398\":347,\"s_Mayo_TN_CC_824\":816,\"s_Mayo_TN_CC_397\":346,\"s_Mayo_TN_CC_119\":40,\"s_Mayo_TN_CC_821\":813,\"s_Mayo_TN_CC_396\":345,\"s_Mayo_TN_CC_118\":39,\"s_Mayo_TN_CC_822\":814,\"s_Mayo_TN_CC_395\":344,\"s_Mayo_TN_CC_117\":38,\"s_Mayo_TN_CC_827\":819,\"s_Mayo_TN_CC_632\":605,\"s_Mayo_TN_CC_828\":820,\"s_Mayo_TN_CC_633\":606,\"s_Mayo_TN_CC_825\":817,\"s_Mayo_TN_CC_630\":603,\"s_Mayo_TN_CC_826\":818,\"s_Mayo_TN_CC_631\":604,\"s_Mayo_TN_CC_430\":383,\"s_Mayo_TN_CC_390\":339,\"s_Mayo_TN_CC_636\":609,\"s_Mayo_TN_CC_431\":384,\"s_Mayo_TN_CC_637\":610,\"s_Mayo_TN_CC_829\":821,\"s_Mayo_TN_CC_634\":607,\"s_Mayo_TN_CC_635\":608,\"s_Mayo_TN_CC_435\":388,\"s_Mayo_TN_CC_434\":387,\"s_Mayo_TN_CC_433\":386,\"s_Mayo_TN_CC_432\":385,\"s_Mayo_TN_CC_439\":392,\"s_Mayo_TN_CC_438\":391,\"s_Mayo_TN_CC_437\":390,\"s_Mayo_TN_CC_436\":389,\"s_Mayo_TN_CC_399\":348,\"s_Mayo_TN_CC_111\":32,\"s_Mayo_TN_CC_112\":33,\"s_Mayo_TN_CC_110\":31,\"s_Mayo_TN_CC_381\":329,\"s_Mayo_TN_CC_103\":23,\"s_Mayo_TN_CC_627\":599,\"s_Mayo_TN_CC_380\":328,\"s_Mayo_TN_CC_102\":22,\"s_Mayo_TN_CC_628\":600,\"s_Mayo_TN_CC_830\":823,\"s_Mayo_TN_CC_383\":331,\"s_Mayo_TN_CC_105\":25,\"s_Mayo_TN_CC_629\":601,\"s_Mayo_TN_CC_831\":824,\"s_Mayo_TN_CC_382\":330,\"s_Mayo_TN_CC_104\":24,\"s_Mayo_TN_CC_832\":825,\"s_Mayo_TN_CC_385\":333,\"s_Mayo_TN_CC_107\":27,\"s_Mayo_TN_CC_833\":826,\"s_Mayo_TN_CC_384\":332,\"s_Mayo_TN_CC_106\":26,\"s_Mayo_TN_CC_834\":827,\"s_Mayo_TN_CC_387\":335,\"s_Mayo_TN_CC_109\":29,\"s_Mayo_TN_CC_835\":828,\"s_Mayo_TN_CC_386\":334,\"s_Mayo_TN_CC_108\":28,\"s_Mayo_TN_CC_836\":829,\"s_Mayo_TN_CC_837\":830,\"s_Mayo_TN_CC_620\":592,\"s_Mayo_TN_CC_838\":831,\"s_Mayo_TN_CC_621\":593,\"s_Mayo_TN_CC_839\":832,\"s_Mayo_TN_CC_622\":594,\"s_Mayo_TN_CC_623\":595,\"s_Mayo_TN_CC_624\":596,\"s_Mayo_TN_CC_625\":597,\"s_Mayo_TN_CC_420\":372,\"s_Mayo_TN_CC_626\":598,\"s_Mayo_TN_CC_422\":374,\"s_Mayo_TN_CC_421\":373,\"s_Mayo_TN_CC_424\":376,\"s_Mayo_TN_CC_423\":375,\"s_Mayo_TN_CC_426\":378,\"s_Mayo_TN_CC_425\":377,\"s_Mayo_TN_CC_428\":380,\"s_Mayo_TN_CC_427\":379,\"s_Mayo_TN_CC_388\":336,\"s_Mayo_TN_CC_429\":381,\"s_Mayo_TN_CC_389\":337,\"s_Mayo_TN_CC_100\":20,\"s_Mayo_TN_CC_101\":21,\"s_Mayo_TN_CC_845\":839,\"s_Mayo_TN_CC_18\":107,\"s_Mayo_TN_CC_846\":840,\"s_Mayo_TN_CC_19\":118,\"s_Mayo_TN_CC_843\":837,\"s_Mayo_TN_CC_16\":85,\"s_Mayo_TN_CC_844\":838,\"s_Mayo_TN_CC_17\":96,\"s_Mayo_TN_CC_139\":62,\"s_Mayo_TN_CC_841\":835,\"s_Mayo_TN_CC_138\":61,\"s_Mayo_TN_CC_842\":836,\"s_Mayo_TN_CC_137\":60,\"s_Mayo_TN_CC_136\":59,\"s_Mayo_TN_CC_840\":834,\"s_Mayo_TN_CC_135\":58,\"s_Mayo_TN_CC_10\":19,\"s_Mayo_TN_CC_452\":407,\"s_Mayo_TN_CC_658\":633,\"s_Mayo_TN_CC_11\":30,\"s_Mayo_TN_CC_453\":408,\"s_Mayo_TN_CC_659\":634,\"s_Mayo_TN_CC_450\":405,\"s_Mayo_TN_CC_656\":631,\"s_Mayo_TN_CC_451\":406,\"s_Mayo_TN_CC_657\":632,\"s_Mayo_TN_CC_849\":843,\"s_Mayo_TN_CC_14\":63,\"s_Mayo_TN_CC_654\":629,\"s_Mayo_TN_CC_15\":74,\"s_Mayo_TN_CC_655\":630,\"s_Mayo_TN_CC_847\":841,\"s_Mayo_TN_CC_12\":41,\"s_Mayo_TN_CC_652\":627,\"s_Mayo_TN_CC_848\":842,\"s_Mayo_TN_CC_13\":52,\"s_Mayo_TN_CC_653\":628,\"s_Mayo_TN_CC_651\":626,\"s_Mayo_TN_CC_650\":625,\"s_Mayo_TN_CC_459\":414,\"s_Mayo_TN_CC_458\":413,\"s_Mayo_TN_CC_457\":412,\"s_Mayo_TN_CC_456\":411,\"s_Mayo_TN_CC_455\":410,\"s_Mayo_TN_CC_454\":409,\"s_Mayo_TN_CC_133\":56,\"s_Mayo_TN_CC_134\":57,\"s_Mayo_TN_CC_131\":54,\"s_Mayo_TN_CC_132\":55,\"s_Mayo_TN_CC_130\":53,\"s_Mayo_TN_CC_854\":849,\"s_Mayo_TN_CC_05\":14,\"s_Mayo_TN_CC_129\":51,\"s_Mayo_TN_CC_855\":850,\"s_Mayo_TN_CC_06\":15,\"s_Mayo_TN_CC_128\":50,\"s_Mayo_TN_CC_856\":851,\"s_Mayo_TN_CC_07\":16,\"s_Mayo_TN_CC_857\":852,\"s_Mayo_TN_CC_08\":17,\"s_Mayo_TN_CC_850\":845,\"s_Mayo_TN_CC_09\":18,\"s_Mayo_TN_CC_125\":47,\"s_Mayo_TN_CC_649\":623,\"s_Mayo_TN_CC_851\":846,\"s_Mayo_TN_CC_124\":46,\"s_Mayo_TN_CC_852\":847,\"s_Mayo_TN_CC_127\":49,\"s_Mayo_TN_CC_853\":848,\"s_Mayo_TN_CC_126\":48,\"s_Mayo_TN_CC_645\":619,\"s_Mayo_TN_CC_440\":394,\"s_Mayo_TN_CC_646\":620,\"s_Mayo_TN_CC_441\":395,\"s_Mayo_TN_CC_647\":621,\"s_Mayo_TN_CC_442\":396,\"s_Mayo_TN_CC_648\":622,\"s_Mayo_TN_CC_858\":853,\"s_Mayo_TN_CC_01\":10,\"s_Mayo_TN_CC_641\":615,\"s_Mayo_TN_CC_859\":854,\"s_Mayo_TN_CC_02\":11,\"s_Mayo_TN_CC_642\":616,\"s_Mayo_TN_CC_03\":12,\"s_Mayo_TN_CC_643\":617,\"s_Mayo_TN_CC_04\":13,\"s_Mayo_TN_CC_644\":618,\"s_Mayo_TN_CC_448\":402,\"s_Mayo_TN_CC_447\":401,\"s_Mayo_TN_CC_640\":614,\"s_Mayo_TN_CC_449\":403,\"s_Mayo_TN_CC_444\":398,\"s_Mayo_TN_CC_443\":397,\"s_Mayo_TN_CC_446\":400,\"s_Mayo_TN_CC_445\":399,\"s_Mayo_TN_CC_120\":42,\"s_Mayo_TN_CC_121\":43,\"s_Mayo_TN_CC_122\":44,\"s_Mayo_TN_CC_123\":45,\"s_Mayo_TN_CC_860\":856,\"s_Mayo_TN_CC_869\":865,\"s_Mayo_TN_CC_862\":858,\"s_Mayo_TN_CC_861\":857,\"s_Mayo_TN_CC_864\":860,\"s_Mayo_TN_CC_863\":859,\"s_Mayo_TN_CC_866\":862,\"s_Mayo_TN_CC_865\":861,\"s_Mayo_TN_CC_868\":864,\"s_Mayo_TN_CC_867\":863,\"s_Mayo_TN_CC_870\":867,\"s_Mayo_TN_CC_871\":868,\"s_Mayo_TN_CC_875\":872,\"s_Mayo_TN_CC_874\":871,\"s_Mayo_TN_CC_873\":870,\"s_Mayo_TN_CC_872\":869,\"s_Mayo_TN_CC_879\":876,\"s_Mayo_TN_CC_878\":875,\"s_Mayo_TN_CC_877\":874,\"s_Mayo_TN_CC_876\":873,\"s_Mayo_TN_CC_880\":878,\"s_Mayo_TN_CC_881\":879,\"s_Mayo_TN_CC_882\":880,\"s_Mayo_TN_CC_613\":584,\"s_Mayo_TN_CC_612\":583,\"s_Mayo_TN_CC_615\":586,\"s_Mayo_TN_CC_614\":585,\"s_Mayo_TN_CC_611\":582,\"s_Mayo_TN_CC_610\":581,\"s_Mayo_TN_CC_888\":886,\"s_Mayo_TN_CC_887\":885,\"s_Mayo_TN_CC_884\":882,\"s_Mayo_TN_CC_617\":588,\"s_Mayo_TN_CC_883\":881,\"s_Mayo_TN_CC_616\":587,\"s_Mayo_TN_CC_886\":884,\"s_Mayo_TN_CC_619\":590,\"s_Mayo_TN_CC_885\":883,\"s_Mayo_TN_CC_618\":589,\"s_Mayo_TN_CC_604\":574,\"s_Mayo_TN_CC_603\":573,\"s_Mayo_TN_CC_602\":572,\"s_Mayo_TN_CC_601\":571,\"s_Mayo_TN_CC_600\":570,\"s_Mayo_TN_CC_609\":579,\"s_Mayo_TN_CC_608\":578,\"s_Mayo_TN_CC_607\":577,\"s_Mayo_TN_CC_606\":576,\"s_Mayo_TN_CC_605\":575,\"s_Mayo_TN_CC_82\":811,\"s_Mayo_TN_CC_81\":800,\"s_Mayo_TN_CC_84\":833,\"s_Mayo_TN_CC_83\":822,\"s_Mayo_TN_CC_190\":119,\"s_Mayo_TN_CC_80\":789,\"s_Mayo_TN_CC_191\":120,\"s_Mayo_TN_CC_192\":121,\"s_Mayo_TN_CC_193\":122,\"s_Mayo_TN_CC_194\":123,\"s_Mayo_TN_CC_195\":124,\"s_Mayo_TN_CC_196\":125,\"s_Mayo_TN_CC_197\":126,\"s_Mayo_TN_CC_198\":127,\"s_Mayo_TN_CC_199\":128,\"s_Mayo_TN_CC_78\":767,\"s_Mayo_TN_CC_79\":778,\"s_Mayo_TN_CC_74\":723,\"s_Mayo_TN_CC_75\":734,\"s_Mayo_TN_CC_76\":745,\"s_Mayo_TN_CC_77\":756,\"s_Mayo_TN_CC_73\":712,\"s_Mayo_TN_CC_72\":701,\"s_Mayo_TN_CC_71\":690,\"s_Mayo_TN_CC_70\":679,\"s_Mayo_TN_CC_180\":108,\"s_Mayo_TN_CC_181\":109,\"s_Mayo_TN_CC_184\":112,\"s_Mayo_TN_CC_185\":113,\"s_Mayo_TN_CC_182\":110,\"s_Mayo_TN_CC_183\":111,\"s_Mayo_TN_CC_188\":116,\"s_Mayo_TN_CC_189\":117,\"s_Mayo_TN_CC_186\":114,\"s_Mayo_TN_CC_187\":115,\"s_Mayo_TN_CC_69\":668,\"s_Mayo_TN_CC_67\":646,\"s_Mayo_TN_CC_68\":657,\"s_Mayo_TN_CC_65\":624,\"s_Mayo_TN_CC_66\":635,\"s_Mayo_TN_CC_63\":602,\"s_Mayo_TN_CC_64\":613,\"s_Mayo_TN_CC_96\":894,\"s_Mayo_TN_CC_97\":895,\"s_Mayo_TN_CC_98\":896,\"s_Mayo_TN_CC_99\":897,\"s_Mayo_TN_CC_91\":889,\"s_Mayo_TN_CC_90\":888,\"s_Mayo_TN_CC_95\":893,\"s_Mayo_TN_CC_94\":892,\"s_Mayo_TN_CC_93\":891,\"s_Mayo_TN_CC_92\":890,\"s_Mayo_TN_CC_87\":866,\"s_Mayo_TN_CC_88\":877,\"s_Mayo_TN_CC_85\":844,\"s_Mayo_TN_CC_86\":855,\"s_Mayo_TN_CC_89\":887,\"s_Mayo_TN_CC_469\":425,\"s_Mayo_TN_CC_467\":423,\"s_Mayo_TN_CC_468\":424,\"s_Mayo_TN_CC_465\":421,\"s_Mayo_TN_CC_466\":422,\"s_Mayo_TN_CC_464\":420,\"s_Mayo_TN_CC_463\":419,\"s_Mayo_TN_CC_462\":418,\"s_Mayo_TN_CC_461\":417,\"s_Mayo_TN_CC_460\":416,\"s_Mayo_TN_CC_476\":433,\"s_Mayo_TN_CC_477\":434,\"s_Mayo_TN_CC_478\":435,\"s_Mayo_TN_CC_479\":436,\"s_Mayo_TN_CC_473\":430,\"s_Mayo_TN_CC_472\":429,\"s_Mayo_TN_CC_475\":432,\"s_Mayo_TN_CC_474\":431,\"s_Mayo_TN_CC_471\":428,\"s_Mayo_TN_CC_470\":427,\"s_Mayo_TN_CC_489\":447,\"s_Mayo_TN_CC_487\":445,\"s_Mayo_TN_CC_488\":446,\"s_Mayo_TN_CC_482\":440,\"s_Mayo_TN_CC_481\":439,\"s_Mayo_TN_CC_480\":438,\"s_Mayo_TN_CC_486\":444,\"s_Mayo_TN_CC_485\":443,\"s_Mayo_TN_CC_484\":442,\"s_Mayo_TN_CC_483\":441,\"s_Mayo_TN_CC_498\":457,\"s_Mayo_TN_CC_499\":458,\"s_Mayo_TN_CC_491\":450,\"s_Mayo_TN_CC_490\":449,\"s_Mayo_TN_CC_493\":452,\"s_Mayo_TN_CC_492\":451,\"s_Mayo_TN_CC_495\":454,\"s_Mayo_TN_CC_494\":453,\"s_Mayo_TN_CC_497\":456,\"s_Mayo_TN_CC_496\":455,\"s_Mayo_TN_CC_308\":248,\"s_Mayo_TN_CC_309\":249,\"s_Mayo_TN_CC_306\":246,\"s_Mayo_TN_CC_307\":247,\"s_Mayo_TN_CC_304\":244,\"s_Mayo_TN_CC_305\":245,\"s_Mayo_TN_CC_302\":242,\"s_Mayo_TN_CC_303\":243,\"s_Mayo_TN_CC_300\":240,\"s_Mayo_TN_CC_301\":241,\"s_Mayo_TN_CC_319\":260,\"s_Mayo_TN_CC_315\":256,\"s_Mayo_TN_CC_316\":257,\"s_Mayo_TN_CC_317\":258,\"s_Mayo_TN_CC_318\":259,\"s_Mayo_TN_CC_311\":252,\"s_Mayo_TN_CC_312\":253,\"s_Mayo_TN_CC_313\":254,\"s_Mayo_TN_CC_314\":255,\"s_Mayo_TN_CC_310\":251,\"s_Mayo_TN_CC_324\":266,\"s_Mayo_TN_CC_325\":267,\"s_Mayo_TN_CC_322\":264,\"s_Mayo_TN_CC_323\":265,\"s_Mayo_TN_CC_328\":270,\"s_Mayo_TN_CC_329\":271,\"s_Mayo_TN_CC_326\":268,\"s_Mayo_TN_CC_327\":269,\"s_Mayo_TN_CC_321\":263,\"s_Mayo_TN_CC_320\":262,\"s_Mayo_TN_CC_333\":276,\"s_Mayo_TN_CC_334\":277,\"s_Mayo_TN_CC_335\":278,\"s_Mayo_TN_CC_336\":279,\"s_Mayo_TN_CC_337\":280,\"s_Mayo_TN_CC_338\":281,\"s_Mayo_TN_CC_339\":282,\"s_Mayo_TN_CC_330\":273,\"s_Mayo_TN_CC_332\":275,\"s_Mayo_TN_CC_331\":274}}"
);
List<String> snpeffExpected = Arrays.asList(
"SNPEFF_AMINO_ACID_LENGTH",
"SNPEFF_TRANSCRIPT_ID",
"SNPEFF_CODON_CHANGE",
"SNPEFF_IMPACT",
"SNPEFF_EXON_ID",
"SNPEFF_GENE_NAME",
"SNPEFF_AMINO_ACID_CHANGE",
"SNPEFF_FUNCTIONAL_CLASS",
"SNPEFF_EFFECT",
"SNPEFF_GENE_BIOTYPE"
);
private Mongo m = MongoConnection.getMongo();
String VCF = "src/test/resources/testData/TNBC_Cases_Controls.snpeff.annotation.vcf";
@Test
public void testParse() throws Exception {
System.out.println("Running: edu.mayo.ve.VCFParser.VCFParserITCase.testParse");
//set the testing collection to a new empty collection
HashMap<Integer,String> results = new HashMap<Integer, String>();
String collection = "thisshouldnot";
String workspace = "workspace1234";
VCFParser parser = new VCFParser();
parser.setTestingCollection(results);
parser.setSaveSamples(false);
parser.setTesting(true);
parser.setReporting(false);
parser.parse(VCF, workspace);
//test to see that the parser is performing to spec
results = parser.getTestingCollection();
assertEquals(826, results.size());
for(Integer i : results.keySet()){
String value = results.get(i);
System.out.println(value);
assertEquals(known.get(i).replaceAll("\\s+",""), results.get(i).replaceAll("\\s+",""));
break;//we could do the entire list...
}
//check that the metadata is correct
assertEquals(metadata.get(0).replaceAll("\\s+",""), parser.getJson().toString().replaceAll("\\s+",""));
System.out.println("Ensuring that SNPEFF columns are identified for indexing correctly");
int count =0;
List<String> snpeffFound = parser.getSNPEFFColsFromJsonObj(parser.getJson());
for(String s: snpeffExpected){
//assertEquals(s.replaceAll("\\s+",""), snpeffFound.get(count).replaceAll("\\s+",""));
count++;
}
String expectedCache = "{ \"key\" : \"workspace1234\" , \"GenotyperControls\" : [ \"Samtools-Pindel\" , \"Pindel\" , \"Samtools\"] , \"SNPEFF_FUNCTIONAL_CLASS\" : [ \"SILENT\" , \"MISSENSE\" , \"NONE\"] , \"SNPEFF_EFFECT\" : [ \"UTR_5_PRIME\" , \"UPSTREAM\" , \"EXON\" , \"CODON_INSERTION\" , \"SYNONYMOUS_CODING\" , \"NON_SYNONYMOUS_CODING\" , \"UTR_3_PRIME\" , \"DOWNSTREAM\" , \"INTERGENIC\" , \"CODON_CHANGE_PLUS_CODON_DELETION\" , \"INTRAGENIC\" , \"INTRON\" , \"FRAME_SHIFT\"] , \"SNPEFF_TRANSCRIPT_ID\" : [ \"NM_015658\" , \"NM_017891\" , \"NR_033183\" , \"NM_001199787\" , \"NM_030937\" , \"NM_001039577\" , \"NR_029834\" , \"NM_001160184\" , \"NM_001130413\" , \"NM_152486\" , \"NM_001256456\" , \"NM_024011\" , \"NM_000815\" , \"NM_001142467\" , \"NM_005101\" , \"NM_152228\" , \"NM_178545\" , \"NM_001256463\" , \"NM_016547\" , \"NM_001205252\" , \"NM_001198993\" , \"NM_016176\" , \"NM_030649\" , \"NM_001198995\" , \"NM_032348\" , \"NM_001080484\" , \"NM_022834\" , \"NR_027693\" , \"NM_153254\" , \"NM_001170535\" , \"NM_001110781\" , \"NM_001170536\" , \"NR_047524\" , \"NR_024540\" , \"NM_002074\" , \"NM_001170688\" , \"NM_014188\" , \"NM_198317\" , \"NR_024321\" , \"NM_001170686\" , \"NR_047526\" , \"NM_017971\" , \"NR_026874\" , \"NR_033908\" , \"NM_138705\" , \"NM_004421\" , \"NM_080605\" , \"NR_015368\" , \"NM_001146685\" , \"NM_001114748\" , \"NM_001039211\" , \"NM_002744\" , \"NM_033487\" , \"NM_182838\" , \"NM_033488\" , \"NM_001130045\" , \"NM_194457\" , \"NM_058167\" , \"NM_198576\" , \"NM_033493\" , \"NM_031921\" , \"NR_038869\" , \"NR_027055\" , \"NM_001127229\" , \"NR_046018\" , \"NM_001242659\" , \"NM_153339\" , \"NM_001014980\"] , \"set\" : [ \"Intersection\" , \"variant2\" , \"variant\"] , \"Genotyper\" : [ \"Samtools-Pindel\" , \"Pindel\" , \"Samtools\"] , \"SNPEFF_EXON_ID\" : [ \"NM_001198995.ex.1\" , \"NM_033488.ex.16\" , \"NM_005101.ex.1\" , \"NM_001130413.ex.3\" , \"NM_001039577.ex.6\" , \"NM_033493.ex.16\" , \"NM_001080484.ex.8\" , \"NM_178545.ex.5\" , \"NM_033493.ex.17\" , \"NM_178545.ex.3\" , \"NM_001130045.ex.15\" , \"NM_001160184.ex.13\" , \"NM_001205252.ex.1\" , \"NM_001080484.ex.1\" , \"NM_198576.ex.29\" , \"NM_024011.ex.17\" , \"NM_058167.ex.7\" , \"NM_198576.ex.22\" , \"NM_198576.ex.23\"] , \"Group\" : [ \"Cases\" , \"Intersection\" , \"Controls\"] , \"SNPEFF_GENE_NAME\" : [ \"KIAA1751\" , \"B3GALT6\" , \"AURKAIP1\" , \"TAS1R3\" , \"LINC00115\" , \"LOC643837\" , \"ATAD3C\" , \"ATAD3A\" , \"ATAD3B\" , \"ISG15\" , \"C1orf159\" , \"VWA1\" , \"OR4F16\" , \"UBE2J2\" , \"RNF223\" , \"NOC2L\" , \"CCNL2\" , \"TTLL10\" , \"TMEM240\" , \"KLHL17\" , \"ACAP3\" , \"GNB1\" , \"HES4\" , \"CDK11A\" , \"SLC35E2\" , \"MIB2\" , \"DDX11L1\" , \"CDK11B\" , \"FAM41C\" , \"TMEM88B\" , \"SSU72\" , \"CPSF3L\" , \"PRKCZ\" , \"MIR200A\" , \"SLC35E2B\" , \"PUSL1\" , \"FAM132A\" , \"MRPL20\" , \"LOC100288069\" , \"LOC254099\" , \"CALML6\" , \"AGRN\" , \"SDF4\" , \"SCNN1D\" , \"GABRD\" , \"C1orf170\" , \"SAMD11\" , \"TMEM52\" , \"NADK\" , \"MXRA8\" , \"LOC100133331\" , \"DVL1\" , \"LOC100130417\" , \"WASH7P\" , \"C1orf233\" , \"PLEKHN1\"] , \"SNPEFF_CODON_CHANGE\" : [ \"gaC/gaT\" , \"Gtc/Atc\" , \"gcG/gcA\" , \"ggC/ggT\" , \"ttC/ttT\" , \"gtG/gtA\" , \"gaC/gaG\" , \"cAt/cGt\" , \"gaA/gaG\" , \"-/G\" , \"aag/aaGAGg\" , \"gagggc/ggc\" , \"Gac/Cac\" , \"ctcctgccgctg/ctg\" , \"Gtg/Atg\" , \"Aga/Cga\" , \"cCc/cAc\" , \"-\" , \"gCg/gTg\" , \"cCg/cTg\" , \"-/AAGAAA\" , \"cGt/cCt\" , \"Tcc/Ccc\" , \"cGc/cAc\" , \"tcG/tcA\" , \"gaT/gaC\" , \"agA/agG\"] , \"SNPEFF_IMPACT\" : [ \"HIGH\" , \"MODERATE\" , \"LOW\" , \"MODIFIER\"] , \"SNPEFF_AMINO_ACID_CHANGE\" : [ \"EG413G\" , \"-738\" , \"-116KK\" , \"P242H\" , \"V1667M\" , \"K404KR\" , \"P1289L\" , \"-511\" , \"R494\" , \"H112R\" , \"P1240L\" , \"R452P\" , \"S45\" , \"A1711\" , \"V56\" , \"V1666I\" , \"R105\" , \"-508?\" , \"-509\" , \"D538H\" , \"A55\" , \"D248\" , \"R1699H\" , \"A1255V\" , \"F1690\" , \"-506?\" , \"D56E\" , \"S476P\" , \"LLPL23L\" , \"D512\" , \"E108\" , \"G1675\"]}";
System.out.println("Ensure that the cache of String values is populated correctly (can't guarentee it got to mongo in this test)");
BasicDBObject dbo = parser.getTypeAhead().convertCacheToDBObj(workspace);
//assertEquals(expectedCache.replaceAll("\\s+",""), dbo.toString().replaceAll("\\s+",""));
//check that the metadata was indeed modified correctly in mongodb
String expectedMetadataAfterChange = "{ \"HEADER\" : { \"FORMAT\" : { \"PL\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\" , \"EntryType\" : \"FORMAT\"} , \"AD\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"Allelic depths for the ref and alt alleles in the order listed\" , \"EntryType\" : \"FORMAT\"} , \"GT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Genotype\" , \"EntryType\" : \"FORMAT\"} , \"GQ\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Genotype Quality\" , \"EntryType\" : \"FORMAT\"} , \"DP\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Approximate read depth (reads with MQ=255 or with bad mates are filtered)\" , \"EntryType\" : \"FORMAT\"} , \"MLPSAF\" : { \"number\" : \".\" , \"type\" : \"Float\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele fraction, in the same order as listed, for each individual sample\" , \"EntryType\" : \"FORMAT\"} , \"DP4\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"The number of high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\" , \"EntryType\" : \"FORMAT\"} , \"MLPSAC\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele count, in the same order as listed, for each individual sample\" , \"EntryType\" : \"FORMAT\"} , \"GL\" : { \"number\" : 3 , \"type\" : \"Float\" , \"Description\" : \"Likelihoods for RR,RA,AA genotypes (R=ref,A=alt)\" , \"EntryType\" : \"FORMAT\"} , \"SP\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Phred-scaled strand bias P-value\" , \"EntryType\" : \"FORMAT\"}} , \"INFO\" : { \"Controls_AN\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AN for Controls\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_AMINO_ACID_LENGTH\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Length of protein in amino acids (actually, transcription length divided by 3)\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_TRANSCRIPT_ID\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Transcript ID for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"UGT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The most probable unconstrained genotype configuration in the trio\" , \"EntryType\" : \"INFO\"} , \"InbreedingCoeff\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Inbreeding coefficient as estimated from the genotype likelihoods per-sample when compared against the Hardy-Weinberg expectation\" , \"EntryType\" : \"INFO\"} , \"Group\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_CODON_CHANGE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Old/New codon for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"AF1\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Max-likelihood estimate of the first ALT allele frequency (assuming HWE)\" , \"EntryType\" : \"INFO\"} , \"Cases_AF\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AF for Cases\" , \"EntryType\" : \"INFO\"} , \"ReadPosRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt vs. Ref read position bias\" , \"EntryType\" : \"INFO\"} , \"DP\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Approximate read depth; some reads may have been filtered\" , \"EntryType\" : \"INFO\"} , \"DS\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Were any of the samples downsampled?\" , \"EntryType\" : \"INFO\"} , \"Controls_AF\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AF for Controls\" , \"EntryType\" : \"INFO\"} , \"Cases_AN\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AN for Cases\" , \"EntryType\" : \"INFO\"} , \"Controls_AC\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AC for Controls\" , \"EntryType\" : \"INFO\"} , \"STR\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Variant is a short tandem repeat\" , \"EntryType\" : \"INFO\"} , \"BaseQRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt Vs. Ref base qualities\" , \"EntryType\" : \"INFO\"} , \"HWE\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Chi^2 based HWE test P-value based on G3\" , \"EntryType\" : \"INFO\"} , \"QD\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Variant Confidence/Quality by Depth\" , \"EntryType\" : \"INFO\"} , \"MQ\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"RMS Mapping Quality\" , \"EntryType\" : \"INFO\"} , \"PC2\" : { \"number\" : 2 , \"type\" : \"Integer\" , \"Description\" : \"Phred probability of the nonRef allele frequency in group1 samples being larger (,smaller) than in group2.\" , \"EntryType\" : \"INFO\"} , \"CGT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The most probable constrained genotype configuration in the trio\" , \"EntryType\" : \"INFO\"} , \"AC\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"Allele count in genotypes, for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"HRun\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Largest Contiguous Homopolymer Run of Variant Allele In Either Direction\" , \"EntryType\" : \"INFO\"} , \"QCHI2\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Phred scaled PCHI2.\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_IMPACT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Impact of the highest-impact effect resulting from the current variant [MODIFIER, LOW, MODERATE, HIGH]\" , \"EntryType\" : \"INFO\"} , \"Dels\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Fraction of Reads Containing Spanning Deletions\" , \"EntryType\" : \"INFO\"} , \"INDEL\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Indicates that the variant is an INDEL.\" , \"EntryType\" : \"INFO\"} , \"PR\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"# permutations yielding a smaller PCHI2.\" , \"EntryType\" : \"INFO\"} , \"AF\" : { \"number\" : \".\" , \"type\" : \"Float\" , \"Description\" : \"Allele Frequency, for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"DP4\" : { \"number\" : 4 , \"type\" : \"Integer\" , \"Description\" : \"# high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\" , \"EntryType\" : \"INFO\"} , \"SVLEN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Difference in length between REF and ALT alleles\" , \"EntryType\" : \"INFO\"} , \"AN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Total number of alleles in called genotypes\" , \"EntryType\" : \"INFO\"} , \"CLR\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Log ratio of genotype likelihoods with and without the constraint\" , \"EntryType\" : \"INFO\"} , \"HaplotypeScore\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Consistency of the site with at most two segregating haplotypes\" , \"EntryType\" : \"INFO\"} , \"PCHI2\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Posterior weighted chi^2 P-value for testing the association between group1 and group2 samples.\" , \"EntryType\" : \"INFO\"} , \"set\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"Genotyper\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_EXON_ID\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Exon ID for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"MLEAC\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the allele counts (not necessarily the same as the AC), for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_GENE_NAME\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Gene name for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"MLEAF\" : { \"number\" : \".\" , \"type\" : \"Float\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the allele frequency (not necessarily the same as the AF), for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"FS\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Phred-scaled p-value using Fisher's exact test to detect strand bias\" , \"EntryType\" : \"INFO\"} , \"G3\" : { \"number\" : 3 , \"type\" : \"Float\" , \"Description\" : \"ML estimate of genotype frequencies\" , \"EntryType\" : \"INFO\"} , \"FQ\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Phred probability of all samples being the same\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_AMINO_ACID_CHANGE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Old/New amino acid for the highest-impact effect resulting from the current variant (in HGVS style)\" , \"EntryType\" : \"INFO\"} , \"GenotyperControls\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"VDB\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Variant Distance Bias\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_FUNCTIONAL_CLASS\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Functional class of the highest-impact effect resulting from the current variant: [NONE, SILENT, MISSENSE, NONSENSE]\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_EFFECT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The highest-impact effect resulting from the current variant (or one of the highest-impact effects, if there is a tie)\" , \"EntryType\" : \"INFO\"} , \"Cases_AC\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AC for Cases\" , \"EntryType\" : \"INFO\"} , \"DB\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"dbSNP Membership\" , \"EntryType\" : \"INFO\"} , \"SVTYPE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Type of structural variant\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_GENE_BIOTYPE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Gene biotype for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"NTLEN\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"Number of bases inserted in place of deleted code\" , \"EntryType\" : \"INFO\"} , \"HOMSEQ\" : { \"number\" : \".\" , \"type\" : \"String\" , \"Description\" : \"Sequence of base pair identical micro-homology at event breakpoints\" , \"EntryType\" : \"INFO\"} , \"MQRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score From Wilcoxon rank sum test of Alt vs. Ref read mapping qualities\" , \"EntryType\" : \"INFO\"} , \"RU\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Tandem repeat unit (bases)\" , \"EntryType\" : \"INFO\"} , \"HOMLEN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Length of base pair identical micro-homology at event breakpoints\" , \"EntryType\" : \"INFO\"} , \"RPA\" : { \"number\" : \".\" , \"type\" : \"Integer\" , \"Description\" : \"Number of times tandem repeat unit is repeated, for each allele (including reference)\" , \"EntryType\" : \"INFO\"} , \"END\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"End position of the variant described in this record\" , \"EntryType\" : \"INFO\"} , \"MQ0\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Total Mapping Quality Zero Reads\" , \"EntryType\" : \"INFO\"} , \"AC1\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Max-likelihood estimate of the first ALT allele count (no HWE assumption)\" , \"EntryType\" : \"INFO\"} , \"PV4\" : { \"number\" : 4 , \"type\" : \"Float\" , \"Description\" : \"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\" , \"EntryType\" : \"INFO\"}}} , \"SAMPLES\" : { \"s_Mayo_TN_CC_254\" : 189 , \"s_Mayo_TN_CC_255\" : 190 , \"s_Mayo_TN_CC_252\" : 187 , \"s_Mayo_TN_CC_253\" : 188 , \"s_Mayo_TN_CC_250\" : 185 , \"s_Mayo_TN_CC_251\" : 186 , \"s_Mayo_TN_CC_530\" : 493 , \"s_Mayo_TN_CC_537\" : 500 , \"s_Mayo_TN_CC_538\" : 501 , \"s_Mayo_TN_CC_535\" : 498 , \"s_Mayo_TN_CC_536\" : 499 , \"s_Mayo_TN_CC_533\" : 496 , \"s_Mayo_TN_CC_534\" : 497 , \"s_Mayo_TN_CC_531\" : 494 , \"s_Mayo_TN_CC_532\" : 495 , \"s_Mayo_TN_CC_259\" : 194 , \"s_Mayo_TN_CC_258\" : 193 , \"s_Mayo_TN_CC_257\" : 192 , \"s_Mayo_TN_CC_539\" : 502 , \"s_Mayo_TN_CC_256\" : 191 , \"s_Mayo_TN_CC_241\" : 175 , \"s_Mayo_TN_CC_242\" : 176 , \"s_Mayo_TN_CC_243\" : 177 , \"s_Mayo_TN_CC_244\" : 178 , \"s_Mayo_TN_CC_240\" : 174 , \"s_Mayo_TN_CC_524\" : 486 , \"s_Mayo_TN_CC_525\" : 487 , \"s_Mayo_TN_CC_526\" : 488 , \"s_Mayo_TN_CC_527\" : 489 , \"s_Mayo_TN_CC_520\" : 482 , \"s_Mayo_TN_CC_521\" : 483 , \"s_Mayo_TN_CC_522\" : 484 , \"s_Mayo_TN_CC_523\" : 485 , \"s_Mayo_TN_CC_249\" : 183 , \"s_Mayo_TN_CC_246\" : 180 , \"s_Mayo_TN_CC_528\" : 490 , \"s_Mayo_TN_CC_245\" : 179 , \"s_Mayo_TN_CC_529\" : 491 , \"s_Mayo_TN_CC_248\" : 182 , \"s_Mayo_TN_CC_247\" : 181 , \"s_Mayo_TN_CC_232\" : 165 , \"s_Mayo_TN_CC_233\" : 166 , \"s_Mayo_TN_CC_230\" : 163 , \"s_Mayo_TN_CC_231\" : 164 , \"s_Mayo_TN_CC_798\" : 787 , \"s_Mayo_TN_CC_797\" : 786 , \"s_Mayo_TN_CC_796\" : 785 , \"s_Mayo_TN_CC_795\" : 784 , \"s_Mayo_TN_CC_799\" : 788 , \"s_Mayo_TN_CC_511\" : 472 , \"s_Mayo_TN_CC_790\" : 779 , \"s_Mayo_TN_CC_512\" : 473 , \"s_Mayo_TN_CC_510\" : 471 , \"s_Mayo_TN_CC_793\" : 782 , \"s_Mayo_TN_CC_515\" : 476 , \"s_Mayo_TN_CC_794\" : 783 , \"s_Mayo_TN_CC_516\" : 477 , \"s_Mayo_TN_CC_791\" : 780 , \"s_Mayo_TN_CC_513\" : 474 , \"s_Mayo_TN_CC_792\" : 781 , \"s_Mayo_TN_CC_514\" : 475 , \"s_Mayo_TN_CC_237\" : 170 , \"s_Mayo_TN_CC_519\" : 480 , \"s_Mayo_TN_CC_236\" : 169 , \"s_Mayo_TN_CC_235\" : 168 , \"s_Mayo_TN_CC_517\" : 478 , \"s_Mayo_TN_CC_234\" : 167 , \"s_Mayo_TN_CC_518\" : 479 , \"s_Mayo_TN_CC_239\" : 172 , \"s_Mayo_TN_CC_238\" : 171 , \"s_Mayo_TN_CC_220\" : 152 , \"s_Mayo_TN_CC_221\" : 153 , \"s_Mayo_TN_CC_222\" : 154 , \"s_Mayo_TN_CC_785\" : 773 , \"s_Mayo_TN_CC_784\" : 772 , \"s_Mayo_TN_CC_787\" : 775 , \"s_Mayo_TN_CC_786\" : 774 , \"s_Mayo_TN_CC_789\" : 777 , \"s_Mayo_TN_CC_788\" : 776 , \"s_Mayo_TN_CC_500\" : 460 , \"s_Mayo_TN_CC_501\" : 461 , \"s_Mayo_TN_CC_502\" : 462 , \"s_Mayo_TN_CC_780\" : 768 , \"s_Mayo_TN_CC_503\" : 463 , \"s_Mayo_TN_CC_781\" : 769 , \"s_Mayo_TN_CC_504\" : 464 , \"s_Mayo_TN_CC_782\" : 770 , \"s_Mayo_TN_CC_505\" : 465 , \"s_Mayo_TN_CC_783\" : 771 , \"s_Mayo_TN_CC_224\" : 156 , \"s_Mayo_TN_CC_506\" : 466 , \"s_Mayo_TN_CC_223\" : 155 , \"s_Mayo_TN_CC_507\" : 467 , \"s_Mayo_TN_CC_226\" : 158 , \"s_Mayo_TN_CC_508\" : 468 , \"s_Mayo_TN_CC_225\" : 157 , \"s_Mayo_TN_CC_509\" : 469 , \"s_Mayo_TN_CC_228\" : 160 , \"s_Mayo_TN_CC_227\" : 159 , \"s_Mayo_TN_CC_229\" : 161 , \"s_Mayo_TN_CC_291\" : 230 , \"s_Mayo_TN_CC_573\" : 540 , \"s_Mayo_TN_CC_779\" : 766 , \"s_Mayo_TN_CC_290\" : 229 , \"s_Mayo_TN_CC_574\" : 541 , \"s_Mayo_TN_CC_571\" : 538 , \"s_Mayo_TN_CC_777\" : 764 , \"s_Mayo_TN_CC_572\" : 539 , \"s_Mayo_TN_CC_778\" : 765 , \"s_Mayo_TN_CC_775\" : 762 , \"s_Mayo_TN_CC_570\" : 537 , \"s_Mayo_TN_CC_776\" : 763 , \"s_Mayo_TN_CC_773\" : 760 , \"s_Mayo_TN_CC_774\" : 761 , \"s_Mayo_TN_CC_299\" : 238 , \"s_Mayo_TN_CC_298\" : 237 , \"s_Mayo_TN_CC_297\" : 236 , \"s_Mayo_TN_CC_296\" : 235 , \"s_Mayo_TN_CC_295\" : 234 , \"s_Mayo_TN_CC_294\" : 233 , \"s_Mayo_TN_CC_293\" : 232 , \"s_Mayo_TN_CC_292\" : 231 , \"s_Mayo_TN_CC_772\" : 759 , \"s_Mayo_TN_CC_771\" : 758 , \"s_Mayo_TN_CC_770\" : 757 , \"s_Mayo_TN_CC_579\" : 546 , \"s_Mayo_TN_CC_578\" : 545 , \"s_Mayo_TN_CC_577\" : 544 , \"s_Mayo_TN_CC_576\" : 543 , \"s_Mayo_TN_CC_575\" : 542 , \"s_Mayo_TN_CC_560\" : 526 , \"s_Mayo_TN_CC_766\" : 752 , \"s_Mayo_TN_CC_561\" : 527 , \"s_Mayo_TN_CC_767\" : 753 , \"s_Mayo_TN_CC_280\" : 218 , \"s_Mayo_TN_CC_562\" : 528 , \"s_Mayo_TN_CC_768\" : 754 , \"s_Mayo_TN_CC_563\" : 529 , \"s_Mayo_TN_CC_769\" : 755 , \"s_Mayo_TN_CC_762\" : 748 , \"s_Mayo_TN_CC_763\" : 749 , \"s_Mayo_TN_CC_764\" : 750 , \"s_Mayo_TN_CC_765\" : 751 , \"s_Mayo_TN_CC_286\" : 224 , \"s_Mayo_TN_CC_285\" : 223 , \"s_Mayo_TN_CC_288\" : 226 , \"s_Mayo_TN_CC_287\" : 225 , \"s_Mayo_TN_CC_282\" : 220 , \"s_Mayo_TN_CC_281\" : 219 , \"s_Mayo_TN_CC_284\" : 222 , \"s_Mayo_TN_CC_283\" : 221 , \"s_Mayo_TN_CC_289\" : 227 , \"s_Mayo_TN_CC_569\" : 535 , \"s_Mayo_TN_CC_568\" : 534 , \"s_Mayo_TN_CC_761\" : 747 , \"s_Mayo_TN_CC_760\" : 746 , \"s_Mayo_TN_CC_565\" : 531 , \"s_Mayo_TN_CC_564\" : 530 , \"s_Mayo_TN_CC_567\" : 533 , \"s_Mayo_TN_CC_566\" : 532 , \"s_Mayo_TN_CC_753\" : 738 , \"s_Mayo_TN_CC_754\" : 739 , \"s_Mayo_TN_CC_751\" : 736 , \"s_Mayo_TN_CC_752\" : 737 , \"s_Mayo_TN_CC_551\" : 516 , \"s_Mayo_TN_CC_757\" : 742 , \"s_Mayo_TN_CC_552\" : 517 , \"s_Mayo_TN_CC_758\" : 743 , \"s_Mayo_TN_CC_755\" : 740 , \"s_Mayo_TN_CC_550\" : 515 , \"s_Mayo_TN_CC_756\" : 741 , \"s_Mayo_TN_CC_273\" : 210 , \"s_Mayo_TN_CC_272\" : 209 , \"s_Mayo_TN_CC_271\" : 208 , \"s_Mayo_TN_CC_759\" : 744 , \"s_Mayo_TN_CC_270\" : 207 , \"s_Mayo_TN_CC_277\" : 214 , \"s_Mayo_TN_CC_276\" : 213 , \"s_Mayo_TN_CC_275\" : 212 , \"s_Mayo_TN_CC_274\" : 211 , \"s_Mayo_TN_CC_278\" : 215 , \"s_Mayo_TN_CC_279\" : 216 , \"s_Mayo_TN_CC_556\" : 521 , \"s_Mayo_TN_CC_555\" : 520 , \"s_Mayo_TN_CC_554\" : 519 , \"s_Mayo_TN_CC_553\" : 518 , \"s_Mayo_TN_CC_750\" : 735 , \"s_Mayo_TN_CC_559\" : 524 , \"s_Mayo_TN_CC_558\" : 523 , \"s_Mayo_TN_CC_557\" : 522 , \"s_Mayo_TN_CC_740\" : 724 , \"s_Mayo_TN_CC_741\" : 725 , \"s_Mayo_TN_CC_742\" : 726 , \"s_Mayo_TN_CC_743\" : 727 , \"s_Mayo_TN_CC_744\" : 728 , \"s_Mayo_TN_CC_745\" : 729 , \"s_Mayo_TN_CC_540\" : 504 , \"s_Mayo_TN_CC_746\" : 730 , \"s_Mayo_TN_CC_541\" : 505 , \"s_Mayo_TN_CC_747\" : 731 , \"s_Mayo_TN_CC_260\" : 196 , \"s_Mayo_TN_CC_748\" : 732 , \"s_Mayo_TN_CC_749\" : 733 , \"s_Mayo_TN_CC_262\" : 198 , \"s_Mayo_TN_CC_261\" : 197 , \"s_Mayo_TN_CC_264\" : 200 , \"s_Mayo_TN_CC_263\" : 199 , \"s_Mayo_TN_CC_266\" : 202 , \"s_Mayo_TN_CC_265\" : 201 , \"s_Mayo_TN_CC_267\" : 203 , \"s_Mayo_TN_CC_268\" : 204 , \"s_Mayo_TN_CC_269\" : 205 , \"s_Mayo_TN_CC_543\" : 507 , \"s_Mayo_TN_CC_542\" : 506 , \"s_Mayo_TN_CC_545\" : 509 , \"s_Mayo_TN_CC_544\" : 508 , \"s_Mayo_TN_CC_547\" : 511 , \"s_Mayo_TN_CC_546\" : 510 , \"s_Mayo_TN_CC_549\" : 513 , \"s_Mayo_TN_CC_548\" : 512 , \"s_Mayo_TN_CC_738\" : 721 , \"s_Mayo_TN_CC_737\" : 720 , \"s_Mayo_TN_CC_739\" : 722 , \"s_Mayo_TN_CC_734\" : 717 , \"s_Mayo_TN_CC_733\" : 716 , \"s_Mayo_TN_CC_736\" : 719 , \"s_Mayo_TN_CC_735\" : 718 , \"s_Mayo_TN_CC_730\" : 713 , \"s_Mayo_TN_CC_732\" : 715 , \"s_Mayo_TN_CC_731\" : 714 , \"s_Mayo_TN_CC_729\" : 711 , \"s_Mayo_TN_CC_728\" : 710 , \"s_Mayo_TN_CC_727\" : 709 , \"s_Mayo_TN_CC_726\" : 708 , \"s_Mayo_TN_CC_725\" : 707 , \"s_Mayo_TN_CC_724\" : 706 , \"s_Mayo_TN_CC_723\" : 705 , \"s_Mayo_TN_CC_722\" : 704 , \"s_Mayo_TN_CC_721\" : 703 , \"s_Mayo_TN_CC_720\" : 702 , \"s_Mayo_TN_CC_716\" : 697 , \"s_Mayo_TN_CC_715\" : 696 , \"s_Mayo_TN_CC_718\" : 699 , \"s_Mayo_TN_CC_717\" : 698 , \"s_Mayo_TN_CC_719\" : 700 , \"s_Mayo_TN_CC_710\" : 691 , \"s_Mayo_TN_CC_712\" : 693 , \"s_Mayo_TN_CC_711\" : 692 , \"s_Mayo_TN_CC_714\" : 695 , \"s_Mayo_TN_CC_713\" : 694 , \"s_Mayo_TN_CC_707\" : 687 , \"s_Mayo_TN_CC_706\" : 686 , \"s_Mayo_TN_CC_705\" : 685 , \"s_Mayo_TN_CC_704\" : 684 , \"s_Mayo_TN_CC_709\" : 689 , \"s_Mayo_TN_CC_708\" : 688 , \"s_Mayo_TN_CC_703\" : 683 , \"s_Mayo_TN_CC_702\" : 682 , \"s_Mayo_TN_CC_701\" : 681 , \"s_Mayo_TN_CC_700\" : 680 , \"s_Mayo_TN_CC_588\" : 556 , \"s_Mayo_TN_CC_589\" : 557 , \"s_Mayo_TN_CC_586\" : 554 , \"s_Mayo_TN_CC_587\" : 555 , \"s_Mayo_TN_CC_585\" : 553 , \"s_Mayo_TN_CC_584\" : 552 , \"s_Mayo_TN_CC_583\" : 551 , \"s_Mayo_TN_CC_582\" : 550 , \"s_Mayo_TN_CC_581\" : 549 , \"s_Mayo_TN_CC_580\" : 548 , \"s_Mayo_TN_CC_597\" : 566 , \"s_Mayo_TN_CC_598\" : 567 , \"s_Mayo_TN_CC_599\" : 568 , \"s_Mayo_TN_CC_594\" : 563 , \"s_Mayo_TN_CC_593\" : 562 , \"s_Mayo_TN_CC_596\" : 565 , \"s_Mayo_TN_CC_595\" : 564 , \"s_Mayo_TN_CC_590\" : 559 , \"s_Mayo_TN_CC_592\" : 561 , \"s_Mayo_TN_CC_591\" : 560 , \"s_Mayo_TN_CC_203\" : 133 , \"s_Mayo_TN_CC_204\" : 134 , \"s_Mayo_TN_CC_201\" : 131 , \"s_Mayo_TN_CC_202\" : 132 , \"s_Mayo_TN_CC_207\" : 137 , \"s_Mayo_TN_CC_208\" : 138 , \"s_Mayo_TN_CC_205\" : 135 , \"s_Mayo_TN_CC_206\" : 136 , \"s_Mayo_TN_CC_209\" : 139 , \"s_Mayo_TN_CC_200\" : 130 , \"s_Mayo_TN_CC_212\" : 143 , \"s_Mayo_TN_CC_213\" : 144 , \"s_Mayo_TN_CC_214\" : 145 , \"s_Mayo_TN_CC_215\" : 146 , \"s_Mayo_TN_CC_216\" : 147 , \"s_Mayo_TN_CC_217\" : 148 , \"s_Mayo_TN_CC_218\" : 149 , \"s_Mayo_TN_CC_219\" : 150 , \"s_Mayo_TN_CC_211\" : 142 , \"s_Mayo_TN_CC_210\" : 141 , \"s_Mayo_TN_CC_37\" : 316 , \"s_Mayo_TN_CC_677\" : 654 , \"s_Mayo_TN_CC_36\" : 305 , \"s_Mayo_TN_CC_676\" : 653 , \"s_Mayo_TN_CC_35\" : 294 , \"s_Mayo_TN_CC_675\" : 652 , \"s_Mayo_TN_CC_34\" : 283 , \"s_Mayo_TN_CC_674\" : 651 , \"s_Mayo_TN_CC_33\" : 272 , \"s_Mayo_TN_CC_32\" : 261 , \"s_Mayo_TN_CC_31\" : 250 , \"s_Mayo_TN_CC_679\" : 656 , \"s_Mayo_TN_CC_30\" : 239 , \"s_Mayo_TN_CC_678\" : 655 , \"s_Mayo_TN_CC_159\" : 84 , \"s_Mayo_TN_CC_350\" : 295 , \"s_Mayo_TN_CC_157\" : 82 , \"s_Mayo_TN_CC_158\" : 83 , \"s_Mayo_TN_CC_353\" : 298 , \"s_Mayo_TN_CC_354\" : 299 , \"s_Mayo_TN_CC_39\" : 338 , \"s_Mayo_TN_CC_351\" : 296 , \"s_Mayo_TN_CC_38\" : 327 , \"s_Mayo_TN_CC_352\" : 297 , \"s_Mayo_TN_CC_358\" : 303 , \"s_Mayo_TN_CC_152\" : 77 , \"s_Mayo_TN_CC_357\" : 302 , \"s_Mayo_TN_CC_151\" : 76 , \"s_Mayo_TN_CC_356\" : 301 , \"s_Mayo_TN_CC_150\" : 75 , \"s_Mayo_TN_CC_355\" : 300 , \"s_Mayo_TN_CC_156\" : 81 , \"s_Mayo_TN_CC_155\" : 80 , \"s_Mayo_TN_CC_154\" : 79 , \"s_Mayo_TN_CC_359\" : 304 , \"s_Mayo_TN_CC_153\" : 78 , \"s_Mayo_TN_CC_40\" : 349 , \"s_Mayo_TN_CC_672\" : 649 , \"s_Mayo_TN_CC_673\" : 650 , \"s_Mayo_TN_CC_670\" : 647 , \"s_Mayo_TN_CC_671\" : 648 , \"s_Mayo_TN_CC_24\" : 173 , \"s_Mayo_TN_CC_664\" : 640 , \"s_Mayo_TN_CC_23\" : 162 , \"s_Mayo_TN_CC_663\" : 639 , \"s_Mayo_TN_CC_26\" : 195 , \"s_Mayo_TN_CC_666\" : 642 , \"s_Mayo_TN_CC_25\" : 184 , \"s_Mayo_TN_CC_665\" : 641 , \"s_Mayo_TN_CC_20\" : 129 , \"s_Mayo_TN_CC_668\" : 644 , \"s_Mayo_TN_CC_667\" : 643 , \"s_Mayo_TN_CC_22\" : 151 , \"s_Mayo_TN_CC_21\" : 140 , \"s_Mayo_TN_CC_669\" : 645 , \"s_Mayo_TN_CC_146\" : 70 , \"s_Mayo_TN_CC_147\" : 71 , \"s_Mayo_TN_CC_148\" : 72 , \"s_Mayo_TN_CC_149\" : 73 , \"s_Mayo_TN_CC_340\" : 284 , \"s_Mayo_TN_CC_28\" : 217 , \"s_Mayo_TN_CC_341\" : 285 , \"s_Mayo_TN_CC_27\" : 206 , \"s_Mayo_TN_CC_342\" : 286 , \"s_Mayo_TN_CC_343\" : 287 , \"s_Mayo_TN_CC_29\" : 228 , \"s_Mayo_TN_CC_345\" : 289 , \"s_Mayo_TN_CC_344\" : 288 , \"s_Mayo_TN_CC_347\" : 291 , \"s_Mayo_TN_CC_141\" : 65 , \"s_Mayo_TN_CC_346\" : 290 , \"s_Mayo_TN_CC_140\" : 64 , \"s_Mayo_TN_CC_349\" : 293 , \"s_Mayo_TN_CC_143\" : 67 , \"s_Mayo_TN_CC_348\" : 292 , \"s_Mayo_TN_CC_142\" : 66 , \"s_Mayo_TN_CC_145\" : 69 , \"s_Mayo_TN_CC_144\" : 68 , \"s_Mayo_TN_CC_660\" : 636 , \"s_Mayo_TN_CC_661\" : 637 , \"s_Mayo_TN_CC_662\" : 638 , \"s_Mayo_TN_CC_55\" : 514 , \"s_Mayo_TN_CC_809\" : 799 , \"s_Mayo_TN_CC_54\" : 503 , \"s_Mayo_TN_CC_808\" : 798 , \"s_Mayo_TN_CC_53\" : 492 , \"s_Mayo_TN_CC_807\" : 797 , \"s_Mayo_TN_CC_52\" : 481 , \"s_Mayo_TN_CC_806\" : 796 , \"s_Mayo_TN_CC_59\" : 558 , \"s_Mayo_TN_CC_699\" : 678 , \"s_Mayo_TN_CC_805\" : 795 , \"s_Mayo_TN_CC_58\" : 547 , \"s_Mayo_TN_CC_698\" : 677 , \"s_Mayo_TN_CC_804\" : 794 , \"s_Mayo_TN_CC_57\" : 536 , \"s_Mayo_TN_CC_697\" : 676 , \"s_Mayo_TN_CC_803\" : 793 , \"s_Mayo_TN_CC_56\" : 525 , \"s_Mayo_TN_CC_696\" : 675 , \"s_Mayo_TN_CC_802\" : 792 , \"s_Mayo_TN_CC_375\" : 322 , \"s_Mayo_TN_CC_801\" : 791 , \"s_Mayo_TN_CC_376\" : 323 , \"s_Mayo_TN_CC_800\" : 790 , \"s_Mayo_TN_CC_373\" : 320 , \"s_Mayo_TN_CC_374\" : 321 , \"s_Mayo_TN_CC_371\" : 318 , \"s_Mayo_TN_CC_372\" : 319 , \"s_Mayo_TN_CC_179\" : 106 , \"s_Mayo_TN_CC_370\" : 317 , \"s_Mayo_TN_CC_178\" : 105 , \"s_Mayo_TN_CC_177\" : 104 , \"s_Mayo_TN_CC_176\" : 103 , \"s_Mayo_TN_CC_175\" : 102 , \"s_Mayo_TN_CC_174\" : 101 , \"s_Mayo_TN_CC_379\" : 326 , \"s_Mayo_TN_CC_173\" : 100 , \"s_Mayo_TN_CC_418\" : 369 , \"s_Mayo_TN_CC_378\" : 325 , \"s_Mayo_TN_CC_172\" : 99 , \"s_Mayo_TN_CC_419\" : 370 , \"s_Mayo_TN_CC_377\" : 324 , \"s_Mayo_TN_CC_171\" : 98 , \"s_Mayo_TN_CC_416\" : 367 , \"s_Mayo_TN_CC_170\" : 97 , \"s_Mayo_TN_CC_694\" : 673 , \"s_Mayo_TN_CC_417\" : 368 , \"s_Mayo_TN_CC_695\" : 674 , \"s_Mayo_TN_CC_414\" : 365 , \"s_Mayo_TN_CC_692\" : 671 , \"s_Mayo_TN_CC_415\" : 366 , \"s_Mayo_TN_CC_693\" : 672 , \"s_Mayo_TN_CC_412\" : 363 , \"s_Mayo_TN_CC_61\" : 580 , \"s_Mayo_TN_CC_690\" : 669 , \"s_Mayo_TN_CC_413\" : 364 , \"s_Mayo_TN_CC_62\" : 591 , \"s_Mayo_TN_CC_691\" : 670 , \"s_Mayo_TN_CC_410\" : 361 , \"s_Mayo_TN_CC_411\" : 362 , \"s_Mayo_TN_CC_60\" : 569 , \"s_Mayo_TN_CC_819\" : 810 , \"s_Mayo_TN_CC_42\" : 371 , \"s_Mayo_TN_CC_818\" : 809 , \"s_Mayo_TN_CC_41\" : 360 , \"s_Mayo_TN_CC_689\" : 667 , \"s_Mayo_TN_CC_44\" : 393 , \"s_Mayo_TN_CC_43\" : 382 , \"s_Mayo_TN_CC_815\" : 806 , \"s_Mayo_TN_CC_46\" : 415 , \"s_Mayo_TN_CC_686\" : 664 , \"s_Mayo_TN_CC_814\" : 805 , \"s_Mayo_TN_CC_45\" : 404 , \"s_Mayo_TN_CC_685\" : 663 , \"s_Mayo_TN_CC_817\" : 808 , \"s_Mayo_TN_CC_48\" : 437 , \"s_Mayo_TN_CC_688\" : 666 , \"s_Mayo_TN_CC_816\" : 807 , \"s_Mayo_TN_CC_47\" : 426 , \"s_Mayo_TN_CC_687\" : 665 , \"s_Mayo_TN_CC_811\" : 802 , \"s_Mayo_TN_CC_362\" : 308 , \"s_Mayo_TN_CC_810\" : 801 , \"s_Mayo_TN_CC_363\" : 309 , \"s_Mayo_TN_CC_49\" : 448 , \"s_Mayo_TN_CC_813\" : 804 , \"s_Mayo_TN_CC_364\" : 310 , \"s_Mayo_TN_CC_812\" : 803 , \"s_Mayo_TN_CC_365\" : 311 , \"s_Mayo_TN_CC_168\" : 94 , \"s_Mayo_TN_CC_169\" : 95 , \"s_Mayo_TN_CC_360\" : 306 , \"s_Mayo_TN_CC_361\" : 307 , \"s_Mayo_TN_CC_165\" : 91 , \"s_Mayo_TN_CC_164\" : 90 , \"s_Mayo_TN_CC_167\" : 93 , \"s_Mayo_TN_CC_166\" : 92 , \"s_Mayo_TN_CC_407\" : 357 , \"s_Mayo_TN_CC_367\" : 313 , \"s_Mayo_TN_CC_161\" : 87 , \"s_Mayo_TN_CC_408\" : 358 , \"s_Mayo_TN_CC_366\" : 312 , \"s_Mayo_TN_CC_160\" : 86 , \"s_Mayo_TN_CC_409\" : 359 , \"s_Mayo_TN_CC_369\" : 315 , \"s_Mayo_TN_CC_163\" : 89 , \"s_Mayo_TN_CC_368\" : 314 , \"s_Mayo_TN_CC_162\" : 88 , \"s_Mayo_TN_CC_403\" : 353 , \"s_Mayo_TN_CC_681\" : 659 , \"s_Mayo_TN_CC_404\" : 354 , \"s_Mayo_TN_CC_682\" : 660 , \"s_Mayo_TN_CC_405\" : 355 , \"s_Mayo_TN_CC_683\" : 661 , \"s_Mayo_TN_CC_406\" : 356 , \"s_Mayo_TN_CC_684\" : 662 , \"s_Mayo_TN_CC_400\" : 350 , \"s_Mayo_TN_CC_401\" : 351 , \"s_Mayo_TN_CC_50\" : 459 , \"s_Mayo_TN_CC_402\" : 352 , \"s_Mayo_TN_CC_51\" : 470 , \"s_Mayo_TN_CC_680\" : 658 , \"s_Mayo_TN_CC_394\" : 343 , \"s_Mayo_TN_CC_116\" : 37 , \"s_Mayo_TN_CC_820\" : 812 , \"s_Mayo_TN_CC_393\" : 342 , \"s_Mayo_TN_CC_115\" : 36 , \"s_Mayo_TN_CC_392\" : 341 , \"s_Mayo_TN_CC_114\" : 35 , \"s_Mayo_TN_CC_638\" : 611 , \"s_Mayo_TN_CC_391\" : 340 , \"s_Mayo_TN_CC_113\" : 34 , \"s_Mayo_TN_CC_639\" : 612 , \"s_Mayo_TN_CC_823\" : 815 , \"s_Mayo_TN_CC_398\" : 347 , \"s_Mayo_TN_CC_824\" : 816 , \"s_Mayo_TN_CC_397\" : 346 , \"s_Mayo_TN_CC_119\" : 40 , \"s_Mayo_TN_CC_821\" : 813 , \"s_Mayo_TN_CC_396\" : 345 , \"s_Mayo_TN_CC_118\" : 39 , \"s_Mayo_TN_CC_822\" : 814 , \"s_Mayo_TN_CC_395\" : 344 , \"s_Mayo_TN_CC_117\" : 38 , \"s_Mayo_TN_CC_827\" : 819 , \"s_Mayo_TN_CC_632\" : 605 , \"s_Mayo_TN_CC_828\" : 820 , \"s_Mayo_TN_CC_633\" : 606 , \"s_Mayo_TN_CC_825\" : 817 , \"s_Mayo_TN_CC_630\" : 603 , \"s_Mayo_TN_CC_826\" : 818 , \"s_Mayo_TN_CC_631\" : 604 , \"s_Mayo_TN_CC_430\" : 383 , \"s_Mayo_TN_CC_390\" : 339 , \"s_Mayo_TN_CC_636\" : 609 , \"s_Mayo_TN_CC_431\" : 384 , \"s_Mayo_TN_CC_637\" : 610 , \"s_Mayo_TN_CC_829\" : 821 , \"s_Mayo_TN_CC_634\" : 607 , \"s_Mayo_TN_CC_635\" : 608 , \"s_Mayo_TN_CC_435\" : 388 , \"s_Mayo_TN_CC_434\" : 387 , \"s_Mayo_TN_CC_433\" : 386 , \"s_Mayo_TN_CC_432\" : 385 , \"s_Mayo_TN_CC_439\" : 392 , \"s_Mayo_TN_CC_438\" : 391 , \"s_Mayo_TN_CC_437\" : 390 , \"s_Mayo_TN_CC_436\" : 389 , \"s_Mayo_TN_CC_399\" : 348 , \"s_Mayo_TN_CC_111\" : 32 , \"s_Mayo_TN_CC_112\" : 33 , \"s_Mayo_TN_CC_110\" : 31 , \"s_Mayo_TN_CC_381\" : 329 , \"s_Mayo_TN_CC_103\" : 23 , \"s_Mayo_TN_CC_627\" : 599 , \"s_Mayo_TN_CC_380\" : 328 , \"s_Mayo_TN_CC_102\" : 22 , \"s_Mayo_TN_CC_628\" : 600 , \"s_Mayo_TN_CC_830\" : 823 , \"s_Mayo_TN_CC_383\" : 331 , \"s_Mayo_TN_CC_105\" : 25 , \"s_Mayo_TN_CC_629\" : 601 , \"s_Mayo_TN_CC_831\" : 824 , \"s_Mayo_TN_CC_382\" : 330 , \"s_Mayo_TN_CC_104\" : 24 , \"s_Mayo_TN_CC_832\" : 825 , \"s_Mayo_TN_CC_385\" : 333 , \"s_Mayo_TN_CC_107\" : 27 , \"s_Mayo_TN_CC_833\" : 826 , \"s_Mayo_TN_CC_384\" : 332 , \"s_Mayo_TN_CC_106\" : 26 , \"s_Mayo_TN_CC_834\" : 827 , \"s_Mayo_TN_CC_387\" : 335 , \"s_Mayo_TN_CC_109\" : 29 , \"s_Mayo_TN_CC_835\" : 828 , \"s_Mayo_TN_CC_386\" : 334 , \"s_Mayo_TN_CC_108\" : 28 , \"s_Mayo_TN_CC_836\" : 829 , \"s_Mayo_TN_CC_837\" : 830 , \"s_Mayo_TN_CC_620\" : 592 , \"s_Mayo_TN_CC_838\" : 831 , \"s_Mayo_TN_CC_621\" : 593 , \"s_Mayo_TN_CC_839\" : 832 , \"s_Mayo_TN_CC_622\" : 594 , \"s_Mayo_TN_CC_623\" : 595 , \"s_Mayo_TN_CC_624\" : 596 , \"s_Mayo_TN_CC_625\" : 597 , \"s_Mayo_TN_CC_420\" : 372 , \"s_Mayo_TN_CC_626\" : 598 , \"s_Mayo_TN_CC_422\" : 374 , \"s_Mayo_TN_CC_421\" : 373 , \"s_Mayo_TN_CC_424\" : 376 , \"s_Mayo_TN_CC_423\" : 375 , \"s_Mayo_TN_CC_426\" : 378 , \"s_Mayo_TN_CC_425\" : 377 , \"s_Mayo_TN_CC_428\" : 380 , \"s_Mayo_TN_CC_427\" : 379 , \"s_Mayo_TN_CC_388\" : 336 , \"s_Mayo_TN_CC_429\" : 381 , \"s_Mayo_TN_CC_389\" : 337 , \"s_Mayo_TN_CC_100\" : 20 , \"s_Mayo_TN_CC_101\" : 21 , \"s_Mayo_TN_CC_845\" : 839 , \"s_Mayo_TN_CC_18\" : 107 , \"s_Mayo_TN_CC_846\" : 840 , \"s_Mayo_TN_CC_19\" : 118 , \"s_Mayo_TN_CC_843\" : 837 , \"s_Mayo_TN_CC_16\" : 85 , \"s_Mayo_TN_CC_844\" : 838 , \"s_Mayo_TN_CC_17\" : 96 , \"s_Mayo_TN_CC_139\" : 62 , \"s_Mayo_TN_CC_841\" : 835 , \"s_Mayo_TN_CC_138\" : 61 , \"s_Mayo_TN_CC_842\" : 836 , \"s_Mayo_TN_CC_137\" : 60 , \"s_Mayo_TN_CC_136\" : 59 , \"s_Mayo_TN_CC_840\" : 834 , \"s_Mayo_TN_CC_135\" : 58 , \"s_Mayo_TN_CC_10\" : 19 , \"s_Mayo_TN_CC_452\" : 407 , \"s_Mayo_TN_CC_658\" : 633 , \"s_Mayo_TN_CC_11\" : 30 , \"s_Mayo_TN_CC_453\" : 408 , \"s_Mayo_TN_CC_659\" : 634 , \"s_Mayo_TN_CC_450\" : 405 , \"s_Mayo_TN_CC_656\" : 631 , \"s_Mayo_TN_CC_451\" : 406 , \"s_Mayo_TN_CC_657\" : 632 , \"s_Mayo_TN_CC_849\" : 843 , \"s_Mayo_TN_CC_14\" : 63 , \"s_Mayo_TN_CC_654\" : 629 , \"s_Mayo_TN_CC_15\" : 74 , \"s_Mayo_TN_CC_655\" : 630 , \"s_Mayo_TN_CC_847\" : 841 , \"s_Mayo_TN_CC_12\" : 41 , \"s_Mayo_TN_CC_652\" : 627 , \"s_Mayo_TN_CC_848\" : 842 , \"s_Mayo_TN_CC_13\" : 52 , \"s_Mayo_TN_CC_653\" : 628 , \"s_Mayo_TN_CC_651\" : 626 , \"s_Mayo_TN_CC_650\" : 625 , \"s_Mayo_TN_CC_459\" : 414 , \"s_Mayo_TN_CC_458\" : 413 , \"s_Mayo_TN_CC_457\" : 412 , \"s_Mayo_TN_CC_456\" : 411 , \"s_Mayo_TN_CC_455\" : 410 , \"s_Mayo_TN_CC_454\" : 409 , \"s_Mayo_TN_CC_133\" : 56 , \"s_Mayo_TN_CC_134\" : 57 , \"s_Mayo_TN_CC_131\" : 54 , \"s_Mayo_TN_CC_132\" : 55 , \"s_Mayo_TN_CC_130\" : 53 , \"s_Mayo_TN_CC_854\" : 849 , \"s_Mayo_TN_CC_05\" : 14 , \"s_Mayo_TN_CC_129\" : 51 , \"s_Mayo_TN_CC_855\" : 850 , \"s_Mayo_TN_CC_06\" : 15 , \"s_Mayo_TN_CC_128\" : 50 , \"s_Mayo_TN_CC_856\" : 851 , \"s_Mayo_TN_CC_07\" : 16 , \"s_Mayo_TN_CC_857\" : 852 , \"s_Mayo_TN_CC_08\" : 17 , \"s_Mayo_TN_CC_850\" : 845 , \"s_Mayo_TN_CC_09\" : 18 , \"s_Mayo_TN_CC_125\" : 47 , \"s_Mayo_TN_CC_649\" : 623 , \"s_Mayo_TN_CC_851\" : 846 , \"s_Mayo_TN_CC_124\" : 46 , \"s_Mayo_TN_CC_852\" : 847 , \"s_Mayo_TN_CC_127\" : 49 , \"s_Mayo_TN_CC_853\" : 848 , \"s_Mayo_TN_CC_126\" : 48 , \"s_Mayo_TN_CC_645\" : 619 , \"s_Mayo_TN_CC_440\" : 394 , \"s_Mayo_TN_CC_646\" : 620 , \"s_Mayo_TN_CC_441\" : 395 , \"s_Mayo_TN_CC_647\" : 621 , \"s_Mayo_TN_CC_442\" : 396 , \"s_Mayo_TN_CC_648\" : 622 , \"s_Mayo_TN_CC_858\" : 853 , \"s_Mayo_TN_CC_01\" : 10 , \"s_Mayo_TN_CC_641\" : 615 , \"s_Mayo_TN_CC_859\" : 854 , \"s_Mayo_TN_CC_02\" : 11 , \"s_Mayo_TN_CC_642\" : 616 , \"s_Mayo_TN_CC_03\" : 12 , \"s_Mayo_TN_CC_643\" : 617 , \"s_Mayo_TN_CC_04\" : 13 , \"s_Mayo_TN_CC_644\" : 618 , \"s_Mayo_TN_CC_448\" : 402 , \"s_Mayo_TN_CC_447\" : 401 , \"s_Mayo_TN_CC_640\" : 614 , \"s_Mayo_TN_CC_449\" : 403 , \"s_Mayo_TN_CC_444\" : 398 , \"s_Mayo_TN_CC_443\" : 397 , \"s_Mayo_TN_CC_446\" : 400 , \"s_Mayo_TN_CC_445\" : 399 , \"s_Mayo_TN_CC_120\" : 42 , \"s_Mayo_TN_CC_121\" : 43 , \"s_Mayo_TN_CC_122\" : 44 , \"s_Mayo_TN_CC_123\" : 45 , \"s_Mayo_TN_CC_860\" : 856 , \"s_Mayo_TN_CC_869\" : 865 , \"s_Mayo_TN_CC_862\" : 858 , \"s_Mayo_TN_CC_861\" : 857 , \"s_Mayo_TN_CC_864\" : 860 , \"s_Mayo_TN_CC_863\" : 859 , \"s_Mayo_TN_CC_866\" : 862 , \"s_Mayo_TN_CC_865\" : 861 , \"s_Mayo_TN_CC_868\" : 864 , \"s_Mayo_TN_CC_867\" : 863 , \"s_Mayo_TN_CC_870\" : 867 , \"s_Mayo_TN_CC_871\" : 868 , \"s_Mayo_TN_CC_875\" : 872 , \"s_Mayo_TN_CC_874\" : 871 , \"s_Mayo_TN_CC_873\" : 870 , \"s_Mayo_TN_CC_872\" : 869 , \"s_Mayo_TN_CC_879\" : 876 , \"s_Mayo_TN_CC_878\" : 875 , \"s_Mayo_TN_CC_877\" : 874 , \"s_Mayo_TN_CC_876\" : 873 , \"s_Mayo_TN_CC_880\" : 878 , \"s_Mayo_TN_CC_881\" : 879 , \"s_Mayo_TN_CC_882\" : 880 , \"s_Mayo_TN_CC_613\" : 584 , \"s_Mayo_TN_CC_612\" : 583 , \"s_Mayo_TN_CC_615\" : 586 , \"s_Mayo_TN_CC_614\" : 585 , \"s_Mayo_TN_CC_611\" : 582 , \"s_Mayo_TN_CC_610\" : 581 , \"s_Mayo_TN_CC_888\" : 886 , \"s_Mayo_TN_CC_887\" : 885 , \"s_Mayo_TN_CC_884\" : 882 , \"s_Mayo_TN_CC_617\" : 588 , \"s_Mayo_TN_CC_883\" : 881 , \"s_Mayo_TN_CC_616\" : 587 , \"s_Mayo_TN_CC_886\" : 884 , \"s_Mayo_TN_CC_619\" : 590 , \"s_Mayo_TN_CC_885\" : 883 , \"s_Mayo_TN_CC_618\" : 589 , \"s_Mayo_TN_CC_604\" : 574 , \"s_Mayo_TN_CC_603\" : 573 , \"s_Mayo_TN_CC_602\" : 572 , \"s_Mayo_TN_CC_601\" : 571 , \"s_Mayo_TN_CC_600\" : 570 , \"s_Mayo_TN_CC_609\" : 579 , \"s_Mayo_TN_CC_608\" : 578 , \"s_Mayo_TN_CC_607\" : 577 , \"s_Mayo_TN_CC_606\" : 576 , \"s_Mayo_TN_CC_605\" : 575 , \"s_Mayo_TN_CC_82\" : 811 , \"s_Mayo_TN_CC_81\" : 800 , \"s_Mayo_TN_CC_84\" : 833 , \"s_Mayo_TN_CC_83\" : 822 , \"s_Mayo_TN_CC_190\" : 119 , \"s_Mayo_TN_CC_80\" : 789 , \"s_Mayo_TN_CC_191\" : 120 , \"s_Mayo_TN_CC_192\" : 121 , \"s_Mayo_TN_CC_193\" : 122 , \"s_Mayo_TN_CC_194\" : 123 , \"s_Mayo_TN_CC_195\" : 124 , \"s_Mayo_TN_CC_196\" : 125 , \"s_Mayo_TN_CC_197\" : 126 , \"s_Mayo_TN_CC_198\" : 127 , \"s_Mayo_TN_CC_199\" : 128 , \"s_Mayo_TN_CC_78\" : 767 , \"s_Mayo_TN_CC_79\" : 778 , \"s_Mayo_TN_CC_74\" : 723 , \"s_Mayo_TN_CC_75\" : 734 , \"s_Mayo_TN_CC_76\" : 745 , \"s_Mayo_TN_CC_77\" : 756 , \"s_Mayo_TN_CC_73\" : 712 , \"s_Mayo_TN_CC_72\" : 701 , \"s_Mayo_TN_CC_71\" : 690 , \"s_Mayo_TN_CC_70\" : 679 , \"s_Mayo_TN_CC_180\" : 108 , \"s_Mayo_TN_CC_181\" : 109 , \"s_Mayo_TN_CC_184\" : 112 , \"s_Mayo_TN_CC_185\" : 113 , \"s_Mayo_TN_CC_182\" : 110 , \"s_Mayo_TN_CC_183\" : 111 , \"s_Mayo_TN_CC_188\" : 116 , \"s_Mayo_TN_CC_189\" : 117 , \"s_Mayo_TN_CC_186\" : 114 , \"s_Mayo_TN_CC_187\" : 115 , \"s_Mayo_TN_CC_69\" : 668 , \"s_Mayo_TN_CC_67\" : 646 , \"s_Mayo_TN_CC_68\" : 657 , \"s_Mayo_TN_CC_65\" : 624 , \"s_Mayo_TN_CC_66\" : 635 , \"s_Mayo_TN_CC_63\" : 602 , \"s_Mayo_TN_CC_64\" : 613 , \"s_Mayo_TN_CC_96\" : 894 , \"s_Mayo_TN_CC_97\" : 895 , \"s_Mayo_TN_CC_98\" : 896 , \"s_Mayo_TN_CC_99\" : 897 , \"s_Mayo_TN_CC_91\" : 889 , \"s_Mayo_TN_CC_90\" : 888 , \"s_Mayo_TN_CC_95\" : 893 , \"s_Mayo_TN_CC_94\" : 892 , \"s_Mayo_TN_CC_93\" : 891 , \"s_Mayo_TN_CC_92\" : 890 , \"s_Mayo_TN_CC_87\" : 866 , \"s_Mayo_TN_CC_88\" : 877 , \"s_Mayo_TN_CC_85\" : 844 , \"s_Mayo_TN_CC_86\" : 855 , \"s_Mayo_TN_CC_89\" : 887 , \"s_Mayo_TN_CC_469\" : 425 , \"s_Mayo_TN_CC_467\" : 423 , \"s_Mayo_TN_CC_468\" : 424 , \"s_Mayo_TN_CC_465\" : 421 , \"s_Mayo_TN_CC_466\" : 422 , \"s_Mayo_TN_CC_464\" : 420 , \"s_Mayo_TN_CC_463\" : 419 , \"s_Mayo_TN_CC_462\" : 418 , \"s_Mayo_TN_CC_461\" : 417 , \"s_Mayo_TN_CC_460\" : 416 , \"s_Mayo_TN_CC_476\" : 433 , \"s_Mayo_TN_CC_477\" : 434 , \"s_Mayo_TN_CC_478\" : 435 , \"s_Mayo_TN_CC_479\" : 436 , \"s_Mayo_TN_CC_473\" : 430 , \"s_Mayo_TN_CC_472\" : 429 , \"s_Mayo_TN_CC_475\" : 432 , \"s_Mayo_TN_CC_474\" : 431 , \"s_Mayo_TN_CC_471\" : 428 , \"s_Mayo_TN_CC_470\" : 427 , \"s_Mayo_TN_CC_489\" : 447 , \"s_Mayo_TN_CC_487\" : 445 , \"s_Mayo_TN_CC_488\" : 446 , \"s_Mayo_TN_CC_482\" : 440 , \"s_Mayo_TN_CC_481\" : 439 , \"s_Mayo_TN_CC_480\" : 438 , \"s_Mayo_TN_CC_486\" : 444 , \"s_Mayo_TN_CC_485\" : 443 , \"s_Mayo_TN_CC_484\" : 442 , \"s_Mayo_TN_CC_483\" : 441 , \"s_Mayo_TN_CC_498\" : 457 , \"s_Mayo_TN_CC_499\" : 458 , \"s_Mayo_TN_CC_491\" : 450 , \"s_Mayo_TN_CC_490\" : 449 , \"s_Mayo_TN_CC_493\" : 452 , \"s_Mayo_TN_CC_492\" : 451 , \"s_Mayo_TN_CC_495\" : 454 , \"s_Mayo_TN_CC_494\" : 453 , \"s_Mayo_TN_CC_497\" : 456 , \"s_Mayo_TN_CC_496\" : 455 , \"s_Mayo_TN_CC_308\" : 248 , \"s_Mayo_TN_CC_309\" : 249 , \"s_Mayo_TN_CC_306\" : 246 , \"s_Mayo_TN_CC_307\" : 247 , \"s_Mayo_TN_CC_304\" : 244 , \"s_Mayo_TN_CC_305\" : 245 , \"s_Mayo_TN_CC_302\" : 242 , \"s_Mayo_TN_CC_303\" : 243 , \"s_Mayo_TN_CC_300\" : 240 , \"s_Mayo_TN_CC_301\" : 241 , \"s_Mayo_TN_CC_319\" : 260 , \"s_Mayo_TN_CC_315\" : 256 , \"s_Mayo_TN_CC_316\" : 257 , \"s_Mayo_TN_CC_317\" : 258 , \"s_Mayo_TN_CC_318\" : 259 , \"s_Mayo_TN_CC_311\" : 252 , \"s_Mayo_TN_CC_312\" : 253 , \"s_Mayo_TN_CC_313\" : 254 , \"s_Mayo_TN_CC_314\" : 255 , \"s_Mayo_TN_CC_310\" : 251 , \"s_Mayo_TN_CC_324\" : 266 , \"s_Mayo_TN_CC_325\" : 267 , \"s_Mayo_TN_CC_322\" : 264 , \"s_Mayo_TN_CC_323\" : 265 , \"s_Mayo_TN_CC_328\" : 270 , \"s_Mayo_TN_CC_329\" : 271 , \"s_Mayo_TN_CC_326\" : 268 , \"s_Mayo_TN_CC_327\" : 269 , \"s_Mayo_TN_CC_321\" : 263 , \"s_Mayo_TN_CC_320\" : 262 , \"s_Mayo_TN_CC_333\" : 276 , \"s_Mayo_TN_CC_334\" : 277 , \"s_Mayo_TN_CC_335\" : 278 , \"s_Mayo_TN_CC_336\" : 279 , \"s_Mayo_TN_CC_337\" : 280 , \"s_Mayo_TN_CC_338\" : 281 , \"s_Mayo_TN_CC_339\" : 282 , \"s_Mayo_TN_CC_330\" : 273 , \"s_Mayo_TN_CC_332\" : 275 , \"s_Mayo_TN_CC_331\" : 274} , \"FORMAT\" : { \"min\" : { \"PL\" : 1 , \"AD\" : 1 , \"GT\" : 1 , \"GQ\" : 1} , \"max\" : { \"PL\" : 1 , \"AD\" : 1 , \"GT\" : 1 , \"GQ\" : 1}}}";
//assertEquals(expectedMetadataAfterChange.replaceAll("\\s+",""), parser.getMetadata().toString().replaceAll("\\s+",""));
}
List<String> dbSNP4 = Arrays.asList(
"{\"CHROM\":\"1\",\"POS\":\"10144\",\"ID\":\"rs144773400\",\"REF\":\"TA\",\"ALT\":\"T\",\"QUAL\":\".\",\"FILTER\":\".\",\"INFO\":{\"RSPOS\":10145,\"dbSNPBuildID\":134,\"SSR\":0,\"SAO\":0,\"VP\":\"050000000005000002000200\",\"WGT\":1,\"VC\":\"DIV\",\"ASP\":true,\"OTHERKG\":true},\"_ident\":\"rs144773400\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"TA\",\"_altAlleles\":[\"T\"],\"_minBP\":10144,\"_maxBP\":10145}",
"{\"CHROM\":\"1\",\"POS\":\"10177\",\"ID\":\"rs201752861\",\"REF\":\"A\",\"ALT\":\"C\",\"QUAL\":\".\",\"FILTER\":\".\",\"INFO\":{\"RSPOS\":10177,\"dbSNPBuildID\":137,\"SSR\":0,\"SAO\":0,\"VP\":\"050000000005000002000100\",\"WGT\":1,\"VC\":\"SNV\",\"ASP\":true,\"OTHERKG\":true},\"_ident\":\"rs201752861\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"A\",\"_altAlleles\":[\"C\"],\"_minBP\":10177,\"_maxBP\":10177}",
"{\"CHROM\":\"1\",\"POS\":\"10180\",\"ID\":\"rs201694901\",\"REF\":\"T\",\"ALT\":\"C\",\"QUAL\":\".\",\"FILTER\":\".\",\"INFO\":{\"RSPOS\":10180,\"dbSNPBuildID\":137,\"SSR\":0,\"SAO\":0,\"VP\":\"050000000005000002000100\",\"WGT\":1,\"VC\":\"SNV\",\"ASP\":true,\"OTHERKG\":true},\"_ident\":\"rs201694901\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"T\",\"_altAlleles\":[\"C\"],\"_minBP\":10180,\"_maxBP\":10180}",
"{\"CHROM\":\"1\",\"POS\":\"10228\",\"ID\":\"rs143255646\",\"REF\":\"TA\",\"ALT\":\"T\",\"QUAL\":\".\",\"FILTER\":\".\",\"INFO\":{\"RSPOS\":10229,\"dbSNPBuildID\":134,\"SSR\":0,\"SAO\":0,\"VP\":\"050000000005000002000200\",\"WGT\":1,\"VC\":\"DIV\",\"ASP\":true,\"OTHERKG\":true},\"_ident\":\"rs143255646\",\"_type\":\"variant\",\"_landmark\":\"1\",\"_refAllele\":\"TA\",\"_altAlleles\":[\"T\"],\"_minBP\":10228,\"_maxBP\":10229}"
);
/**
* This method should not hang, even though there are not samples!
*/
@Test
public void testHang() throws ProcessTerminatedException {
System.out.println("Running: edu.mayo.ve.VCFParser.VCFParserITCase.testHang");
String collection = "thisshouldnot";
String workspace = "workspace1234";
VCFParser parser = new VCFParser();
parser.parse(null, "src/test/resources/testData/dbSNP4Variants.vcf",workspace,1000,true, reporting, true);
HashMap<Integer, String> col = parser.getTestingCollection();
int i =0;
for(String s : dbSNP4){
assertEquals(s, col.get(i));
i++;
}
System.out.println(parser.getJson());
}
@Test
public void testSoftSearch() throws ProcessTerminatedException {
System.out.println("Running: edu.mayo.ve.VCFParser.VCFParserITCase.testSoftSearch");
String softSearchVCF = "src/test/resources/testData/SoftSearch_for_Dan.vcf";
VCFParser parser = new VCFParser();
String workspace = "workspace1234";
parser.parse(null, softSearchVCF,workspace,1000000,true, reporting, true);
HashMap<Integer, String> col = parser.getTestingCollection();
// for(String s : col.values()){
// System.out.println(s);
System.out.println("
System.out.println(parser.getJson().toString());
}
//DEPRICATED
// String metaAddCache = "{ \"FORMAT\" : { \"PL\" : 1, \"AD\" : 1, \"GT\" : 1, \"GQ\" : 1, \"DP\" : 1, \"MLPSAF\" : 1, \"MLPSAC\" : 1 }, \"INFO\" : { \"HaplotypeScore\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Consistency of the site with at most two segregating haplotypes\", \"EntryType\" : \"INFO\" }, \"InbreedingCoeff\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Inbreeding coefficient as estimated from the genotype likelihoods per-sample when compared against the Hardy-Weinberg expectation\", \"EntryType\" : \"INFO\" }, \"MLEAC\" : { \"number\" : null, \"type\" : \"Integer\", \"Description\" : \"Maximum likelihood expectation (MLE) for the allele counts (not necessarily the same as the AC), for each ALT allele, in the same order as listed\", \"EntryType\" : \"INFO\" }, \"MLEAF\" : { \"number\" : null, \"type\" : \"Float\", \"Description\" : \"Maximum likelihood expectation (MLE) for the allele frequency (not necessarily the same as the AF), for each ALT allele, in the same order as listed\", \"EntryType\" : \"INFO\" }, \"FS\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Phred-scaled p-value using Fisher's exact test to detect strand bias\", \"EntryType\" : \"INFO\" }, \"ReadPosRankSum\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt vs. Ref read position bias\", \"EntryType\" : \"INFO\" }, \"DP\" : { \"number\" : 1, \"type\" : \"Integer\", \"Description\" : \"Approximate read depth; some reads may have been filtered\", \"EntryType\" : \"INFO\" }, \"DS\" : { \"number\" : 0, \"type\" : \"Flag\", \"Description\" : \"Were any of the samples downsampled?\", \"EntryType\" : \"INFO\" }, \"STR\" : { \"number\" : 0, \"type\" : \"Flag\", \"Description\" : \"Variant is a short tandem repeat\", \"EntryType\" : \"INFO\" }, \"BaseQRankSum\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt Vs. Ref base qualities\", \"EntryType\" : \"INFO\" }, \"QD\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Variant Confidence/Quality by Depth\", \"EntryType\" : \"INFO\" }, \"MQ\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"RMS Mapping Quality\", \"EntryType\" : \"INFO\" }, \"AC\" : { \"number\" : null, \"type\" : \"Integer\", \"Description\" : \"Allele count in genotypes, for each ALT allele, in the same order as listed\", \"EntryType\" : \"INFO\" }, \"PL\" : { \"number\" : null, \"type\" : \"Integer\", \"Description\" : \"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\", \"EntryType\" : \"FORMAT\" }, \"AD\" : { \"number\" : null, \"type\" : \"Integer\", \"Description\" : \"Allelic depths for the ref and alt alleles in the order listed\", \"EntryType\" : \"FORMAT\" }, \"GT\" : { \"number\" : 1, \"type\" : \"String\", \"Description\" : \"Genotype\", \"EntryType\" : \"FORMAT\" }, \"MQRankSum\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Z-score From Wilcoxon rank sum test of Alt vs. Ref read mapping qualities\", \"EntryType\" : \"INFO\" }, \"RU\" : { \"number\" : 1, \"type\" : \"String\", \"Description\" : \"Tandem repeat unit (bases)\", \"EntryType\" : \"INFO\" }, \"Dels\" : { \"number\" : 1, \"type\" : \"Float\", \"Description\" : \"Fraction of Reads Containing Spanning Deletions\", \"EntryType\" : \"INFO\" }, \"GQ\" : { \"number\" : 1, \"type\" : \"Integer\", \"Description\" : \"Genotype Quality\", \"EntryType\" : \"FORMAT\" }, \"RPA\" : { \"number\" : null, \"type\" : \"Integer\", \"Description\" : \"Number of times tandem repeat unit is repeated, for each allele (including reference)\", \"EntryType\" : \"INFO\" }, \"AF\" : { \"number\" : null, \"type\" : \"Float\", \"Description\" : \"Allele Frequency, for each ALT allele, in the same order as listed\", \"EntryType\" : \"INFO\" }, \"MLPSAF\" : { \"number\" : null, \"type\" : \"Float\", \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele fraction, in the same order as listed, for each individual sample\", \"EntryType\" : \"FORMAT\" }, \"MQ0\" : { \"number\" : 1, \"type\" : \"Integer\", \"Description\" : \"Total Mapping Quality Zero Reads\", \"EntryType\" : \"INFO\" }, \"MLPSAC\" : { \"number\" : null, \"type\" : \"Integer\", \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele count, in the same order as listed, for each individual sample\", \"EntryType\" : \"FORMAT\" }, \"AN\" : { \"number\" : 1, \"type\" : \"Integer\", \"Description\" : \"Total number of alleles in called genotypes\", \"EntryType\" : \"INFO\" } }, \"SAMPLES\" : { \"s_Mayo_TN_CC_394\" : 91, \"s_Mayo_TN_CC_393\" : 90, \"s_Mayo_TN_CC_392\" : 89, \"s_Mayo_TN_CC_391\" : 88, \"s_Mayo_TN_CC_398\" : 95, \"s_Mayo_TN_CC_397\" : 94, \"s_Mayo_TN_CC_396\" : 93, \"s_Mayo_TN_CC_395\" : 92, \"s_Mayo_TN_CC_350\" : 47, \"s_Mayo_TN_CC_390\" : 87, \"s_Mayo_TN_CC_353\" : 50, \"s_Mayo_TN_CC_354\" : 51, \"s_Mayo_TN_CC_351\" : 48, \"s_Mayo_TN_CC_352\" : 49, \"s_Mayo_TN_CC_358\" : 55, \"s_Mayo_TN_CC_357\" : 54, \"s_Mayo_TN_CC_356\" : 53, \"s_Mayo_TN_CC_355\" : 52, \"s_Mayo_TN_CC_359\" : 56, \"s_Mayo_TN_CC_399\" : 96, \"s_Mayo_TN_CC_381\" : 78, \"s_Mayo_TN_CC_380\" : 77, \"s_Mayo_TN_CC_383\" : 80, \"s_Mayo_TN_CC_382\" : 79, \"s_Mayo_TN_CC_385\" : 82, \"s_Mayo_TN_CC_319\" : 16, \"s_Mayo_TN_CC_384\" : 81, \"s_Mayo_TN_CC_387\" : 84, \"s_Mayo_TN_CC_386\" : 83, \"s_Mayo_TN_CC_315\" : 12, \"s_Mayo_TN_CC_316\" : 13, \"s_Mayo_TN_CC_317\" : 14, \"s_Mayo_TN_CC_318\" : 15, \"s_Mayo_TN_CC_340\" : 37, \"s_Mayo_TN_CC_341\" : 38, \"s_Mayo_TN_CC_313\" : 10, \"s_Mayo_TN_CC_342\" : 39, \"s_Mayo_TN_CC_314\" : 11, \"s_Mayo_TN_CC_343\" : 40, \"s_Mayo_TN_CC_345\" : 42, \"s_Mayo_TN_CC_344\" : 41, \"s_Mayo_TN_CC_347\" : 44, \"s_Mayo_TN_CC_346\" : 43, \"s_Mayo_TN_CC_349\" : 46, \"s_Mayo_TN_CC_348\" : 45, \"s_Mayo_TN_CC_388\" : 85, \"s_Mayo_TN_CC_389\" : 86, \"s_Mayo_TN_CC_375\" : 72, \"s_Mayo_TN_CC_324\" : 21, \"s_Mayo_TN_CC_376\" : 73, \"s_Mayo_TN_CC_325\" : 22, \"s_Mayo_TN_CC_373\" : 70, \"s_Mayo_TN_CC_322\" : 19, \"s_Mayo_TN_CC_374\" : 71, \"s_Mayo_TN_CC_323\" : 20, \"s_Mayo_TN_CC_371\" : 68, \"s_Mayo_TN_CC_328\" : 25, \"s_Mayo_TN_CC_372\" : 69, \"s_Mayo_TN_CC_329\" : 26, \"s_Mayo_TN_CC_326\" : 23, \"s_Mayo_TN_CC_370\" : 67, \"s_Mayo_TN_CC_327\" : 24, \"s_Mayo_TN_CC_321\" : 18, \"s_Mayo_TN_CC_379\" : 76, \"s_Mayo_TN_CC_320\" : 17, \"s_Mayo_TN_CC_378\" : 75, \"s_Mayo_TN_CC_377\" : 74, \"s_Mayo_TN_CC_362\" : 59, \"s_Mayo_TN_CC_333\" : 30, \"s_Mayo_TN_CC_363\" : 60, \"s_Mayo_TN_CC_334\" : 31, \"s_Mayo_TN_CC_364\" : 61, \"s_Mayo_TN_CC_335\" : 32, \"s_Mayo_TN_CC_365\" : 62, \"s_Mayo_TN_CC_336\" : 33, \"s_Mayo_TN_CC_337\" : 34, \"s_Mayo_TN_CC_338\" : 35, \"s_Mayo_TN_CC_339\" : 36, \"s_Mayo_TN_CC_360\" : 57, \"s_Mayo_TN_CC_361\" : 58, \"s_Mayo_TN_CC_407\" : 104, \"s_Mayo_TN_CC_367\" : 64, \"s_Mayo_TN_CC_330\" : 27, \"s_Mayo_TN_CC_408\" : 105, \"s_Mayo_TN_CC_366\" : 63, \"s_Mayo_TN_CC_369\" : 66, \"s_Mayo_TN_CC_332\" : 29, \"s_Mayo_TN_CC_368\" : 65, \"s_Mayo_TN_CC_331\" : 28, \"s_Mayo_TN_CC_403\" : 100, \"s_Mayo_TN_CC_404\" : 101, \"s_Mayo_TN_CC_405\" : 102, \"s_Mayo_TN_CC_406\" : 103, \"s_Mayo_TN_CC_400\" : 97, \"s_Mayo_TN_CC_401\" : 98, \"s_Mayo_TN_CC_402\" : 99 }, \"_id\" : \"52a645c4b760a44afaf4f340\", \"alias\" : \"BATCH4\", \"key\" : \"wbf34e9a3d0e0f829381be058cb253c5890623551\", \"owner\" : \"steve\", \"ready\" : 1, \"status\" : \"workspace is ready\", \"timestamp\" : \"2013-12-09T22:36+0000\" }";
// String metaAddCacheResult = "{\"FORMAT\":{\"PL\":1,\"AD\":1,\"GT\":1,\"GQ\":1,\"DP\":1,\"MLPSAF\":1,\"MLPSAC\":1},\"INFO\":{\"HaplotypeScore\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Consistency of the site with at most two segregating haplotypes\",\"EntryType\":\"INFO\"},\"InbreedingCoeff\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Inbreeding coefficient as estimated from the genotype likelihoods per-sample when compared against the Hardy-Weinberg expectation\",\"EntryType\":\"INFO\"},\"MLEAC\":{\"number\":null,\"type\":\"Integer\",\"Description\":\"Maximum likelihood expectation (MLE) for the allele counts (not necessarily the same as the AC), for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"MLEAF\":{\"number\":null,\"type\":\"Float\",\"Description\":\"Maximum likelihood expectation (MLE) for the allele frequency (not necessarily the same as the AF), for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"FS\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Phred-scaled p-value using Fisher's exact test to detect strand bias\",\"EntryType\":\"INFO\"},\"ReadPosRankSum\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Z-score from Wilcoxon rank sum test of Alt vs. Ref read position bias\",\"EntryType\":\"INFO\"},\"DP\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Approximate read depth; some reads may have been filtered\",\"EntryType\":\"INFO\"},\"DS\":{\"number\":0,\"type\":\"Flag\",\"Description\":\"Were any of the samples downsampled?\",\"EntryType\":\"INFO\"},\"STR\":{\"number\":0,\"type\":\"Flag\",\"Description\":\"Variant is a short tandem repeat\",\"EntryType\":\"INFO\"},\"BaseQRankSum\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Z-score from Wilcoxon rank sum test of Alt Vs. Ref base qualities\",\"EntryType\":\"INFO\"},\"QD\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Variant Confidence/Quality by Depth\",\"EntryType\":\"INFO\"},\"MQ\":{\"number\":1,\"type\":\"Float\",\"Description\":\"RMS Mapping Quality\",\"EntryType\":\"INFO\"},\"AC\":{\"number\":null,\"type\":\"Integer\",\"Description\":\"Allele count in genotypes, for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"PL\":{\"number\":null,\"type\":\"Integer\",\"Description\":\"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\",\"EntryType\":\"FORMAT\"},\"AD\":{\"number\":null,\"type\":\"Integer\",\"Description\":\"Allelic depths for the ref and alt alleles in the order listed\",\"EntryType\":\"FORMAT\"},\"GT\":{\"number\":1,\"type\":\"String\",\"Description\":\"Genotype\",\"EntryType\":\"FORMAT\"},\"MQRankSum\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Z-score From Wilcoxon rank sum test of Alt vs. Ref read mapping qualities\",\"EntryType\":\"INFO\"},\"RU\":{\"number\":1,\"type\":\"String\",\"Description\":\"Tandem repeat unit (bases)\",\"EntryType\":\"INFO\",\"type_ahead_overrun\":true},\"Dels\":{\"number\":1,\"type\":\"Float\",\"Description\":\"Fraction of Reads Containing Spanning Deletions\",\"EntryType\":\"INFO\"},\"GQ\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Genotype Quality\",\"EntryType\":\"FORMAT\"},\"RPA\":{\"number\":null,\"type\":\"Integer\",\"Description\":\"Number of times tandem repeat unit is repeated, for each allele (including reference)\",\"EntryType\":\"INFO\"},\"AF\":{\"number\":null,\"type\":\"Float\",\"Description\":\"Allele Frequency, for each ALT allele, in the same order as listed\",\"EntryType\":\"INFO\"},\"MLPSAF\":{\"number\":null,\"type\":\"Float\",\"Description\":\"Maximum likelihood expectation (MLE) for the alternate allele fraction, in the same order as listed, for each individual sample\",\"EntryType\":\"FORMAT\"},\"MQ0\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Total Mapping Quality Zero Reads\",\"EntryType\":\"INFO\"},\"MLPSAC\":{\"number\":null,\"type\":\"Integer\",\"Description\":\"Maximum likelihood expectation (MLE) for the alternate allele count, in the same order as listed, for each individual sample\",\"EntryType\":\"FORMAT\"},\"AN\":{\"number\":1,\"type\":\"Integer\",\"Description\":\"Total number of alleles in called genotypes\",\"EntryType\":\"INFO\"}},\"SAMPLES\":{\"s_Mayo_TN_CC_394\":91,\"s_Mayo_TN_CC_393\":90,\"s_Mayo_TN_CC_392\":89,\"s_Mayo_TN_CC_391\":88,\"s_Mayo_TN_CC_398\":95,\"s_Mayo_TN_CC_397\":94,\"s_Mayo_TN_CC_396\":93,\"s_Mayo_TN_CC_395\":92,\"s_Mayo_TN_CC_350\":47,\"s_Mayo_TN_CC_390\":87,\"s_Mayo_TN_CC_353\":50,\"s_Mayo_TN_CC_354\":51,\"s_Mayo_TN_CC_351\":48,\"s_Mayo_TN_CC_352\":49,\"s_Mayo_TN_CC_358\":55,\"s_Mayo_TN_CC_357\":54,\"s_Mayo_TN_CC_356\":53,\"s_Mayo_TN_CC_355\":52,\"s_Mayo_TN_CC_359\":56,\"s_Mayo_TN_CC_399\":96,\"s_Mayo_TN_CC_381\":78,\"s_Mayo_TN_CC_380\":77,\"s_Mayo_TN_CC_383\":80,\"s_Mayo_TN_CC_382\":79,\"s_Mayo_TN_CC_385\":82,\"s_Mayo_TN_CC_319\":16,\"s_Mayo_TN_CC_384\":81,\"s_Mayo_TN_CC_387\":84,\"s_Mayo_TN_CC_386\":83,\"s_Mayo_TN_CC_315\":12,\"s_Mayo_TN_CC_316\":13,\"s_Mayo_TN_CC_317\":14,\"s_Mayo_TN_CC_318\":15,\"s_Mayo_TN_CC_340\":37,\"s_Mayo_TN_CC_341\":38,\"s_Mayo_TN_CC_313\":10,\"s_Mayo_TN_CC_342\":39,\"s_Mayo_TN_CC_314\":11,\"s_Mayo_TN_CC_343\":40,\"s_Mayo_TN_CC_345\":42,\"s_Mayo_TN_CC_344\":41,\"s_Mayo_TN_CC_347\":44,\"s_Mayo_TN_CC_346\":43,\"s_Mayo_TN_CC_349\":46,\"s_Mayo_TN_CC_348\":45,\"s_Mayo_TN_CC_388\":85,\"s_Mayo_TN_CC_389\":86,\"s_Mayo_TN_CC_375\":72,\"s_Mayo_TN_CC_324\":21,\"s_Mayo_TN_CC_376\":73,\"s_Mayo_TN_CC_325\":22,\"s_Mayo_TN_CC_373\":70,\"s_Mayo_TN_CC_322\":19,\"s_Mayo_TN_CC_374\":71,\"s_Mayo_TN_CC_323\":20,\"s_Mayo_TN_CC_371\":68,\"s_Mayo_TN_CC_328\":25,\"s_Mayo_TN_CC_372\":69,\"s_Mayo_TN_CC_329\":26,\"s_Mayo_TN_CC_326\":23,\"s_Mayo_TN_CC_370\":67,\"s_Mayo_TN_CC_327\":24,\"s_Mayo_TN_CC_321\":18,\"s_Mayo_TN_CC_379\":76,\"s_Mayo_TN_CC_320\":17,\"s_Mayo_TN_CC_378\":75,\"s_Mayo_TN_CC_377\":74,\"s_Mayo_TN_CC_362\":59,\"s_Mayo_TN_CC_333\":30,\"s_Mayo_TN_CC_363\":60,\"s_Mayo_TN_CC_334\":31,\"s_Mayo_TN_CC_364\":61,\"s_Mayo_TN_CC_335\":32,\"s_Mayo_TN_CC_365\":62,\"s_Mayo_TN_CC_336\":33,\"s_Mayo_TN_CC_337\":34,\"s_Mayo_TN_CC_338\":35,\"s_Mayo_TN_CC_339\":36,\"s_Mayo_TN_CC_360\":57,\"s_Mayo_TN_CC_361\":58,\"s_Mayo_TN_CC_407\":104,\"s_Mayo_TN_CC_367\":64,\"s_Mayo_TN_CC_330\":27,\"s_Mayo_TN_CC_408\":105,\"s_Mayo_TN_CC_366\":63,\"s_Mayo_TN_CC_369\":66,\"s_Mayo_TN_CC_332\":29,\"s_Mayo_TN_CC_368\":65,\"s_Mayo_TN_CC_331\":28,\"s_Mayo_TN_CC_403\":100,\"s_Mayo_TN_CC_404\":101,\"s_Mayo_TN_CC_405\":102,\"s_Mayo_TN_CC_406\":103,\"s_Mayo_TN_CC_400\":97,\"s_Mayo_TN_CC_401\":98,\"s_Mayo_TN_CC_402\":99},\"_id\":\"52a645c4b760a44afaf4f340\",\"alias\":\"BATCH4\",\"key\":\"wbf34e9a3d0e0f829381be058cb253c5890623551\",\"owner\":\"steve\",\"ready\":1,\"status\":\"workspace is ready\",\"timestamp\":\"2013-12-09T22:36+0000\"}";
// @Test
// public void testUpdateMetadataWTypeAhead(){
// Set<String> typeAheadKeysLargerThanCache = new HashSet<String>();
// typeAheadKeysLargerThanCache.add("RU"); // lets say RU was bigger than cache size.
// VCFParser v = new VCFParser();
// JsonParser parser = new JsonParser();
// JsonObject meta = (JsonObject)parser.parse(metaAddCache);
// JsonObject result = v.updateMetadataWTypeAhead(meta, typeAheadKeysLargerThanCache);
// assertEquals(metaAddCacheResult, result.toString());
public String provision(String alias){
String workspace;
System.out.println("Make sure to have MongoDB up and running on localhost (or wherever specified in your sys.properties file) before you try to run this functional test!");
System.out.println("VCFParserITCase.Provision a new workspace...");
Provision prov = new Provision();
String json = prov.provision(user,alias);
DBObject w = (DBObject) JSON.parse(json);
workspace = (String) w.get(Tokens.KEY);
System.out.println("Workspace provisioned with key: " + workspace);
return workspace;
}
String user = "test";
int overflowThreshold = 50000;
/**
* This function will test that the parse worked correctly AND it loaded everything into MongoDB in the correct way
*/
@Test
public void testParseAndLoad() throws ProcessTerminatedException {
System.out.println("Running: edu.mayo.ve.VCFParser.VCFParserITCase.testParseAndLoad");
String alias = "alias";
String workspaceID = provision(alias);;
System.out.println("VCFParserITCase.Loading data into a new workspace...");
VCFParser parser = new VCFParser();
//false,false at the end of this call are correct for loading to MongoDB
parser.setSaveSamples(true);
TypeAhead thead = new TypeAhead("INFO", overflowThreshold, reporting);
parser.setReporting(reporting);
parser.setTypeAhead(thead);
parser.parse(VCF, workspaceID); //put true in the second to last param for verbose load reporting
//test that the metadata was loaded correctly
System.out.println(parser.getMetadata().toString()); //workspace as it is in memory in the parser
String resultMeta = (new MetaData()).getWorkspaceJSON(workspaceID); //workspace as it is saved in mongodb
testMetaDataLoaded(parser.getMetadata().toString(), resultMeta);
//test that the number of data rows is correct
//check that the indexes are correct
String indexedJson = (new Index()).getIndexes(workspaceID);
DBObject indexeddbo = (DBObject) JSON.parse(indexedJson);
BasicDBList fields = (BasicDBList) indexeddbo.get("fields");
System.out.println(indexeddbo.toString());
Set<String> actualKeys = new HashSet<String>();
for(Object o : fields){
DBObject next = (DBObject) o;
//System.out.println(next);
actualKeys.add((String)next.get("name"));
}
Set<String> expectedKeys = new HashSet<String>();
expectedKeys.addAll(Arrays.asList("_id_",
"FORMAT.GenotypePostitiveCount_1",
"FORMAT.GenotypePositiveList_1",
"INFO.SNPEFF_AMINO_ACID_LENGTH_1",
"INFO.SNPEFF_TRANSCRIPT_ID_1",
"INFO.SNPEFF_CODON_CHANGE_1",
"INFO.SNPEFF_IMPACT_1",
"INFO.SNPEFF_EXON_ID_1",
"INFO.SNPEFF_GENE_NAME_1",
"INFO.SNPEFF_AMINO_ACID_CHANGE_1",
"INFO.SNPEFF_FUNCTIONAL_CLASS_1",
"INFO.SNPEFF_EFFECT_1",
"INFO.SNPEFF_GENE_BIOTYPE_1",
"FORMAT.min.PL_1",
"FORMAT.max.PL_1",
"FORMAT.min.AD_1",
"FORMAT.max.AD_1",
"FORMAT.min.GT_1",
"FORMAT.max.GT_1",
"FORMAT.min.GQ_1",
"FORMAT.max.GQ_1",
"FORMAT.HeterozygousList_1",
"FORMAT.HomozygousList_1"
));
assertEquals(expectedKeys,actualKeys);
//other tests....
//delete the workspace
System.out.println("Deleting Workspace: " + workspaceID);
Workspace wksp = new Workspace();
wksp.deleteWorkspace(workspaceID);
}
//@Test
public void testMetaDataLoaded(String resultBeforeSave, String resultAfterSave){
System.out.println("Running: edu.mayo.ve.VCFParser.VCFParserITCase.testMetaDataLoaded");
//String resultBeforeSave = "{ \"INFO\" : { \"Controls_AN\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AN for Controls\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_AMINO_ACID_LENGTH\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Length of protein in amino acids (actually, transcription length divided by 3)\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_TRANSCRIPT_ID\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Transcript ID for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"UGT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The most probable unconstrained genotype configuration in the trio\" , \"EntryType\" : \"INFO\"} , \"InbreedingCoeff\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Inbreeding coefficient as estimated from the genotype likelihoods per-sample when compared against the Hardy-Weinberg expectation\" , \"EntryType\" : \"INFO\"} , \"Group\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_CODON_CHANGE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Old/New codon for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"Cases_AF\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AF for Cases\" , \"EntryType\" : \"INFO\"} , \"AF1\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Max-likelihood estimate of the first ALT allele frequency (assuming HWE)\" , \"EntryType\" : \"INFO\"} , \"ReadPosRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt vs. Ref read position bias\" , \"EntryType\" : \"INFO\"} , \"DP\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Approximate read depth; some reads may have been filtered\" , \"EntryType\" : \"INFO\"} , \"DS\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Were any of the samples downsampled?\" , \"EntryType\" : \"INFO\"} , \"Controls_AF\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AF for Controls\" , \"EntryType\" : \"INFO\"} , \"Cases_AN\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AN for Cases\" , \"EntryType\" : \"INFO\"} , \"Controls_AC\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AC for Controls\" , \"EntryType\" : \"INFO\"} , \"STR\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Variant is a short tandem repeat\" , \"EntryType\" : \"INFO\"} , \"BaseQRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt Vs. Ref base qualities\" , \"EntryType\" : \"INFO\"} , \"HWE\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Chi^2 based HWE test P-value based on G3\" , \"EntryType\" : \"INFO\"} , \"QD\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Variant Confidence/Quality by Depth\" , \"EntryType\" : \"INFO\"} , \"MQ\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"RMS Mapping Quality\" , \"EntryType\" : \"INFO\"} , \"PC2\" : { \"number\" : 2 , \"type\" : \"Integer\" , \"Description\" : \"Phred probability of the nonRef allele frequency in group1 samples being larger (,smaller) than in group2.\" , \"EntryType\" : \"INFO\"} , \"CGT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The most probable constrained genotype configuration in the trio\" , \"EntryType\" : \"INFO\"} , \"AC\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Allele count in genotypes, for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"AD\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Allelic depths for the ref and alt alleles in the order listed\" , \"EntryType\" : \"FORMAT\"} , \"QCHI2\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Phred scaled PCHI2.\" , \"EntryType\" : \"INFO\"} , \"HRun\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Largest Contiguous Homopolymer Run of Variant Allele In Either Direction\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_IMPACT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Impact of the highest-impact effect resulting from the current variant [MODIFIER, LOW, MODERATE, HIGH]\" , \"EntryType\" : \"INFO\"} , \"Dels\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Fraction of Reads Containing Spanning Deletions\" , \"EntryType\" : \"INFO\"} , \"INDEL\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Indicates that the variant is an INDEL.\" , \"EntryType\" : \"INFO\"} , \"PR\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"# permutations yielding a smaller PCHI2.\" , \"EntryType\" : \"INFO\"} , \"AF\" : { \"number\" : null , \"type\" : \"Float\" , \"Description\" : \"Allele Frequency, for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"DP4\" : { \"number\" : 4 , \"type\" : \"Integer\" , \"Description\" : \"# high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\" , \"EntryType\" : \"INFO\"} , \"MLPSAF\" : { \"number\" : null , \"type\" : \"Float\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele fraction, in the same order as listed, for each individual sample\" , \"EntryType\" : \"FORMAT\"} , \"MLPSAC\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele count, in the same order as listed, for each individual sample\" , \"EntryType\" : \"FORMAT\"} , \"SVLEN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Difference in length between REF and ALT alleles\" , \"EntryType\" : \"INFO\"} , \"AN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Total number of alleles in called genotypes\" , \"EntryType\" : \"INFO\"} , \"CLR\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Log ratio of genotype likelihoods with and without the constraint\" , \"EntryType\" : \"INFO\"} , \"HaplotypeScore\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Consistency of the site with at most two segregating haplotypes\" , \"EntryType\" : \"INFO\"} , \"PCHI2\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Posterior weighted chi^2 P-value for testing the association between group1 and group2 samples.\" , \"EntryType\" : \"INFO\"} , \"set\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"Genotyper\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_EXON_ID\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Exon ID for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"MLEAC\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the allele counts (not necessarily the same as the AC), for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_GENE_NAME\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Gene name for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"MLEAF\" : { \"number\" : null , \"type\" : \"Float\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the allele frequency (not necessarily the same as the AF), for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"FS\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Phred-scaled p-value using Fisher's exact test to detect strand bias\" , \"EntryType\" : \"INFO\"} , \"G3\" : { \"number\" : 3 , \"type\" : \"Float\" , \"Description\" : \"ML estimate of genotype frequencies\" , \"EntryType\" : \"INFO\"} , \"FQ\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Phred probability of all samples being the same\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_AMINO_ACID_CHANGE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Old/New amino acid for the highest-impact effect resulting from the current variant (in HGVS style)\" , \"EntryType\" : \"INFO\"} , \"GenotyperControls\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"VDB\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Variant Distance Bias\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_FUNCTIONAL_CLASS\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Functional class of the highest-impact effect resulting from the current variant: [NONE, SILENT, MISSENSE, NONSENSE]\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_EFFECT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The highest-impact effect resulting from the current variant (or one of the highest-impact effects, if there is a tie)\" , \"EntryType\" : \"INFO\"} , \"Cases_AC\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AC for Cases\" , \"EntryType\" : \"INFO\"} , \"DB\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"dbSNP Membership\" , \"EntryType\" : \"INFO\"} , \"SVTYPE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Type of structural variant\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_GENE_BIOTYPE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Gene biotype for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"SP\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Phred-scaled strand bias P-value\" , \"EntryType\" : \"FORMAT\"} , \"NTLEN\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Number of bases inserted in place of deleted code\" , \"EntryType\" : \"INFO\"} , \"PL\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\" , \"EntryType\" : \"FORMAT\"} , \"GT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Genotype\" , \"EntryType\" : \"FORMAT\"} , \"HOMSEQ\" : { \"number\" : null , \"type\" : \"String\" , \"Description\" : \"Sequence of base pair identical micro-homology at event breakpoints\" , \"EntryType\" : \"INFO\"} , \"RU\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Tandem repeat unit (bases)\" , \"EntryType\" : \"INFO\"} , \"MQRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score From Wilcoxon rank sum test of Alt vs. Ref read mapping qualities\" , \"EntryType\" : \"INFO\"} , \"GQ\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Genotype Quality\" , \"EntryType\" : \"FORMAT\"} , \"RPA\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Number of times tandem repeat unit is repeated, for each allele (including reference)\" , \"EntryType\" : \"INFO\"} , \"HOMLEN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Length of base pair identical micro-homology at event breakpoints\" , \"EntryType\" : \"INFO\"} , \"END\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"End position of the variant described in this record\" , \"EntryType\" : \"INFO\"} , \"MQ0\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Total Mapping Quality Zero Reads\" , \"EntryType\" : \"INFO\"} , \"GL\" : { \"number\" : 3 , \"type\" : \"Float\" , \"Description\" : \"Likelihoods for RR,RA,AA genotypes (R=ref,A=alt)\" , \"EntryType\" : \"FORMAT\"} , \"AC1\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Max-likelihood estimate of the first ALT allele count (no HWE assumption)\" , \"EntryType\" : \"INFO\"} , \"PV4\" : { \"number\" : 4 , \"type\" : \"Float\" , \"Description\" : \"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\" , \"EntryType\" : \"INFO\"}} , \"SAMPLES\" : { \"s_Mayo_TN_CC_254\" : 189 , \"s_Mayo_TN_CC_255\" : 190 , \"s_Mayo_TN_CC_252\" : 187 , \"s_Mayo_TN_CC_253\" : 188 , \"s_Mayo_TN_CC_250\" : 185 , \"s_Mayo_TN_CC_251\" : 186 , \"s_Mayo_TN_CC_530\" : 493 , \"s_Mayo_TN_CC_537\" : 500 , \"s_Mayo_TN_CC_538\" : 501 , \"s_Mayo_TN_CC_535\" : 498 , \"s_Mayo_TN_CC_536\" : 499 , \"s_Mayo_TN_CC_533\" : 496 , \"s_Mayo_TN_CC_534\" : 497 , \"s_Mayo_TN_CC_531\" : 494 , \"s_Mayo_TN_CC_532\" : 495 , \"s_Mayo_TN_CC_259\" : 194 , \"s_Mayo_TN_CC_258\" : 193 , \"s_Mayo_TN_CC_257\" : 192 , \"s_Mayo_TN_CC_539\" : 502 , \"s_Mayo_TN_CC_256\" : 191 , \"s_Mayo_TN_CC_241\" : 175 , \"s_Mayo_TN_CC_242\" : 176 , \"s_Mayo_TN_CC_243\" : 177 , \"s_Mayo_TN_CC_244\" : 178 , \"s_Mayo_TN_CC_240\" : 174 , \"s_Mayo_TN_CC_524\" : 486 , \"s_Mayo_TN_CC_525\" : 487 , \"s_Mayo_TN_CC_526\" : 488 , \"s_Mayo_TN_CC_527\" : 489 , \"s_Mayo_TN_CC_520\" : 482 , \"s_Mayo_TN_CC_521\" : 483 , \"s_Mayo_TN_CC_522\" : 484 , \"s_Mayo_TN_CC_523\" : 485 , \"s_Mayo_TN_CC_249\" : 183 , \"s_Mayo_TN_CC_246\" : 180 , \"s_Mayo_TN_CC_528\" : 490 , \"s_Mayo_TN_CC_245\" : 179 , \"s_Mayo_TN_CC_529\" : 491 , \"s_Mayo_TN_CC_248\" : 182 , \"s_Mayo_TN_CC_247\" : 181 , \"s_Mayo_TN_CC_232\" : 165 , \"s_Mayo_TN_CC_233\" : 166 , \"s_Mayo_TN_CC_230\" : 163 , \"s_Mayo_TN_CC_231\" : 164 , \"s_Mayo_TN_CC_798\" : 787 , \"s_Mayo_TN_CC_797\" : 786 , \"s_Mayo_TN_CC_796\" : 785 , \"s_Mayo_TN_CC_795\" : 784 , \"s_Mayo_TN_CC_799\" : 788 , \"s_Mayo_TN_CC_511\" : 472 , \"s_Mayo_TN_CC_790\" : 779 , \"s_Mayo_TN_CC_512\" : 473 , \"s_Mayo_TN_CC_510\" : 471 , \"s_Mayo_TN_CC_793\" : 782 , \"s_Mayo_TN_CC_515\" : 476 , \"s_Mayo_TN_CC_794\" : 783 , \"s_Mayo_TN_CC_516\" : 477 , \"s_Mayo_TN_CC_791\" : 780 , \"s_Mayo_TN_CC_513\" : 474 , \"s_Mayo_TN_CC_792\" : 781 , \"s_Mayo_TN_CC_514\" : 475 , \"s_Mayo_TN_CC_237\" : 170 , \"s_Mayo_TN_CC_519\" : 480 , \"s_Mayo_TN_CC_236\" : 169 , \"s_Mayo_TN_CC_235\" : 168 , \"s_Mayo_TN_CC_517\" : 478 , \"s_Mayo_TN_CC_234\" : 167 , \"s_Mayo_TN_CC_518\" : 479 , \"s_Mayo_TN_CC_239\" : 172 , \"s_Mayo_TN_CC_238\" : 171 , \"s_Mayo_TN_CC_220\" : 152 , \"s_Mayo_TN_CC_221\" : 153 , \"s_Mayo_TN_CC_222\" : 154 , \"s_Mayo_TN_CC_785\" : 773 , \"s_Mayo_TN_CC_784\" : 772 , \"s_Mayo_TN_CC_787\" : 775 , \"s_Mayo_TN_CC_786\" : 774 , \"s_Mayo_TN_CC_789\" : 777 , \"s_Mayo_TN_CC_788\" : 776 , \"s_Mayo_TN_CC_500\" : 460 , \"s_Mayo_TN_CC_501\" : 461 , \"s_Mayo_TN_CC_502\" : 462 , \"s_Mayo_TN_CC_780\" : 768 , \"s_Mayo_TN_CC_503\" : 463 , \"s_Mayo_TN_CC_781\" : 769 , \"s_Mayo_TN_CC_504\" : 464 , \"s_Mayo_TN_CC_782\" : 770 , \"s_Mayo_TN_CC_505\" : 465 , \"s_Mayo_TN_CC_783\" : 771 , \"s_Mayo_TN_CC_224\" : 156 , \"s_Mayo_TN_CC_506\" : 466 , \"s_Mayo_TN_CC_223\" : 155 , \"s_Mayo_TN_CC_507\" : 467 , \"s_Mayo_TN_CC_226\" : 158 , \"s_Mayo_TN_CC_508\" : 468 , \"s_Mayo_TN_CC_225\" : 157 , \"s_Mayo_TN_CC_509\" : 469 , \"s_Mayo_TN_CC_228\" : 160 , \"s_Mayo_TN_CC_227\" : 159 , \"s_Mayo_TN_CC_229\" : 161 , \"s_Mayo_TN_CC_291\" : 230 , \"s_Mayo_TN_CC_573\" : 540 , \"s_Mayo_TN_CC_779\" : 766 , \"s_Mayo_TN_CC_290\" : 229 , \"s_Mayo_TN_CC_574\" : 541 , \"s_Mayo_TN_CC_571\" : 538 , \"s_Mayo_TN_CC_777\" : 764 , \"s_Mayo_TN_CC_572\" : 539 , \"s_Mayo_TN_CC_778\" : 765 , \"s_Mayo_TN_CC_775\" : 762 , \"s_Mayo_TN_CC_570\" : 537 , \"s_Mayo_TN_CC_776\" : 763 , \"s_Mayo_TN_CC_773\" : 760 , \"s_Mayo_TN_CC_774\" : 761 , \"s_Mayo_TN_CC_299\" : 238 , \"s_Mayo_TN_CC_298\" : 237 , \"s_Mayo_TN_CC_297\" : 236 , \"s_Mayo_TN_CC_296\" : 235 , \"s_Mayo_TN_CC_295\" : 234 , \"s_Mayo_TN_CC_294\" : 233 , \"s_Mayo_TN_CC_293\" : 232 , \"s_Mayo_TN_CC_292\" : 231 , \"s_Mayo_TN_CC_772\" : 759 , \"s_Mayo_TN_CC_771\" : 758 , \"s_Mayo_TN_CC_770\" : 757 , \"s_Mayo_TN_CC_579\" : 546 , \"s_Mayo_TN_CC_578\" : 545 , \"s_Mayo_TN_CC_577\" : 544 , \"s_Mayo_TN_CC_576\" : 543 , \"s_Mayo_TN_CC_575\" : 542 , \"s_Mayo_TN_CC_560\" : 526 , \"s_Mayo_TN_CC_766\" : 752 , \"s_Mayo_TN_CC_561\" : 527 , \"s_Mayo_TN_CC_767\" : 753 , \"s_Mayo_TN_CC_280\" : 218 , \"s_Mayo_TN_CC_562\" : 528 , \"s_Mayo_TN_CC_768\" : 754 , \"s_Mayo_TN_CC_563\" : 529 , \"s_Mayo_TN_CC_769\" : 755 , \"s_Mayo_TN_CC_762\" : 748 , \"s_Mayo_TN_CC_763\" : 749 , \"s_Mayo_TN_CC_764\" : 750 , \"s_Mayo_TN_CC_765\" : 751 , \"s_Mayo_TN_CC_286\" : 224 , \"s_Mayo_TN_CC_285\" : 223 , \"s_Mayo_TN_CC_288\" : 226 , \"s_Mayo_TN_CC_287\" : 225 , \"s_Mayo_TN_CC_282\" : 220 , \"s_Mayo_TN_CC_281\" : 219 , \"s_Mayo_TN_CC_284\" : 222 , \"s_Mayo_TN_CC_283\" : 221 , \"s_Mayo_TN_CC_289\" : 227 , \"s_Mayo_TN_CC_569\" : 535 , \"s_Mayo_TN_CC_568\" : 534 , \"s_Mayo_TN_CC_761\" : 747 , \"s_Mayo_TN_CC_760\" : 746 , \"s_Mayo_TN_CC_565\" : 531 , \"s_Mayo_TN_CC_564\" : 530 , \"s_Mayo_TN_CC_567\" : 533 , \"s_Mayo_TN_CC_566\" : 532 , \"s_Mayo_TN_CC_753\" : 738 , \"s_Mayo_TN_CC_754\" : 739 , \"s_Mayo_TN_CC_751\" : 736 , \"s_Mayo_TN_CC_752\" : 737 , \"s_Mayo_TN_CC_551\" : 516 , \"s_Mayo_TN_CC_757\" : 742 , \"s_Mayo_TN_CC_552\" : 517 , \"s_Mayo_TN_CC_758\" : 743 , \"s_Mayo_TN_CC_755\" : 740 , \"s_Mayo_TN_CC_550\" : 515 , \"s_Mayo_TN_CC_756\" : 741 , \"s_Mayo_TN_CC_273\" : 210 , \"s_Mayo_TN_CC_272\" : 209 , \"s_Mayo_TN_CC_271\" : 208 , \"s_Mayo_TN_CC_759\" : 744 , \"s_Mayo_TN_CC_270\" : 207 , \"s_Mayo_TN_CC_277\" : 214 , \"s_Mayo_TN_CC_276\" : 213 , \"s_Mayo_TN_CC_275\" : 212 , \"s_Mayo_TN_CC_274\" : 211 , \"s_Mayo_TN_CC_278\" : 215 , \"s_Mayo_TN_CC_279\" : 216 , \"s_Mayo_TN_CC_556\" : 521 , \"s_Mayo_TN_CC_555\" : 520 , \"s_Mayo_TN_CC_554\" : 519 , \"s_Mayo_TN_CC_553\" : 518 , \"s_Mayo_TN_CC_750\" : 735 , \"s_Mayo_TN_CC_559\" : 524 , \"s_Mayo_TN_CC_558\" : 523 , \"s_Mayo_TN_CC_557\" : 522 , \"s_Mayo_TN_CC_740\" : 724 , \"s_Mayo_TN_CC_741\" : 725 , \"s_Mayo_TN_CC_742\" : 726 , \"s_Mayo_TN_CC_743\" : 727 , \"s_Mayo_TN_CC_744\" : 728 , \"s_Mayo_TN_CC_745\" : 729 , \"s_Mayo_TN_CC_540\" : 504 , \"s_Mayo_TN_CC_746\" : 730 , \"s_Mayo_TN_CC_541\" : 505 , \"s_Mayo_TN_CC_747\" : 731 , \"s_Mayo_TN_CC_260\" : 196 , \"s_Mayo_TN_CC_748\" : 732 , \"s_Mayo_TN_CC_749\" : 733 , \"s_Mayo_TN_CC_262\" : 198 , \"s_Mayo_TN_CC_261\" : 197 , \"s_Mayo_TN_CC_264\" : 200 , \"s_Mayo_TN_CC_263\" : 199 , \"s_Mayo_TN_CC_266\" : 202 , \"s_Mayo_TN_CC_265\" : 201 , \"s_Mayo_TN_CC_267\" : 203 , \"s_Mayo_TN_CC_268\" : 204 , \"s_Mayo_TN_CC_269\" : 205 , \"s_Mayo_TN_CC_543\" : 507 , \"s_Mayo_TN_CC_542\" : 506 , \"s_Mayo_TN_CC_545\" : 509 , \"s_Mayo_TN_CC_544\" : 508 , \"s_Mayo_TN_CC_547\" : 511 , \"s_Mayo_TN_CC_546\" : 510 , \"s_Mayo_TN_CC_549\" : 513 , \"s_Mayo_TN_CC_548\" : 512 , \"s_Mayo_TN_CC_738\" : 721 , \"s_Mayo_TN_CC_737\" : 720 , \"s_Mayo_TN_CC_739\" : 722 , \"s_Mayo_TN_CC_734\" : 717 , \"s_Mayo_TN_CC_733\" : 716 , \"s_Mayo_TN_CC_736\" : 719 , \"s_Mayo_TN_CC_735\" : 718 , \"s_Mayo_TN_CC_730\" : 713 , \"s_Mayo_TN_CC_732\" : 715 , \"s_Mayo_TN_CC_731\" : 714 , \"s_Mayo_TN_CC_729\" : 711 , \"s_Mayo_TN_CC_728\" : 710 , \"s_Mayo_TN_CC_727\" : 709 , \"s_Mayo_TN_CC_726\" : 708 , \"s_Mayo_TN_CC_725\" : 707 , \"s_Mayo_TN_CC_724\" : 706 , \"s_Mayo_TN_CC_723\" : 705 , \"s_Mayo_TN_CC_722\" : 704 , \"s_Mayo_TN_CC_721\" : 703 , \"s_Mayo_TN_CC_720\" : 702 , \"s_Mayo_TN_CC_716\" : 697 , \"s_Mayo_TN_CC_715\" : 696 , \"s_Mayo_TN_CC_718\" : 699 , \"s_Mayo_TN_CC_717\" : 698 , \"s_Mayo_TN_CC_719\" : 700 , \"s_Mayo_TN_CC_710\" : 691 , \"s_Mayo_TN_CC_712\" : 693 , \"s_Mayo_TN_CC_711\" : 692 , \"s_Mayo_TN_CC_714\" : 695 , \"s_Mayo_TN_CC_713\" : 694 , \"s_Mayo_TN_CC_707\" : 687 , \"s_Mayo_TN_CC_706\" : 686 , \"s_Mayo_TN_CC_705\" : 685 , \"s_Mayo_TN_CC_704\" : 684 , \"s_Mayo_TN_CC_709\" : 689 , \"s_Mayo_TN_CC_708\" : 688 , \"s_Mayo_TN_CC_703\" : 683 , \"s_Mayo_TN_CC_702\" : 682 , \"s_Mayo_TN_CC_701\" : 681 , \"s_Mayo_TN_CC_700\" : 680 , \"s_Mayo_TN_CC_588\" : 556 , \"s_Mayo_TN_CC_589\" : 557 , \"s_Mayo_TN_CC_586\" : 554 , \"s_Mayo_TN_CC_587\" : 555 , \"s_Mayo_TN_CC_585\" : 553 , \"s_Mayo_TN_CC_584\" : 552 , \"s_Mayo_TN_CC_583\" : 551 , \"s_Mayo_TN_CC_582\" : 550 , \"s_Mayo_TN_CC_581\" : 549 , \"s_Mayo_TN_CC_580\" : 548 , \"s_Mayo_TN_CC_597\" : 566 , \"s_Mayo_TN_CC_598\" : 567 , \"s_Mayo_TN_CC_599\" : 568 , \"s_Mayo_TN_CC_594\" : 563 , \"s_Mayo_TN_CC_593\" : 562 , \"s_Mayo_TN_CC_596\" : 565 , \"s_Mayo_TN_CC_595\" : 564 , \"s_Mayo_TN_CC_590\" : 559 , \"s_Mayo_TN_CC_592\" : 561 , \"s_Mayo_TN_CC_591\" : 560 , \"s_Mayo_TN_CC_203\" : 133 , \"s_Mayo_TN_CC_204\" : 134 , \"s_Mayo_TN_CC_201\" : 131 , \"s_Mayo_TN_CC_202\" : 132 , \"s_Mayo_TN_CC_207\" : 137 , \"s_Mayo_TN_CC_208\" : 138 , \"s_Mayo_TN_CC_205\" : 135 , \"s_Mayo_TN_CC_206\" : 136 , \"s_Mayo_TN_CC_209\" : 139 , \"s_Mayo_TN_CC_200\" : 130 , \"s_Mayo_TN_CC_212\" : 143 , \"s_Mayo_TN_CC_213\" : 144 , \"s_Mayo_TN_CC_214\" : 145 , \"s_Mayo_TN_CC_215\" : 146 , \"s_Mayo_TN_CC_216\" : 147 , \"s_Mayo_TN_CC_217\" : 148 , \"s_Mayo_TN_CC_218\" : 149 , \"s_Mayo_TN_CC_219\" : 150 , \"s_Mayo_TN_CC_211\" : 142 , \"s_Mayo_TN_CC_210\" : 141 , \"s_Mayo_TN_CC_37\" : 316 , \"s_Mayo_TN_CC_677\" : 654 , \"s_Mayo_TN_CC_36\" : 305 , \"s_Mayo_TN_CC_676\" : 653 , \"s_Mayo_TN_CC_35\" : 294 , \"s_Mayo_TN_CC_675\" : 652 , \"s_Mayo_TN_CC_34\" : 283 , \"s_Mayo_TN_CC_674\" : 651 , \"s_Mayo_TN_CC_33\" : 272 , \"s_Mayo_TN_CC_32\" : 261 , \"s_Mayo_TN_CC_31\" : 250 , \"s_Mayo_TN_CC_679\" : 656 , \"s_Mayo_TN_CC_30\" : 239 , \"s_Mayo_TN_CC_678\" : 655 , \"s_Mayo_TN_CC_159\" : 84 , \"s_Mayo_TN_CC_350\" : 295 , \"s_Mayo_TN_CC_157\" : 82 , \"s_Mayo_TN_CC_158\" : 83 , \"s_Mayo_TN_CC_353\" : 298 , \"s_Mayo_TN_CC_354\" : 299 , \"s_Mayo_TN_CC_39\" : 338 , \"s_Mayo_TN_CC_351\" : 296 , \"s_Mayo_TN_CC_38\" : 327 , \"s_Mayo_TN_CC_352\" : 297 , \"s_Mayo_TN_CC_358\" : 303 , \"s_Mayo_TN_CC_152\" : 77 , \"s_Mayo_TN_CC_357\" : 302 , \"s_Mayo_TN_CC_151\" : 76 , \"s_Mayo_TN_CC_356\" : 301 , \"s_Mayo_TN_CC_150\" : 75 , \"s_Mayo_TN_CC_355\" : 300 , \"s_Mayo_TN_CC_156\" : 81 , \"s_Mayo_TN_CC_155\" : 80 , \"s_Mayo_TN_CC_154\" : 79 , \"s_Mayo_TN_CC_359\" : 304 , \"s_Mayo_TN_CC_153\" : 78 , \"s_Mayo_TN_CC_40\" : 349 , \"s_Mayo_TN_CC_672\" : 649 , \"s_Mayo_TN_CC_673\" : 650 , \"s_Mayo_TN_CC_670\" : 647 , \"s_Mayo_TN_CC_671\" : 648 , \"s_Mayo_TN_CC_24\" : 173 , \"s_Mayo_TN_CC_664\" : 640 , \"s_Mayo_TN_CC_23\" : 162 , \"s_Mayo_TN_CC_663\" : 639 , \"s_Mayo_TN_CC_26\" : 195 , \"s_Mayo_TN_CC_666\" : 642 , \"s_Mayo_TN_CC_25\" : 184 , \"s_Mayo_TN_CC_665\" : 641 , \"s_Mayo_TN_CC_20\" : 129 , \"s_Mayo_TN_CC_668\" : 644 , \"s_Mayo_TN_CC_667\" : 643 , \"s_Mayo_TN_CC_22\" : 151 , \"s_Mayo_TN_CC_21\" : 140 , \"s_Mayo_TN_CC_669\" : 645 , \"s_Mayo_TN_CC_146\" : 70 , \"s_Mayo_TN_CC_147\" : 71 , \"s_Mayo_TN_CC_148\" : 72 , \"s_Mayo_TN_CC_149\" : 73 , \"s_Mayo_TN_CC_340\" : 284 , \"s_Mayo_TN_CC_28\" : 217 , \"s_Mayo_TN_CC_341\" : 285 , \"s_Mayo_TN_CC_27\" : 206 , \"s_Mayo_TN_CC_342\" : 286 , \"s_Mayo_TN_CC_343\" : 287 , \"s_Mayo_TN_CC_29\" : 228 , \"s_Mayo_TN_CC_345\" : 289 , \"s_Mayo_TN_CC_344\" : 288 , \"s_Mayo_TN_CC_347\" : 291 , \"s_Mayo_TN_CC_141\" : 65 , \"s_Mayo_TN_CC_346\" : 290 , \"s_Mayo_TN_CC_140\" : 64 , \"s_Mayo_TN_CC_349\" : 293 , \"s_Mayo_TN_CC_143\" : 67 , \"s_Mayo_TN_CC_348\" : 292 , \"s_Mayo_TN_CC_142\" : 66 , \"s_Mayo_TN_CC_145\" : 69 , \"s_Mayo_TN_CC_144\" : 68 , \"s_Mayo_TN_CC_660\" : 636 , \"s_Mayo_TN_CC_661\" : 637 , \"s_Mayo_TN_CC_662\" : 638 , \"s_Mayo_TN_CC_55\" : 514 , \"s_Mayo_TN_CC_809\" : 799 , \"s_Mayo_TN_CC_54\" : 503 , \"s_Mayo_TN_CC_808\" : 798 , \"s_Mayo_TN_CC_53\" : 492 , \"s_Mayo_TN_CC_807\" : 797 , \"s_Mayo_TN_CC_52\" : 481 , \"s_Mayo_TN_CC_806\" : 796 , \"s_Mayo_TN_CC_59\" : 558 , \"s_Mayo_TN_CC_699\" : 678 , \"s_Mayo_TN_CC_805\" : 795 , \"s_Mayo_TN_CC_58\" : 547 , \"s_Mayo_TN_CC_698\" : 677 , \"s_Mayo_TN_CC_804\" : 794 , \"s_Mayo_TN_CC_57\" : 536 , \"s_Mayo_TN_CC_697\" : 676 , \"s_Mayo_TN_CC_803\" : 793 , \"s_Mayo_TN_CC_56\" : 525 , \"s_Mayo_TN_CC_696\" : 675 , \"s_Mayo_TN_CC_802\" : 792 , \"s_Mayo_TN_CC_375\" : 322 , \"s_Mayo_TN_CC_801\" : 791 , \"s_Mayo_TN_CC_376\" : 323 , \"s_Mayo_TN_CC_800\" : 790 , \"s_Mayo_TN_CC_373\" : 320 , \"s_Mayo_TN_CC_374\" : 321 , \"s_Mayo_TN_CC_371\" : 318 , \"s_Mayo_TN_CC_372\" : 319 , \"s_Mayo_TN_CC_179\" : 106 , \"s_Mayo_TN_CC_370\" : 317 , \"s_Mayo_TN_CC_178\" : 105 , \"s_Mayo_TN_CC_177\" : 104 , \"s_Mayo_TN_CC_176\" : 103 , \"s_Mayo_TN_CC_175\" : 102 , \"s_Mayo_TN_CC_174\" : 101 , \"s_Mayo_TN_CC_379\" : 326 , \"s_Mayo_TN_CC_173\" : 100 , \"s_Mayo_TN_CC_418\" : 369 , \"s_Mayo_TN_CC_378\" : 325 , \"s_Mayo_TN_CC_172\" : 99 , \"s_Mayo_TN_CC_419\" : 370 , \"s_Mayo_TN_CC_377\" : 324 , \"s_Mayo_TN_CC_171\" : 98 , \"s_Mayo_TN_CC_416\" : 367 , \"s_Mayo_TN_CC_170\" : 97 , \"s_Mayo_TN_CC_694\" : 673 , \"s_Mayo_TN_CC_417\" : 368 , \"s_Mayo_TN_CC_695\" : 674 , \"s_Mayo_TN_CC_414\" : 365 , \"s_Mayo_TN_CC_692\" : 671 , \"s_Mayo_TN_CC_415\" : 366 , \"s_Mayo_TN_CC_693\" : 672 , \"s_Mayo_TN_CC_412\" : 363 , \"s_Mayo_TN_CC_61\" : 580 , \"s_Mayo_TN_CC_690\" : 669 , \"s_Mayo_TN_CC_413\" : 364 , \"s_Mayo_TN_CC_62\" : 591 , \"s_Mayo_TN_CC_691\" : 670 , \"s_Mayo_TN_CC_410\" : 361 , \"s_Mayo_TN_CC_411\" : 362 , \"s_Mayo_TN_CC_60\" : 569 , \"s_Mayo_TN_CC_819\" : 810 , \"s_Mayo_TN_CC_42\" : 371 , \"s_Mayo_TN_CC_818\" : 809 , \"s_Mayo_TN_CC_41\" : 360 , \"s_Mayo_TN_CC_689\" : 667 , \"s_Mayo_TN_CC_44\" : 393 , \"s_Mayo_TN_CC_43\" : 382 , \"s_Mayo_TN_CC_815\" : 806 , \"s_Mayo_TN_CC_46\" : 415 , \"s_Mayo_TN_CC_686\" : 664 , \"s_Mayo_TN_CC_814\" : 805 , \"s_Mayo_TN_CC_45\" : 404 , \"s_Mayo_TN_CC_685\" : 663 , \"s_Mayo_TN_CC_817\" : 808 , \"s_Mayo_TN_CC_48\" : 437 , \"s_Mayo_TN_CC_688\" : 666 , \"s_Mayo_TN_CC_816\" : 807 , \"s_Mayo_TN_CC_47\" : 426 , \"s_Mayo_TN_CC_687\" : 665 , \"s_Mayo_TN_CC_811\" : 802 , \"s_Mayo_TN_CC_362\" : 308 , \"s_Mayo_TN_CC_810\" : 801 , \"s_Mayo_TN_CC_363\" : 309 , \"s_Mayo_TN_CC_49\" : 448 , \"s_Mayo_TN_CC_813\" : 804 , \"s_Mayo_TN_CC_364\" : 310 , \"s_Mayo_TN_CC_812\" : 803 , \"s_Mayo_TN_CC_365\" : 311 , \"s_Mayo_TN_CC_168\" : 94 , \"s_Mayo_TN_CC_169\" : 95 , \"s_Mayo_TN_CC_360\" : 306 , \"s_Mayo_TN_CC_361\" : 307 , \"s_Mayo_TN_CC_165\" : 91 , \"s_Mayo_TN_CC_164\" : 90 , \"s_Mayo_TN_CC_167\" : 93 , \"s_Mayo_TN_CC_166\" : 92 , \"s_Mayo_TN_CC_407\" : 357 , \"s_Mayo_TN_CC_367\" : 313 , \"s_Mayo_TN_CC_161\" : 87 , \"s_Mayo_TN_CC_408\" : 358 , \"s_Mayo_TN_CC_366\" : 312 , \"s_Mayo_TN_CC_160\" : 86 , \"s_Mayo_TN_CC_409\" : 359 , \"s_Mayo_TN_CC_369\" : 315 , \"s_Mayo_TN_CC_163\" : 89 , \"s_Mayo_TN_CC_368\" : 314 , \"s_Mayo_TN_CC_162\" : 88 , \"s_Mayo_TN_CC_403\" : 353 , \"s_Mayo_TN_CC_681\" : 659 , \"s_Mayo_TN_CC_404\" : 354 , \"s_Mayo_TN_CC_682\" : 660 , \"s_Mayo_TN_CC_405\" : 355 , \"s_Mayo_TN_CC_683\" : 661 , \"s_Mayo_TN_CC_406\" : 356 , \"s_Mayo_TN_CC_684\" : 662 , \"s_Mayo_TN_CC_400\" : 350 , \"s_Mayo_TN_CC_401\" : 351 , \"s_Mayo_TN_CC_50\" : 459 , \"s_Mayo_TN_CC_402\" : 352 , \"s_Mayo_TN_CC_51\" : 470 , \"s_Mayo_TN_CC_680\" : 658 , \"s_Mayo_TN_CC_394\" : 343 , \"s_Mayo_TN_CC_116\" : 37 , \"s_Mayo_TN_CC_820\" : 812 , \"s_Mayo_TN_CC_393\" : 342 , \"s_Mayo_TN_CC_115\" : 36 , \"s_Mayo_TN_CC_392\" : 341 , \"s_Mayo_TN_CC_114\" : 35 , \"s_Mayo_TN_CC_638\" : 611 , \"s_Mayo_TN_CC_391\" : 340 , \"s_Mayo_TN_CC_113\" : 34 , \"s_Mayo_TN_CC_639\" : 612 , \"s_Mayo_TN_CC_823\" : 815 , \"s_Mayo_TN_CC_398\" : 347 , \"s_Mayo_TN_CC_824\" : 816 , \"s_Mayo_TN_CC_397\" : 346 , \"s_Mayo_TN_CC_119\" : 40 , \"s_Mayo_TN_CC_821\" : 813 , \"s_Mayo_TN_CC_396\" : 345 , \"s_Mayo_TN_CC_118\" : 39 , \"s_Mayo_TN_CC_822\" : 814 , \"s_Mayo_TN_CC_395\" : 344 , \"s_Mayo_TN_CC_117\" : 38 , \"s_Mayo_TN_CC_827\" : 819 , \"s_Mayo_TN_CC_632\" : 605 , \"s_Mayo_TN_CC_828\" : 820 , \"s_Mayo_TN_CC_633\" : 606 , \"s_Mayo_TN_CC_825\" : 817 , \"s_Mayo_TN_CC_630\" : 603 , \"s_Mayo_TN_CC_826\" : 818 , \"s_Mayo_TN_CC_631\" : 604 , \"s_Mayo_TN_CC_430\" : 383 , \"s_Mayo_TN_CC_390\" : 339 , \"s_Mayo_TN_CC_636\" : 609 , \"s_Mayo_TN_CC_431\" : 384 , \"s_Mayo_TN_CC_637\" : 610 , \"s_Mayo_TN_CC_829\" : 821 , \"s_Mayo_TN_CC_634\" : 607 , \"s_Mayo_TN_CC_635\" : 608 , \"s_Mayo_TN_CC_435\" : 388 , \"s_Mayo_TN_CC_434\" : 387 , \"s_Mayo_TN_CC_433\" : 386 , \"s_Mayo_TN_CC_432\" : 385 , \"s_Mayo_TN_CC_439\" : 392 , \"s_Mayo_TN_CC_438\" : 391 , \"s_Mayo_TN_CC_437\" : 390 , \"s_Mayo_TN_CC_436\" : 389 , \"s_Mayo_TN_CC_399\" : 348 , \"s_Mayo_TN_CC_111\" : 32 , \"s_Mayo_TN_CC_112\" : 33 , \"s_Mayo_TN_CC_110\" : 31 , \"s_Mayo_TN_CC_381\" : 329 , \"s_Mayo_TN_CC_103\" : 23 , \"s_Mayo_TN_CC_627\" : 599 , \"s_Mayo_TN_CC_380\" : 328 , \"s_Mayo_TN_CC_102\" : 22 , \"s_Mayo_TN_CC_628\" : 600 , \"s_Mayo_TN_CC_830\" : 823 , \"s_Mayo_TN_CC_383\" : 331 , \"s_Mayo_TN_CC_105\" : 25 , \"s_Mayo_TN_CC_629\" : 601 , \"s_Mayo_TN_CC_831\" : 824 , \"s_Mayo_TN_CC_382\" : 330 , \"s_Mayo_TN_CC_104\" : 24 , \"s_Mayo_TN_CC_832\" : 825 , \"s_Mayo_TN_CC_385\" : 333 , \"s_Mayo_TN_CC_107\" : 27 , \"s_Mayo_TN_CC_833\" : 826 , \"s_Mayo_TN_CC_384\" : 332 , \"s_Mayo_TN_CC_106\" : 26 , \"s_Mayo_TN_CC_834\" : 827 , \"s_Mayo_TN_CC_387\" : 335 , \"s_Mayo_TN_CC_109\" : 29 , \"s_Mayo_TN_CC_835\" : 828 , \"s_Mayo_TN_CC_386\" : 334 , \"s_Mayo_TN_CC_108\" : 28 , \"s_Mayo_TN_CC_836\" : 829 , \"s_Mayo_TN_CC_837\" : 830 , \"s_Mayo_TN_CC_620\" : 592 , \"s_Mayo_TN_CC_838\" : 831 , \"s_Mayo_TN_CC_621\" : 593 , \"s_Mayo_TN_CC_839\" : 832 , \"s_Mayo_TN_CC_622\" : 594 , \"s_Mayo_TN_CC_623\" : 595 , \"s_Mayo_TN_CC_624\" : 596 , \"s_Mayo_TN_CC_625\" : 597 , \"s_Mayo_TN_CC_420\" : 372 , \"s_Mayo_TN_CC_626\" : 598 , \"s_Mayo_TN_CC_422\" : 374 , \"s_Mayo_TN_CC_421\" : 373 , \"s_Mayo_TN_CC_424\" : 376 , \"s_Mayo_TN_CC_423\" : 375 , \"s_Mayo_TN_CC_426\" : 378 , \"s_Mayo_TN_CC_425\" : 377 , \"s_Mayo_TN_CC_428\" : 380 , \"s_Mayo_TN_CC_427\" : 379 , \"s_Mayo_TN_CC_388\" : 336 , \"s_Mayo_TN_CC_429\" : 381 , \"s_Mayo_TN_CC_389\" : 337 , \"s_Mayo_TN_CC_100\" : 20 , \"s_Mayo_TN_CC_101\" : 21 , \"s_Mayo_TN_CC_845\" : 839 , \"s_Mayo_TN_CC_18\" : 107 , \"s_Mayo_TN_CC_846\" : 840 , \"s_Mayo_TN_CC_19\" : 118 , \"s_Mayo_TN_CC_843\" : 837 , \"s_Mayo_TN_CC_16\" : 85 , \"s_Mayo_TN_CC_844\" : 838 , \"s_Mayo_TN_CC_17\" : 96 , \"s_Mayo_TN_CC_139\" : 62 , \"s_Mayo_TN_CC_841\" : 835 , \"s_Mayo_TN_CC_138\" : 61 , \"s_Mayo_TN_CC_842\" : 836 , \"s_Mayo_TN_CC_137\" : 60 , \"s_Mayo_TN_CC_136\" : 59 , \"s_Mayo_TN_CC_840\" : 834 , \"s_Mayo_TN_CC_135\" : 58 , \"s_Mayo_TN_CC_10\" : 19 , \"s_Mayo_TN_CC_452\" : 407 , \"s_Mayo_TN_CC_658\" : 633 , \"s_Mayo_TN_CC_11\" : 30 , \"s_Mayo_TN_CC_453\" : 408 , \"s_Mayo_TN_CC_659\" : 634 , \"s_Mayo_TN_CC_450\" : 405 , \"s_Mayo_TN_CC_656\" : 631 , \"s_Mayo_TN_CC_451\" : 406 , \"s_Mayo_TN_CC_657\" : 632 , \"s_Mayo_TN_CC_849\" : 843 , \"s_Mayo_TN_CC_14\" : 63 , \"s_Mayo_TN_CC_654\" : 629 , \"s_Mayo_TN_CC_15\" : 74 , \"s_Mayo_TN_CC_655\" : 630 , \"s_Mayo_TN_CC_847\" : 841 , \"s_Mayo_TN_CC_12\" : 41 , \"s_Mayo_TN_CC_652\" : 627 , \"s_Mayo_TN_CC_848\" : 842 , \"s_Mayo_TN_CC_13\" : 52 , \"s_Mayo_TN_CC_653\" : 628 , \"s_Mayo_TN_CC_651\" : 626 , \"s_Mayo_TN_CC_650\" : 625 , \"s_Mayo_TN_CC_459\" : 414 , \"s_Mayo_TN_CC_458\" : 413 , \"s_Mayo_TN_CC_457\" : 412 , \"s_Mayo_TN_CC_456\" : 411 , \"s_Mayo_TN_CC_455\" : 410 , \"s_Mayo_TN_CC_454\" : 409 , \"s_Mayo_TN_CC_133\" : 56 , \"s_Mayo_TN_CC_134\" : 57 , \"s_Mayo_TN_CC_131\" : 54 , \"s_Mayo_TN_CC_132\" : 55 , \"s_Mayo_TN_CC_130\" : 53 , \"s_Mayo_TN_CC_854\" : 849 , \"s_Mayo_TN_CC_05\" : 14 , \"s_Mayo_TN_CC_129\" : 51 , \"s_Mayo_TN_CC_855\" : 850 , \"s_Mayo_TN_CC_06\" : 15 , \"s_Mayo_TN_CC_128\" : 50 , \"s_Mayo_TN_CC_856\" : 851 , \"s_Mayo_TN_CC_07\" : 16 , \"s_Mayo_TN_CC_857\" : 852 , \"s_Mayo_TN_CC_08\" : 17 , \"s_Mayo_TN_CC_850\" : 845 , \"s_Mayo_TN_CC_09\" : 18 , \"s_Mayo_TN_CC_125\" : 47 , \"s_Mayo_TN_CC_649\" : 623 , \"s_Mayo_TN_CC_851\" : 846 , \"s_Mayo_TN_CC_124\" : 46 , \"s_Mayo_TN_CC_852\" : 847 , \"s_Mayo_TN_CC_127\" : 49 , \"s_Mayo_TN_CC_853\" : 848 , \"s_Mayo_TN_CC_126\" : 48 , \"s_Mayo_TN_CC_645\" : 619 , \"s_Mayo_TN_CC_440\" : 394 , \"s_Mayo_TN_CC_646\" : 620 , \"s_Mayo_TN_CC_441\" : 395 , \"s_Mayo_TN_CC_647\" : 621 , \"s_Mayo_TN_CC_442\" : 396 , \"s_Mayo_TN_CC_648\" : 622 , \"s_Mayo_TN_CC_858\" : 853 , \"s_Mayo_TN_CC_01\" : 10 , \"s_Mayo_TN_CC_641\" : 615 , \"s_Mayo_TN_CC_859\" : 854 , \"s_Mayo_TN_CC_02\" : 11 , \"s_Mayo_TN_CC_642\" : 616 , \"s_Mayo_TN_CC_03\" : 12 , \"s_Mayo_TN_CC_643\" : 617 , \"s_Mayo_TN_CC_04\" : 13 , \"s_Mayo_TN_CC_644\" : 618 , \"s_Mayo_TN_CC_448\" : 402 , \"s_Mayo_TN_CC_447\" : 401 , \"s_Mayo_TN_CC_640\" : 614 , \"s_Mayo_TN_CC_449\" : 403 , \"s_Mayo_TN_CC_444\" : 398 , \"s_Mayo_TN_CC_443\" : 397 , \"s_Mayo_TN_CC_446\" : 400 , \"s_Mayo_TN_CC_445\" : 399 , \"s_Mayo_TN_CC_120\" : 42 , \"s_Mayo_TN_CC_121\" : 43 , \"s_Mayo_TN_CC_122\" : 44 , \"s_Mayo_TN_CC_123\" : 45 , \"s_Mayo_TN_CC_860\" : 856 , \"s_Mayo_TN_CC_869\" : 865 , \"s_Mayo_TN_CC_862\" : 858 , \"s_Mayo_TN_CC_861\" : 857 , \"s_Mayo_TN_CC_864\" : 860 , \"s_Mayo_TN_CC_863\" : 859 , \"s_Mayo_TN_CC_866\" : 862 , \"s_Mayo_TN_CC_865\" : 861 , \"s_Mayo_TN_CC_868\" : 864 , \"s_Mayo_TN_CC_867\" : 863 , \"s_Mayo_TN_CC_870\" : 867 , \"s_Mayo_TN_CC_871\" : 868 , \"s_Mayo_TN_CC_875\" : 872 , \"s_Mayo_TN_CC_874\" : 871 , \"s_Mayo_TN_CC_873\" : 870 , \"s_Mayo_TN_CC_872\" : 869 , \"s_Mayo_TN_CC_879\" : 876 , \"s_Mayo_TN_CC_878\" : 875 , \"s_Mayo_TN_CC_877\" : 874 , \"s_Mayo_TN_CC_876\" : 873 , \"s_Mayo_TN_CC_880\" : 878 , \"s_Mayo_TN_CC_881\" : 879 , \"s_Mayo_TN_CC_882\" : 880 , \"s_Mayo_TN_CC_613\" : 584 , \"s_Mayo_TN_CC_612\" : 583 , \"s_Mayo_TN_CC_615\" : 586 , \"s_Mayo_TN_CC_614\" : 585 , \"s_Mayo_TN_CC_611\" : 582 , \"s_Mayo_TN_CC_610\" : 581 , \"s_Mayo_TN_CC_888\" : 886 , \"s_Mayo_TN_CC_887\" : 885 , \"s_Mayo_TN_CC_884\" : 882 , \"s_Mayo_TN_CC_617\" : 588 , \"s_Mayo_TN_CC_883\" : 881 , \"s_Mayo_TN_CC_616\" : 587 , \"s_Mayo_TN_CC_886\" : 884 , \"s_Mayo_TN_CC_619\" : 590 , \"s_Mayo_TN_CC_885\" : 883 , \"s_Mayo_TN_CC_618\" : 589 , \"s_Mayo_TN_CC_604\" : 574 , \"s_Mayo_TN_CC_603\" : 573 , \"s_Mayo_TN_CC_602\" : 572 , \"s_Mayo_TN_CC_601\" : 571 , \"s_Mayo_TN_CC_600\" : 570 , \"s_Mayo_TN_CC_609\" : 579 , \"s_Mayo_TN_CC_608\" : 578 , \"s_Mayo_TN_CC_607\" : 577 , \"s_Mayo_TN_CC_606\" : 576 , \"s_Mayo_TN_CC_605\" : 575 , \"s_Mayo_TN_CC_82\" : 811 , \"s_Mayo_TN_CC_81\" : 800 , \"s_Mayo_TN_CC_84\" : 833 , \"s_Mayo_TN_CC_83\" : 822 , \"s_Mayo_TN_CC_190\" : 119 , \"s_Mayo_TN_CC_80\" : 789 , \"s_Mayo_TN_CC_191\" : 120 , \"s_Mayo_TN_CC_192\" : 121 , \"s_Mayo_TN_CC_193\" : 122 , \"s_Mayo_TN_CC_194\" : 123 , \"s_Mayo_TN_CC_195\" : 124 , \"s_Mayo_TN_CC_196\" : 125 , \"s_Mayo_TN_CC_197\" : 126 , \"s_Mayo_TN_CC_198\" : 127 , \"s_Mayo_TN_CC_199\" : 128 , \"s_Mayo_TN_CC_78\" : 767 , \"s_Mayo_TN_CC_79\" : 778 , \"s_Mayo_TN_CC_74\" : 723 , \"s_Mayo_TN_CC_75\" : 734 , \"s_Mayo_TN_CC_76\" : 745 , \"s_Mayo_TN_CC_77\" : 756 , \"s_Mayo_TN_CC_73\" : 712 , \"s_Mayo_TN_CC_72\" : 701 , \"s_Mayo_TN_CC_71\" : 690 , \"s_Mayo_TN_CC_70\" : 679 , \"s_Mayo_TN_CC_180\" : 108 , \"s_Mayo_TN_CC_181\" : 109 , \"s_Mayo_TN_CC_184\" : 112 , \"s_Mayo_TN_CC_185\" : 113 , \"s_Mayo_TN_CC_182\" : 110 , \"s_Mayo_TN_CC_183\" : 111 , \"s_Mayo_TN_CC_188\" : 116 , \"s_Mayo_TN_CC_189\" : 117 , \"s_Mayo_TN_CC_186\" : 114 , \"s_Mayo_TN_CC_187\" : 115 , \"s_Mayo_TN_CC_69\" : 668 , \"s_Mayo_TN_CC_67\" : 646 , \"s_Mayo_TN_CC_68\" : 657 , \"s_Mayo_TN_CC_65\" : 624 , \"s_Mayo_TN_CC_66\" : 635 , \"s_Mayo_TN_CC_63\" : 602 , \"s_Mayo_TN_CC_64\" : 613 , \"s_Mayo_TN_CC_96\" : 894 , \"s_Mayo_TN_CC_97\" : 895 , \"s_Mayo_TN_CC_98\" : 896 , \"s_Mayo_TN_CC_99\" : 897 , \"s_Mayo_TN_CC_91\" : 889 , \"s_Mayo_TN_CC_90\" : 888 , \"s_Mayo_TN_CC_95\" : 893 , \"s_Mayo_TN_CC_94\" : 892 , \"s_Mayo_TN_CC_93\" : 891 , \"s_Mayo_TN_CC_92\" : 890 , \"s_Mayo_TN_CC_87\" : 866 , \"s_Mayo_TN_CC_88\" : 877 , \"s_Mayo_TN_CC_85\" : 844 , \"s_Mayo_TN_CC_86\" : 855 , \"s_Mayo_TN_CC_89\" : 887 , \"s_Mayo_TN_CC_469\" : 425 , \"s_Mayo_TN_CC_467\" : 423 , \"s_Mayo_TN_CC_468\" : 424 , \"s_Mayo_TN_CC_465\" : 421 , \"s_Mayo_TN_CC_466\" : 422 , \"s_Mayo_TN_CC_464\" : 420 , \"s_Mayo_TN_CC_463\" : 419 , \"s_Mayo_TN_CC_462\" : 418 , \"s_Mayo_TN_CC_461\" : 417 , \"s_Mayo_TN_CC_460\" : 416 , \"s_Mayo_TN_CC_476\" : 433 , \"s_Mayo_TN_CC_477\" : 434 , \"s_Mayo_TN_CC_478\" : 435 , \"s_Mayo_TN_CC_479\" : 436 , \"s_Mayo_TN_CC_473\" : 430 , \"s_Mayo_TN_CC_472\" : 429 , \"s_Mayo_TN_CC_475\" : 432 , \"s_Mayo_TN_CC_474\" : 431 , \"s_Mayo_TN_CC_471\" : 428 , \"s_Mayo_TN_CC_470\" : 427 , \"s_Mayo_TN_CC_489\" : 447 , \"s_Mayo_TN_CC_487\" : 445 , \"s_Mayo_TN_CC_488\" : 446 , \"s_Mayo_TN_CC_482\" : 440 , \"s_Mayo_TN_CC_481\" : 439 , \"s_Mayo_TN_CC_480\" : 438 , \"s_Mayo_TN_CC_486\" : 444 , \"s_Mayo_TN_CC_485\" : 443 , \"s_Mayo_TN_CC_484\" : 442 , \"s_Mayo_TN_CC_483\" : 441 , \"s_Mayo_TN_CC_498\" : 457 , \"s_Mayo_TN_CC_499\" : 458 , \"s_Mayo_TN_CC_491\" : 450 , \"s_Mayo_TN_CC_490\" : 449 , \"s_Mayo_TN_CC_493\" : 452 , \"s_Mayo_TN_CC_492\" : 451 , \"s_Mayo_TN_CC_495\" : 454 , \"s_Mayo_TN_CC_494\" : 453 , \"s_Mayo_TN_CC_497\" : 456 , \"s_Mayo_TN_CC_496\" : 455 , \"s_Mayo_TN_CC_308\" : 248 , \"s_Mayo_TN_CC_309\" : 249 , \"s_Mayo_TN_CC_306\" : 246 , \"s_Mayo_TN_CC_307\" : 247 , \"s_Mayo_TN_CC_304\" : 244 , \"s_Mayo_TN_CC_305\" : 245 , \"s_Mayo_TN_CC_302\" : 242 , \"s_Mayo_TN_CC_303\" : 243 , \"s_Mayo_TN_CC_300\" : 240 , \"s_Mayo_TN_CC_301\" : 241 , \"s_Mayo_TN_CC_319\" : 260 , \"s_Mayo_TN_CC_315\" : 256 , \"s_Mayo_TN_CC_316\" : 257 , \"s_Mayo_TN_CC_317\" : 258 , \"s_Mayo_TN_CC_318\" : 259 , \"s_Mayo_TN_CC_311\" : 252 , \"s_Mayo_TN_CC_312\" : 253 , \"s_Mayo_TN_CC_313\" : 254 , \"s_Mayo_TN_CC_314\" : 255 , \"s_Mayo_TN_CC_310\" : 251 , \"s_Mayo_TN_CC_324\" : 266 , \"s_Mayo_TN_CC_325\" : 267 , \"s_Mayo_TN_CC_322\" : 264 , \"s_Mayo_TN_CC_323\" : 265 , \"s_Mayo_TN_CC_328\" : 270 , \"s_Mayo_TN_CC_329\" : 271 , \"s_Mayo_TN_CC_326\" : 268 , \"s_Mayo_TN_CC_327\" : 269 , \"s_Mayo_TN_CC_321\" : 263 , \"s_Mayo_TN_CC_320\" : 262 , \"s_Mayo_TN_CC_333\" : 276 , \"s_Mayo_TN_CC_334\" : 277 , \"s_Mayo_TN_CC_335\" : 278 , \"s_Mayo_TN_CC_336\" : 279 , \"s_Mayo_TN_CC_337\" : 280 , \"s_Mayo_TN_CC_338\" : 281 , \"s_Mayo_TN_CC_339\" : 282 , \"s_Mayo_TN_CC_330\" : 273 , \"s_Mayo_TN_CC_332\" : 275 , \"s_Mayo_TN_CC_331\" : 274} , \"FORMAT\" : { \"min\" : { \"PL\" : 1 , \"AD\" : 1 , \"GT\" : 1 , \"GQ\" : 1} , \"max\" : { \"PL\" : 1 , \"AD\" : 1 , \"GT\" : 1 , \"GQ\" : 1}}}";
//String resultAfterSave = "{ \"_id\" : \"52d6af9d4206e1ed4e54f7b4\" , \"INFO\" : { \"Controls_AN\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AN for Controls\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_AMINO_ACID_LENGTH\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Length of protein in amino acids (actually, transcription length divided by 3)\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_TRANSCRIPT_ID\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Transcript ID for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"UGT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The most probable unconstrained genotype configuration in the trio\" , \"EntryType\" : \"INFO\"} , \"InbreedingCoeff\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Inbreeding coefficient as estimated from the genotype likelihoods per-sample when compared against the Hardy-Weinberg expectation\" , \"EntryType\" : \"INFO\"} , \"Group\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_CODON_CHANGE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Old/New codon for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"Cases_AF\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AF for Cases\" , \"EntryType\" : \"INFO\"} , \"AF1\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Max-likelihood estimate of the first ALT allele frequency (assuming HWE)\" , \"EntryType\" : \"INFO\"} , \"ReadPosRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt vs. Ref read position bias\" , \"EntryType\" : \"INFO\"} , \"DP\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Approximate read depth; some reads may have been filtered\" , \"EntryType\" : \"INFO\"} , \"DS\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Were any of the samples downsampled?\" , \"EntryType\" : \"INFO\"} , \"Controls_AF\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AF for Controls\" , \"EntryType\" : \"INFO\"} , \"Cases_AN\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AN for Cases\" , \"EntryType\" : \"INFO\"} , \"Controls_AC\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AC for Controls\" , \"EntryType\" : \"INFO\"} , \"STR\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Variant is a short tandem repeat\" , \"EntryType\" : \"INFO\"} , \"BaseQRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score from Wilcoxon rank sum test of Alt Vs. Ref base qualities\" , \"EntryType\" : \"INFO\"} , \"HWE\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Chi^2 based HWE test P-value based on G3\" , \"EntryType\" : \"INFO\"} , \"QD\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Variant Confidence/Quality by Depth\" , \"EntryType\" : \"INFO\"} , \"MQ\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"RMS Mapping Quality\" , \"EntryType\" : \"INFO\"} , \"PC2\" : { \"number\" : 2 , \"type\" : \"Integer\" , \"Description\" : \"Phred probability of the nonRef allele frequency in group1 samples being larger (,smaller) than in group2.\" , \"EntryType\" : \"INFO\"} , \"CGT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The most probable constrained genotype configuration in the trio\" , \"EntryType\" : \"INFO\"} , \"AC\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Allele count in genotypes, for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"AD\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Allelic depths for the ref and alt alleles in the order listed\" , \"EntryType\" : \"FORMAT\"} , \"QCHI2\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Phred scaled PCHI2.\" , \"EntryType\" : \"INFO\"} , \"HRun\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Largest Contiguous Homopolymer Run of Variant Allele In Either Direction\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_IMPACT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Impact of the highest-impact effect resulting from the current variant [MODIFIER, LOW, MODERATE, HIGH]\" , \"EntryType\" : \"INFO\"} , \"Dels\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Fraction of Reads Containing Spanning Deletions\" , \"EntryType\" : \"INFO\"} , \"INDEL\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"Indicates that the variant is an INDEL.\" , \"EntryType\" : \"INFO\"} , \"PR\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"# permutations yielding a smaller PCHI2.\" , \"EntryType\" : \"INFO\"} , \"AF\" : { \"number\" : null , \"type\" : \"Float\" , \"Description\" : \"Allele Frequency, for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"DP4\" : { \"number\" : 4 , \"type\" : \"Integer\" , \"Description\" : \"# high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\" , \"EntryType\" : \"INFO\"} , \"MLPSAF\" : { \"number\" : null , \"type\" : \"Float\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele fraction, in the same order as listed, for each individual sample\" , \"EntryType\" : \"FORMAT\"} , \"MLPSAC\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the alternate allele count, in the same order as listed, for each individual sample\" , \"EntryType\" : \"FORMAT\"} , \"SVLEN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Difference in length between REF and ALT alleles\" , \"EntryType\" : \"INFO\"} , \"AN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Total number of alleles in called genotypes\" , \"EntryType\" : \"INFO\"} , \"CLR\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Log ratio of genotype likelihoods with and without the constraint\" , \"EntryType\" : \"INFO\"} , \"HaplotypeScore\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Consistency of the site with at most two segregating haplotypes\" , \"EntryType\" : \"INFO\"} , \"PCHI2\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Posterior weighted chi^2 P-value for testing the association between group1 and group2 samples.\" , \"EntryType\" : \"INFO\"} , \"set\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"Genotyper\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_EXON_ID\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Exon ID for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"MLEAC\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the allele counts (not necessarily the same as the AC), for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_GENE_NAME\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Gene name for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"MLEAF\" : { \"number\" : null , \"type\" : \"Float\" , \"Description\" : \"Maximum likelihood expectation (MLE) for the allele frequency (not necessarily the same as the AF), for each ALT allele, in the same order as listed\" , \"EntryType\" : \"INFO\"} , \"FS\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Phred-scaled p-value using Fisher's exact test to detect strand bias\" , \"EntryType\" : \"INFO\"} , \"G3\" : { \"number\" : 3 , \"type\" : \"Float\" , \"Description\" : \"ML estimate of genotype frequencies\" , \"EntryType\" : \"INFO\"} , \"FQ\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Phred probability of all samples being the same\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_AMINO_ACID_CHANGE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Old/New amino acid for the highest-impact effect resulting from the current variant (in HGVS style)\" , \"EntryType\" : \"INFO\"} , \"GenotyperControls\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Source VCF for the merged record in CombineVariants\" , \"EntryType\" : \"INFO\"} , \"VDB\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Variant Distance Bias\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_FUNCTIONAL_CLASS\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Functional class of the highest-impact effect resulting from the current variant: [NONE, SILENT, MISSENSE, NONSENSE]\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_EFFECT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"The highest-impact effect resulting from the current variant (or one of the highest-impact effects, if there is a tie)\" , \"EntryType\" : \"INFO\"} , \"Cases_AC\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Original AC for Cases\" , \"EntryType\" : \"INFO\"} , \"DB\" : { \"number\" : 0 , \"type\" : \"Flag\" , \"Description\" : \"dbSNP Membership\" , \"EntryType\" : \"INFO\"} , \"SVTYPE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Type of structural variant\" , \"EntryType\" : \"INFO\"} , \"SNPEFF_GENE_BIOTYPE\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Gene biotype for the highest-impact effect resulting from the current variant\" , \"EntryType\" : \"INFO\"} , \"SP\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Phred-scaled strand bias P-value\" , \"EntryType\" : \"FORMAT\"} , \"NTLEN\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Number of bases inserted in place of deleted code\" , \"EntryType\" : \"INFO\"} , \"PL\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\" , \"EntryType\" : \"FORMAT\"} , \"GT\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Genotype\" , \"EntryType\" : \"FORMAT\"} , \"HOMSEQ\" : { \"number\" : null , \"type\" : \"String\" , \"Description\" : \"Sequence of base pair identical micro-homology at event breakpoints\" , \"EntryType\" : \"INFO\"} , \"RU\" : { \"number\" : 1 , \"type\" : \"String\" , \"Description\" : \"Tandem repeat unit (bases)\" , \"EntryType\" : \"INFO\"} , \"MQRankSum\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Z-score From Wilcoxon rank sum test of Alt vs. Ref read mapping qualities\" , \"EntryType\" : \"INFO\"} , \"GQ\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Genotype Quality\" , \"EntryType\" : \"FORMAT\"} , \"RPA\" : { \"number\" : null , \"type\" : \"Integer\" , \"Description\" : \"Number of times tandem repeat unit is repeated, for each allele (including reference)\" , \"EntryType\" : \"INFO\"} , \"HOMLEN\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Length of base pair identical micro-homology at event breakpoints\" , \"EntryType\" : \"INFO\"} , \"END\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"End position of the variant described in this record\" , \"EntryType\" : \"INFO\"} , \"MQ0\" : { \"number\" : 1 , \"type\" : \"Integer\" , \"Description\" : \"Total Mapping Quality Zero Reads\" , \"EntryType\" : \"INFO\"} , \"GL\" : { \"number\" : 3 , \"type\" : \"Float\" , \"Description\" : \"Likelihoods for RR,RA,AA genotypes (R=ref,A=alt)\" , \"EntryType\" : \"FORMAT\"} , \"AC1\" : { \"number\" : 1 , \"type\" : \"Float\" , \"Description\" : \"Max-likelihood estimate of the first ALT allele count (no HWE assumption)\" , \"EntryType\" : \"INFO\"} , \"PV4\" : { \"number\" : 4 , \"type\" : \"Float\" , \"Description\" : \"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\" , \"EntryType\" : \"INFO\"}} , \"SAMPLES\" : { \"s_Mayo_TN_CC_254\" : 189 , \"s_Mayo_TN_CC_255\" : 190 , \"s_Mayo_TN_CC_252\" : 187 , \"s_Mayo_TN_CC_253\" : 188 , \"s_Mayo_TN_CC_250\" : 185 , \"s_Mayo_TN_CC_251\" : 186 , \"s_Mayo_TN_CC_530\" : 493 , \"s_Mayo_TN_CC_537\" : 500 , \"s_Mayo_TN_CC_538\" : 501 , \"s_Mayo_TN_CC_535\" : 498 , \"s_Mayo_TN_CC_536\" : 499 , \"s_Mayo_TN_CC_533\" : 496 , \"s_Mayo_TN_CC_534\" : 497 , \"s_Mayo_TN_CC_531\" : 494 , \"s_Mayo_TN_CC_532\" : 495 , \"s_Mayo_TN_CC_259\" : 194 , \"s_Mayo_TN_CC_258\" : 193 , \"s_Mayo_TN_CC_257\" : 192 , \"s_Mayo_TN_CC_539\" : 502 , \"s_Mayo_TN_CC_256\" : 191 , \"s_Mayo_TN_CC_241\" : 175 , \"s_Mayo_TN_CC_242\" : 176 , \"s_Mayo_TN_CC_243\" : 177 , \"s_Mayo_TN_CC_244\" : 178 , \"s_Mayo_TN_CC_240\" : 174 , \"s_Mayo_TN_CC_524\" : 486 , \"s_Mayo_TN_CC_525\" : 487 , \"s_Mayo_TN_CC_526\" : 488 , \"s_Mayo_TN_CC_527\" : 489 , \"s_Mayo_TN_CC_520\" : 482 , \"s_Mayo_TN_CC_521\" : 483 , \"s_Mayo_TN_CC_522\" : 484 , \"s_Mayo_TN_CC_523\" : 485 , \"s_Mayo_TN_CC_249\" : 183 , \"s_Mayo_TN_CC_246\" : 180 , \"s_Mayo_TN_CC_528\" : 490 , \"s_Mayo_TN_CC_245\" : 179 , \"s_Mayo_TN_CC_529\" : 491 , \"s_Mayo_TN_CC_248\" : 182 , \"s_Mayo_TN_CC_247\" : 181 , \"s_Mayo_TN_CC_232\" : 165 , \"s_Mayo_TN_CC_233\" : 166 , \"s_Mayo_TN_CC_230\" : 163 , \"s_Mayo_TN_CC_231\" : 164 , \"s_Mayo_TN_CC_798\" : 787 , \"s_Mayo_TN_CC_797\" : 786 , \"s_Mayo_TN_CC_796\" : 785 , \"s_Mayo_TN_CC_795\" : 784 , \"s_Mayo_TN_CC_799\" : 788 , \"s_Mayo_TN_CC_511\" : 472 , \"s_Mayo_TN_CC_790\" : 779 , \"s_Mayo_TN_CC_512\" : 473 , \"s_Mayo_TN_CC_510\" : 471 , \"s_Mayo_TN_CC_793\" : 782 , \"s_Mayo_TN_CC_515\" : 476 , \"s_Mayo_TN_CC_794\" : 783 , \"s_Mayo_TN_CC_516\" : 477 , \"s_Mayo_TN_CC_791\" : 780 , \"s_Mayo_TN_CC_513\" : 474 , \"s_Mayo_TN_CC_792\" : 781 , \"s_Mayo_TN_CC_514\" : 475 , \"s_Mayo_TN_CC_237\" : 170 , \"s_Mayo_TN_CC_519\" : 480 , \"s_Mayo_TN_CC_236\" : 169 , \"s_Mayo_TN_CC_235\" : 168 , \"s_Mayo_TN_CC_517\" : 478 , \"s_Mayo_TN_CC_234\" : 167 , \"s_Mayo_TN_CC_518\" : 479 , \"s_Mayo_TN_CC_239\" : 172 , \"s_Mayo_TN_CC_238\" : 171 , \"s_Mayo_TN_CC_220\" : 152 , \"s_Mayo_TN_CC_221\" : 153 , \"s_Mayo_TN_CC_222\" : 154 , \"s_Mayo_TN_CC_785\" : 773 , \"s_Mayo_TN_CC_784\" : 772 , \"s_Mayo_TN_CC_787\" : 775 , \"s_Mayo_TN_CC_786\" : 774 , \"s_Mayo_TN_CC_789\" : 777 , \"s_Mayo_TN_CC_788\" : 776 , \"s_Mayo_TN_CC_500\" : 460 , \"s_Mayo_TN_CC_501\" : 461 , \"s_Mayo_TN_CC_502\" : 462 , \"s_Mayo_TN_CC_780\" : 768 , \"s_Mayo_TN_CC_503\" : 463 , \"s_Mayo_TN_CC_781\" : 769 , \"s_Mayo_TN_CC_504\" : 464 , \"s_Mayo_TN_CC_782\" : 770 , \"s_Mayo_TN_CC_505\" : 465 , \"s_Mayo_TN_CC_783\" : 771 , \"s_Mayo_TN_CC_224\" : 156 , \"s_Mayo_TN_CC_506\" : 466 , \"s_Mayo_TN_CC_223\" : 155 , \"s_Mayo_TN_CC_507\" : 467 , \"s_Mayo_TN_CC_226\" : 158 , \"s_Mayo_TN_CC_508\" : 468 , \"s_Mayo_TN_CC_225\" : 157 , \"s_Mayo_TN_CC_509\" : 469 , \"s_Mayo_TN_CC_228\" : 160 , \"s_Mayo_TN_CC_227\" : 159 , \"s_Mayo_TN_CC_229\" : 161 , \"s_Mayo_TN_CC_291\" : 230 , \"s_Mayo_TN_CC_573\" : 540 , \"s_Mayo_TN_CC_779\" : 766 , \"s_Mayo_TN_CC_290\" : 229 , \"s_Mayo_TN_CC_574\" : 541 , \"s_Mayo_TN_CC_571\" : 538 , \"s_Mayo_TN_CC_777\" : 764 , \"s_Mayo_TN_CC_572\" : 539 , \"s_Mayo_TN_CC_778\" : 765 , \"s_Mayo_TN_CC_775\" : 762 , \"s_Mayo_TN_CC_570\" : 537 , \"s_Mayo_TN_CC_776\" : 763 , \"s_Mayo_TN_CC_773\" : 760 , \"s_Mayo_TN_CC_774\" : 761 , \"s_Mayo_TN_CC_299\" : 238 , \"s_Mayo_TN_CC_298\" : 237 , \"s_Mayo_TN_CC_297\" : 236 , \"s_Mayo_TN_CC_296\" : 235 , \"s_Mayo_TN_CC_295\" : 234 , \"s_Mayo_TN_CC_294\" : 233 , \"s_Mayo_TN_CC_293\" : 232 , \"s_Mayo_TN_CC_292\" : 231 , \"s_Mayo_TN_CC_772\" : 759 , \"s_Mayo_TN_CC_771\" : 758 , \"s_Mayo_TN_CC_770\" : 757 , \"s_Mayo_TN_CC_579\" : 546 , \"s_Mayo_TN_CC_578\" : 545 , \"s_Mayo_TN_CC_577\" : 544 , \"s_Mayo_TN_CC_576\" : 543 , \"s_Mayo_TN_CC_575\" : 542 , \"s_Mayo_TN_CC_560\" : 526 , \"s_Mayo_TN_CC_766\" : 752 , \"s_Mayo_TN_CC_561\" : 527 , \"s_Mayo_TN_CC_767\" : 753 , \"s_Mayo_TN_CC_280\" : 218 , \"s_Mayo_TN_CC_562\" : 528 , \"s_Mayo_TN_CC_768\" : 754 , \"s_Mayo_TN_CC_563\" : 529 , \"s_Mayo_TN_CC_769\" : 755 , \"s_Mayo_TN_CC_762\" : 748 , \"s_Mayo_TN_CC_763\" : 749 , \"s_Mayo_TN_CC_764\" : 750 , \"s_Mayo_TN_CC_765\" : 751 , \"s_Mayo_TN_CC_286\" : 224 , \"s_Mayo_TN_CC_285\" : 223 , \"s_Mayo_TN_CC_288\" : 226 , \"s_Mayo_TN_CC_287\" : 225 , \"s_Mayo_TN_CC_282\" : 220 , \"s_Mayo_TN_CC_281\" : 219 , \"s_Mayo_TN_CC_284\" : 222 , \"s_Mayo_TN_CC_283\" : 221 , \"s_Mayo_TN_CC_289\" : 227 , \"s_Mayo_TN_CC_569\" : 535 , \"s_Mayo_TN_CC_568\" : 534 , \"s_Mayo_TN_CC_761\" : 747 , \"s_Mayo_TN_CC_760\" : 746 , \"s_Mayo_TN_CC_565\" : 531 , \"s_Mayo_TN_CC_564\" : 530 , \"s_Mayo_TN_CC_567\" : 533 , \"s_Mayo_TN_CC_566\" : 532 , \"s_Mayo_TN_CC_753\" : 738 , \"s_Mayo_TN_CC_754\" : 739 , \"s_Mayo_TN_CC_751\" : 736 , \"s_Mayo_TN_CC_752\" : 737 , \"s_Mayo_TN_CC_551\" : 516 , \"s_Mayo_TN_CC_757\" : 742 , \"s_Mayo_TN_CC_552\" : 517 , \"s_Mayo_TN_CC_758\" : 743 , \"s_Mayo_TN_CC_755\" : 740 , \"s_Mayo_TN_CC_550\" : 515 , \"s_Mayo_TN_CC_756\" : 741 , \"s_Mayo_TN_CC_273\" : 210 , \"s_Mayo_TN_CC_272\" : 209 , \"s_Mayo_TN_CC_271\" : 208 , \"s_Mayo_TN_CC_759\" : 744 , \"s_Mayo_TN_CC_270\" : 207 , \"s_Mayo_TN_CC_277\" : 214 , \"s_Mayo_TN_CC_276\" : 213 , \"s_Mayo_TN_CC_275\" : 212 , \"s_Mayo_TN_CC_274\" : 211 , \"s_Mayo_TN_CC_278\" : 215 , \"s_Mayo_TN_CC_279\" : 216 , \"s_Mayo_TN_CC_556\" : 521 , \"s_Mayo_TN_CC_555\" : 520 , \"s_Mayo_TN_CC_554\" : 519 , \"s_Mayo_TN_CC_553\" : 518 , \"s_Mayo_TN_CC_750\" : 735 , \"s_Mayo_TN_CC_559\" : 524 , \"s_Mayo_TN_CC_558\" : 523 , \"s_Mayo_TN_CC_557\" : 522 , \"s_Mayo_TN_CC_740\" : 724 , \"s_Mayo_TN_CC_741\" : 725 , \"s_Mayo_TN_CC_742\" : 726 , \"s_Mayo_TN_CC_743\" : 727 , \"s_Mayo_TN_CC_744\" : 728 , \"s_Mayo_TN_CC_745\" : 729 , \"s_Mayo_TN_CC_540\" : 504 , \"s_Mayo_TN_CC_746\" : 730 , \"s_Mayo_TN_CC_541\" : 505 , \"s_Mayo_TN_CC_747\" : 731 , \"s_Mayo_TN_CC_260\" : 196 , \"s_Mayo_TN_CC_748\" : 732 , \"s_Mayo_TN_CC_749\" : 733 , \"s_Mayo_TN_CC_262\" : 198 , \"s_Mayo_TN_CC_261\" : 197 , \"s_Mayo_TN_CC_264\" : 200 , \"s_Mayo_TN_CC_263\" : 199 , \"s_Mayo_TN_CC_266\" : 202 , \"s_Mayo_TN_CC_265\" : 201 , \"s_Mayo_TN_CC_267\" : 203 , \"s_Mayo_TN_CC_268\" : 204 , \"s_Mayo_TN_CC_269\" : 205 , \"s_Mayo_TN_CC_543\" : 507 , \"s_Mayo_TN_CC_542\" : 506 , \"s_Mayo_TN_CC_545\" : 509 , \"s_Mayo_TN_CC_544\" : 508 , \"s_Mayo_TN_CC_547\" : 511 , \"s_Mayo_TN_CC_546\" : 510 , \"s_Mayo_TN_CC_549\" : 513 , \"s_Mayo_TN_CC_548\" : 512 , \"s_Mayo_TN_CC_738\" : 721 , \"s_Mayo_TN_CC_737\" : 720 , \"s_Mayo_TN_CC_739\" : 722 , \"s_Mayo_TN_CC_734\" : 717 , \"s_Mayo_TN_CC_733\" : 716 , \"s_Mayo_TN_CC_736\" : 719 , \"s_Mayo_TN_CC_735\" : 718 , \"s_Mayo_TN_CC_730\" : 713 , \"s_Mayo_TN_CC_732\" : 715 , \"s_Mayo_TN_CC_731\" : 714 , \"s_Mayo_TN_CC_729\" : 711 , \"s_Mayo_TN_CC_728\" : 710 , \"s_Mayo_TN_CC_727\" : 709 , \"s_Mayo_TN_CC_726\" : 708 , \"s_Mayo_TN_CC_725\" : 707 , \"s_Mayo_TN_CC_724\" : 706 , \"s_Mayo_TN_CC_723\" : 705 , \"s_Mayo_TN_CC_722\" : 704 , \"s_Mayo_TN_CC_721\" : 703 , \"s_Mayo_TN_CC_720\" : 702 , \"s_Mayo_TN_CC_716\" : 697 , \"s_Mayo_TN_CC_715\" : 696 , \"s_Mayo_TN_CC_718\" : 699 , \"s_Mayo_TN_CC_717\" : 698 , \"s_Mayo_TN_CC_719\" : 700 , \"s_Mayo_TN_CC_710\" : 691 , \"s_Mayo_TN_CC_712\" : 693 , \"s_Mayo_TN_CC_711\" : 692 , \"s_Mayo_TN_CC_714\" : 695 , \"s_Mayo_TN_CC_713\" : 694 , \"s_Mayo_TN_CC_707\" : 687 , \"s_Mayo_TN_CC_706\" : 686 , \"s_Mayo_TN_CC_705\" : 685 , \"s_Mayo_TN_CC_704\" : 684 , \"s_Mayo_TN_CC_709\" : 689 , \"s_Mayo_TN_CC_708\" : 688 , \"s_Mayo_TN_CC_703\" : 683 , \"s_Mayo_TN_CC_702\" : 682 , \"s_Mayo_TN_CC_701\" : 681 , \"s_Mayo_TN_CC_700\" : 680 , \"s_Mayo_TN_CC_588\" : 556 , \"s_Mayo_TN_CC_589\" : 557 , \"s_Mayo_TN_CC_586\" : 554 , \"s_Mayo_TN_CC_587\" : 555 , \"s_Mayo_TN_CC_585\" : 553 , \"s_Mayo_TN_CC_584\" : 552 , \"s_Mayo_TN_CC_583\" : 551 , \"s_Mayo_TN_CC_582\" : 550 , \"s_Mayo_TN_CC_581\" : 549 , \"s_Mayo_TN_CC_580\" : 548 , \"s_Mayo_TN_CC_597\" : 566 , \"s_Mayo_TN_CC_598\" : 567 , \"s_Mayo_TN_CC_599\" : 568 , \"s_Mayo_TN_CC_594\" : 563 , \"s_Mayo_TN_CC_593\" : 562 , \"s_Mayo_TN_CC_596\" : 565 , \"s_Mayo_TN_CC_595\" : 564 , \"s_Mayo_TN_CC_590\" : 559 , \"s_Mayo_TN_CC_592\" : 561 , \"s_Mayo_TN_CC_591\" : 560 , \"s_Mayo_TN_CC_203\" : 133 , \"s_Mayo_TN_CC_204\" : 134 , \"s_Mayo_TN_CC_201\" : 131 , \"s_Mayo_TN_CC_202\" : 132 , \"s_Mayo_TN_CC_207\" : 137 , \"s_Mayo_TN_CC_208\" : 138 , \"s_Mayo_TN_CC_205\" : 135 , \"s_Mayo_TN_CC_206\" : 136 , \"s_Mayo_TN_CC_209\" : 139 , \"s_Mayo_TN_CC_200\" : 130 , \"s_Mayo_TN_CC_212\" : 143 , \"s_Mayo_TN_CC_213\" : 144 , \"s_Mayo_TN_CC_214\" : 145 , \"s_Mayo_TN_CC_215\" : 146 , \"s_Mayo_TN_CC_216\" : 147 , \"s_Mayo_TN_CC_217\" : 148 , \"s_Mayo_TN_CC_218\" : 149 , \"s_Mayo_TN_CC_219\" : 150 , \"s_Mayo_TN_CC_211\" : 142 , \"s_Mayo_TN_CC_210\" : 141 , \"s_Mayo_TN_CC_37\" : 316 , \"s_Mayo_TN_CC_677\" : 654 , \"s_Mayo_TN_CC_36\" : 305 , \"s_Mayo_TN_CC_676\" : 653 , \"s_Mayo_TN_CC_35\" : 294 , \"s_Mayo_TN_CC_675\" : 652 , \"s_Mayo_TN_CC_34\" : 283 , \"s_Mayo_TN_CC_674\" : 651 , \"s_Mayo_TN_CC_33\" : 272 , \"s_Mayo_TN_CC_32\" : 261 , \"s_Mayo_TN_CC_31\" : 250 , \"s_Mayo_TN_CC_679\" : 656 , \"s_Mayo_TN_CC_30\" : 239 , \"s_Mayo_TN_CC_678\" : 655 , \"s_Mayo_TN_CC_159\" : 84 , \"s_Mayo_TN_CC_350\" : 295 , \"s_Mayo_TN_CC_157\" : 82 , \"s_Mayo_TN_CC_158\" : 83 , \"s_Mayo_TN_CC_353\" : 298 , \"s_Mayo_TN_CC_354\" : 299 , \"s_Mayo_TN_CC_39\" : 338 , \"s_Mayo_TN_CC_351\" : 296 , \"s_Mayo_TN_CC_38\" : 327 , \"s_Mayo_TN_CC_352\" : 297 , \"s_Mayo_TN_CC_358\" : 303 , \"s_Mayo_TN_CC_152\" : 77 , \"s_Mayo_TN_CC_357\" : 302 , \"s_Mayo_TN_CC_151\" : 76 , \"s_Mayo_TN_CC_356\" : 301 , \"s_Mayo_TN_CC_150\" : 75 , \"s_Mayo_TN_CC_355\" : 300 , \"s_Mayo_TN_CC_156\" : 81 , \"s_Mayo_TN_CC_155\" : 80 , \"s_Mayo_TN_CC_154\" : 79 , \"s_Mayo_TN_CC_359\" : 304 , \"s_Mayo_TN_CC_153\" : 78 , \"s_Mayo_TN_CC_40\" : 349 , \"s_Mayo_TN_CC_672\" : 649 , \"s_Mayo_TN_CC_673\" : 650 , \"s_Mayo_TN_CC_670\" : 647 , \"s_Mayo_TN_CC_671\" : 648 , \"s_Mayo_TN_CC_24\" : 173 , \"s_Mayo_TN_CC_664\" : 640 , \"s_Mayo_TN_CC_23\" : 162 , \"s_Mayo_TN_CC_663\" : 639 , \"s_Mayo_TN_CC_26\" : 195 , \"s_Mayo_TN_CC_666\" : 642 , \"s_Mayo_TN_CC_25\" : 184 , \"s_Mayo_TN_CC_665\" : 641 , \"s_Mayo_TN_CC_20\" : 129 , \"s_Mayo_TN_CC_668\" : 644 , \"s_Mayo_TN_CC_667\" : 643 , \"s_Mayo_TN_CC_22\" : 151 , \"s_Mayo_TN_CC_21\" : 140 , \"s_Mayo_TN_CC_669\" : 645 , \"s_Mayo_TN_CC_146\" : 70 , \"s_Mayo_TN_CC_147\" : 71 , \"s_Mayo_TN_CC_148\" : 72 , \"s_Mayo_TN_CC_149\" : 73 , \"s_Mayo_TN_CC_340\" : 284 , \"s_Mayo_TN_CC_28\" : 217 , \"s_Mayo_TN_CC_341\" : 285 , \"s_Mayo_TN_CC_27\" : 206 , \"s_Mayo_TN_CC_342\" : 286 , \"s_Mayo_TN_CC_343\" : 287 , \"s_Mayo_TN_CC_29\" : 228 , \"s_Mayo_TN_CC_345\" : 289 , \"s_Mayo_TN_CC_344\" : 288 , \"s_Mayo_TN_CC_347\" : 291 , \"s_Mayo_TN_CC_141\" : 65 , \"s_Mayo_TN_CC_346\" : 290 , \"s_Mayo_TN_CC_140\" : 64 , \"s_Mayo_TN_CC_349\" : 293 , \"s_Mayo_TN_CC_143\" : 67 , \"s_Mayo_TN_CC_348\" : 292 , \"s_Mayo_TN_CC_142\" : 66 , \"s_Mayo_TN_CC_145\" : 69 , \"s_Mayo_TN_CC_144\" : 68 , \"s_Mayo_TN_CC_660\" : 636 , \"s_Mayo_TN_CC_661\" : 637 , \"s_Mayo_TN_CC_662\" : 638 , \"s_Mayo_TN_CC_55\" : 514 , \"s_Mayo_TN_CC_809\" : 799 , \"s_Mayo_TN_CC_54\" : 503 , \"s_Mayo_TN_CC_808\" : 798 , \"s_Mayo_TN_CC_53\" : 492 , \"s_Mayo_TN_CC_807\" : 797 , \"s_Mayo_TN_CC_52\" : 481 , \"s_Mayo_TN_CC_806\" : 796 , \"s_Mayo_TN_CC_59\" : 558 , \"s_Mayo_TN_CC_699\" : 678 , \"s_Mayo_TN_CC_805\" : 795 , \"s_Mayo_TN_CC_58\" : 547 , \"s_Mayo_TN_CC_698\" : 677 , \"s_Mayo_TN_CC_804\" : 794 , \"s_Mayo_TN_CC_57\" : 536 , \"s_Mayo_TN_CC_697\" : 676 , \"s_Mayo_TN_CC_803\" : 793 , \"s_Mayo_TN_CC_56\" : 525 , \"s_Mayo_TN_CC_696\" : 675 , \"s_Mayo_TN_CC_802\" : 792 , \"s_Mayo_TN_CC_375\" : 322 , \"s_Mayo_TN_CC_801\" : 791 , \"s_Mayo_TN_CC_376\" : 323 , \"s_Mayo_TN_CC_800\" : 790 , \"s_Mayo_TN_CC_373\" : 320 , \"s_Mayo_TN_CC_374\" : 321 , \"s_Mayo_TN_CC_371\" : 318 , \"s_Mayo_TN_CC_372\" : 319 , \"s_Mayo_TN_CC_179\" : 106 , \"s_Mayo_TN_CC_370\" : 317 , \"s_Mayo_TN_CC_178\" : 105 , \"s_Mayo_TN_CC_177\" : 104 , \"s_Mayo_TN_CC_176\" : 103 , \"s_Mayo_TN_CC_175\" : 102 , \"s_Mayo_TN_CC_174\" : 101 , \"s_Mayo_TN_CC_379\" : 326 , \"s_Mayo_TN_CC_173\" : 100 , \"s_Mayo_TN_CC_418\" : 369 , \"s_Mayo_TN_CC_378\" : 325 , \"s_Mayo_TN_CC_172\" : 99 , \"s_Mayo_TN_CC_419\" : 370 , \"s_Mayo_TN_CC_377\" : 324 , \"s_Mayo_TN_CC_171\" : 98 , \"s_Mayo_TN_CC_416\" : 367 , \"s_Mayo_TN_CC_170\" : 97 , \"s_Mayo_TN_CC_694\" : 673 , \"s_Mayo_TN_CC_417\" : 368 , \"s_Mayo_TN_CC_695\" : 674 , \"s_Mayo_TN_CC_414\" : 365 , \"s_Mayo_TN_CC_692\" : 671 , \"s_Mayo_TN_CC_415\" : 366 , \"s_Mayo_TN_CC_693\" : 672 , \"s_Mayo_TN_CC_412\" : 363 , \"s_Mayo_TN_CC_61\" : 580 , \"s_Mayo_TN_CC_690\" : 669 , \"s_Mayo_TN_CC_413\" : 364 , \"s_Mayo_TN_CC_62\" : 591 , \"s_Mayo_TN_CC_691\" : 670 , \"s_Mayo_TN_CC_410\" : 361 , \"s_Mayo_TN_CC_411\" : 362 , \"s_Mayo_TN_CC_60\" : 569 , \"s_Mayo_TN_CC_819\" : 810 , \"s_Mayo_TN_CC_42\" : 371 , \"s_Mayo_TN_CC_818\" : 809 , \"s_Mayo_TN_CC_41\" : 360 , \"s_Mayo_TN_CC_689\" : 667 , \"s_Mayo_TN_CC_44\" : 393 , \"s_Mayo_TN_CC_43\" : 382 , \"s_Mayo_TN_CC_815\" : 806 , \"s_Mayo_TN_CC_46\" : 415 , \"s_Mayo_TN_CC_686\" : 664 , \"s_Mayo_TN_CC_814\" : 805 , \"s_Mayo_TN_CC_45\" : 404 , \"s_Mayo_TN_CC_685\" : 663 , \"s_Mayo_TN_CC_817\" : 808 , \"s_Mayo_TN_CC_48\" : 437 , \"s_Mayo_TN_CC_688\" : 666 , \"s_Mayo_TN_CC_816\" : 807 , \"s_Mayo_TN_CC_47\" : 426 , \"s_Mayo_TN_CC_687\" : 665 , \"s_Mayo_TN_CC_811\" : 802 , \"s_Mayo_TN_CC_362\" : 308 , \"s_Mayo_TN_CC_810\" : 801 , \"s_Mayo_TN_CC_363\" : 309 , \"s_Mayo_TN_CC_49\" : 448 , \"s_Mayo_TN_CC_813\" : 804 , \"s_Mayo_TN_CC_364\" : 310 , \"s_Mayo_TN_CC_812\" : 803 , \"s_Mayo_TN_CC_365\" : 311 , \"s_Mayo_TN_CC_168\" : 94 , \"s_Mayo_TN_CC_169\" : 95 , \"s_Mayo_TN_CC_360\" : 306 , \"s_Mayo_TN_CC_361\" : 307 , \"s_Mayo_TN_CC_165\" : 91 , \"s_Mayo_TN_CC_164\" : 90 , \"s_Mayo_TN_CC_167\" : 93 , \"s_Mayo_TN_CC_166\" : 92 , \"s_Mayo_TN_CC_407\" : 357 , \"s_Mayo_TN_CC_367\" : 313 , \"s_Mayo_TN_CC_161\" : 87 , \"s_Mayo_TN_CC_408\" : 358 , \"s_Mayo_TN_CC_366\" : 312 , \"s_Mayo_TN_CC_160\" : 86 , \"s_Mayo_TN_CC_409\" : 359 , \"s_Mayo_TN_CC_369\" : 315 , \"s_Mayo_TN_CC_163\" : 89 , \"s_Mayo_TN_CC_368\" : 314 , \"s_Mayo_TN_CC_162\" : 88 , \"s_Mayo_TN_CC_403\" : 353 , \"s_Mayo_TN_CC_681\" : 659 , \"s_Mayo_TN_CC_404\" : 354 , \"s_Mayo_TN_CC_682\" : 660 , \"s_Mayo_TN_CC_405\" : 355 , \"s_Mayo_TN_CC_683\" : 661 , \"s_Mayo_TN_CC_406\" : 356 , \"s_Mayo_TN_CC_684\" : 662 , \"s_Mayo_TN_CC_400\" : 350 , \"s_Mayo_TN_CC_401\" : 351 , \"s_Mayo_TN_CC_50\" : 459 , \"s_Mayo_TN_CC_402\" : 352 , \"s_Mayo_TN_CC_51\" : 470 , \"s_Mayo_TN_CC_680\" : 658 , \"s_Mayo_TN_CC_394\" : 343 , \"s_Mayo_TN_CC_116\" : 37 , \"s_Mayo_TN_CC_820\" : 812 , \"s_Mayo_TN_CC_393\" : 342 , \"s_Mayo_TN_CC_115\" : 36 , \"s_Mayo_TN_CC_392\" : 341 , \"s_Mayo_TN_CC_114\" : 35 , \"s_Mayo_TN_CC_638\" : 611 , \"s_Mayo_TN_CC_391\" : 340 , \"s_Mayo_TN_CC_113\" : 34 , \"s_Mayo_TN_CC_639\" : 612 , \"s_Mayo_TN_CC_823\" : 815 , \"s_Mayo_TN_CC_398\" : 347 , \"s_Mayo_TN_CC_824\" : 816 , \"s_Mayo_TN_CC_397\" : 346 , \"s_Mayo_TN_CC_119\" : 40 , \"s_Mayo_TN_CC_821\" : 813 , \"s_Mayo_TN_CC_396\" : 345 , \"s_Mayo_TN_CC_118\" : 39 , \"s_Mayo_TN_CC_822\" : 814 , \"s_Mayo_TN_CC_395\" : 344 , \"s_Mayo_TN_CC_117\" : 38 , \"s_Mayo_TN_CC_827\" : 819 , \"s_Mayo_TN_CC_632\" : 605 , \"s_Mayo_TN_CC_828\" : 820 , \"s_Mayo_TN_CC_633\" : 606 , \"s_Mayo_TN_CC_825\" : 817 , \"s_Mayo_TN_CC_630\" : 603 , \"s_Mayo_TN_CC_826\" : 818 , \"s_Mayo_TN_CC_631\" : 604 , \"s_Mayo_TN_CC_430\" : 383 , \"s_Mayo_TN_CC_390\" : 339 , \"s_Mayo_TN_CC_636\" : 609 , \"s_Mayo_TN_CC_431\" : 384 , \"s_Mayo_TN_CC_637\" : 610 , \"s_Mayo_TN_CC_829\" : 821 , \"s_Mayo_TN_CC_634\" : 607 , \"s_Mayo_TN_CC_635\" : 608 , \"s_Mayo_TN_CC_435\" : 388 , \"s_Mayo_TN_CC_434\" : 387 , \"s_Mayo_TN_CC_433\" : 386 , \"s_Mayo_TN_CC_432\" : 385 , \"s_Mayo_TN_CC_439\" : 392 , \"s_Mayo_TN_CC_438\" : 391 , \"s_Mayo_TN_CC_437\" : 390 , \"s_Mayo_TN_CC_436\" : 389 , \"s_Mayo_TN_CC_399\" : 348 , \"s_Mayo_TN_CC_111\" : 32 , \"s_Mayo_TN_CC_112\" : 33 , \"s_Mayo_TN_CC_110\" : 31 , \"s_Mayo_TN_CC_381\" : 329 , \"s_Mayo_TN_CC_103\" : 23 , \"s_Mayo_TN_CC_627\" : 599 , \"s_Mayo_TN_CC_380\" : 328 , \"s_Mayo_TN_CC_102\" : 22 , \"s_Mayo_TN_CC_628\" : 600 , \"s_Mayo_TN_CC_830\" : 823 , \"s_Mayo_TN_CC_383\" : 331 , \"s_Mayo_TN_CC_105\" : 25 , \"s_Mayo_TN_CC_629\" : 601 , \"s_Mayo_TN_CC_831\" : 824 , \"s_Mayo_TN_CC_382\" : 330 , \"s_Mayo_TN_CC_104\" : 24 , \"s_Mayo_TN_CC_832\" : 825 , \"s_Mayo_TN_CC_385\" : 333 , \"s_Mayo_TN_CC_107\" : 27 , \"s_Mayo_TN_CC_833\" : 826 , \"s_Mayo_TN_CC_384\" : 332 , \"s_Mayo_TN_CC_106\" : 26 , \"s_Mayo_TN_CC_834\" : 827 , \"s_Mayo_TN_CC_387\" : 335 , \"s_Mayo_TN_CC_109\" : 29 , \"s_Mayo_TN_CC_835\" : 828 , \"s_Mayo_TN_CC_386\" : 334 , \"s_Mayo_TN_CC_108\" : 28 , \"s_Mayo_TN_CC_836\" : 829 , \"s_Mayo_TN_CC_837\" : 830 , \"s_Mayo_TN_CC_620\" : 592 , \"s_Mayo_TN_CC_838\" : 831 , \"s_Mayo_TN_CC_621\" : 593 , \"s_Mayo_TN_CC_839\" : 832 , \"s_Mayo_TN_CC_622\" : 594 , \"s_Mayo_TN_CC_623\" : 595 , \"s_Mayo_TN_CC_624\" : 596 , \"s_Mayo_TN_CC_625\" : 597 , \"s_Mayo_TN_CC_420\" : 372 , \"s_Mayo_TN_CC_626\" : 598 , \"s_Mayo_TN_CC_422\" : 374 , \"s_Mayo_TN_CC_421\" : 373 , \"s_Mayo_TN_CC_424\" : 376 , \"s_Mayo_TN_CC_423\" : 375 , \"s_Mayo_TN_CC_426\" : 378 , \"s_Mayo_TN_CC_425\" : 377 , \"s_Mayo_TN_CC_428\" : 380 , \"s_Mayo_TN_CC_427\" : 379 , \"s_Mayo_TN_CC_388\" : 336 , \"s_Mayo_TN_CC_429\" : 381 , \"s_Mayo_TN_CC_389\" : 337 , \"s_Mayo_TN_CC_100\" : 20 , \"s_Mayo_TN_CC_101\" : 21 , \"s_Mayo_TN_CC_845\" : 839 , \"s_Mayo_TN_CC_18\" : 107 , \"s_Mayo_TN_CC_846\" : 840 , \"s_Mayo_TN_CC_19\" : 118 , \"s_Mayo_TN_CC_843\" : 837 , \"s_Mayo_TN_CC_16\" : 85 , \"s_Mayo_TN_CC_844\" : 838 , \"s_Mayo_TN_CC_17\" : 96 , \"s_Mayo_TN_CC_139\" : 62 , \"s_Mayo_TN_CC_841\" : 835 , \"s_Mayo_TN_CC_138\" : 61 , \"s_Mayo_TN_CC_842\" : 836 , \"s_Mayo_TN_CC_137\" : 60 , \"s_Mayo_TN_CC_136\" : 59 , \"s_Mayo_TN_CC_840\" : 834 , \"s_Mayo_TN_CC_135\" : 58 , \"s_Mayo_TN_CC_10\" : 19 , \"s_Mayo_TN_CC_452\" : 407 , \"s_Mayo_TN_CC_658\" : 633 , \"s_Mayo_TN_CC_11\" : 30 , \"s_Mayo_TN_CC_453\" : 408 , \"s_Mayo_TN_CC_659\" : 634 , \"s_Mayo_TN_CC_450\" : 405 , \"s_Mayo_TN_CC_656\" : 631 , \"s_Mayo_TN_CC_451\" : 406 , \"s_Mayo_TN_CC_657\" : 632 , \"s_Mayo_TN_CC_849\" : 843 , \"s_Mayo_TN_CC_14\" : 63 , \"s_Mayo_TN_CC_654\" : 629 , \"s_Mayo_TN_CC_15\" : 74 , \"s_Mayo_TN_CC_655\" : 630 , \"s_Mayo_TN_CC_847\" : 841 , \"s_Mayo_TN_CC_12\" : 41 , \"s_Mayo_TN_CC_652\" : 627 , \"s_Mayo_TN_CC_848\" : 842 , \"s_Mayo_TN_CC_13\" : 52 , \"s_Mayo_TN_CC_653\" : 628 , \"s_Mayo_TN_CC_651\" : 626 , \"s_Mayo_TN_CC_650\" : 625 , \"s_Mayo_TN_CC_459\" : 414 , \"s_Mayo_TN_CC_458\" : 413 , \"s_Mayo_TN_CC_457\" : 412 , \"s_Mayo_TN_CC_456\" : 411 , \"s_Mayo_TN_CC_455\" : 410 , \"s_Mayo_TN_CC_454\" : 409 , \"s_Mayo_TN_CC_133\" : 56 , \"s_Mayo_TN_CC_134\" : 57 , \"s_Mayo_TN_CC_131\" : 54 , \"s_Mayo_TN_CC_132\" : 55 , \"s_Mayo_TN_CC_130\" : 53 , \"s_Mayo_TN_CC_854\" : 849 , \"s_Mayo_TN_CC_05\" : 14 , \"s_Mayo_TN_CC_129\" : 51 , \"s_Mayo_TN_CC_855\" : 850 , \"s_Mayo_TN_CC_06\" : 15 , \"s_Mayo_TN_CC_128\" : 50 , \"s_Mayo_TN_CC_856\" : 851 , \"s_Mayo_TN_CC_07\" : 16 , \"s_Mayo_TN_CC_857\" : 852 , \"s_Mayo_TN_CC_08\" : 17 , \"s_Mayo_TN_CC_850\" : 845 , \"s_Mayo_TN_CC_09\" : 18 , \"s_Mayo_TN_CC_125\" : 47 , \"s_Mayo_TN_CC_649\" : 623 , \"s_Mayo_TN_CC_851\" : 846 , \"s_Mayo_TN_CC_124\" : 46 , \"s_Mayo_TN_CC_852\" : 847 , \"s_Mayo_TN_CC_127\" : 49 , \"s_Mayo_TN_CC_853\" : 848 , \"s_Mayo_TN_CC_126\" : 48 , \"s_Mayo_TN_CC_645\" : 619 , \"s_Mayo_TN_CC_440\" : 394 , \"s_Mayo_TN_CC_646\" : 620 , \"s_Mayo_TN_CC_441\" : 395 , \"s_Mayo_TN_CC_647\" : 621 , \"s_Mayo_TN_CC_442\" : 396 , \"s_Mayo_TN_CC_648\" : 622 , \"s_Mayo_TN_CC_858\" : 853 , \"s_Mayo_TN_CC_01\" : 10 , \"s_Mayo_TN_CC_641\" : 615 , \"s_Mayo_TN_CC_859\" : 854 , \"s_Mayo_TN_CC_02\" : 11 , \"s_Mayo_TN_CC_642\" : 616 , \"s_Mayo_TN_CC_03\" : 12 , \"s_Mayo_TN_CC_643\" : 617 , \"s_Mayo_TN_CC_04\" : 13 , \"s_Mayo_TN_CC_644\" : 618 , \"s_Mayo_TN_CC_448\" : 402 , \"s_Mayo_TN_CC_447\" : 401 , \"s_Mayo_TN_CC_640\" : 614 , \"s_Mayo_TN_CC_449\" : 403 , \"s_Mayo_TN_CC_444\" : 398 , \"s_Mayo_TN_CC_443\" : 397 , \"s_Mayo_TN_CC_446\" : 400 , \"s_Mayo_TN_CC_445\" : 399 , \"s_Mayo_TN_CC_120\" : 42 , \"s_Mayo_TN_CC_121\" : 43 , \"s_Mayo_TN_CC_122\" : 44 , \"s_Mayo_TN_CC_123\" : 45 , \"s_Mayo_TN_CC_860\" : 856 , \"s_Mayo_TN_CC_869\" : 865 , \"s_Mayo_TN_CC_862\" : 858 , \"s_Mayo_TN_CC_861\" : 857 , \"s_Mayo_TN_CC_864\" : 860 , \"s_Mayo_TN_CC_863\" : 859 , \"s_Mayo_TN_CC_866\" : 862 , \"s_Mayo_TN_CC_865\" : 861 , \"s_Mayo_TN_CC_868\" : 864 , \"s_Mayo_TN_CC_867\" : 863 , \"s_Mayo_TN_CC_870\" : 867 , \"s_Mayo_TN_CC_871\" : 868 , \"s_Mayo_TN_CC_875\" : 872 , \"s_Mayo_TN_CC_874\" : 871 , \"s_Mayo_TN_CC_873\" : 870 , \"s_Mayo_TN_CC_872\" : 869 , \"s_Mayo_TN_CC_879\" : 876 , \"s_Mayo_TN_CC_878\" : 875 , \"s_Mayo_TN_CC_877\" : 874 , \"s_Mayo_TN_CC_876\" : 873 , \"s_Mayo_TN_CC_880\" : 878 , \"s_Mayo_TN_CC_881\" : 879 , \"s_Mayo_TN_CC_882\" : 880 , \"s_Mayo_TN_CC_613\" : 584 , \"s_Mayo_TN_CC_612\" : 583 , \"s_Mayo_TN_CC_615\" : 586 , \"s_Mayo_TN_CC_614\" : 585 , \"s_Mayo_TN_CC_611\" : 582 , \"s_Mayo_TN_CC_610\" : 581 , \"s_Mayo_TN_CC_888\" : 886 , \"s_Mayo_TN_CC_887\" : 885 , \"s_Mayo_TN_CC_884\" : 882 , \"s_Mayo_TN_CC_617\" : 588 , \"s_Mayo_TN_CC_883\" : 881 , \"s_Mayo_TN_CC_616\" : 587 , \"s_Mayo_TN_CC_886\" : 884 , \"s_Mayo_TN_CC_619\" : 590 , \"s_Mayo_TN_CC_885\" : 883 , \"s_Mayo_TN_CC_618\" : 589 , \"s_Mayo_TN_CC_604\" : 574 , \"s_Mayo_TN_CC_603\" : 573 , \"s_Mayo_TN_CC_602\" : 572 , \"s_Mayo_TN_CC_601\" : 571 , \"s_Mayo_TN_CC_600\" : 570 , \"s_Mayo_TN_CC_609\" : 579 , \"s_Mayo_TN_CC_608\" : 578 , \"s_Mayo_TN_CC_607\" : 577 , \"s_Mayo_TN_CC_606\" : 576 , \"s_Mayo_TN_CC_605\" : 575 , \"s_Mayo_TN_CC_82\" : 811 , \"s_Mayo_TN_CC_81\" : 800 , \"s_Mayo_TN_CC_84\" : 833 , \"s_Mayo_TN_CC_83\" : 822 , \"s_Mayo_TN_CC_190\" : 119 , \"s_Mayo_TN_CC_80\" : 789 , \"s_Mayo_TN_CC_191\" : 120 , \"s_Mayo_TN_CC_192\" : 121 , \"s_Mayo_TN_CC_193\" : 122 , \"s_Mayo_TN_CC_194\" : 123 , \"s_Mayo_TN_CC_195\" : 124 , \"s_Mayo_TN_CC_196\" : 125 , \"s_Mayo_TN_CC_197\" : 126 , \"s_Mayo_TN_CC_198\" : 127 , \"s_Mayo_TN_CC_199\" : 128 , \"s_Mayo_TN_CC_78\" : 767 , \"s_Mayo_TN_CC_79\" : 778 , \"s_Mayo_TN_CC_74\" : 723 , \"s_Mayo_TN_CC_75\" : 734 , \"s_Mayo_TN_CC_76\" : 745 , \"s_Mayo_TN_CC_77\" : 756 , \"s_Mayo_TN_CC_73\" : 712 , \"s_Mayo_TN_CC_72\" : 701 , \"s_Mayo_TN_CC_71\" : 690 , \"s_Mayo_TN_CC_70\" : 679 , \"s_Mayo_TN_CC_180\" : 108 , \"s_Mayo_TN_CC_181\" : 109 , \"s_Mayo_TN_CC_184\" : 112 , \"s_Mayo_TN_CC_185\" : 113 , \"s_Mayo_TN_CC_182\" : 110 , \"s_Mayo_TN_CC_183\" : 111 , \"s_Mayo_TN_CC_188\" : 116 , \"s_Mayo_TN_CC_189\" : 117 , \"s_Mayo_TN_CC_186\" : 114 , \"s_Mayo_TN_CC_187\" : 115 , \"s_Mayo_TN_CC_69\" : 668 , \"s_Mayo_TN_CC_67\" : 646 , \"s_Mayo_TN_CC_68\" : 657 , \"s_Mayo_TN_CC_65\" : 624 , \"s_Mayo_TN_CC_66\" : 635 , \"s_Mayo_TN_CC_63\" : 602 , \"s_Mayo_TN_CC_64\" : 613 , \"s_Mayo_TN_CC_96\" : 894 , \"s_Mayo_TN_CC_97\" : 895 , \"s_Mayo_TN_CC_98\" : 896 , \"s_Mayo_TN_CC_99\" : 897 , \"s_Mayo_TN_CC_91\" : 889 , \"s_Mayo_TN_CC_90\" : 888 , \"s_Mayo_TN_CC_95\" : 893 , \"s_Mayo_TN_CC_94\" : 892 , \"s_Mayo_TN_CC_93\" : 891 , \"s_Mayo_TN_CC_92\" : 890 , \"s_Mayo_TN_CC_87\" : 866 , \"s_Mayo_TN_CC_88\" : 877 , \"s_Mayo_TN_CC_85\" : 844 , \"s_Mayo_TN_CC_86\" : 855 , \"s_Mayo_TN_CC_89\" : 887 , \"s_Mayo_TN_CC_469\" : 425 , \"s_Mayo_TN_CC_467\" : 423 , \"s_Mayo_TN_CC_468\" : 424 , \"s_Mayo_TN_CC_465\" : 421 , \"s_Mayo_TN_CC_466\" : 422 , \"s_Mayo_TN_CC_464\" : 420 , \"s_Mayo_TN_CC_463\" : 419 , \"s_Mayo_TN_CC_462\" : 418 , \"s_Mayo_TN_CC_461\" : 417 , \"s_Mayo_TN_CC_460\" : 416 , \"s_Mayo_TN_CC_476\" : 433 , \"s_Mayo_TN_CC_477\" : 434 , \"s_Mayo_TN_CC_478\" : 435 , \"s_Mayo_TN_CC_479\" : 436 , \"s_Mayo_TN_CC_473\" : 430 , \"s_Mayo_TN_CC_472\" : 429 , \"s_Mayo_TN_CC_475\" : 432 , \"s_Mayo_TN_CC_474\" : 431 , \"s_Mayo_TN_CC_471\" : 428 , \"s_Mayo_TN_CC_470\" : 427 , \"s_Mayo_TN_CC_489\" : 447 , \"s_Mayo_TN_CC_487\" : 445 , \"s_Mayo_TN_CC_488\" : 446 , \"s_Mayo_TN_CC_482\" : 440 , \"s_Mayo_TN_CC_481\" : 439 , \"s_Mayo_TN_CC_480\" : 438 , \"s_Mayo_TN_CC_486\" : 444 , \"s_Mayo_TN_CC_485\" : 443 , \"s_Mayo_TN_CC_484\" : 442 , \"s_Mayo_TN_CC_483\" : 441 , \"s_Mayo_TN_CC_498\" : 457 , \"s_Mayo_TN_CC_499\" : 458 , \"s_Mayo_TN_CC_491\" : 450 , \"s_Mayo_TN_CC_490\" : 449 , \"s_Mayo_TN_CC_493\" : 452 , \"s_Mayo_TN_CC_492\" : 451 , \"s_Mayo_TN_CC_495\" : 454 , \"s_Mayo_TN_CC_494\" : 453 , \"s_Mayo_TN_CC_497\" : 456 , \"s_Mayo_TN_CC_496\" : 455 , \"s_Mayo_TN_CC_308\" : 248 , \"s_Mayo_TN_CC_309\" : 249 , \"s_Mayo_TN_CC_306\" : 246 , \"s_Mayo_TN_CC_307\" : 247 , \"s_Mayo_TN_CC_304\" : 244 , \"s_Mayo_TN_CC_305\" : 245 , \"s_Mayo_TN_CC_302\" : 242 , \"s_Mayo_TN_CC_303\" : 243 , \"s_Mayo_TN_CC_300\" : 240 , \"s_Mayo_TN_CC_301\" : 241 , \"s_Mayo_TN_CC_319\" : 260 , \"s_Mayo_TN_CC_315\" : 256 , \"s_Mayo_TN_CC_316\" : 257 , \"s_Mayo_TN_CC_317\" : 258 , \"s_Mayo_TN_CC_318\" : 259 , \"s_Mayo_TN_CC_311\" : 252 , \"s_Mayo_TN_CC_312\" : 253 , \"s_Mayo_TN_CC_313\" : 254 , \"s_Mayo_TN_CC_314\" : 255 , \"s_Mayo_TN_CC_310\" : 251 , \"s_Mayo_TN_CC_324\" : 266 , \"s_Mayo_TN_CC_325\" : 267 , \"s_Mayo_TN_CC_322\" : 264 , \"s_Mayo_TN_CC_323\" : 265 , \"s_Mayo_TN_CC_328\" : 270 , \"s_Mayo_TN_CC_329\" : 271 , \"s_Mayo_TN_CC_326\" : 268 , \"s_Mayo_TN_CC_327\" : 269 , \"s_Mayo_TN_CC_321\" : 263 , \"s_Mayo_TN_CC_320\" : 262 , \"s_Mayo_TN_CC_333\" : 276 , \"s_Mayo_TN_CC_334\" : 277 , \"s_Mayo_TN_CC_335\" : 278 , \"s_Mayo_TN_CC_336\" : 279 , \"s_Mayo_TN_CC_337\" : 280 , \"s_Mayo_TN_CC_338\" : 281 , \"s_Mayo_TN_CC_339\" : 282 , \"s_Mayo_TN_CC_330\" : 273 , \"s_Mayo_TN_CC_332\" : 275 , \"s_Mayo_TN_CC_331\" : 274} , \"FORMAT\" : { \"min\" : { \"PL\" : 1 , \"AD\" : 1 , \"GT\" : 1 , \"GQ\" : 1} , \"max\" : { \"PL\" : 1 , \"AD\" : 1 , \"GT\" : 1 , \"GQ\" : 1}} , \"owner\" : \"test\" , \"key\" : \"w07fec0b293246f32f25a151dde4c1dbe92da77a8\" , \"timestamp\" : \"2014-01-15T15:56+0000\" , \"alias\" : \"alias\"}";
DBObject before = (DBObject) JSON.parse(resultBeforeSave);
DBObject after = (DBObject) JSON.parse(resultAfterSave);
System.out.println("Checking FORMAT");
assertTrue(before.keySet().contains("FORMAT"));
assertTrue(after.keySet().contains("FORMAT"));
System.out.println(before.get("FORMAT").toString());
System.out.println(after.get("FORMAT").toString());
assertEquals(before.get("FORMAT"), after.get("FORMAT"));
System.out.println("Checking INFO");
assertTrue(before.keySet().contains("HEADER"));
assertTrue(after.keySet().contains("HEADER"));
assertEquals(before.get("HEADER"), after.get("HEADER"));
System.out.println("Checking SAMPLES");
assertTrue(before.keySet().contains("SAMPLES"));
assertTrue(after.keySet().contains("SAMPLES"));
assertEquals(before.get("SAMPLES"), after.get("SAMPLES"));
}
@Test
public void bioRAnnotationExample() throws ProcessTerminatedException {
System.out.println("Running: edu.mayo.ve.VCFParser.VCFParserITCase.bioRAnnotationExample");
String BioRAnnotatedVCF = "src/test/resources/testData/Case.ControlsFirst10K.vcf.gz";
String alias = "CaseControls";
String workspaceID = provision(alias);
VCFParser parser = new VCFParser();
parser.parse(null, VCF, workspaceID, overflowThreshold, false, reporting, true);
//delete the workspace
System.out.println("Deleting Workspace: " + workspaceID);
Workspace wksp = new Workspace();
wksp.deleteWorkspace(workspaceID);
}
}
|
package integration.resources;
import static org.analogweb.core.fake.FakeApplication.fakeApplication;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import org.analogweb.ReadableBuffer;
import org.analogweb.core.DefaultApplicationProperties;
import org.analogweb.core.DefaultReadableBuffer;
import org.analogweb.core.fake.FakeApplication;
import org.analogweb.core.fake.ResponseResult;
import org.analogweb.util.Maps;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class IntrgrationTest {
private FakeApplication app;
@After
public void tearDown() {
app.shutdown();
}
@Test
public void testFound() {
app = fakeApplication(DefaultApplicationProperties.properties("integration.testcase"));
ResponseResult actual = app.request("/helloworld", "GET");
assertThat(actual.getStatus(), is(200));
assertThat(actual.toBody(), is("Hello World"));
assertThat(actual.getResponseHeader().get("Content-Type").get(0),
is("text/plain; charset=UTF-8"));
}
@Test
public void testMethodNotAllowed() {
app = fakeApplication(DefaultApplicationProperties.properties("integration.testcase"));
ResponseResult actual = app.request("/helloworld", "POST");
assertThat(actual.getStatus(), is(405));
}
@Test
public void testPathvariable() {
app = fakeApplication(DefaultApplicationProperties.properties("integration.testcase"));
ResponseResult actual = app.request("/hello/snowgooseyk/world", "GET");
assertThat(actual.getStatus(), is(200));
assertThat(actual.toBody(), is("Hello snowgooseyk World"));
assertThat(actual.getResponseHeader().get("Content-Type").get(0),
is("text/plain; charset=UTF-8"));
actual = app.request("/hello/snowgoose/yk/world", "GET");
assertThat(actual.getStatus(), is(404));
}
@Test
public void testMetaAnnotation() {
app = fakeApplication(DefaultApplicationProperties.properties("integration.testcase"));
ResponseResult actual = app.request("/helloUserAgent", "GET",
Maps.newHashMap("User-Agent", Arrays.asList("JUnit")));
assertThat(actual.getStatus(), is(200));
assertThat(actual.toBody(), is("Hello World JUnit"));
assertThat(actual.getResponseHeader().get("Content-Type").get(0),
is("text/plain; charset=UTF-8"));
}
@Test
public void testPostFormToBean() {
app = fakeApplication(DefaultApplicationProperties.properties("integration.testcase"));
ReadableBuffer body = DefaultReadableBuffer.readBuffer(new ByteArrayInputStream("baa=foo".getBytes()));
ResponseResult actual = app
.request(
"/helloBean",
"POST",
Maps.newHashMap("Content-Type",
Arrays.asList("application/x-www-form-urlencoded")), body);
assertThat(actual.getStatus(), is(200));
assertThat(
actual.toBody(),
is("foo"));
assertThat(actual.getResponseHeader().get("Content-Type").get(0),
is("text/plain; charset=UTF-8"));
}
@Test
public void testVoid() {
app = fakeApplication(DefaultApplicationProperties.properties("integration.testcase"));
ResponseResult actual = app.request("/helloNothing", "GET");
assertThat(actual.getStatus(), is(204));
actual = app.request("/helloNull", "GET");
assertThat(actual.getStatus(), is(204));
}
}
|
package io.bdrc.lucene.bo;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
/**
* Unit test for simple App.
*/
public class TibetanAnalyzerTest
{
static TokenStream tokenize(String input, Tokenizer tokenizer) throws IOException {
tokenizer.close();
tokenizer.end();
Reader reader = new StringReader(input);
tokenizer.setReader(reader);
tokenizer.reset();
return tokenizer;
}
private void assertTokenStream(String string, List<String> expected, Tokenizer tokenizer) {
TokenStream tokenStream = null;
try {
tokenStream = tokenize(string, tokenizer);
List<String> termList = new ArrayList<String>();
CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
while (tokenStream.incrementToken()) {
termList.add(charTermAttribute.toString());
}
/** prints out the list of terms */
System.out.println(string + " => " + String.join(" ", termList));
assertThat(termList, is(expected));
} catch (IOException e) {
assertTrue(false);
}
}
@BeforeClass
public static void init() {
System.out.println("before the test sequence");
}
@Test
public void test1() throws IOException
{
System.out.println("Test1: TibSyllableTokenizer()");
String input = "བཀྲ་ཤིས། བདེ་ལེགས།";
List<String> expected = Arrays.asList("བཀྲ", "ཤིས", "བདེ" ,"ལེགས");
assertTokenStream(input, expected, new TibSyllableTokenizer());
}
@Test
public void test2()
{
System.out.println("test 2");
assertFalse(false);
}
@AfterClass
public static void finish() {
System.out.println("after the test sequence");
}
}
|
package org.apache.catalina.util;
import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import org.junit.Ignore;
import org.junit.Test;
public class TestStrftime {
@Test
public void parseText() throws Exception {
long t = 1358675873;
String pat = "%Y-%m-%d %X %z";
Strftime strftime = new Strftime(pat);
String converted = strftime.convertDateFormat(pat);
System.out.println(converted);
SimpleDateFormat f = new SimpleDateFormat(converted);
assertEquals(t, f.parse("2013-01-20 18:57:53 JST").getTime() / 1000);
}
}
|
package org.commcare.util;
import org.junit.Assert;
import org.junit.Test;
/**Tests for the GetJsonProperty
*
*
* @author rcostello
*/
public class GetJsonPropertyTest {
@Test
public void getJsonProperty() {
String testObj1 = "{name: Sam}";
String testVal1 = GetJsonProperty.getJsonProperty(testObj1, "name");
String testVal2 = GetJsonProperty.getJsonProperty(testObj1, "city");
Assert.assertEquals(testVal1, "Sam");
Assert.assertEquals(testVal2, "");
}
}
|
package org.mvel2.marshalling;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import junit.framework.TestCase;
import org.mvel2.MVEL;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.util.StringAppender;
import com.thoughtworks.xstream.XStream;
/**
* Generates templates to marshaller classes.
* TODO
* -Currently uses BeanInfo, needs to handle all MVEL getter/setter types
* -Use objenesis or equivalent to always be able to handle no-arg constructor
* -handle special immutable classes like BigInteger, BigDecimal(which are already done, but are there others?)
* -As well as allowing users to register custom templates, maybe also custom built in marshallers (i.e. how map, collection, array currently works)
* -Support optional generated imports, to reduce verbosity
* -some issue related to values allowed in a Map
*
*/
public class MarshallingTest extends TestCase {
public static enum Type {
PRIMITIVE, CHAR, STRING, DATE, CALENDAR, BIG_INTEGER, BIG_DECIMAL, ARRAY, MAP, COLLECTION, OBJECT;
}
public static class ObjectConverter {
private Class type;
private ObjectConverterEntry[] fields;
public ObjectConverter(Class type,
ObjectConverterEntry[] fields) {
this.type = type;
this.fields = fields;
}
public Class getType() {
return this.type;
}
public ObjectConverterEntry[] getFields() {
return fields;
}
}
public static class ObjectConverterEntry {
private String name;
private Type type;
private Method method;
public ObjectConverterEntry(String name,
Method method,
Type type) {
this.name = name;
this.type = type;
this.method = method;
}
public String getName() {
return name;
}
public Type getType() {
return type;
}
public Method getMethod() {
return this.method;
}
}
public static class MarshallerContext {
private Marshaller marshaller;
private StringAppender appender = new StringAppender();
public MarshallerContext(Marshaller marshaller) {
this.marshaller = marshaller;
this.appender = new StringAppender();
}
public void marshall(Object object) {
marshaller.marshall( object,
this );
}
public StringAppender getAppender() {
return appender;
}
}
public static interface CustomMarshaller {
public void marshall(Object object,
MarshallerContext ctx);
}
public static class EpocDateMarshaller
implements
CustomMarshaller {
public void marshall(Object object,
MarshallerContext ctx) {
ctx.getAppender().append( "new java.util.Date(" + ((Date) object).getTime() + ")" );
}
}
public static class EpocDefaultCalendarMarshaller
implements
CustomMarshaller {
private CustomMarshaller dateMarshaller;
public EpocDefaultCalendarMarshaller() {
this( new EpocDateMarshaller() );
}
public EpocDefaultCalendarMarshaller(CustomMarshaller dateMarshaller) {
this.dateMarshaller = dateMarshaller;
}
public void marshall(Object object,
MarshallerContext ctx) {
ctx.getAppender().append( "with ( java.util.Calendar.getInstance() ) { time = " );
this.dateMarshaller.marshall( ((Calendar) object).getTime(),
ctx );
ctx.getAppender().append( "} " );
}
}
public static class Marshaller {
private Map<Class, ObjectConverter> converters;
private CustomMarshaller dateMarshaller;
private CustomMarshaller calendarMarshaller;
public Marshaller() {
this( new HashMap<Type, CustomMarshaller>() );
}
public Marshaller(Map<Type, CustomMarshaller> custom) {
this.converters = new HashMap<Class, ObjectConverter>();
this.dateMarshaller = custom.get( Type.DATE );
if ( this.dateMarshaller == null ) {
this.dateMarshaller = new EpocDateMarshaller();
}
this.calendarMarshaller = custom.get( Type.CALENDAR );
if ( this.calendarMarshaller == null ) {
this.calendarMarshaller = new EpocDefaultCalendarMarshaller();
}
}
public void marshall(Object object,
MarshallerContext ctx) {
marshall( object,
getType( object.getClass() ),
ctx );
}
public void marshall(Object object,
Type type,
MarshallerContext ctx) {
if ( object == null ) {
ctx.getAppender().append( "null" );
return;
}
if ( type != Type.OBJECT ) {
marshallValue( object,
type,
ctx );
} else {
Class cls = object.getClass();
ObjectConverter converter = this.converters.get( cls );
if ( converter == null ) {
converter = generateConverter( cls );
this.converters.put( cls,
converter );
}
try {
int i = 0;
ctx.getAppender().append( "new " + cls.getName() + "().{ " );
for ( ObjectConverterEntry entry : converter.getFields() ) {
if ( i++ != 0 ) {
ctx.getAppender().append( ", " );
}
ctx.getAppender().append( entry.getName() );
ctx.getAppender().append( " = " );
marshallValue( entry.getMethod().invoke( object,
null ),
entry.getType(),
ctx );
}
} catch ( Exception e ) {
throw new IllegalStateException( "Unable to marshall object " + object,
e );
}
ctx.getAppender().append( " }" );
}
}
private void marshallValue(Object object,
Type type,
MarshallerContext ctx) {
if ( object == null ) {
ctx.getAppender().append( "null" );
return;
}
switch ( type ) {
case PRIMITIVE : {
ctx.getAppender().append( object );
break;
}
case CHAR : {
ctx.getAppender().append( "'" );
ctx.getAppender().append( object );
ctx.getAppender().append( "'" );
break;
}
case STRING : {
ctx.getAppender().append( "'" );
ctx.getAppender().append( object );
ctx.getAppender().append( "'" );
break;
}
case DATE : {
dateMarshaller.marshall( object,
ctx );
break;
}
case CALENDAR : {
calendarMarshaller.marshall( object,
ctx );
break;
}
case BIG_INTEGER : {
ctx.getAppender().append( object );
break;
}
case BIG_DECIMAL : {
ctx.getAppender().append( object );
break;
}
case ARRAY : {
marshallArray( object,
ctx );
break;
}
case MAP : {
marshallMap( (Map) object,
ctx );
break;
}
case COLLECTION : {
marshallCollection( (Collection) object,
ctx );
break;
}
case OBJECT : {
marshall( object,
type,
ctx );
break;
}
}
}
private ObjectConverter generateConverter(Class cls) {
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo( cls );
} catch ( IntrospectionException e ) {
throw new RuntimeException( e );
}
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
List<ObjectConverterEntry> list = new ArrayList<ObjectConverterEntry>();
for ( int i = 0, length = props.length; i < length; i++ ) {
PropertyDescriptor prop = props[i];
if ( "class".equals( prop.getName() ) ) {
continue;
}
list.add( new ObjectConverterEntry( prop.getName(),
prop.getReadMethod(),
getType( prop.getPropertyType() ) ) );
}
return new ObjectConverter( cls,
list.toArray( new ObjectConverterEntry[list.size()] ) );
}
private Type getType(Class cls) {
Type type = null;
if ( cls.isPrimitive() || Number.class.isAssignableFrom( cls ) ) {
type = Type.PRIMITIVE;
} else if ( Character.class.isAssignableFrom( cls ) ) {
type = Type.CHAR;
} else if ( String.class.isAssignableFrom( cls ) ) {
type = Type.STRING;
} else if ( Date.class.isAssignableFrom( cls ) ) {
type = Type.DATE;
} else if ( Calendar.class.isAssignableFrom( cls ) ) {
type = Type.CALENDAR;
} else if ( BigInteger.class.isAssignableFrom( cls ) ) {
type = Type.BIG_INTEGER;
} else if ( BigDecimal.class.isAssignableFrom( cls ) ) {
type = Type.BIG_DECIMAL;
} else if ( cls.isArray() ) {
type = Type.ARRAY;
} else if ( Map.class.isAssignableFrom( cls ) ) {
type = Type.MAP;
} else if ( Collection.class.isAssignableFrom( cls ) ) {
type = Type.COLLECTION;
} else {
type = Type.OBJECT;
}
return type;
}
private void marshallMap(Map map,
MarshallerContext ctx) {
ctx.getAppender().append( " [ " );
int i = 0;
for ( Iterator<Entry> it = map.entrySet().iterator(); it.hasNext(); i++ ) {
if ( i != 0 ) {
ctx.getAppender().append( ", " );
}
Entry entry = it.next();
marshall( entry.getKey(),
ctx );
ctx.getAppender().append( ':' );
marshall( entry.getValue(),
ctx );
}
ctx.getAppender().append( " ] " );
}
private void marshallCollection(Collection collection,
MarshallerContext ctx) {
ctx.getAppender().append( " [ " );
int i = 0;
for ( Iterator it = collection.iterator(); it.hasNext(); i++ ) {
if ( i != 0 ) {
ctx.getAppender().append( ", " );
}
marshall( it.next(),
ctx );
}
ctx.getAppender().append( " ] " );
}
private void marshallArray(Object array,
MarshallerContext ctx) {
ctx.getAppender().append( " { " );
for ( int i = 0, length = Array.getLength( array ); i < length; i++ ) {
if ( i != 0 ) {
ctx.getAppender().append( ", " );
}
marshall( Array.get( array,
i ),
ctx );
}
ctx.getAppender().append( " } " );
}
public String marshallToString(Object object) {
MarshallerContext ctx = new MarshallerContext( this );
marshall( object,
ctx );
return ctx.getAppender().toString();
}
}
private Object getData() {
Pet pet = new Pet();
pet.setName( "rover" );
pet.setAge( 7 );
List list = new ArrayList();
list.add( "a" );
list.add( 12 );
list.add( new SomeNumers( 10.02f,
22.02,
5,
100l,
new BigDecimal( 23.0234d,
MathContext.DECIMAL128 ),
new BigInteger( "1001" ) ) );
list.add( new Date() );
//list.add( 'b' ); // generates ok but breaks round trip equals
list.add( new Cheese( "cheddar",
6 ) );
pet.setList( list );
pet.setArray( new int[]{1, 2, 3} );
Map map = new HashMap();
//map.put( new Date(), new Cheese( "stilton", 11) ); // TODO why doesn't this work
map.put( "key1",
13 );
map.put( "key3",
"value3" );
map.put( "key2",
15 );
map.put( "key4",
new Cheese( "stilton",
11 ) );
Calendar cal = Calendar.getInstance();
// cal.setTime( new Date() );
// map.put( "key5",
// cal ); // TODO why doesn't this work.
//map.put( "key4", new String[] { "a", "b" } ); // TODO why doesn't this work
Person person = new Person();
person.setName( "mark" );
person.setAge( 33 );
person.setPet( pet );
person.setSomeDate( new Date() );
person.setMap( map );
cal = Calendar.getInstance();
cal.setTime( new Date() );
person.setCal( cal );
return person;
}
private static final int COUNT = 0;
public void testXStream() {
XStream xstream = new XStream();
// run once to allow for caching
Object data1 = getData();
String str = xstream.toXML( data1 );
System.out.println( str );
Object data2 = xstream.fromXML( str );
assertNotSame( data1,
data2 );
assertEquals( data1,
data2 );
long start = System.currentTimeMillis();
for ( int i = 0; i < COUNT; i++ ) {
data1 = getData();
str = xstream.toXML( data1 );
data2 = xstream.fromXML( str );
assertNotSame( data1,
data2 );
assertEquals( data1,
data2 );
}
long end = System.currentTimeMillis();
System.out.println( "xstream : " + (end - start) );
}
public void testMVEL() throws Exception {
Marshaller marshaller = new Marshaller();
// run once to generate templates
Object data1 = getData();
String str = marshaller.marshallToString( data1 );
System.out.println( str );
Object data2 = MVEL.eval( str );
assertNotSame( data1,
data2 );
assertEquals( data1,
data2 );
long start = System.currentTimeMillis();
for ( int i = 0; i < COUNT; i++ ) {
data1 = getData();
str = marshaller.marshallToString( data1 );
data2 = MVEL.eval( str );
assertNotSame( data1,
data2 );
assertEquals( data1,
data2 );
}
long end = System.currentTimeMillis();
System.out.println( "mvel : " + (end - start) );
}
public static class SomeNumers {
private float aFloat;
private double aDouble;
private int aInt;
private long aLong;
private BigDecimal aBigDecimal;
private BigInteger aBigInteger;
public SomeNumers() {
}
public SomeNumers(float float1,
double double1,
int int1,
long long1,
BigDecimal bigDecimal,
BigInteger bigInteger) {
super();
aFloat = float1;
aDouble = double1;
aInt = int1;
aLong = long1;
aBigDecimal = bigDecimal;
aBigInteger = bigInteger;
}
public float getAFloat() {
return aFloat;
}
public void setAFloat(float float1) {
aFloat = float1;
}
public double getADouble() {
return aDouble;
}
public void setADouble(double double1) {
aDouble = double1;
}
public int getAInt() {
return aInt;
}
public void setAInt(int int1) {
aInt = int1;
}
public long getALong() {
return aLong;
}
public void setALong(long long1) {
aLong = long1;
}
public BigDecimal getABigDecimal() {
return aBigDecimal;
}
public void setABigDecimal(BigDecimal bigDecimal) {
aBigDecimal = bigDecimal;
}
public BigInteger getABigInteger() {
return aBigInteger;
}
public void setABigInteger(BigInteger bigInteger) {
aBigInteger = bigInteger;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((aBigDecimal == null) ? 0 : aBigDecimal.hashCode());
result = prime * result + ((aBigInteger == null) ? 0 : aBigInteger.hashCode());
long temp;
temp = Double.doubleToLongBits( aDouble );
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Float.floatToIntBits( aFloat );
result = prime * result + aInt;
result = prime * result + (int) (aLong ^ (aLong >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
SomeNumers other = (SomeNumers) obj;
if ( aBigDecimal == null ) {
if ( other.aBigDecimal != null ) return false;
} else if ( !aBigDecimal.equals( other.aBigDecimal ) ) return false;
if ( aBigInteger == null ) {
if ( other.aBigInteger != null ) return false;
} else if ( !aBigInteger.equals( other.aBigInteger ) ) return false;
if ( Double.doubleToLongBits( aDouble ) != Double.doubleToLongBits( other.aDouble ) ) return false;
if ( Float.floatToIntBits( aFloat ) != Float.floatToIntBits( other.aFloat ) ) return false;
if ( aInt != other.aInt ) return false;
if ( aLong != other.aLong ) return false;
return true;
}
}
public static class Person {
private String name;
private int age;
private Date someDate;
private Pet pet;
private Object nullTest;
private Map map;
private Calendar cal;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Pet getPet() {
return this.pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
public Date getSomeDate() {
return someDate;
}
public void setSomeDate(Date someDate) {
this.someDate = someDate;
}
public Object getNullTest() {
return nullTest;
}
public void setNullTest(Object nullTest) {
this.nullTest = nullTest;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public Calendar getCal() {
return cal;
}
public void setCal(Calendar cal) {
this.cal = cal;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((cal == null) ? 0 : cal.hashCode());
result = prime * result + ((map == null) ? 0 : map.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((nullTest == null) ? 0 : nullTest.hashCode());
result = prime * result + ((pet == null) ? 0 : pet.hashCode());
result = prime * result + ((someDate == null) ? 0 : someDate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
Person other = (Person) obj;
if ( age != other.age ) return false;
if ( cal == null ) {
if ( other.cal != null ) return false;
} else if ( !cal.equals( other.cal ) ) return false;
if ( map == null ) {
if ( other.map != null ) return false;
} else if ( !map.equals( other.map ) ) return false;
if ( name == null ) {
if ( other.name != null ) return false;
} else if ( !name.equals( other.name ) ) return false;
if ( nullTest == null ) {
if ( other.nullTest != null ) return false;
} else if ( !nullTest.equals( other.nullTest ) ) return false;
if ( pet == null ) {
if ( other.pet != null ) return false;
} else if ( !pet.equals( other.pet ) ) return false;
if ( someDate == null ) {
if ( other.someDate != null ) return false;
} else if ( !someDate.equals( other.someDate ) ) return false;
return true;
}
}
public static class Pet {
private String name;
private Integer age;
private List list;
private int[] array;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer agr) {
this.age = agr;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public int[] getArray() {
return array;
}
public void setArray(int[] array) {
this.array = array;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + Arrays.hashCode( array );
result = prime * result + ((list == null) ? 0 : list.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
Pet other = (Pet) obj;
if ( age == null ) {
if ( other.age != null ) return false;
} else if ( !age.equals( other.age ) ) return false;
if ( !Arrays.equals( array,
other.array ) ) return false;
if ( list == null ) {
if ( other.list != null ) return false;
} else if ( !list.equals( other.list ) ) return false;
if ( name == null ) {
if ( other.name != null ) return false;
} else if ( !name.equals( other.name ) ) return false;
return true;
}
}
public static class Cheese {
private String type;
private int age;
private boolean edible;
public Cheese() {
}
public Cheese(String type,
int age) {
this.type = type;
this.age = age;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isEdible() {
return edible;
}
public void setEdible(boolean edible) {
this.edible = edible;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + (edible ? 1231 : 1237);
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
Cheese other = (Cheese) obj;
if ( age != other.age ) return false;
if ( edible != other.edible ) return false;
if ( type == null ) {
if ( other.type != null ) return false;
} else if ( !type.equals( other.type ) ) return false;
return true;
}
}
}
|
package org.unidle.social.test;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.support.AbstractConnection;
public class ConnectionStub<A> extends AbstractConnection<A> {
private final ConnectionData connectionData;
private final UserProfile userProfile;
public ConnectionStub(final ConnectionData connectionData,
final UserProfile userProfile) {
super(connectionData, null);
this.connectionData = connectionData;
this.userProfile = userProfile;
}
public ConnectionStub(final ConnectionData connectionData) {
super(connectionData, null);
this.connectionData = connectionData;
this.userProfile = null;
}
@Override
public UserProfile fetchUserProfile() {
return userProfile;
}
@Override
public A getApi() {
throw new UnsupportedOperationException();
}
@Override
public ConnectionData createData() {
return connectionData;
}
}
|
package ru.r2cloud.jradio.blocks;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import ru.r2cloud.jradio.ArrayFloatInput;
public class MultiplyTest {
@Test
public void test() throws Exception {
Multiply multiply = new Multiply(new ArrayFloatInput(2.0f, 0.0f), new ArrayFloatInput(2.0f, 0.0f));
assertEquals(4.0f, multiply.readFloat(), 0.0f);
multiply.close();
}
}
|
package se.tla.mavenversionbumper.vcs;
import static junit.framework.Assert.*;
import org.apache.commons.exec.CommandLine;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import se.tla.mavenversionbumper.Module;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
/**
* Test of the Git class.
*/
public class GitTest {
public static final String COMMANDPATH = "git.exe";
Properties defaultCommandProperties;
Git defaultSubject;
FakeExecutor defaultExecutor;
File pomFile;
static final String COMMIT_MSG = "COMMITED AS ....";
static final String LABEL = "TAG, Tag, tag";
@Before
public void before() throws IOException {
defaultCommandProperties = new Properties();
defaultCommandProperties.setProperty(AbstractVersionControl.VERSIONCONTROL, Git.ACRONYM);
defaultCommandProperties.setProperty(Git.COMMANDPATH, COMMANDPATH);
defaultExecutor = new FakeExecutor();
defaultSubject = new Git(defaultCommandProperties);
defaultSubject.setExecutor(defaultExecutor);
pomFile = File.createTempFile("foo", "bar");
pomFile.deleteOnExit();
}
@After
public void after() {
pomFile.delete();
}
@Test
public void testRestore() throws IOException {
Module module = new TestableModule(pomFile, "foo", "bar", "1", null, null);
defaultSubject.restore(Arrays.asList(module));
assertEquals(1, defaultExecutor.commandLines.size());
CommandLine commandLine = defaultExecutor.commandLines.get(0);
assertEquals(COMMANDPATH, commandLine.getExecutable());
String[] arguments = commandLine.getArguments();
assertEquals(2, arguments.length);
assertEquals("checkout", arguments[0]);
assertEquals(pomFile.getName(), arguments[1]);
}
@Test
public void testCommit() {
Module module = new TestableModule(pomFile, "foo", "bar", "1", COMMIT_MSG, null);
defaultSubject.commit(Arrays.asList(module));
assertEquals(1, defaultExecutor.commandLines.size());
CommandLine commandLine = defaultExecutor.commandLines.get(0);
assertEquals(COMMANDPATH, commandLine.getExecutable());
String[] arguments = commandLine.getArguments();
assertEquals(4, arguments.length);
assertEquals("commit", arguments[0]);
assertEquals("-m", arguments[1]);
assertEquals("\"" + COMMIT_MSG + "\"", arguments[2]);
assertEquals(pomFile.getName(), arguments[3]);
}
@Test
public void testLabel() {
Module module = new TestableModule(pomFile, "foo", "bar", "1", null, LABEL);
defaultSubject.label(Arrays.asList(module));
assertEquals(1, defaultExecutor.commandLines.size());
CommandLine commandLine = defaultExecutor.commandLines.get(0);
assertEquals(COMMANDPATH, commandLine.getExecutable());
String[] arguments = commandLine.getArguments();
assertEquals(3, arguments.length);
assertEquals("tag", arguments[0]);
assertEquals("-f", arguments[1]);
assertEquals("\"" + LABEL + "\"", arguments[2]);
}
}
|
package com.thoughtworks.xstream.mapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.SingleValueConverter;
public interface Mapper {
/**
* Place holder type used for null values.
*/
class Null {}
/**
* How a class name should be represented in its serialized form.
*/
String serializedClass(Class<?> type);
/**
* How a serialized class representation should be mapped back to a real class.
*/
Class<?> realClass(String elementName);
/**
* How a class member should be represented in its serialized form.
*/
String serializedMember(Class<?> type, String memberName);
/**
* How a serialized member representation should be mapped back to a real member.
*/
String realMember(Class<?> type, String serialized);
/**
* Whether this type is a simple immutable value (int, boolean, String, URL, etc). Immutable types will be
* repeatedly written in the serialized stream, instead of using object references.
*/
boolean isImmutableValueType(Class<?> type);
/**
* Whether this type is referenceable in a stream.
*
* @since upcoming
*/
boolean isReferenceable(Class<?> type);
Class<?> defaultImplementationOf(Class<?> type);
/**
* Get the alias for an attribute's name.
*
* @param attribute the attribute
* @return the alias
* @since 1.2
*/
String aliasForAttribute(String attribute);
/**
* Get the attribute's name for an alias.
*
* @param alias the alias
* @return the attribute's name
* @since 1.2
*/
String attributeForAlias(String alias);
/**
* Get the alias for a system attribute's name.
*
* @param attribute the system attribute
* @return the alias
* @since 1.3.1
*/
String aliasForSystemAttribute(String attribute);
/**
* Get the name of the field that acts as the default collection for an object, or return null if there is none.
*
* @param definedIn owning type
* @param itemType item type
* @param itemFieldName optional item element name
*/
String getFieldNameForItemTypeAndName(Class<?> definedIn, Class<?> itemType, String itemFieldName);
Class<?> getItemTypeForItemFieldName(Class<?> definedIn, String itemFieldName);
ImplicitCollectionMapping getImplicitCollectionDefForFieldName(Class<?> itemType, String fieldName);
/**
* Determine whether a specific member should be serialized.
*
* @since 1.1.3
*/
boolean shouldSerializeMember(Class<?> definedIn, String fieldName);
interface ImplicitCollectionMapping {
String getFieldName();
String getItemFieldName();
Class<?> getItemType();
String getKeyFieldName();
}
Converter getLocalConverter(Class<?> definedIn, String fieldName);
<T extends Mapper> T lookupMapperOfType(final Class<T> type);
/**
* Returns a single value converter to be used in a specific field.
*
* @param fieldName the field name
* @param type the field type
* @param definedIn the type which defines this field
* @return a SingleValueConverter or null if there no such converter should be used for this field.
* @since 1.2.2
*/
SingleValueConverter getConverterFromItemType(String fieldName, Class<?> type, Class<?> definedIn);
/**
* Returns which converter to use for an specific attribute in a type.
*
* @param definedIn the field's parent
* @param attribute the attribute name
* @deprecated As of 1.3.1, use {@link #getConverterFromAttribute(Class, String, Class)}
*/
@Deprecated
SingleValueConverter getConverterFromAttribute(Class<?> definedIn, String attribute);
/**
* Returns which converter to use for an specific attribute in a type.
*
* @param definedIn the field's parent
* @param attribute the attribute name
* @param type the type the converter should create
* @since 1.3.1
*/
SingleValueConverter getConverterFromAttribute(Class<?> definedIn, String attribute, Class<?> type);
}
|
package org.jdesktop.swingx.test;
import java.beans.PropertyChangeEvent;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import org.jdesktop.swingx.event.TableColumnModelExtListener;
import org.jdesktop.test.PropertyChangeReport;
/**
* A TableColumnExtListener that stores the received TableColumnEvents and
* PropertyChangeEvents originating from the TableColumns contained in the
* TableColumnModel.
*/
public class ColumnModelReport implements TableColumnModelExtListener {
/**
* Holds a list of all received ValueChangeEvents.
*/
private List<TableColumnModelEvent> removedEvents = Collections.synchronizedList(new LinkedList<TableColumnModelEvent>());
private List<TableColumnModelEvent> addedEvents = Collections.synchronizedList(new LinkedList<TableColumnModelEvent>());
private List<TableColumnModelEvent> movedEvents = Collections.synchronizedList(new LinkedList<TableColumnModelEvent>());
private List<ListSelectionEvent> selectionEvents = Collections.synchronizedList(new LinkedList<ListSelectionEvent>());
private List<ChangeEvent> changeEvents = Collections.synchronizedList(new LinkedList<ChangeEvent>());
// private List<PropertyChangeEvent> columnPropertyEvents = new LinkedList<PropertyChangeEvent>();
private PropertyChangeReport propertyReport = new PropertyChangeReport();
public void columnAdded(TableColumnModelEvent e) {
addedEvents.add(0, e);
}
public void columnMarginChanged(ChangeEvent e) {
changeEvents.add(0, e);
}
public void columnMoved(TableColumnModelEvent e) {
movedEvents.add(0, e);
}
public void columnRemoved(TableColumnModelEvent e) {
removedEvents.add(0, e);
}
public void columnSelectionChanged(ListSelectionEvent e) {
selectionEvents.add(0, e);
}
public void columnPropertyChange(PropertyChangeEvent e) {
propertyReport.propertyChange(e);
}
public boolean hasEvents() {
return getEventCount() > 0;
}
public void clear() {
addedEvents.clear();
removedEvents.clear();
movedEvents.clear();
changeEvents.clear();
selectionEvents.clear();
propertyReport.clear();
}
public int getEventCount() {
return addedEvents.size() + removedEvents.size() + movedEvents.size() +
changeEvents.size() + selectionEvents.size() + propertyReport.getEventCount();
}
public boolean hasRemovedEvent() {
return !removedEvents.isEmpty();
}
public TableColumnModelEvent getLastRemoveEvent() {
return removedEvents.isEmpty() ? null : removedEvents.get(0);
}
public boolean hasAddedEvent() {
return !addedEvents.isEmpty();
}
public TableColumnModelEvent getLastAddEvent() {
return addedEvents.isEmpty() ? null : addedEvents.get(0);
}
public boolean hasChangeEvent() {
return !changeEvents.isEmpty();
}
public int getChangeEventCount() {
return changeEvents.size();
}
public ChangeEvent getLastChangeEvent() {
return hasChangeEvent() ? changeEvents.get(0) : null;
}
public boolean hasSelectionEvent() {
return !selectionEvents.isEmpty();
}
public int getSelectionEventCount() {
return selectionEvents.size();
}
public ListSelectionEvent getLastSelectionEvent() {
return hasSelectionEvent() ? selectionEvents.get(0) : null;
}
public boolean hasColumnPropertyEvent() {
return propertyReport.hasEvents();
}
public int getColumnPropertyEventCount() {
return propertyReport.getEventCount();
}
public PropertyChangeEvent getLastColumnPropertyEvent() {
return propertyReport.getLastEvent();
}
public int getColumnPropertyEventCount(String property) {
return propertyReport.getEventCount(property);
}
public Object getLastColumnPropertyEvent(String property) {
return propertyReport.getLastEvent(property);
}
public PropertyChangeReport getPropertyChangeReport() {
return propertyReport;
}
}
|
package com.tpcstld.twozerogame;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
@SuppressWarnings("deprecation")
public class MainView extends View {
//Internal Constants
static final int BASE_ANIMATION_TIME = 100000000;
private static final String TAG = MainView.class.getSimpleName();
private static final float MERGING_ACCELERATION = (float) -0.5;
private static final float INITIAL_VELOCITY = (1 - MERGING_ACCELERATION) / 4;
public final int numCellTypes = 21;
private final BitmapDrawable[] bitmapCell = new BitmapDrawable[numCellTypes];
public final MainGame game;
//Internal variables
private final Paint paint = new Paint();
public boolean hasSaveState = false;
public boolean continueButtonEnabled = false;
public int startingX;
public int startingY;
public int endingX;
public int endingY;
//Icon variables
public int sYIcons;
public int sXNewGame;
public int sXUndo;
public int iconSize;
//Misc
boolean refreshLastTime = true;
//Timing
private long lastFPSTime = System.nanoTime();
//Text
private float titleTextSize;
private float bodyTextSize;
private float headerTextSize;
private float instructionsTextSize;
private float gameOverTextSize;
//Layout variables
private int cellSize = 0;
private float textSize = 0;
private float cellTextSize = 0;
private int gridWidth = 0;
private int textPaddingSize;
private int iconPaddingSize;
//Assets
private Drawable backgroundRectangle;
private Drawable lightUpRectangle;
private Drawable fadeRectangle;
private Bitmap background = null;
private BitmapDrawable loseGameOverlay;
private BitmapDrawable winGameContinueOverlay;
private BitmapDrawable winGameFinalOverlay;
//Text variables
private int sYAll;
private int titleStartYAll;
private int bodyStartYAll;
private int eYAll;
private int titleWidthHighScore;
private int titleWidthScore;
public MainView(Context context) {
super(context);
Resources resources = context.getResources();
//Loading resources
game = new MainGame(context, this);
try {
//Getting assets
backgroundRectangle = resources.getDrawable(R.drawable.background_rectangle);
lightUpRectangle = resources.getDrawable(R.drawable.light_up_rectangle);
fadeRectangle = resources.getDrawable(R.drawable.fade_rectangle);
this.setBackgroundColor(resources.getColor(R.color.background));
Typeface font = Typeface.createFromAsset(resources.getAssets(), "ClearSans-Bold.ttf");
paint.setTypeface(font);
paint.setAntiAlias(true);
} catch (Exception e) {
Log.e(TAG, "Error getting assets?", e);
}
setOnTouchListener(new InputListener(this));
game.newGame();
}
private static int log2(int n) {
if (n <= 0) throw new IllegalArgumentException();
return 31 - Integer.numberOfLeadingZeros(n);
}
@Override
public void onDraw(Canvas canvas) {
//Reset the transparency of the screen
canvas.drawBitmap(background, 0, 0, paint);
drawScoreText(canvas);
if (!game.isActive() && !game.aGrid.isAnimationActive()) {
drawNewGameButton(canvas, true);
}
drawCells(canvas);
if (!game.isActive()) {
drawEndGameState(canvas);
}
if (!game.canContinue()) {
drawEndlessText(canvas);
}
//Refresh the screen if there is still an animation running
if (game.aGrid.isAnimationActive()) {
invalidate(startingX, startingY, endingX, endingY);
tick();
//Refresh one last time on game end.
} else if (!game.isActive() && refreshLastTime) {
invalidate();
refreshLastTime = false;
}
}
@Override
protected void onSizeChanged(int width, int height, int oldW, int oldH) {
super.onSizeChanged(width, height, oldW, oldH);
getLayout(width, height);
createBitmapCells();
createBackgroundBitmap(width, height);
createOverlays();
}
private void drawDrawable(Canvas canvas, Drawable draw, int startingX, int startingY, int endingX, int endingY) {
draw.setBounds(startingX, startingY, endingX, endingY);
draw.draw(canvas);
}
private void drawCellText(Canvas canvas, int value) {
int textShiftY = centerText();
if (value >= 8) {
paint.setColor(getResources().getColor(R.color.text_white));
} else {
paint.setColor(getResources().getColor(R.color.text_black));
}
canvas.drawText("" + value, cellSize / 2, cellSize / 2 - textShiftY, paint);
}
private void drawScoreText(Canvas canvas) {
//Drawing the score text: Ver 2
paint.setTextSize(bodyTextSize);
paint.setTextAlign(Paint.Align.CENTER);
int bodyWidthHighScore = (int) (paint.measureText("" + game.highScore));
int bodyWidthScore = (int) (paint.measureText("" + game.score));
int textWidthHighScore = Math.max(titleWidthHighScore, bodyWidthHighScore) + textPaddingSize * 2;
int textWidthScore = Math.max(titleWidthScore, bodyWidthScore) + textPaddingSize * 2;
int textMiddleHighScore = textWidthHighScore / 2;
int textMiddleScore = textWidthScore / 2;
int eXHighScore = endingX;
int sXHighScore = eXHighScore - textWidthHighScore;
int eXScore = sXHighScore - textPaddingSize;
int sXScore = eXScore - textWidthScore;
//Outputting high-scores box
backgroundRectangle.setBounds(sXHighScore, sYAll, eXHighScore, eYAll);
backgroundRectangle.draw(canvas);
paint.setTextSize(titleTextSize);
paint.setColor(getResources().getColor(R.color.text_brown));
canvas.drawText(getResources().getString(R.string.high_score), sXHighScore + textMiddleHighScore, titleStartYAll, paint);
paint.setTextSize(bodyTextSize);
paint.setColor(getResources().getColor(R.color.text_white));
canvas.drawText(String.valueOf(game.highScore), sXHighScore + textMiddleHighScore, bodyStartYAll, paint);
//Outputting scores box
backgroundRectangle.setBounds(sXScore, sYAll, eXScore, eYAll);
backgroundRectangle.draw(canvas);
paint.setTextSize(titleTextSize);
paint.setColor(getResources().getColor(R.color.text_brown));
canvas.drawText(getResources().getString(R.string.score), sXScore + textMiddleScore, titleStartYAll, paint);
paint.setTextSize(bodyTextSize);
paint.setColor(getResources().getColor(R.color.text_white));
canvas.drawText(String.valueOf(game.score), sXScore + textMiddleScore, bodyStartYAll, paint);
}
private void drawNewGameButton(Canvas canvas, boolean lightUp) {
if (lightUp) {
drawDrawable(canvas,
lightUpRectangle,
sXNewGame,
sYIcons,
sXNewGame + iconSize,
sYIcons + iconSize
);
} else {
drawDrawable(canvas,
backgroundRectangle,
sXNewGame,
sYIcons, sXNewGame + iconSize,
sYIcons + iconSize
);
}
drawDrawable(canvas,
getResources().getDrawable(R.drawable.ic_action_refresh),
sXNewGame + iconPaddingSize,
sYIcons + iconPaddingSize,
sXNewGame + iconSize - iconPaddingSize,
sYIcons + iconSize - iconPaddingSize
);
}
private void drawUndoButton(Canvas canvas) {
drawDrawable(canvas,
backgroundRectangle,
sXUndo,
sYIcons, sXUndo + iconSize,
sYIcons + iconSize
);
drawDrawable(canvas,
getResources().getDrawable(R.drawable.ic_action_undo),
sXUndo + iconPaddingSize,
sYIcons + iconPaddingSize,
sXUndo + iconSize - iconPaddingSize,
sYIcons + iconSize - iconPaddingSize
);
}
private void drawHeader(Canvas canvas) {
paint.setTextSize(headerTextSize);
paint.setColor(getResources().getColor(R.color.text_black));
paint.setTextAlign(Paint.Align.LEFT);
int textShiftY = centerText() * 2;
int headerStartY = sYAll - textShiftY;
canvas.drawText(getResources().getString(R.string.header), startingX, headerStartY, paint);
}
private void drawInstructions(Canvas canvas) {
paint.setTextSize(instructionsTextSize);
paint.setTextAlign(Paint.Align.LEFT);
int textShiftY = centerText() * 2;
canvas.drawText(getResources().getString(R.string.instructions),
startingX, endingY - textShiftY + textPaddingSize, paint);
}
private void drawBackground(Canvas canvas) {
drawDrawable(canvas, backgroundRectangle, startingX, startingY, endingX, endingY);
}
//Renders the set of 16 background squares.
private void drawBackgroundGrid(Canvas canvas) {
Resources resources = getResources();
Drawable backgroundCell = resources.getDrawable(R.drawable.cell_rectangle);
// Outputting the game grid
for (int xx = 0; xx < game.numSquaresX; xx++) {
for (int yy = 0; yy < game.numSquaresY; yy++) {
int sX = startingX + gridWidth + (cellSize + gridWidth) * xx;
int eX = sX + cellSize;
int sY = startingY + gridWidth + (cellSize + gridWidth) * yy;
int eY = sY + cellSize;
drawDrawable(canvas, backgroundCell, sX, sY, eX, eY);
}
}
}
private void drawCells(Canvas canvas) {
paint.setTextSize(textSize);
paint.setTextAlign(Paint.Align.CENTER);
// Outputting the individual cells
for (int xx = 0; xx < game.numSquaresX; xx++) {
for (int yy = 0; yy < game.numSquaresY; yy++) {
int sX = startingX + gridWidth + (cellSize + gridWidth) * xx;
int eX = sX + cellSize;
int sY = startingY + gridWidth + (cellSize + gridWidth) * yy;
int eY = sY + cellSize;
Tile currentTile = game.grid.getCellContent(xx, yy);
if (currentTile != null) {
//Get and represent the value of the tile
int value = currentTile.getValue();
int index = log2(value);
//Check for any active animations
ArrayList<AnimationCell> aArray = game.aGrid.getAnimationCell(xx, yy);
boolean animated = false;
for (int i = aArray.size() - 1; i >= 0; i
AnimationCell aCell = aArray.get(i);
//If this animation is not active, skip it
if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) {
animated = true;
}
if (!aCell.isActive()) {
continue;
}
if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) { // Spawning animation
double percentDone = aCell.getPercentageDone();
float textScaleSize = (float) (percentDone);
paint.setTextSize(textSize * textScaleSize);
float cellScaleSize = cellSize / 2 * (1 - textScaleSize);
bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize));
bitmapCell[index].draw(canvas);
} else if (aCell.getAnimationType() == MainGame.MERGE_ANIMATION) { // Merging Animation
double percentDone = aCell.getPercentageDone();
float textScaleSize = (float) (1 + INITIAL_VELOCITY * percentDone
+ MERGING_ACCELERATION * percentDone * percentDone / 2);
paint.setTextSize(textSize * textScaleSize);
float cellScaleSize = cellSize / 2 * (1 - textScaleSize);
bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize));
bitmapCell[index].draw(canvas);
} else if (aCell.getAnimationType() == MainGame.MOVE_ANIMATION) { // Moving animation
double percentDone = aCell.getPercentageDone();
int tempIndex = index;
if (aArray.size() >= 2) {
tempIndex = tempIndex - 1;
}
int previousX = aCell.extras[0];
int previousY = aCell.extras[1];
int currentX = currentTile.getX();
int currentY = currentTile.getY();
int dX = (int) ((currentX - previousX) * (cellSize + gridWidth) * (percentDone - 1) * 1.0);
int dY = (int) ((currentY - previousY) * (cellSize + gridWidth) * (percentDone - 1) * 1.0);
bitmapCell[tempIndex].setBounds(sX + dX, sY + dY, eX + dX, eY + dY);
bitmapCell[tempIndex].draw(canvas);
}
animated = true;
}
//No active animations? Just draw the cell
if (!animated) {
bitmapCell[index].setBounds(sX, sY, eX, eY);
bitmapCell[index].draw(canvas);
}
}
}
}
}
private void drawEndGameState(Canvas canvas) {
double alphaChange = 1;
continueButtonEnabled = false;
for (AnimationCell animation : game.aGrid.globalAnimation) {
if (animation.getAnimationType() == MainGame.FADE_GLOBAL_ANIMATION) {
alphaChange = animation.getPercentageDone();
}
}
BitmapDrawable displayOverlay = null;
if (game.gameWon()) {
if (game.canContinue()) {
continueButtonEnabled = true;
displayOverlay = winGameContinueOverlay;
} else {
displayOverlay = winGameFinalOverlay;
}
} else if (game.gameLost()) {
displayOverlay = loseGameOverlay;
}
if (displayOverlay != null) {
displayOverlay.setBounds(startingX, startingY, endingX, endingY);
displayOverlay.setAlpha((int) (255 * alphaChange));
displayOverlay.draw(canvas);
}
}
private void drawEndlessText(Canvas canvas) {
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(bodyTextSize);
paint.setColor(getResources().getColor(R.color.text_black));
canvas.drawText(getResources().getString(R.string.endless), startingX, sYIcons - centerText() * 2, paint);
}
private void createEndGameStates(Canvas canvas, boolean win, boolean showButton) {
int width = endingX - startingX;
int length = endingY - startingY;
int middleX = width / 2;
int middleY = length / 2;
if (win) {
lightUpRectangle.setAlpha(127);
drawDrawable(canvas, lightUpRectangle, 0, 0, width, length);
lightUpRectangle.setAlpha(255);
paint.setColor(getResources().getColor(R.color.text_white));
paint.setAlpha(255);
paint.setTextSize(gameOverTextSize);
paint.setTextAlign(Paint.Align.CENTER);
int textBottom = middleY - centerText();
canvas.drawText(getResources().getString(R.string.you_win), middleX, textBottom, paint);
paint.setTextSize(bodyTextSize);
String text = showButton ? getResources().getString(R.string.go_on) :
getResources().getString(R.string.for_now);
canvas.drawText(text, middleX, textBottom + textPaddingSize * 2 - centerText() * 2, paint);
} else {
fadeRectangle.setAlpha(127);
drawDrawable(canvas, fadeRectangle, 0, 0, width, length);
fadeRectangle.setAlpha(255);
paint.setColor(getResources().getColor(R.color.text_black));
paint.setAlpha(255);
paint.setTextSize(gameOverTextSize);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(getResources().getString(R.string.game_over), middleX, middleY - centerText(), paint);
}
}
private void createBackgroundBitmap(int width, int height) {
background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(background);
drawHeader(canvas);
drawNewGameButton(canvas, false);
drawUndoButton(canvas);
drawBackground(canvas);
drawBackgroundGrid(canvas);
drawInstructions(canvas);
}
private void createBitmapCells() {
Resources resources = getResources();
int[] cellRectangleIds = getCellRectangleIds();
paint.setTextAlign(Paint.Align.CENTER);
for (int xx = 1; xx < bitmapCell.length; xx++) {
int value = (int) Math.pow(2, xx);
paint.setTextSize(cellTextSize);
float tempTextSize = cellTextSize * cellSize * 0.9f / Math.max(cellSize * 0.9f, paint.measureText(String.valueOf(value)));
paint.setTextSize(tempTextSize);
Bitmap bitmap = Bitmap.createBitmap(cellSize, cellSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawDrawable(canvas, resources.getDrawable(cellRectangleIds[xx]), 0, 0, cellSize, cellSize);
drawCellText(canvas, value);
bitmapCell[xx] = new BitmapDrawable(resources, bitmap);
}
}
private int[] getCellRectangleIds() {
int[] cellRectangleIds = new int[numCellTypes];
cellRectangleIds[0] = R.drawable.cell_rectangle;
cellRectangleIds[1] = R.drawable.cell_rectangle_2;
cellRectangleIds[2] = R.drawable.cell_rectangle_4;
cellRectangleIds[3] = R.drawable.cell_rectangle_8;
cellRectangleIds[4] = R.drawable.cell_rectangle_16;
cellRectangleIds[5] = R.drawable.cell_rectangle_32;
cellRectangleIds[6] = R.drawable.cell_rectangle_64;
cellRectangleIds[7] = R.drawable.cell_rectangle_128;
cellRectangleIds[8] = R.drawable.cell_rectangle_256;
cellRectangleIds[9] = R.drawable.cell_rectangle_512;
cellRectangleIds[10] = R.drawable.cell_rectangle_1024;
cellRectangleIds[11] = R.drawable.cell_rectangle_2048;
for (int xx = 12; xx < cellRectangleIds.length; xx++) {
cellRectangleIds[xx] = R.drawable.cell_rectangle_4096;
}
return cellRectangleIds;
}
private void createOverlays() {
Resources resources = getResources();
//Initialize overlays
Bitmap bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
createEndGameStates(canvas, true, true);
winGameContinueOverlay = new BitmapDrawable(resources, bitmap);
bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
createEndGameStates(canvas, true, false);
winGameFinalOverlay = new BitmapDrawable(resources, bitmap);
bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
createEndGameStates(canvas, false, false);
loseGameOverlay = new BitmapDrawable(resources, bitmap);
}
private void tick() {
long currentTime = System.nanoTime();
game.aGrid.tickAll(currentTime - lastFPSTime);
lastFPSTime = currentTime;
}
public void resyncTime() {
lastFPSTime = System.nanoTime();
}
private void getLayout(int width, int height) {
cellSize = Math.min(width / (game.numSquaresX + 1), height / (game.numSquaresY + 3));
gridWidth = cellSize / 7;
int screenMiddleX = width / 2;
int screenMiddleY = height / 2;
int boardMiddleY = screenMiddleY + cellSize / 2;
iconSize = cellSize / 2;
//Grid Dimensions
double halfNumSquaresX = game.numSquaresX / 2d;
double halfNumSquaresY = game.numSquaresY / 2d;
startingX = (int) (screenMiddleX - (cellSize + gridWidth) * halfNumSquaresX - gridWidth / 2);
endingX = (int) (screenMiddleX + (cellSize + gridWidth) * halfNumSquaresX + gridWidth / 2);
startingY = (int) (boardMiddleY - (cellSize + gridWidth) * halfNumSquaresY - gridWidth / 2);
endingY = (int) (boardMiddleY + (cellSize + gridWidth) * halfNumSquaresY + gridWidth / 2);
float widthWithPadding = endingX - startingX;
// Text Dimensions
paint.setTextSize(cellSize);
textSize = cellSize * cellSize / Math.max(cellSize, paint.measureText("0000"));
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(1000);
instructionsTextSize = Math.min(
1000f * (widthWithPadding / (paint.measureText(getResources().getString(R.string.instructions)))),
textSize / 1.5f
);
gameOverTextSize = Math.min(
Math.min(
1000f * ((widthWithPadding - gridWidth * 2) / (paint.measureText(getResources().getString(R.string.game_over)))),
textSize * 2
),
1000f * ((widthWithPadding - gridWidth * 2) / (paint.measureText(getResources().getString(R.string.you_win))))
);
paint.setTextSize(cellSize);
cellTextSize = textSize;
titleTextSize = textSize / 3;
bodyTextSize = (int) (textSize / 1.5);
headerTextSize = textSize * 2;
textPaddingSize = (int) (textSize / 3);
iconPaddingSize = (int) (textSize / 5);
paint.setTextSize(titleTextSize);
int textShiftYAll = centerText();
//static variables
sYAll = (int) (startingY - cellSize * 1.5);
titleStartYAll = (int) (sYAll + textPaddingSize + titleTextSize / 2 - textShiftYAll);
bodyStartYAll = (int) (titleStartYAll + textPaddingSize + titleTextSize / 2 + bodyTextSize / 2);
titleWidthHighScore = (int) (paint.measureText(getResources().getString(R.string.high_score)));
titleWidthScore = (int) (paint.measureText(getResources().getString(R.string.score)));
paint.setTextSize(bodyTextSize);
textShiftYAll = centerText();
eYAll = (int) (bodyStartYAll + textShiftYAll + bodyTextSize / 2 + textPaddingSize);
sYIcons = (startingY + eYAll) / 2 - iconSize / 2;
sXNewGame = (endingX - iconSize);
sXUndo = sXNewGame - iconSize * 3 / 2 - iconPaddingSize;
resyncTime();
}
private int centerText() {
return (int) ((paint.descent() + paint.ascent()) / 2);
}
}
|
package sokoban.Elements;
import java.util.ArrayList;
import sokoban.Map;
public abstract class ElementMovable extends Element {
public abstract String Show();
public boolean Deplacer(String s, Map m)
{
//On rcupre la map
ArrayList<ArrayList<ElementNonMovable>> map = m.getStructure();
//On rcupre les lments mouvable :
ArrayList<ElementMovable> elMouv = m.getElemMouvable();
switch (s) {
case "z": // Si on veux dplacer vers le haut :
{
return testCollision(m, map, CoordonneeX,CoordonneeY-1);
}
case "s":
{
return testCollision(m, map, CoordonneeX,CoordonneeY+1);
}
case "q":
{
return testCollision(m, map, CoordonneeX-1,CoordonneeY);
}
case "d":
{
return testCollision(m, map, CoordonneeX+1,CoordonneeY);
}
default:
return false;
}
}
private boolean testCollision(Map m,ArrayList<ArrayList<ElementNonMovable>> map, int X, int Y) {
//Si on a un ElementNonMovable :
if( map.get(CoordonneeX).get(CoordonneeY-1) instanceof Wall)
{
return false;
}
else
{
//On parcourt le tableau d'lment mouvable :
ElementMovable el;
if( (el = m.getElemMovable(X, Y)) != null)
{
//Si on a une Box au dessus de Mario on tente de dplacer
if(!el.Deplacer("z", m))
{
return false;
}
}
this.CoordonneeY -= 1;
return true;
}
}
/*
* Reois la coordonnes X :
*/
public int getCoordonneeX()
{
return this.CoordonneeX;
}
/*
* Reoi la coordonnee Y :
*/
public int getCoordonneeY()
{
return this.CoordonneeY;
}
}
|
package yuku.alkitab.base.widget;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
public abstract class VerseInlineLinkSpan extends ClickableSpan {
public interface Factory {
VerseInlineLinkSpan create(final Type type, final int arif);
}
private final Type type;
private final int arif;
private final Object source;
public enum Type {
footnote,
xref,
}
public VerseInlineLinkSpan(final Type type, final int arif, final Object source) {
this.type = type;
this.arif = arif;
this.source = source;
}
@Override
public final void onClick(final View widget) {
onClick(type, arif, source);
}
public abstract void onClick(final Type type, final int arif, final Object source);
@Override
public void updateDrawState(final TextPaint ds) {
// don't call super to prevent link underline and link coloring
// NOP
}
}
|
package com.letscode.lcg.screens;
import net.engio.mbassy.listener.Handler;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.letscode.lcg.Assets;
import com.letscode.lcg.Context;
import com.letscode.lcg.actor.Board;
import com.letscode.lcg.actor.FieldActor;
import com.letscode.lcg.actor.ParticleSystem;
import com.letscode.lcg.enums.ActionCost;
import com.letscode.lcg.enums.BuildMode;
import com.letscode.lcg.enums.BuildingGoldCost;
import com.letscode.lcg.enums.CommandType;
import com.letscode.lcg.model.Field;
import com.letscode.lcg.network.Events;
import com.letscode.lcg.network.messages.GameEndMessage;
import com.letscode.lcg.network.messages.MoveDoneMessage;
import com.letscode.lcg.network.messages.MoveMessage;
import com.letscode.lcg.network.messages.NextPlayerMessage;
import com.letscode.lcg.network.messages.YourTurnMessage;
import com.letscode.ui.BaseScreen;
import com.letscode.ui.UiApp;
public class PlayScreen extends BaseScreen {
Context context;
Button endTurnButton;
Button buildTownhallButton, buildGoldmineButton, buildBarricadeButton;
Label actionPointsValueLabel, goldValueLabel, turnPlayerLabel;
Board board;
public PlayScreen(Context context) {
super(context.app);
this.context = context;
UiApp app = context.app;
Events.subscribe(this);
buildTownhallButton = new TextButton("Townhall", app.skin);
buildGoldmineButton = new TextButton("Goldmine", app.skin);
buildBarricadeButton = new TextButton("Barricade", app.skin);
Label actionPointsLabel = new Label("Action Points:", app.skin);
actionPointsValueLabel = new Label("0", app.skin);
Label goldLabel = new Label("Gold: ", app.skin);
goldValueLabel = new Label("0", app.skin);
Table statsTable = new Table(app.skin);
statsTable.add(actionPointsLabel);
statsTable.add(actionPointsValueLabel);
statsTable.row();
statsTable.add(goldLabel);
statsTable.add(goldValueLabel);
mainTable.add(statsTable);
// Setup things about player's turn
Table turnTable = new Table(app.skin);
turnPlayerLabel = new Label("hgw", app.skin);
turnPlayerLabel.setAlignment(Align.center);
setTurnPlayerLabel(context.network.getClientNickname());
endTurnButton = new TextButton("End turn", app.skin);
endTurnButton.addListener(endTurnButtonListener);
endTurnButton.setVisible(false);
turnTable.add(turnPlayerLabel).expandX().fill();
turnTable.row();
turnTable.add(endTurnButton).spaceTop(20);
mainTable.add(turnTable).expandX().fill();
// Setup build buttons
Table buttonsTable = new Table(app.skin);
buildTownhallButton = new TextButton("Townhall", app.skin);
buildTownhallButton.addListener(buildTownhallButtonListener);
buildGoldmineButton = new TextButton("Goldmine", app.skin);
buildGoldmineButton.addListener(buildGoldmineButtonListener);
buildBarricadeButton = new TextButton("Barricade", app.skin);
buildBarricadeButton.addListener(buildBarricadeButtonListener);
buttonsTable.add(buildTownhallButton);
buttonsTable.add(buildGoldmineButton);
buttonsTable.add(buildBarricadeButton);
mainTable.add(buttonsTable);
// Setup game board
board = new Board(context);
mainTable.row();
Table boardTable = new Table(app.skin);
boardTable.setBackground(new TextureRegionDrawable(Assets.backgroundTexture));
boardTable.setColor(Color.valueOf("C5D8C5"));
boardTable.add(board).expand().fill();
mainTable.add(boardTable).expand().fill().colspan(3);
mainTable.layout();
board.init();
board.addListener(boardListener);
context.app.setClearColor(Color.valueOf("9EAE9E"));
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
getStage().getCamera().update();
context.shapeRenderer.setProjectionMatrix(getStage().getCamera().combined);
}
private void setBuildMode(BuildMode buildMode) {
context.currentBuildMode = buildMode;
buildTownhallButton.setDisabled(true);
buildTownhallButton.setChecked(buildMode == BuildMode.Townhall);
buildTownhallButton.setDisabled(false);
buildGoldmineButton.setDisabled(true);
buildGoldmineButton.setChecked(buildMode == BuildMode.Goldmine);
buildGoldmineButton.setDisabled(false);
buildBarricadeButton.setDisabled(true);
buildBarricadeButton.setChecked(buildMode == BuildMode.Barricade);
buildBarricadeButton.setDisabled(false);
}
private void setTurnPlayerLabel(String playerName) {
boolean thisPlayerMoves = playerName.equals(context.getPlayerNickname());
String labelText = thisPlayerMoves ? "Now you move!" : (playerName != null ? playerName : "");
turnPlayerLabel.setText(labelText);
turnPlayerLabel.setColor(context.colorsForPlayers.get(playerName));
}
/**
* Checks if move is possible and then it's being made.
*
* @param fieldActor
*/
private void tryToMakeMove(FieldActor fieldActor) {
CommandType commandType = null;
boolean shouldSendCommand = false;
int rowIndex = fieldActor.getRowIndex();
int colIndex = fieldActor.getColIndex();
Field field = context.map.getField(rowIndex, colIndex);
String thisPlayerName = context.getPlayerNickname();
boolean isOwnedByPlayer = context.map.isFieldOwnedBy(thisPlayerName, rowIndex, colIndex);
boolean canPlayerBuildOnField = isOwnedByPlayer && field.building == null;
int currentActionPoints = Integer.parseInt(actionPointsValueLabel.getText().toString());
int currentGold = Integer.parseInt(goldValueLabel.getText().toString());
if (context.currentBuildMode == BuildMode.None) {
if (!isOwnedByPlayer) {
commandType = CommandType.conquer;
shouldSendCommand = context.map.canPlayerAttackField(thisPlayerName, rowIndex, colIndex)
&& currentActionPoints >= ActionCost.CONQUER_EMPTY_FIELD;
if (shouldSendCommand) {
if (field.building != null) {
field.building = null;
ParticleSystem explodeBuilding = new ParticleSystem("explode.ps");
explodeBuilding.setPosition(
fieldActor.getX() + fieldActor.getWidth() / 2,
fieldActor.getY() + fieldActor.getHeight() / 3);
explodeBuilding.toFront();
board.addActor(explodeBuilding);
}
else {
field.owner = thisPlayerName;
}
currentActionPoints -= ActionCost.CONQUER_EMPTY_FIELD;
}
}
else if (field.type.equals(Field.TYPE_GOLD)
&& currentActionPoints >= ActionCost.MINE_GOLD
&& field.building != null
&& field.building.equals(Field.BUILDING_GOLDMINE)) {
commandType = CommandType.mine_gold;
shouldSendCommand = true;
currentActionPoints -= ActionCost.MINE_GOLD;
}
}
else if (context.currentBuildMode == BuildMode.Townhall) {
commandType = CommandType.build_townhall;
shouldSendCommand = canPlayerBuildOnField
&& currentActionPoints >= ActionCost.BUILD_TOWNHALL
&& currentGold >= BuildingGoldCost.TOWNHALL;
if (shouldSendCommand) {
field.building = Field.BUILDING_TOWNHALL;
currentActionPoints -= ActionCost.BUILD_TOWNHALL;
currentGold -= BuildingGoldCost.TOWNHALL;
setBuildMode(BuildMode.None);
}
}
else if (context.currentBuildMode == BuildMode.Goldmine) {
commandType = CommandType.build_mine;
shouldSendCommand =
field.type.equals(Field.TYPE_GOLD)
&& canPlayerBuildOnField
&& currentActionPoints >= ActionCost.BUILD_MINE
&& currentGold >= BuildingGoldCost.GOLDMINE;
if (shouldSendCommand) {
field.building = Field.BUILDING_GOLDMINE;
currentActionPoints -= ActionCost.BUILD_MINE;
currentGold -= BuildingGoldCost.GOLDMINE;
setBuildMode(BuildMode.None);
}
}
else if (context.currentBuildMode == BuildMode.Barricade) {
commandType = CommandType.build_barricade;
shouldSendCommand = canPlayerBuildOnField
&& currentActionPoints >= ActionCost.BUILD_BARRICADE
&& currentGold >= BuildingGoldCost.BARRICADE;
if (shouldSendCommand) {
field.building = Field.BUILDING_BARRICADE;
currentActionPoints -= ActionCost.BUILD_BARRICADE;
currentGold -= BuildingGoldCost.BARRICADE;
setBuildMode(BuildMode.None);
}
}
if (shouldSendCommand) {
actionPointsValueLabel.setText(new Integer(currentActionPoints).toString());
goldValueLabel.setText(new Integer(currentGold).toString());
context.network.sendMakeMoveMessage(rowIndex, colIndex, commandType);
}
}
private void updateGoldAndActionPoints(int actionPoints, int gold) {
actionPointsValueLabel.setText(Integer.toString(actionPoints));
goldValueLabel.setText(Integer.toString(gold));
}
// Network Events
@Handler
public void moveHandler(MoveMessage message) {
Field fld = context.map.getField(message.row, message.col);
if (message.what == CommandType.conquer) {
// TODO: enable particle effect
if (fld.building != null) {
fld.building = null;
}
else {
fld.owner = message.who;
}
}
else if (message.what == CommandType.build_mine) {
fld.building = Field.BUILDING_GOLDMINE;
}
else if (message.what == CommandType.build_townhall) {
fld.building = Field.BUILDING_TOWNHALL;
}
else if (message.what == CommandType.build_barricade) {
fld.building = Field.BUILDING_BARRICADE;
}
}
@Handler
public void nextPlayerHandler(NextPlayerMessage message) {
setTurnPlayerLabel(message.nickname);
endTurnButton.setVisible(false);
}
@Handler
public void yourTurnHandler(YourTurnMessage message) {
endTurnButton.setVisible(true);
updateGoldAndActionPoints(message.actionPoints, message.gold);
setTurnPlayerLabel(context.getPlayerNickname());
}
@Handler
public void endGameMessage(GameEndMessage message) {
app.switchScreens(new GameResultScreen(context, message.winner));
}
@Handler
public void moveDoneHandler(MoveDoneMessage message) {
updateGoldAndActionPoints(message.actionPoints, message.gold);
if (message.actionPoints == 0) {
endTurnButton.setVisible(false);
}
}
// GUI Events
ClickListener buildTownhallButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
setBuildMode(buildTownhallButton.isChecked() ? BuildMode.Townhall : BuildMode.None);
super.clicked(event, x, y);
}
};
ClickListener buildGoldmineButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
setBuildMode(buildGoldmineButton.isChecked() ? BuildMode.Goldmine : BuildMode.None);
super.clicked(event, x, y);
}
};
ClickListener buildBarricadeButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
setBuildMode(buildBarricadeButton.isChecked() ? BuildMode.Barricade : BuildMode.None);
super.clicked(event, x, y);
}
};
EventListener boardListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Actor actor = event.getTarget() instanceof FieldActor ? (FieldActor) event.getTarget() : null;
if (actor != null) {
if (actor instanceof FieldActor) {
FieldActor fieldActor = (FieldActor)actor;
fieldActor.animateTouched();
if (fieldActor.getField() != null) {
tryToMakeMove(fieldActor);
}
}
}
};
};
ClickListener endTurnButtonListener = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
context.network.sendEndTurnMessage();
endTurnButton.setVisible(false);
}
};
@Override
public void act(float delta) {
super.act(delta);
context.network.update();
}
@Override
public void onBackPress() {}
}
|
package de.uka.ipd.sdq.beagle.core;
import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression;
import de.uka.ipd.sdq.beagle.core.judge.EvaluableExpressionFitnessFunction;
import de.uka.ipd.sdq.beagle.core.measurement.BranchDecisionMeasurementResult;
import de.uka.ipd.sdq.beagle.core.measurement.LoopRepetitionCountMeasurementResult;
import de.uka.ipd.sdq.beagle.core.measurement.ParameterChangeMeasurementResult;
import de.uka.ipd.sdq.beagle.core.measurement.ResourceDemandMeasurementResult;
import org.apache.commons.lang3.Validate;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Blackboard implements Serializable {
/**
* Serialisation version UID, see {@link java.io.Serializable}.
*/
private static final long serialVersionUID = 6382577321150787599L;
/**
* All measurable SEFF Elements.
*/
private final Set<MeasurableSeffElement> allSeffElements = new HashSet<>();
/**
* All Resource Demanding Internal Actions.
*/
private final Set<ResourceDemandingInternalAction> rdias = new HashSet<>();
/**
* All SEFF Branches.
*/
private final Set<SeffBranch> branches = new HashSet<>();
/**
* All SEFF Loops.
*/
private final Set<SeffLoop> loops = new HashSet<>();
/**
* All External Call Parameter.
*/
private final Set<ExternalCallParameter> externalCallParameters = new HashSet<>();
/**
* All resource demanding internal actions which are to be measured.
*/
private final Set<ResourceDemandingInternalAction> rdiasToBeMeasured = new HashSet<>();
/**
* All SEFF branches which are to be measured.
*/
private final Set<SeffBranch> branchesToBeMeasured = new HashSet<>();
/**
* All SEFF loops which are to be count.
*/
private final Set<SeffLoop> loopsToBeMeasured = new HashSet<>();
/**
* All external call parameter which are to be measured.
*/
private final Set<ExternalCallParameter> externalCallParameterToBeMeasured = new HashSet<>();
/**
* All resource demanding internal results.
*/
private final Map<ResourceDemandingInternalAction, Set<ResourceDemandMeasurementResult>> rdiasMeasurementResults =
new HashMap<>();
/**
* All SEFF branches results.
*/
private final Map<SeffBranch, Set<BranchDecisionMeasurementResult>> branchDecisionMeasurementResults =
new HashMap<>();
/**
* All SEFF loop count results.
*/
private final Map<SeffLoop, Set<LoopRepetitionCountMeasurementResult>> loopRepititionCountMeasurementResults =
new HashMap<>();
/**
* All parameter change results.
*/
private final Map<ExternalCallParameter, Set<ParameterChangeMeasurementResult>> parameterChangeMeasurementResults =
new HashMap<>();
/**
* All evaluable expressions.
*/
private final Map<MeasurableSeffElement, Set<EvaluableExpression>> proposedExpressions = new HashMap<>();
/**
* Is the final expression.
*/
private final Map<MeasurableSeffElement, EvaluableExpression> finalExpressions = new HashMap<>();
/**
* Is the function to get a better evaluable expression result.
*/
private final EvaluableExpressionFitnessFunction fitnessFunction;
/**
* Private data of tools, written through {@link #writeFor(Class, Serializable)}.
*/
private final Map<Class<? extends BlackboardStorer<? extends Serializable>>, Object> privateWrittenData =
new HashMap<>();
/**
* Creates a new blackboard that can be used to analyse the given elements.
*
* @param rdias All resource demanding internal action to be known to analysers.
* @param branches All SEFF branches to be known to analysers.
* @param loops All SEFF loops to be known to analysers.
* @param externalCalls All external call parameter to be known to analysers.
* @param fitnessFunction The function to get better evaluable expression results.
*/
public Blackboard(final Set<ResourceDemandingInternalAction> rdias, final Set<SeffBranch> branches,
final Set<SeffLoop> loops, final Set<ExternalCallParameter> externalCalls,
final EvaluableExpressionFitnessFunction fitnessFunction) {
Validate.noNullElements(rdias);
Validate.noNullElements(branches);
Validate.noNullElements(loops);
Validate.noNullElements(externalCalls);
Validate.notNull(fitnessFunction);
this.rdias.addAll(rdias);
this.branches.addAll(branches);
this.loops.addAll(loops);
this.externalCallParameters.addAll(externalCalls);
this.fitnessFunction = fitnessFunction;
this.allSeffElements.addAll(rdias);
this.allSeffElements.addAll(branches);
this.allSeffElements.addAll(loops);
this.allSeffElements.addAll(externalCalls);
for (final SeffBranch branch : this.branches) {
this.branchDecisionMeasurementResults.put(branch, new HashSet<>());
}
for (final SeffLoop loop : this.loops) {
this.loopRepititionCountMeasurementResults.put(loop, new HashSet<>());
}
for (final ExternalCallParameter parameter : this.externalCallParameters) {
this.parameterChangeMeasurementResults.put(parameter, new HashSet<>());
}
for (final ResourceDemandingInternalAction rdia : this.rdias) {
this.rdiasMeasurementResults.put(rdia, new HashSet<>());
}
for (final MeasurableSeffElement element : this.allSeffElements) {
this.proposedExpressions.put(element, new HashSet<>());
}
}
/**
* All {@linkplain ResourceDemandingInternalAction resource demanding internal
* actions} known to Beagle.
*
* @return all {@linkplain ResourceDemandingInternalAction resource demanding internal
* actions} known to Beagle. Changes to the returned set will not modify the
* blackboard content. Is never {@code null}.
*/
public Set<ResourceDemandingInternalAction> getAllRdias() {
return new HashSet<>(this.rdias);
}
/**
* All {@linkplain SeffBranch SEFF branches} known to Beagle.
*
* @return all {@linkplain SeffBranch SEFF branches} known to Beagle. Changes to the
* returned set will not modify the blackboard content. Is never {@code null}.
*/
public Set<SeffBranch> getAllSeffBranches() {
return new HashSet<>(this.branches);
}
/**
* All {@linkplain SeffLoop SEFF loops} known to Beagle.
*
* @return all {@linkplain SeffLoop SEFF loops} known to Beagle. Changes to the
* returned set will not modify the blackboard content. Is never {@code null}.
*/
public Set<SeffLoop> getAllSeffLoops() {
return new HashSet<>(this.loops);
}
/**
* Returns all {@linkplain ExternalCallParameter external call parameters} known to
* Beagle.
*
* @return All {@linkplain ExternalCallParameter external call parameters} known to
* Beagle. Is never {@code null}.
*/
public Set<ExternalCallParameter> getAllExternalCallParameters() {
return new HashSet<>(this.externalCallParameters);
}
/**
* {@linkplain ResourceDemandingInternalAction RDIAs} that shall be measured for their
* resource demands.
*
* @return All {@linkplain ResourceDemandingInternalAction resource demanding internal
* actions} to be measured. Changes to the returned set will not modify the
* blackboard content. Is never {@code null}.
*/
public Set<ResourceDemandingInternalAction> getRdiasToBeMeasured() {
return new HashSet<>(this.rdiasToBeMeasured);
}
/**
* {@linkplain SeffBranch SEFF branches} that shall be measured for their branch
* decisions.
*
* @return All {@linkplain SeffBranch SEFF branches} to be measured. Changes to the
* returned set will not modify the blackboard content. Is never {@code null}.
*/
public Set<SeffBranch> getSeffBranchesToBeMeasured() {
return new HashSet<>(this.branchesToBeMeasured);
}
/**
* {@linkplain SeffLoop SEFF loops} that shall be measured for their repetitions.
*
* @return All {@linkplain SeffLoop SEFF loops} to be measured. Changes to the
* returned set will not modify the blackboard content. Is never {@code null}.
*/
public Set<SeffLoop> getSeffLoopsToBeMeasured() {
return new HashSet<>(this.loopsToBeMeasured);
}
/**
* Returns all {@linkplain ExternalCallParameter external call parameters} which shall
* be measured.
*
* @return All {@linkplain ExternalCallParameter external call parameters} which shall
* be measured. Is never {@code null}.
*/
public Set<ExternalCallParameter> getExternalCallParametersToBeMeasured() {
return new HashSet<>(this.externalCallParameterToBeMeasured);
}
/**
* Reports that {@code rdias} shall be measured for its resource demands.
*
* @param toMeasureRdias Resource demanding internal actions that shall be measured.
* Must not be {@code null} and must be known to this blackboard.
* @see #addToBeMeasuredRdias(Collection)
*/
public void addToBeMeasuredRdias(final ResourceDemandingInternalAction... toMeasureRdias) {
Validate.noNullElements(toMeasureRdias);
Validate.isTrue(this.rdias.containsAll(Arrays.asList(toMeasureRdias)),
"toMeasureRdias may only contain elements that are already on the blackboard");
this.rdiasToBeMeasured.addAll(Arrays.asList(toMeasureRdias));
}
/**
* Reports that {@code rdias} shall be measured for its resource demands.
*
* @param toMeasureRdias Resource demanding internal actions that shall be measured.
* Must not be {@code null} and must be known to this blackboard.
* @see #addToBeMeasuredRdias(ResourceDemandingInternalAction...)
*/
public void addToBeMeasuredRdias(final Collection<ResourceDemandingInternalAction> toMeasureRdias) {
Validate.noNullElements(toMeasureRdias);
Validate.isTrue(this.rdias.containsAll(toMeasureRdias),
"toMeasureRdias may only contain elements that are already on the blackboard");
this.rdiasToBeMeasured.addAll(toMeasureRdias);
}
/**
* Reports that {@code branches} shall be measured for its branch decisions.
*
* @param toMeasureBranches SEFF branches that shall be measured. Must not be
* {@code null} and must be known to this blackboard.
* @see #addToBeMeasuredSeffBranches(Collection)
*/
public void addToBeMeasuredSeffBranches(final SeffBranch... toMeasureBranches) {
Validate.noNullElements(toMeasureBranches);
Validate.isTrue(this.branches.containsAll(Arrays.asList(toMeasureBranches)),
"toMeasureBranches may only contain elements that are already on the blackboard");
this.branchesToBeMeasured.addAll(Arrays.asList(toMeasureBranches));
}
/**
* Reports that {@code branches} shall be measured for its branch decisions.
*
* @param toMeasureBranches SEFF branches that shall be measured. Must not be
* {@code null} and must be known to this blackboard.
* @see #addToBeMeasuredSeffBranches(SeffBranch...)
*/
public void addToBeMeasuredSeffBranches(final Collection<SeffBranch> toMeasureBranches) {
Validate.noNullElements(toMeasureBranches);
Validate.isTrue(this.branches.containsAll(toMeasureBranches),
"toMeasureBranches may only contain elements that are already on the blackboard");
this.branchesToBeMeasured.addAll(toMeasureBranches);
}
/**
* Reports that {@code loops} shall be measured for its repetitions.
*
* @param toMeasureLoops SEFF Loops that shall be measured. Must not be {@code null}
* and must be known to this blackboard.
* @see #addToBeMeasuredSeffLoops(Collection)
*/
public void addToBeMeasuredSeffLoops(final SeffLoop... toMeasureLoops) {
Validate.noNullElements(toMeasureLoops);
Validate.isTrue(this.loops.containsAll(Arrays.asList(toMeasureLoops)),
"toMeasureLoops may only contain elements that are already on the blackboard");
this.loopsToBeMeasured.addAll(Arrays.asList(toMeasureLoops));
}
/**
* Reports that {@code loops} shall be measured for its repetitions.
*
* @param toMeasureLoops SEFF Loops that shall be measured. Must not be {@code null}
* and must be known to this blackboard.
* @see #addToBeMeasuredSeffLoops(SeffLoop...)
*/
public void addToBeMeasuredSeffLoops(final Collection<SeffLoop> toMeasureLoops) {
Validate.noNullElements(toMeasureLoops);
Validate.isTrue(this.loops.containsAll(toMeasureLoops),
"toMeasureLoops may only contain elements that are already on the blackboard");
this.loopsToBeMeasured.addAll(toMeasureLoops);
}
/**
* Reports that {@code parameters} shall be measured.
*
* @param parameters external call parameters that shall be measured. Must not be
* {@code null} and must be known to this blackboard.
* @see #addToBeMeasuredExternalCallParameters(Collection)
*/
public void addToBeMeasuredExternalCallParameters(final ExternalCallParameter... parameters) {
Validate.noNullElements(parameters);
Validate.isTrue(this.externalCallParameters.containsAll(Arrays.asList(parameters)),
"parameters may only contain elements that are already on the blackboard");
this.externalCallParameterToBeMeasured.addAll(Arrays.asList(parameters));
}
/**
* Reports that {@code parameters} shall be measured.
*
* @param parameters external call parameters that shall be measured. Must not be
* {@code null} and must be known to this blackboard.
* @see #addToBeMeasuredExternalCallParameters(ExternalCallParameter...)
*/
public void addToBeMeasuredExternalCallParameters(final Collection<ExternalCallParameter> parameters) {
Validate.noNullElements(parameters);
Validate.isTrue(this.externalCallParameters.containsAll(parameters),
"parameters may only contain elements that are already on the blackboard");
this.externalCallParameterToBeMeasured.addAll(parameters);
}
/**
* Clears the list of {@code rdiasToBeMeasured}.
*
*/
public void clearToBeMeasuredRdias() {
this.rdiasToBeMeasured.clear();
}
/**
* Clears the list of {@code branchesToBeMeasured}.
*
*/
public void clearToBeMeasuredBranches() {
this.branchesToBeMeasured.clear();
}
/**
* Clears the list of {@code loopsToBeMeasured}.
*
*/
public void clearToBeMeasuredLoops() {
this.loopsToBeMeasured.clear();
}
/**
* Clears the list of {@code externalCallParameterToBeMeasured}.
*
*/
public void clearToBeMeasuredExternalCalls() {
this.externalCallParameterToBeMeasured.clear();
}
/**
* Gets all results yet measured for the resource demands of {@code rdia}.
*
* @param rdia An resource demanding internal action to get the measurement results
* of. Must not be {@code null}.
* @return All measurement results reported for {@code rdia}. Changes to the returned
* set will not modify the blackboard content. Is never {@code null}.
*/
public Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(final ResourceDemandingInternalAction rdia) {
Validate.notNull(rdia);
Validate.isTrue(this.rdias.contains(rdia));
return new HashSet<>(this.rdiasMeasurementResults.get(rdia));
}
/**
* Gets all results yet measured for branch decisions of {@code branch}.
*
* @param branch A SEFF Branch to get the measurement results of. Must not be
* {@code null}.
* @return All measurement results reported for {@code branch}. Changes to the
* returned set will not modify the blackboard content. Is never {@code null}.
*/
public Set<BranchDecisionMeasurementResult> getMeasurementResultsFor(final SeffBranch branch) {
Validate.notNull(branch);
Validate.isTrue(this.branches.contains(branch));
return new HashSet<>(this.branchDecisionMeasurementResults.get(branch));
}
/**
* Gets all results yet measured for the loop repetitions of {@code loop}.
*
* @param loop A SEFF Loop to get the measurement results of. Must not be {@code null}
* .
* @return All measurement results reported for {@code loop}. Changes to the returned
* set will not modify the blackboard content. Is never {@code null}.
*/
public Set<LoopRepetitionCountMeasurementResult> getMeasurementResultsFor(final SeffLoop loop) {
Validate.notNull(loop);
Validate.isTrue(this.loops.contains(loop));
return new HashSet<>(this.loopRepititionCountMeasurementResults.get(loop));
}
/**
* Gets all results yet measured for the external parameter
* {@code externalCallParameter}.
*
* @param externalCallParameter An external parameter to get the measurement results
* of. Must not be {@code null}.
* @return All measurement results reported for {@code externalCallParameter}. Changes
* to the returned set will not modify the blackboard content. Is never
* {@code null}.
*/
public Set<ParameterChangeMeasurementResult> getMeasurementResultsFor(
final ExternalCallParameter externalCallParameter) {
Validate.notNull(externalCallParameter);
Validate.isTrue(this.externalCallParameters.contains(externalCallParameter));
return new HashSet<>(this.parameterChangeMeasurementResults.get(externalCallParameter));
}
/**
* Adds a measurement result for the provided {@code rdia}.
*
* @param rdia A resource demanding internal action that was measured. Must not be
* {@code null} .
* @param results The result of that measurement. Must not be {@code null}.
*/
public void addMeasurementResultFor(final ResourceDemandingInternalAction rdia,
final ResourceDemandMeasurementResult results) {
Validate.notNull(rdia);
Validate.notNull(results);
Validate.isTrue(this.rdias.contains(rdia), "rdia must already be on the blackboard");
this.rdiasMeasurementResults.get(rdia).add(results);
}
/**
* Adds a measurement result for the provided {@code branch}.
*
* @param branch A SEFF Branch which was measured. Must not be {@code null}.
* @param results The result of that measurement. Must not be {@code null}.
*/
public void addMeasurementResultFor(final SeffBranch branch, final BranchDecisionMeasurementResult results) {
Validate.notNull(branch);
Validate.notNull(results);
Validate.isTrue(this.branches.contains(branch), "branch must already be on the blackboard");
this.branchDecisionMeasurementResults.get(branch).add(results);
}
/**
* Adds a measurement result for the provided {@code loop}.
*
* @param loop A SEFF Loop which was measured. Must not be {@code null}.
* @param results The result of that measurement. Must not be {@code null}.
*/
public void addMeasurementResultFor(final SeffLoop loop, final LoopRepetitionCountMeasurementResult results) {
Validate.notNull(loop);
Validate.notNull(results);
Validate.isTrue(this.loops.contains(loop), "loop must already be on the blackboard");
this.loopRepititionCountMeasurementResults.get(loop).add(results);
}
/**
* Adds a measurement result for the provided {@code loop}.
*
* @param parameter An external call parameter which was measured. Must not be
* {@code null}.
* @param results The result of that measurement. Must not be {@code null}.
*/
public void addMeasurementResultFor(final ExternalCallParameter parameter,
final ParameterChangeMeasurementResult results) {
Validate.notNull(parameter);
Validate.notNull(results);
Validate.isTrue(this.externalCallParameters.contains(parameter), "parameter must already be on the blackboard");
this.parameterChangeMeasurementResults.get(parameter).add(results);
}
/**
* Returns a set of all {@linkplain EvaluableExpression evaluable expressions}
* proposed for {@code element}.
*
* @param element A SEFF element. Must not be {@code null}.
* @return A set of all {@linkplain EvaluableExpression evaluable expressions}
* proposed for {@code element}.
*/
public Set<EvaluableExpression> getProposedExpressionFor(final MeasurableSeffElement element) {
Validate.notNull(element);
Validate.isTrue(this.allSeffElements.contains(element), "element must already be on the blackboard");
return new HashSet<>(this.proposedExpressions.get(element));
}
public void addProposedExpressionFor(final MeasurableSeffElement element, final EvaluableExpression expression) {
Validate.notNull(element);
Validate.notNull(expression);
Validate.isTrue(this.allSeffElements.contains(element), "element must already be on the blackboard");
this.proposedExpressions.get(element).add(expression);
}
/**
* Returns the final expression set for {@code element}. The return value of this
* method may change if
* {@link #setFinalExpressionFor(MeasurableSeffElement, EvaluableExpression)} is
* called with the same {@code element} between calls to
* {@code addProposedExpressionFor} with this element as parameter.
*
* @param element A SEFF element. Must not be {@code null}.
* @return The expression momentarily marked to be the final for {@code element}.
* {@code null} if no expression has been marked yet.
*/
public EvaluableExpression getFinalExpressionFor(final MeasurableSeffElement element) {
Validate.notNull(element);
Validate.isTrue(this.allSeffElements.contains(element), "element must already be on the blackboard");
return this.finalExpressions.get(element);
}
public void setFinalExpressionFor(final MeasurableSeffElement element, final EvaluableExpression expression) {
Validate.notNull(element);
Validate.isTrue(this.allSeffElements.contains(element), "element must already be on the blackboard");
this.finalExpressions.put(element, expression);
}
/**
* Returns an object which holds and is responsible allows access to the fitness
* function grading {@linkplain EvaluableExpression evaluable expressions} regarding
* their fitness.
*
* @return An object which holds and is responsible allows access to the fitness
* function grading {@linkplain EvaluableExpression evaluable expressions}
* regarding their fitness.
*/
public EvaluableExpressionFitnessFunction getFitnessFunction() {
return this.fitnessFunction;
}
public <WRITTEN_TYPE extends Serializable> void writeFor(
final Class<? extends BlackboardStorer<WRITTEN_TYPE>> writer, final WRITTEN_TYPE written) {
Validate.notNull(writer);
this.privateWrittenData.put(writer, written);
}
/**
* Reads data previously written for {@code writer} through
* {@link #writeFor(Class, Serializable)}.
*
* @param writer The class the desired data was written for. Must not be {@code null}.
* @param <WRITTEN_TYPE> The type of the data to be read.
* @return The data written in the last call to {@linkplain #writeFor} for
* {@code writer}. {@code null} if no data has been written for {@code writer}
* yet.
* @see #writeFor(Class, Serializable)
*/
@SuppressWarnings("unchecked")
public <WRITTEN_TYPE extends Serializable> WRITTEN_TYPE readFor(
final Class<? extends BlackboardStorer<WRITTEN_TYPE>> writer) {
Validate.notNull(writer);
/*
* This performs a cast based on generics. While the cast can not be checked by
* the JVM at runtime, type safety is assured by the signature of {@link
* #writeFor}, which is the only method writing data to {@link
* #privateWrittenData}.
*/
return (WRITTEN_TYPE) this.privateWrittenData.get(writer);
}
}
|
package us.kbase.jgiintegration.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static us.kbase.jgiintegration.common.JGIUtils.wipeRemoteServer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMultipart;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import us.kbase.abstracthandle.AbstractHandleClient;
import us.kbase.abstracthandle.Handle;
import us.kbase.auth.AuthService;
import us.kbase.auth.AuthToken;
import us.kbase.common.service.JsonClientException;
import us.kbase.common.service.ServerException;
import us.kbase.common.service.Tuple2;
import us.kbase.jgiintegration.common.JGIFileLocation;
import us.kbase.jgiintegration.common.JGIOrganismPage;
import us.kbase.jgiintegration.common.JGIUtils.WipeException;
import us.kbase.shock.client.BasicShockClient;
import us.kbase.shock.client.ShockFileInformation;
import us.kbase.shock.client.ShockNode;
import us.kbase.shock.client.ShockNodeId;
import us.kbase.wipedev03.WipeDev03Client;
import us.kbase.workspace.ListObjectsParams;
import us.kbase.workspace.ObjectData;
import us.kbase.workspace.ObjectIdentity;
import us.kbase.workspace.ProvenanceAction;
import us.kbase.workspace.WorkspaceClient;
import us.kbase.workspace.WorkspaceIdentity;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.CollectingAlertHandler;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.github.fge.jsonpatch.diff.JsonDiff;
public class JGIIntegrationTest {
//TODO WAIT: may need to parallelize tests. If so print thread ID with all output
//should probably use slf4j instead of print statements, but can't be arsed for now
/* Set to true to write objects to the objects folder set below.
* This will overwrite the prior objects, so archive them if necessary
* first.
*/
private static final boolean SAVE_WS_OBJECTS = false;
private static final String WS_OBJECTS_FOLDER = "workspace_objects";
private static final boolean DEBUG_EMAIL = false;
private static final String WS_URL =
"https://dev03.berkeley.kbase.us/services/ws";
private static final String HANDLE_URL =
"https://dev03.berkeley.kbase.us/services/handle_service";
private static final String WIPE_URL =
"http://dev03.berkeley.kbase.us:9000";
private static final int PUSH_TO_WS_TIMEOUT_SEC = 30 * 60; //30min
private static final int PUSH_TO_WS_SLEEP_SEC = 5;
//for testing. If you're not wiping the database most likely you need to
//not test versions either.
private static final boolean SKIP_WIPE = false;
private static final boolean SKIP_VERSION_ASSERT = false;
private static final String EXT_JSON = ".json";
private static final String EXT_META_JSON = ".meta.json";
private static final String EXT_PROV_JSON = ".prov.json";
private static final String TYPE_READ_PREFIX =
"KBaseFile.PairedEndLibrary";
private static final String TYPE_ASSEMBLY_PREFIX =
"KBaseFile.AssemblyFile";
private static final String TYPE_ANNOTATION_PREFIX =
"KBaseFile.AnnotationFile";
private static final String FILELOC_READ = "lib1";
private static final String FILELOC_ASSEMBLY = "assembly_file";
private static final String FILELOC_ANNOTATION = "annotation_file";
private static final Map<String, String> TYPE_TO_FILELOC =
new HashMap<String, String>();
static {
TYPE_TO_FILELOC.put(TYPE_READ_PREFIX, FILELOC_READ);
TYPE_TO_FILELOC.put(TYPE_ASSEMBLY_PREFIX, FILELOC_ASSEMBLY);
TYPE_TO_FILELOC.put(TYPE_ANNOTATION_PREFIX, FILELOC_ANNOTATION);
}
private static String JGI_USER;
private static String JGI_PWD;
private static String KB_USER_1;
private static String KB_PWD_1;
private static String KB_USER_2;
private static String KB_PWD_2;
private static String KB_SHOCKADMIN_USER;
private static String KB_SHOCKADMIN_PWD;
private static Folder GMAIL;
private static String MAIL_SUBJECT_SUCCESS =
"JGI/KBase data transfer succeeded";
private static List<String> MAIL_BODY_SUCCESS_START =
new LinkedList<String>();
static {
MAIL_BODY_SUCCESS_START.add("Dear KBase user,");
MAIL_BODY_SUCCESS_START.add("Your data has been pushed to KBase.");
MAIL_BODY_SUCCESS_START.add("You can find your imported files at the links below.");
MAIL_BODY_SUCCESS_START.add("");
}
private static List<String> MAIL_BODY_SUCCESS_END =
new LinkedList<String>();
static {
MAIL_BODY_SUCCESS_END.add("");
MAIL_BODY_SUCCESS_END.add("");
MAIL_BODY_SUCCESS_END.add("Alternately, you can access the data in " +
"the 'Shared With Me' tab in the Narrative data panel. For " +
"more information, see the Push to KBase tutorial here: http://kbase.us/transfer-jgi-data/");
MAIL_BODY_SUCCESS_END.add("If you have any questions, please contact help@kbase.us");
MAIL_BODY_SUCCESS_END.add("JGI-KBase");
}
private static String MAIL_SUBJECT_FAIL = "JGI/KBase data transfer failed";
private static String MAIL_BODY_FAIL =
"\r\nDear KBase user, \r\n" +
"\r\n" +
"An unexpected error occurred while processing your upload request for %s.\r\n" +
"\r\n" +
"An email has been sent to\r\n" +
" the system administrators. If this is urgent, please contact help@kbase.us\r\n" +
"\r\n" +
"JGI-KBase";
private static AbstractHandleClient HANDLE_CLI;
private static WipeDev03Client WIPE;
private static final ObjectMapper SORTED_MAPPER = new ObjectMapper();
static {
SORTED_MAPPER.configure(
SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
}
@BeforeClass
public static void setUpClass() throws Exception {
Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
if (SAVE_WS_OBJECTS) {
System.out.println("Saving workspace objects to git repo");
}
if (SKIP_WIPE) {
System.out.println("Skipping wipe of test data stores");
}
if (SKIP_VERSION_ASSERT) {
System.out.println("Not testing object versions");
}
JGI_USER = System.getProperty("test.jgi.user");
JGI_PWD = System.getProperty("test.jgi.pwd");
KB_USER_1 = System.getProperty("test.kbase.user1");
KB_PWD_1 = System.getProperty("test.kbase.pwd1");
KB_USER_2 = System.getProperty("test.kbase.user2");
KB_PWD_2 = System.getProperty("test.kbase.pwd2");
KB_SHOCKADMIN_USER = System.getProperty("test.kbase.shockadmin.user");
KB_SHOCKADMIN_PWD = System.getProperty("test.kbase.shockadmin.pwd");
String gmailuser = System.getProperty("test.kbase.jgi.gmail.user");
String gmailpwd = System.getProperty("test.kbase.jgi.gmail.pwd");
String wipeUser = System.getProperty("test.kbase.wipe_user");
String wipePwd = System.getProperty("test.kbase.wipe_pwd");
if (!SKIP_WIPE) {
WIPE = wipeRemoteServer(new URL(WIPE_URL), wipeUser, wipePwd);
}
System.out.print("Connecting to gmail test account...");
Session session = Session.getInstance(new Properties());
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", gmailuser, gmailpwd);
GMAIL = store.getFolder("inbox");
System.out.println("Done.");
HANDLE_CLI = new AbstractHandleClient(
new URL(HANDLE_URL), KB_USER_1, KB_PWD_1);
HANDLE_CLI.setIsInsecureHttpConnectionAllowed(true);
HANDLE_CLI.setAllSSLCertificatesTrusted(true);
}
@AfterClass
public static void cleanUpClass() throws Exception {
// Check if the WS server is down after the tests
// if so then we should restart
System.out.println("Checking Workspace server status...");
try {
WorkspaceClient wsCli = new WorkspaceClient(new URL(WS_URL));
wsCli.setIsInsecureHttpConnectionAllowed(true);
wsCli.setAllSSLCertificatesTrusted(true);
wsCli.setConnectionReadTimeOut(5000);
System.out.println("Workspace is still running, version is: "
+ wsCli.ver());
} catch (Exception e) {
// we assume any exception means the server is down.
System.out.println("The Workspace service seems to be down, " +
"attempting a restart. Exception was: ");
e.printStackTrace();
Tuple2<Long, String> w = WIPE.restartWorkspace();
if (w.getE1() > 0 ) {
throw new WipeException(
"Restart of the test server failed. The wipe server said:\n"
+ w.getE2());
}
System.out.println("Restart was successful. Server said:\n" +
w.getE2());
}
}
private static class FileSpec {
private final JGIFileLocation location;
private final String type;
private final long expectedVersion;
private final String shockMD5;
/** note the workspace dummy MD5 is the workspace object with the
* variable handle contents replaced by the string "dummy"
*/
public FileSpec(JGIFileLocation location, String type,
long expectedVersion, String shockMD5) {
super();
this.location = location;
this.type = type;
this.expectedVersion = expectedVersion;
this.shockMD5 = shockMD5;
}
public JGIFileLocation getLocation() {
return location;
}
public String getType() {
return type;
}
public long getExpectedVersion() {
return expectedVersion;
}
public String getShockMD5() {
return shockMD5;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("FileSpec [location=");
builder.append(location);
builder.append(", type=");
builder.append(type);
builder.append(", expectedVersion=");
builder.append(expectedVersion);
builder.append(", shockMD5=");
builder.append(shockMD5);
builder.append("]");
return builder.toString();
}
}
private static class TestSpec {
private final String organismCode;
private final String kbaseUser;
private final String kbasePassword;
private final List<FileSpec> filespecs =
new LinkedList<JGIIntegrationTest.FileSpec>();
private final List<FileSpec> unselect =
new LinkedList<JGIIntegrationTest.FileSpec>();
public TestSpec(String organismCode, String kbaseUser,
String kbasePassword) {
if (organismCode == null) {
throw new NullPointerException(organismCode);
}
if (kbaseUser == null) {
throw new NullPointerException(kbaseUser);
}
if (kbasePassword == null) {
throw new NullPointerException(kbasePassword);
}
this.organismCode = organismCode;
this.kbaseUser = kbaseUser;
this.kbasePassword = kbasePassword;
}
public void addFileSpec(FileSpec spec) {
addFileSpec(spec, false);
}
public void addFileSpec(FileSpec spec, boolean unselect) {
filespecs.add(spec);
if (unselect) {
this.unselect.add(spec);
}
}
public String getOrganismCode() {
return organismCode;
}
public String getKBaseUser() {
return kbaseUser;
}
public String getKBasePassword() {
return kbasePassword;
}
public List<FileSpec> getFilespecs() {
return new LinkedList<FileSpec>(filespecs);
}
public List<FileSpec> getFilespecsToUnselect() {
return new LinkedList<FileSpec>(unselect);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TestSpec [organismCode=");
builder.append(organismCode);
builder.append(", kbaseUser=");
builder.append(kbaseUser);
builder.append(", kbasePassword=");
builder.append(kbasePassword);
builder.append(", filespecs=");
builder.append(filespecs);
builder.append(", unselect=");
builder.append(unselect);
builder.append("]");
return builder.toString();
}
}
private static class TestResult {
private final String shockID;
private final String shockURL;
private final String handleID;
private final String workspaceName;
public TestResult(String workspaceName, String shockID,
String shockURL, String handleID) {
super();
this.shockID = shockID;
this.shockURL = shockURL;
this.handleID = handleID;
this.workspaceName = workspaceName;
}
public String getShockID() {
return shockID;
}
public String getShockURL() {
return shockURL;
}
public String getHandleID() {
return handleID;
}
public String getWorkspaceName() {
return workspaceName;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TestResult [shockID=");
builder.append(shockID);
builder.append(", shockURL=");
builder.append(shockURL);
builder.append(", handleID=");
builder.append(handleID);
builder.append(", workspaceName=");
builder.append(workspaceName);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((handleID == null) ? 0 : handleID.hashCode());
result = prime * result
+ ((shockID == null) ? 0 : shockID.hashCode());
result = prime * result
+ ((shockURL == null) ? 0 : shockURL.hashCode());
result = prime * result
+ ((workspaceName == null) ? 0 : workspaceName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestResult other = (TestResult) obj;
if (handleID == null) {
if (other.handleID != null)
return false;
} else if (!handleID.equals(other.handleID))
return false;
if (shockID == null) {
if (other.shockID != null)
return false;
} else if (!shockID.equals(other.shockID))
return false;
if (shockURL == null) {
if (other.shockURL != null)
return false;
} else if (!shockURL.equals(other.shockURL))
return false;
if (workspaceName == null) {
if (other.workspaceName != null)
return false;
} else if (!workspaceName.equals(other.workspaceName))
return false;
return true;
}
}
@SuppressWarnings("serial")
private static class TestException extends RuntimeException {
public TestException(String msg) {
super(msg);
}
}
@Before
public void beforeTest() {
System.out.println("
}
@After
public void afterTest() {
System.out.println("
}
@Test
public void pushFailedEmail() throws Exception {
int emailTimeoutSec = 30 * 60;
System.out.print("Shutting down test workspace... ");
Tuple2<Long, String> w = WIPE.shutDownWorkspace();
if (w.getE1() > 0 ) {
throw new WipeException(
"Shutdown of the test server failed. The wipe server said:\n" +
w.getE2());
}
System.out.println("done. Server said:\n" + w.getE2());
Date start = new Date();
try {
TestSpec tspec = new TestSpec("BurspATCC52813", KB_USER_1,
KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC and Genome Assembly",
"final.assembly.fasta"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"5c66abbb2515674a074d2a41ecf01017"));
WebClient cli = new WebClient();
List<String> alerts = new LinkedList<String>();
String wsName = processTestSpec(tspec, cli,
new CollectingAlertHandler(alerts), false);
System.out.println(String.format(
"Finished push at UI level at %s for test %s",
new Date(), getTestMethodName()));
String body = getPtKBEmailBody(emailTimeoutSec, false);
String expectedBody = String.format(MAIL_BODY_FAIL, wsName);
assertThat("got correct failure email", body, is(expectedBody));
cli.closeAllWindows();
} catch (Exception e) {
restartWSonFail();
throw e;
} catch (AssertionError e) {
restartWSonFail();
throw e;
}
System.out.print("Restarting test workspace... ");
w = WIPE.restartWorkspace();
if (w.getE1() > 0 ) {
throw new WipeException(
"Restart of the test server failed. The wipe server said:\n" +
w.getE2());
}
System.out.println("done. Server said:\n" + w.getE2());
System.out.println("Test elapsed time: " +
calculateElapsed(start, new Date()));
}
private void restartWSonFail() throws IOException, JsonClientException {
System.out.println("Caught an exception while the workspace was " +
"down. Restarting workspace and throwing original " +
"exception.");
Tuple2<Long, String> w = WIPE.restartWorkspace();
if (w.getE1() > 0) {
System.out.println("Restart of the test server failed. " +
"The wipe server said:" + w.getE2());
}
}
@Test
public void pushSingleFile() throws Exception {
TestSpec tspec = new TestSpec("BlaspURHD0036", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"7625.2.79179.AGTTCC.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"5c66abbb2515674a074d2a41ecf01017"));
runTest(tspec);
}
@Test
public void pushSingleFileDeleteShockNodeAndRepush() throws Exception {
/* Tests JGI code that memoizes shocknodes for files that have been
* previously pushed.
*/
TestSpec tspec = new TestSpec("MarpieDSM16108", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"9364.7.131005.CTAGCT.anqdp.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"6bd062af06cf31f73eea9906bbe6ae85"));
TestResult tr = runTest(tspec).get(tspec.getFilespecs().get(0));
AuthToken token = AuthService.login(KB_SHOCKADMIN_USER,
KB_SHOCKADMIN_PWD).getToken();
BasicShockClient cli = new BasicShockClient(new URL(tr.getShockURL()),
token);
cli.getNode(new ShockNodeId(tr.getShockID())).delete();
TestSpec tspec2 = new TestSpec("MarpieDSM16108", KB_USER_1, KB_PWD_1);
tspec2.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"9364.7.131005.CTAGCT.anqdp.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 2L,
"6bd062af06cf31f73eea9906bbe6ae85"));
TestResult tr2 = runTest(tspec2).get(tspec2.getFilespecs().get(0));
assertThat("Used different shock node",
tr.getShockID().equals(tr2.getShockID()), is(false));
assertThat("Used different handle id",
tr.getHandleID().equals(tr2.getHandleID()), is(false));
}
@Test
public void pushAssembly() throws Exception {
TestSpec tspec = new TestSpec("LutspHel_I_33_5", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC and Genome Assembly",
"final.assembly.fasta"),
"KBaseFile.AssemblyFile-2.1", 1L,
"934f168f5e5a016e16efde3097c2632a"));
runTest(tspec);
}
@Test
public void rejectAnnotation() throws Exception {
TestSpec tspec = new TestSpec("ThaarcSCAB663P07", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("IMG Data",
"14052.assembled.gff",
true), //expect rejection
"KBaseFile.AnnotationFile-2.1", 1L,
"04c5df5bb396cb80842befb9ff47e35b"));
runTest(tspec);
}
//restore when we push annotations again
// @Test
// public void pushAnnotation() throws Exception {
// TestSpec tspec = new TestSpec("ThaarcSCAB663P07", KB_USER_1, KB_PWD_1);
// tspec.addFileSpec(new FileSpec(
// new JGIFileLocation("IMG Data",
// "14052.assembled.gff"),
// "KBaseFile.AnnotationFile-2.1", 1L,
// "04c5df5bb396cb80842befb9ff47e35b"));
// runTest(tspec);
@Test
public void pushTwoFiles() throws Exception {
TestSpec tspec = new TestSpec("AlimarDSM23064", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"6501.2.45840.GCAAGG.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"f0b44aae6c1714965dd345f368c7927a"));
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("Raw Data",
"6501.2.45840.GCAAGG.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"ff117914a28ffa48b520707e89fa683c"));
runTest(tspec);
}
@Test
public void pushTwoFilesSameGroup() throws Exception {
TestSpec tspec = new TestSpec("ColspSCAC281C22", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"6622.1.49213.GTCCGC.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"9e4d728e9e676086fb8f30c4f093274d"));
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"8440.1.101057.AGTCA.anqdp.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"5cb8fd67fa7514468daf560d2ce679fc"));
runTest(tspec);
}
@Test
public void pushSameFileWithSameClient() throws Exception {
FileSpec fs1 = new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"6787.4.54588.CTTGTA.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"b9a27bd18400c8c16285da69048fe15f");
FileSpec fs2 = new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"6787.4.54588.CTTGTA.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 2L,
"b9a27bd18400c8c16285da69048fe15f");
TestSpec tspec1 = new TestSpec("CanThiBermud0003", KB_USER_1, KB_PWD_1);
tspec1.addFileSpec(fs1);
TestSpec tspec2 = new TestSpec("CanThiBermud0003", KB_USER_1, KB_PWD_1);
tspec2.addFileSpec(fs2);
System.out.println("Starting test " + getTestMethodName());
Date start = new Date();
WebClient cli = new WebClient();
List<String> alerts = new LinkedList<String>();
String wsName = processTestSpec(tspec1, cli,
new CollectingAlertHandler(alerts), false);
System.out.println(String.format(
"Finished push at UI level at %s for test %s part 1",
new Date(), getTestMethodName()));
Map<FileSpec, TestResult> res1 = checkResults(tspec1, wsName);
processTestSpec(tspec2, cli, new CollectingAlertHandler(alerts), true);
System.out.println(String.format(
"Finished push at UI level at %s for test %s part 2",
new Date(), getTestMethodName()));
Map<FileSpec, TestResult> res2 = checkResults(tspec2, wsName);
cli.closeAllWindows();
System.out.println("Test elapsed time: " +
calculateElapsed(start, new Date()));
System.out.println();
assertThat("No alerts triggered", alerts.isEmpty(), is (true));
assertThat("Pushing same file twice uses same shock node",
res2.get(fs2), is(res1.get(fs1)));
}
@Test
public void pushSameFileWithDifferentClient() throws Exception {
FileSpec fs1 = new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"8446.4.101451.AGAAGA.anqdp.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"26306e5cc8f3178713df5e2f9594c894");
FileSpec fs2 = new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"8446.4.101451.AGAAGA.anqdp.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 2L,
"26306e5cc8f3178713df5e2f9594c894");
TestSpec tspec1 = new TestSpec("ActgenspDSM45722", KB_USER_1, KB_PWD_1);
tspec1.addFileSpec(fs1);
TestSpec tspec2 = new TestSpec("ActgenspDSM45722", KB_USER_1, KB_PWD_1);
tspec2.addFileSpec(fs2);
System.out.println("Starting test " + getTestMethodName());
Date start = new Date();
WebClient cli = new WebClient();
List<String> alerts = new LinkedList<String>();
String wsName = processTestSpec(tspec1, cli,
new CollectingAlertHandler(alerts), false);
System.out.println(String.format(
"Finished push at UI level at %s for test %s part 1",
new Date(), getTestMethodName()));
Map<FileSpec, TestResult> res1 = checkResults(tspec1, wsName);
cli = new WebClient(); //this is the only major difference from the same client test
processTestSpec(tspec2, cli, new CollectingAlertHandler(alerts), false);
System.out.println(String.format(
"Finished push at UI level at %s for test %s part 2",
new Date(), getTestMethodName()));
Map<FileSpec, TestResult> res2 = checkResults(tspec2, wsName);
cli.closeAllWindows();
System.out.println("Test elapsed time: " +
calculateElapsed(start, new Date()));
System.out.println();
assertThat("No alerts triggered", alerts.isEmpty(), is (true));
assertThat("Pushing same file twice uses same shock node",
res2.get(fs2), is(res1.get(fs1)));
}
@Test
public void pushSameFileDifferentUsers() throws Exception {
FileSpec fs1 = new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"6133.1.38460.TGCTGG.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"7952ee14bef7eb5d5aa55f41ff40dab7");
FileSpec fs2 = new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"6133.1.38460.TGCTGG.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"7952ee14bef7eb5d5aa55f41ff40dab7");
TestSpec tspec1 = new TestSpec("BacspJ001005J19_2", KB_USER_1,
KB_PWD_1);
tspec1.addFileSpec(fs1);
TestSpec tspec2 = new TestSpec("BacspJ001005J19_2", KB_USER_2,
KB_PWD_2);
tspec2.addFileSpec(fs2);
System.out.println("Starting test " + getTestMethodName());
Date start = new Date();
WebClient cli = new WebClient();
List<String> alerts = new LinkedList<String>();
String wsName = processTestSpec(tspec1, cli,
new CollectingAlertHandler(alerts), false);
System.out.println(String.format(
"Finished push at UI level at %s for test %s part 1",
new Date(), getTestMethodName()));
Map<FileSpec, TestResult> res1 = checkResults(tspec1, wsName);
wsName = processTestSpec(tspec2, cli, new CollectingAlertHandler(alerts), true);
System.out.println(String.format(
"Finished push at UI level at %s for test %s part 2",
new Date(), getTestMethodName()));
Map<FileSpec, TestResult> res2 = checkResults(tspec2, wsName);
cli.closeAllWindows();
System.out.println("Test elapsed time: " +
calculateElapsed(start, new Date()));
System.out.println();
assertThat("No alerts triggered", alerts.isEmpty(), is(true));
assertThat("Pushing same file twice uses same shock node",
res2.get(fs2).getShockID(), is(res1.get(fs1).getShockID()));
assertThat("Pushing same file twice uses same shock url",
res2.get(fs2).getShockURL(), is(res1.get(fs1).getShockURL()));
assertThat("Pushing same file twice uses same handle id",
res2.get(fs2).getHandleID(), is(res1.get(fs1).getHandleID()));
}
@Test
public void pushNothing() throws Exception {
TestSpec tspec = new TestSpec("BlaspURHD0036", KB_USER_1, KB_PWD_1); //if parallelize, change to unused page
List<String> alerts = new LinkedList<String>();
try {
runTest(tspec, new CollectingAlertHandler(alerts));
fail("Pushed without files selected");
} catch (ElementNotFoundException enfe) {
assertThat("Correct exception for alert test", enfe.getMessage(),
is("elementName=[form] attributeName=[name] attributeValue=[form]"));
}
Thread.sleep(1000); // wait for alert to finish
assertThat("Only one alert triggered", alerts.size(), is(1));
assertThat("Correct alert", alerts.get(0),
is("No JAMO files were selected for Push to KBase. Please use the checkboxes to select some files!"));
}
@Test
public void unselectAndPushNothing() throws Exception {
TestSpec tspec = new TestSpec("BlaspURHD0036", KB_USER_1, KB_PWD_1); //if parallelize, change to unused page
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"7625.2.79179.AGTTCC.adnq.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"5c66abbb2515674a074d2a41ecf01017"),
true); //unselect after selecting
List<String> alerts = new LinkedList<String>();
try {
runTest(tspec, new CollectingAlertHandler(alerts));
fail("Pushed without files selected");
} catch (ElementNotFoundException enfe) {
assertThat("Correct exception for alert test", enfe.getMessage(),
is("elementName=[form] attributeName=[name] attributeValue=[form]"));
}
Thread.sleep(1000); // wait for alert to finish
assertThat("Only one alert triggered", alerts.size(), is(1));
assertThat("Correct alert", alerts.get(0),
is("No JAMO files were selected for Push to KBase. Please use the checkboxes to select some files!"));
}
@Test
public void unselectAndPushOne() throws Exception {
TestSpec tspec = new TestSpec("GeobraDSM44526", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC Filtered Raw Data",
"8446.4.101451.ACGATA.anqdp.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"foo"),
true); //unselect after selecting
FileSpec spec = new FileSpec(new JGIFileLocation("Raw Data",
"8446.4.101451.ACGATA.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"04cc65af00b0b0cd0afc91b002798fb1");
tspec.addFileSpec(spec);
String wsName = runTest(tspec).get(spec).getWorkspaceName();
WorkspaceClient wsCli = new WorkspaceClient(
new URL(WS_URL), KB_USER_1, KB_PWD_1);
wsCli.setIsInsecureHttpConnectionAllowed(true);
wsCli.setAllSSLCertificatesTrusted(true);
assertThat("Only one object in workspace",
wsCli.listObjects(new ListObjectsParams()
.withWorkspaces(Arrays.asList(wsName))).size(), is(1));
}
@Test
public void rejectOneFile() throws Exception {
TestSpec tspec = new TestSpec("RosstaDSM19981_2", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC and Genome Assembly",
"QC.finalReport.pdf",
true), //expect rejection
"KBaseFile.PairedEndLibrary-2.1", 1L,
"foo1")
);
runTest(tspec);
}
@Test
public void rejectOnePushOne() throws Exception {
TestSpec tspec = new TestSpec("AllhisDSM15230", KB_USER_1, KB_PWD_1);
tspec.addFileSpec(new FileSpec(
new JGIFileLocation("QC and Genome Assembly",
"8327.8.98186.CTAGCT.artifact.clean.fastq.gz",
true), //expect rejection
"KBaseFile.PairedEndLibrary-2.1", 1L,
"foo")
);
FileSpec spec = new FileSpec(new JGIFileLocation("QC Filtered Raw Data",
"8327.8.98186.CTAGCT.anqdp.fastq.gz"),
"KBaseFile.PairedEndLibrary-2.1", 1L,
"a4d84286988f9c85aa6c7f0e4feee81b");
tspec.addFileSpec(spec);
String wsName = runTest(tspec).get(spec).getWorkspaceName();
WorkspaceClient wsCli = new WorkspaceClient(
new URL(WS_URL), KB_USER_1, KB_PWD_1);
wsCli.setIsInsecureHttpConnectionAllowed(true);
wsCli.setAllSSLCertificatesTrusted(true);
assertThat("Only one object in workspace",
wsCli.listObjects(new ListObjectsParams()
.withWorkspaces(Arrays.asList(wsName))).size(), is(1));
}
private Map<FileSpec, TestResult> runTest(TestSpec tspec)
throws Exception {
List<String> alerts = new LinkedList<String>();
Map<FileSpec, TestResult> res =
runTest(tspec, new CollectingAlertHandler(alerts));
assertThat("No alerts triggered", alerts.isEmpty(), is (true));
return res;
}
private Map<FileSpec, TestResult> runTest(
TestSpec tspec, AlertHandler handler)
throws Exception {
System.out.println("Starting test " + getTestMethodName());
Date start = new Date();
WebClient cli = new WebClient();
String wsName = processTestSpec(tspec, cli, handler, false);
System.out.println(String.format(
"Finished push at UI level at %s for test %s",
new Date(), getTestMethodName()));
Map<FileSpec, TestResult> res = checkResults(tspec, wsName);
cli.closeAllWindows();
System.out.println("Test elapsed time: " +
calculateElapsed(start, new Date()));
System.out.println();
return res;
}
private String processTestSpec(TestSpec tspec, WebClient cli,
AlertHandler handler, boolean skipLogin)
throws Exception {
cli.setAlertHandler(handler);
JGIOrganismPage org;
if (skipLogin) {
org = new JGIOrganismPage(cli, tspec.getOrganismCode(), null,
null);
} else {
org = new JGIOrganismPage(cli, tspec.getOrganismCode(),
JGI_USER, JGI_PWD);
}
for (FileSpec fs: tspec.getFilespecs()) {
org.selectFile(fs.getLocation());
}
for (FileSpec fs: tspec.getFilespecsToUnselect()) {
org.selectFile(fs.getLocation(), false);
}
System.out.print("Clearing test email account... ");
if (!GMAIL.isOpen()) {
GMAIL.open(Folder.READ_WRITE);
}
for (Message m: GMAIL.getMessages()) {
m.setFlag(Flags.Flag.DELETED, true);
}
GMAIL.expunge();
System.out.println("Done.");
org.pushToKBase(tspec.getKBaseUser(), tspec.getKBasePassword());
return org.getWorkspaceName(tspec.getKBaseUser());
}
private Map<FileSpec, TestResult> checkResults(
TestSpec tspec,
String workspace)
throws Exception {
System.out.println("Checking result in workspace " + workspace);
Map<FileSpec,TestResult> res = new HashMap<FileSpec, TestResult>();
Long start = System.nanoTime();
ObjectData wsObj = null;
WorkspaceClient wsClient = new WorkspaceClient(new URL(WS_URL),
tspec.getKBaseUser(), tspec.getKBasePassword());
wsClient.setIsInsecureHttpConnectionAllowed(true);
wsClient.setAllSSLCertificatesTrusted(true);
for (FileSpec fs: tspec.getFilespecs()) {
if (tspec.getFilespecsToUnselect().contains(fs)) {
continue;
}
if (fs.getLocation().isExpectedRejection()) {
continue;
}
while(wsObj == null) {
String fileName = fs.getLocation().getFile();
checkTimeout(start, PUSH_TO_WS_TIMEOUT_SEC,
String.format(
"Timed out attempting to access object %s with version %s in workspace %s after %s sec",
fileName, fs.getExpectedVersion(), workspace,
PUSH_TO_WS_TIMEOUT_SEC));
try {
wsObj = wsClient.getObjects(Arrays.asList(
new ObjectIdentity()
.withWorkspace(workspace)
.withName(fileName)))
.get(0);
if (wsObj.getInfo().getE5() < fs.getExpectedVersion()) {
wsObj = null;
}
} catch (ServerException se) {
if (se.getMessage() == null) {
System.out.println(String.format(
"Got null pointer in server exception at %s",
new Date()));
System.out.println(se.getData());
throw se;
}
String e1 = String.format(
"Object %s cannot be accessed: User %s may not read workspace %s",
fs.getLocation().getFile(), tspec.getKBaseUser(),
workspace);
if (!se.getMessage().equals(e1)) {
checkErrorAcceptable(fs, workspace, se.getMessage());
} //otherwise try again
Thread.sleep(PUSH_TO_WS_SLEEP_SEC * 1000);
}
}
System.out.println(String.format(
"Retrieved file from workspace after %s seconds",
((System.nanoTime() - start) / 1000000000)));
Map<String, String> wsmeta = wsClient.getWorkspaceInfo(
new WorkspaceIdentity().withWorkspace(workspace)).getE9();
Map<String, String> expectedMeta = new HashMap<String, String>();
expectedMeta.put("show_in_narrative_data_panel", "1");
assertThat("correct workspace metadata", wsmeta, is(expectedMeta));
res.put(fs, checkResults(wsObj, tspec, fs));
wsObj = null;
}
assertNoIllegalFilesPushed(tspec, workspace, wsClient);
checkEmail(workspace, tspec);
return res;
}
private void assertNoIllegalFilesPushed(TestSpec tspec, String workspace,
WorkspaceClient wsClient) throws Exception {
for (FileSpec fs: tspec.getFilespecs()) {
if (fs.getLocation().isExpectedRejection()) {
try {
wsClient.getObjects(Arrays.asList(
new ObjectIdentity()
.withWorkspace(workspace)
.withName(fs.getLocation().getFile())))
.get(0);
fail(String.format("Illegal file %s pushed",
fs.getLocation()));
} catch (ServerException se) {
if (se.getMessage() == null) {
System.out.println(
"Got null pointer in server exception");
System.out.println(se.getData());
throw se;
}
checkErrorAcceptable(fs, workspace, se.getMessage());
}
}
}
}
private void checkErrorAcceptable(FileSpec fs, String workspace,
String message) {
String e1 = String.format(
"Object %s cannot be accessed: No workspace with name %s exists",
fs.getLocation().getFile(), workspace);
String e2 = String.format(
"No object with name %s exists in workspace",
fs.getLocation().getFile());
if (message.equals(e1)) {
return;
}
if (message.startsWith(e2)) {
return;
}
System.out.println(String.format(
"Got unnacceptable exception at %s:", new Date()));
System.out.println(message);
fail("got unacceptable exception from workspace: " + message);
}
private TestResult checkResults(
ObjectData wsObj, TestSpec tspec, FileSpec fs)
throws Exception {
String fileContainerName = getFileContainerName(fs.getType());
System.out.println(String.format("checking file " + fs.getLocation()));
@SuppressWarnings("unchecked")
Map<String, Object> data = wsObj.getData().asClassInstance(Map.class);
@SuppressWarnings("unchecked")
Map<String, Object> fileContainer =
(Map<String, Object>) data.get(fileContainerName);
@SuppressWarnings("unchecked")
Map<String, Object> file =
(Map<String, Object>) fileContainer.get("file");
String hid = (String) file.get("hid");
String shockID = (String) file.get("id");
String url = (String) file.get("url");
file.put("hid", "dummy");
file.put("id", "dummy");
file.put("url", "dummy");
Map<String,String> meta = wsObj.getInfo().getE11();
String wsName = wsObj.getInfo().getE8();
List<ProvenanceAction> prov = wsObj.getProvenance();
if (SAVE_WS_OBJECTS) {
writeObjectAsJsonToFile(data, tspec, fs, EXT_JSON);
writeObjectAsJsonToFile(meta, tspec, fs, EXT_META_JSON);
writeObjectAsJsonToFile(prov, tspec, fs, EXT_PROV_JSON);
}
List<JsonNode> diffs = checkWorkspaceData(tspec, fs, data, meta, prov);
JsonNode datadiff = diffs.get(0);
JsonNode metadiff = diffs.get(1);
JsonNode provdiff = diffs.get(2);
Handle h = HANDLE_CLI.hidsToHandles(Arrays.asList(hid)).get(0);
AuthToken token = AuthService.login(tspec.getKBaseUser(),
tspec.getKBasePassword()).getToken();
BasicShockClient shock = new BasicShockClient(new URL(url), token,
true);
ShockNode node = shock.getNode(new ShockNodeId(shockID));
System.out.println("got shock MD5: " +
node.getFileInformation().getChecksum("md5"));
assertThat("no changes in workspace object", datadiff.size(),
is(0));
assertThat("no changes in workspace object metadata",
metadiff.size(), is(0));
assertThat("no changes in workspace object provenance",
provdiff.size(), is(0));
assertThat("object type correct", wsObj.getInfo().getE3(),
is(fs.getType()));
if (!SKIP_VERSION_ASSERT) {
assertThat("correct version of object", wsObj.getInfo().getE5(),
is(fs.getExpectedVersion()));
}
assertThat("no error from handle service", wsObj.getHandleStacktrace(),
is((String) null));
assertThat("handle type correct", h.getType(), is("shock"));
assertThat("handle hid correct", h.getHid(), is(hid));
assertThat("handle shock id correct", h.getId(), is(shockID));
assertThat("handle url correct", h.getUrl(), is(url));
//can't check ACLs, can only check that file is accessible
//need to be owner to see ACLs
ShockFileInformation sf = node.getFileInformation();
assertThat("Shock file md5 correct", sf.getChecksum("md5"),
is(fs.getShockMD5()));
assertThat("Shock filename correct", sf.getName(),
is(fs.getLocation().getFile()));
return new TestResult(wsName, shockID, url, hid);
}
private void checkEmail(String ws, TestSpec tspec) throws Exception {
int timeoutSec = 10 * 60;
int filecount = 0;
for (FileSpec fs: tspec.getFilespecs()) {
if (!fs.getLocation().isExpectedRejection() &&
!tspec.getFilespecsToUnselect().contains(fs)) {
filecount++;
}
}
if (filecount == 0) {
return;
}
String body = getPtKBEmailBody(timeoutSec, true);
checkEmailBody(ws, tspec, body);
}
private void debugEmail(String msg) {
if (DEBUG_EMAIL) {
System.out.println(msg);
}
}
private String getPtKBEmailBody(int timeoutSec, boolean success)
throws MessagingException, IOException, InterruptedException {
String subject = success ? MAIL_SUBJECT_SUCCESS : MAIL_SUBJECT_FAIL;
String body = null;
Long start = System.nanoTime();
System.out.print("Getting email... ");
while(body == null) {
debugEmail("");
checkTimeout(start, timeoutSec,
String.format(
"Timed out attempting to retrieve push " +
(success ? "success" : "fail") + " email after %s sec",
timeoutSec));
debugEmail("Opening gmail");
if (!GMAIL.isOpen()) {
GMAIL.open(Folder.READ_WRITE);
}
debugEmail("Getting messages");
for (Message m: GMAIL.getMessages()) {
debugEmail("Subject: " + m.getSubject());
if (body == null) {
if (m.getSubject().equals(subject)) {
MimeMultipart mm = (MimeMultipart) m.getContent();
body = mm.getBodyPart(0).getContent().toString();
}
}
debugEmail("Deleting message");
m.setFlag(Flags.Flag.DELETED, true); //clear the inbox after each test
}
debugEmail("Expunging");
GMAIL.expunge();
debugEmail("Sleeping");
Thread.sleep(PUSH_TO_WS_SLEEP_SEC * 1000);
}
System.out.println(String.format(
"retrieved " + (success ? "success" : "fail") +
" email after %s seconds",
((System.nanoTime() - start) / 1000000000)));
return body;
}
private void checkEmailBody(String ws, TestSpec tspec, String body) {
Map<String, String> expectedUrls = new HashMap<String, String>();
for (FileSpec fs: tspec.getFilespecs()) { //should probably make this a method in testspec
if (!fs.getLocation().isExpectedRejection() &&
!tspec.getFilespecsToUnselect().contains(fs)) {
expectedUrls.put(fs.getLocation().getFile(),
"https://narrative.kbase.us/functional-site/#/jgi/import/" +
ws + "/" + fs.getLocation().getFile());
}
}
String[] emailLines = body.split("\r\n");
int startlines = MAIL_BODY_SUCCESS_START.size();
int endlines = MAIL_BODY_SUCCESS_END.size();
List<String> emailStart = Arrays.asList(Arrays.copyOfRange(
emailLines, 0, startlines));
assertThat("correct email start recieved", emailStart,
is(MAIL_BODY_SUCCESS_START));
List<String> emailEnd = Arrays.asList(Arrays.copyOfRange(
emailLines, emailLines.length - endlines, emailLines.length));
assertThat("correct email end recieved", emailEnd,
is(MAIL_BODY_SUCCESS_END));
Map<String, String> rcvdUrls = new HashMap<String, String>();
List<String> urls = Arrays.asList(Arrays.copyOfRange(
emailLines, startlines, emailLines.length - endlines));
assertThat("url line count multiple of 3", urls.size() % 3, is(0));
for (int i = 0; i < urls.size(); i += 3) {
rcvdUrls.put(urls.get(i), urls.get(i + 1));
assertThat("blank line between urls", urls.get(i + 2), is(""));
}
assertThat("correct email urls", rcvdUrls, is(expectedUrls));
}
private String getFileContainerName(String type) {
for (String typePrefix: TYPE_TO_FILELOC.keySet()) {
if (type.startsWith(typePrefix)) {
return TYPE_TO_FILELOC.get(typePrefix);
}
}
throw new TestException("Unsupported type: " + type);
}
private List<JsonNode> checkWorkspaceData(TestSpec tspec, FileSpec fs,
Map<String, Object> wsdata, Map<String, String> wsmeta,
List<ProvenanceAction> prov)
throws Exception {
Map<String, Object> expectedData = loadWorkspaceObject(tspec, fs);
Map<String, String> expectedMeta = loadWorkspaceObjectMeta(tspec, fs);
List<ProvenanceAction> expectedProv =
loadWorkspaceObjectProvenance(tspec, fs);
JsonNode datadiff = checkDataEquivalent(expectedData, wsdata,
tspec, fs, "Workspace object", EXT_JSON);
JsonNode metadiff = checkDataEquivalent(expectedMeta, wsmeta,
tspec, fs, "Workspace object metadata", EXT_META_JSON);
JsonNode provdiff = checkDataEquivalent(expectedProv, prov,
tspec, fs, "Workspace object provenance", EXT_PROV_JSON);
return Arrays.asList(datadiff, metadiff, provdiff);
}
private JsonNode checkDataEquivalent(Object expectedData, Object data,
TestSpec tspec, FileSpec fs, String name, String ext) {
ObjectMapper mapper = new ObjectMapper();
JsonNode datadiff = JsonDiff.asJson(mapper.valueToTree(expectedData),
mapper.valueToTree(data));
if (datadiff.size() != 0) {
System.out.println(name + " changed:");
System.out.println(datadiff);
System.out.println("Original data at " +
getSavedDataFilePath(tspec, fs, ext));
}
return datadiff;
}
private void writeObjectAsJsonToFile(Object data,
TestSpec tspec, FileSpec fs, String extension) throws Exception {
Path p = getSavedDataFilePath(tspec, fs, extension);
BufferedWriter writer = Files.newBufferedWriter(p,
Charset.forName("UTF-8"));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValue(writer, data);
}
private Map<String, Object> loadWorkspaceObject(TestSpec tspec,
FileSpec fs) throws Exception {
BufferedReader reader = getReaderForFile(tspec, fs, EXT_JSON);
@SuppressWarnings("unchecked")
Map<String, Object> data = new ObjectMapper()
.readValue(reader, Map.class);
reader.close();
return data;
}
private Map<String, String> loadWorkspaceObjectMeta(TestSpec tspec,
FileSpec fs) throws Exception {
BufferedReader reader = getReaderForFile(tspec, fs,
EXT_META_JSON);
@SuppressWarnings("unchecked")
Map<String, String> meta = new ObjectMapper()
.readValue(reader, Map.class);
reader.close();
return meta;
}
private List<ProvenanceAction> loadWorkspaceObjectProvenance(
TestSpec tspec, FileSpec fs) throws Exception {
BufferedReader reader = getReaderForFile(tspec, fs,
EXT_PROV_JSON);
@SuppressWarnings("unchecked")
List<ProvenanceAction> prov = new ObjectMapper().readValue(reader,
List.class);
reader.close();
return prov;
}
private BufferedReader getReaderForFile(TestSpec tspec,
FileSpec fs, String extension) throws Exception {
Path p = getSavedDataFilePath(tspec, fs, extension);
BufferedReader reader = Files.newBufferedReader(p,
Charset.forName("UTF-8"));
return reader;
}
private Path getSavedDataFilePath(TestSpec tspec, FileSpec fs,
String extension) {
String filesep = "%-%";
String filename = tspec.getOrganismCode() + filesep +
fs.getLocation().getGroup().replace(' ', '_') + filesep +
fs.getLocation().getFile() + extension;
return Paths.get(WS_OBJECTS_FOLDER, filename).toAbsolutePath();
}
private String getTestMethodName() {
Exception e = new Exception();
e.fillInStackTrace();
for (int i = 1; i < 4; i++) {
if (!e.getStackTrace()[i].getMethodName().equals("runTest")) {
return e.getStackTrace()[i].getMethodName();
}
}
throw new TestException("Couldn't get test method name");
}
private static void checkTimeout(Long startNanos, int timeoutSec,
String message) {
if ((System.nanoTime() - startNanos) / 1000000000 > timeoutSec) {
System.out.println(message);
throw new TestException(message);
}
}
public static String calculateElapsed(Date start, Date complete) {
double secdiff = ((double) (complete.getTime() - start.getTime()))
/ 1000.0;
long hours = (long) secdiff / 3600;
long mins = (long) secdiff / 60;
double secs = secdiff % 60;
return hours + "h " + mins + "m " + String.format("%.3fs", secs);
}
}
|
package de.mibtex.export;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import de.mibtex.BibtexEntry;
import de.mibtex.BibtexViewer;
import de.mibtex.citationservice.CitationEntry;
/**
* A class that generates a .csv file with all BibTeX entries for the citation
* service
*
* @author Christopher Sontag
*/
public class ExportCitations extends Export {
public ExportCitations(String path, String file) throws Exception {
super(path, file);
}
@Override
public void writeDocument() {
List<CitationEntry> newCitations = new ArrayList<CitationEntry>();
List<CitationEntry> citations = readCitationFile(new File(
BibtexViewer.CITATION_DIR, "citations.csv"));
for (BibtexEntry entry : entries.values()) {
CitationEntry newEntry = new CitationEntry(entry.key,
BibtexEntry.toURL(entry.title), -1, 0);
if (citations.contains(newEntry)) {
newCitations.add(citations.get(citations.indexOf(newEntry)));
} else {
newCitations.add(newEntry);
}
}
writeCitationFile(new File(BibtexViewer.CITATION_DIR, "citations.csv"),
newCitations);
}
protected List<CitationEntry> readCitationFile(File file) {
System.out.print("Reading " + file.getName() + "... ");
List<CitationEntry> entries = new ArrayList<CitationEntry>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
for (String line; (line = br.readLine()) != null;) {
entries.add(CitationEntry.getFromCSV(line));
}
} catch (IOException e) {
System.out.println("IOException for " + file.getAbsolutePath());
}
System.out.println("done.");
return entries;
}
protected void writeCitationFile(File file, List<CitationEntry> entries) {
System.out.print("Updating " + file.getName() + "... ");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
for (CitationEntry entry : entries) {
out.append(entry.getCSVString());
}
out.close();
} catch (FileNotFoundException e) {
System.out.println("Not found " + file.getAbsolutePath());
} catch (IOException e) {
System.out.println("IOException for " + file.getAbsolutePath());
}
System.out.println("done.");
}
}
|
package org.ilrt.mca;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Mike Jones (mike.a.jones@bristol.ac.uk)
*/
public class Common {
// TODO look at using JodaTime to parse XSD dates
private Common() {
}
public static String parseXsdDate(final Date date) {
String temp = new SimpleDateFormat(DATE_FORMAT_STRING).format(date);
return temp.substring(0, temp.length() - 2) + ":"
+ temp.substring(temp.length() - 2, temp.length());
}
public static Date parseXsdDate(final String XsdDate) throws ParseException {
String temp = XsdDate.substring(0, XsdDate.length() - 3)
+ XsdDate.substring(XsdDate.length() - 2, XsdDate.length());
return new SimpleDateFormat(DATE_FORMAT_STRING).parse(temp);
}
public static String parseDate(final Date date) throws ParseException {
return new SimpleDateFormat(DATE_FORMAT_STRING).format(date);
}
// TODO ICKY QUICK FIX - LOOK AT JODA TIME FOR XSD DATE FORMATS
public static Date parseDate(String date) throws ParseException {
if (date.endsWith("Z")) {
date = date.substring(0, date.length() - 1);
}
return new SimpleDateFormat(DATE_FORMAT_STRING_WITHOUT_TZ).parse(date);
}
private static String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ssZ";
private static String DATE_FORMAT_STRING_WITHOUT_TZ = "yyyy-MM-dd'T'HH:mm:ss";
public static String MCA_STUB = "mca://registry/";
public static String TEMPLATE_STUB = "template:
public static String AUDIT_GRAPH_URI = "mca://audit/";
/**
* This method closes all opened tags in the provided string
* e.g. "hello <b>world" => "hello <b>world</b>"<br/>
* Designed for xhtml strings. Has an issue with non-xml tags such as <br><br/>
* as having and odd number will case an additional <br> to be added to the end of the string.
*
* @param s
* @return String with all opened tags closed
*/
public static String closeAllTags(String s)
{
// first clean up any unclosed tag
s = s.replaceAll("<[^>]*$", "");
// token matches a word, tag, or special character
Pattern token = Pattern.compile("<\\/?([^> ]+)[^>]*\\/?>");
int charCount = 0;
Stack openTags = new Stack();
// Set the default for the max number of characters
// (only counts characters outside of HTML tags)
int maxChars = s.length();
Matcher myMatcher = token.matcher(s);
while ((charCount < maxChars) && (myMatcher.find())) {
//Find the next tag
String tag = myMatcher.group(1);
// if this tag matches a closing tag, remove from stack
if (!openTags.empty() && openTags.peek().toString().equals(tag)) openTags.pop();
// else add to stack
else openTags.push(tag);
}
// Close any tags which were left open
while (!openTags.empty()) s += "</" + openTags.pop().toString() + ">";
return s;
}
}
|
package com.flytxt.tp.store;
import java.io.IOException;
import com.flytxt.tp.marker.Marker;
import com.flytxt.tp.marker.MarkerSerDer;
import com.flytxt.tp.store.chronicle.ChronicleWriter;
import com.flytxt.tp.store.chronicle.StreamData;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class StreamStore implements Store {
private MarkerSerDer serDer = new MarkerSerDer();
private ChronicleWriter<StreamData> queueWriter;
private StreamData streamData = new StreamData();
private String baseDir = "/tmp/tx-processor";
private String fileName = "";
public StreamStore(String baseDir, String... args) {
super();
this.baseDir = baseDir.endsWith("/") ? baseDir : baseDir + "/";
this.queueWriter = new ChronicleWriter<>(this.baseDir);
queueWriter.init();
}
@Override
public void set(String fileName) {
this.fileName = fileName;
}
@Override
public synchronized void save(byte[] data, String fileName, Marker... markers) throws IOException {
byte[] serData = serDer.toBytes(markers);
streamData.setBytes(serData);
queueWriter.write(streamData);
}
@Override
public String done() throws IOException {
log.info("[StreamStore|done|File processed: {}]", fileName);
return null;
}
@Override
public void close() throws Exception {
if (queueWriter != null) {
queueWriter.destroy();
}
}
}
|
package me.dslztx.assist.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;
/**
* @author dslztx
*/
public class CharCodingAssist {
public static byte[] encode(String str, Charset charset) {
if (StringAssist.isBlank(str)) {
return null;
}
if (charset == null) {
throw new RuntimeException("charset is null");
}
return str.getBytes(charset);
}
public static String decode(byte[] bytes, Charset charset) {
if (ArrayAssist.isEmpty(bytes)) {
return null;
}
if (charset == null) {
throw new RuntimeException("charset is null");
}
return new String(bytes, charset);
}
public static String unescapedHTMLEscapeSequence(String s) {
if (StringAssist.isBlank(s)) {
return s;
}
StringBuilder sb = new StringBuilder();
StringBuilder buffer = new StringBuilder();
char c;
for (int index = 0; index < s.length(); index++) {
c = s.charAt(index);
if (c == '&') {
if (buffer.length() == 0) {
buffer.append(c);
} else {
sb.append(buffer.toString());
buffer.setLength(0);
buffer.append(c);
}
} else if (c == '
if (buffer.length() == 1) {
buffer.append(c);
} else {
if (buffer.length() > 0) {
sb.append(buffer.toString());
buffer.setLength(0);
}
sb.append(c);
}
} else if (c == 'x' || c == 'X') {
if (buffer.length() == 2) {
buffer.append(c);
} else {
if (buffer.length() > 0) {
sb.append(buffer.toString());
buffer.setLength(0);
}
sb.append(c);
}
} else if (CharAssist.isDigitChar(c) || CharAssist.isHexChar(c)) {
if (CharAssist.isDigitChar(c)) {
if (buffer.length() >= 2) {
buffer.append(c);
} else {
if (buffer.length() > 0) {
sb.append(buffer.toString());
buffer.setLength(0);
}
sb.append(c);
}
} else {
if (buffer.length() > 2 && (buffer.charAt(2) == 'X' || buffer.charAt(2) == 'x')) {
buffer.append(c);
} else {
if (buffer.length() > 0) {
sb.append(buffer.toString());
buffer.setLength(0);
}
sb.append(c);
}
}
} else if (c == ';') {
if (buffer.length() > 2) {
if (buffer.length() == 3 && (buffer.charAt(2) == 'x' || buffer.charAt(2) == 'X')) {
sb.append(buffer.toString());
buffer.setLength(0);
sb.append(c);
} else {
try {
buffer.append(c);
sb.append(charFromHTMLEscapeSequence(buffer.toString()));
} catch (NumberFormatException e) {
sb.append(buffer.toString());
}
buffer.setLength(0);
}
} else {
if (buffer.length() > 0) {
sb.append(buffer.toString());
buffer.setLength(0);
}
sb.append(c);
}
} else {
if (buffer.length() > 0) {
sb.append(buffer.toString());
buffer.setLength(0);
}
sb.append(c);
}
}
return sb.toString();
}
public static char charFromHTMLEscapeSequence(String s) throws NumberFormatException {
if (StringAssist.isEmpty(s) || s.length() < 4) {
throw new NumberFormatException("illegal html escape sequence");
}
if (s.charAt(0) != '&' || s.charAt(1) != '#' || s.charAt(s.length() - 1) != ';') {
throw new NumberFormatException("illegal html escape sequence");
}
int start = 2;
int end = s.length() - 2;
if (s.charAt(start) == 'x' || s.charAt(start) == 'X') {
if (start + 1 == end) {
throw new NumberFormatException("illegal html escape sequence");
}
int value = NumberAssist.hexStrToDec(s, start + 1, end);
return (char)value;
} else {
int value = NumberAssist.decStrToDec(s, start, end);
return (char)value;
}
}
public static boolean isFileNotEncodedWith(File file, Charset charset) throws IOException {
if (file == null || !file.exists()) {
throw new RuntimeException("file not exists");
}
if (charset == null) {
throw new RuntimeException("charset not specify");
}
byte[] direct = IOUtils.toByteArray(new FileInputStream(file));
String ss = new String(direct, charset);
byte[] indirect = ss.getBytes(charset);
return !Arrays.equals(direct, indirect);
}
public static void main(String[] args) {
String a = "";
String b =
CharCodingAssist.decode(CharCodingAssist.encode("", Charset.forName("GBK")), Charset.forName("GBK"));
System.out.println(a.equals(b));
}
}
|
package org.atlasapi.neo4j;
import org.neo4j.driver.v1.AuthToken;
import org.neo4j.driver.v1.Config;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import static com.google.common.base.Preconditions.checkNotNull;
public class Neo4jSessionFactory {
private final Driver driver;
private Neo4jSessionFactory(Driver driver) {
this.driver = checkNotNull(driver);
}
public static Neo4jSessionFactory create(
String host, int port, AuthToken authToken, int maxIdleSessions
) {
return new Neo4jSessionFactory(GraphDatabase
.driver(
"bolt://" + checkNotNull(host) + ":" + port,
checkNotNull(authToken),
Config.build()
.withMaxIdleSessions(maxIdleSessions)
.withEncryptionLevel(Config.EncryptionLevel.NONE)
.toConfig()
));
}
public Session getSession() {
return driver.session();
}
public void close() {
driver.close();
}
}
|
package com.microsoft.azure;
import com.microsoft.rest.RestException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/**
* Defines a list response from a paging operation. The pages are
* lazy initialized when an instance of this class is iterated.
*
* @param <E> the element type.
*/
public abstract class PagedList<E> implements List<E> {
/** The actual items in the list. */
private List<E> items;
/** Stores the latest page fetched. */
private Page<E> currentPage;
/** Cached page right after the current one. */
private Page<E> cachedPage;
/**
* Creates an instance of Pagedlist.
*/
public PagedList() {
items = new ArrayList<>();
}
/**
* Creates an instance of PagedList from a {@link Page} response.
*
* @param page the {@link Page} object.
*/
public PagedList(Page<E> page) {
this();
List<E> retrievedItems = page.getItems();
if (retrievedItems != null) {
items.addAll(retrievedItems);
}
currentPage = page;
cachePage(page.getNextPageLink());
}
private void cachePage(String nextPageLink) {
try {
while (nextPageLink != null) {
cachedPage = nextPage(nextPageLink);
nextPageLink = cachedPage.getNextPageLink();
if (hasNextPage()) {
// a legit, non-empty page has been fetched, otherwise keep fetching
break;
}
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
/**
* Override this method to load the next page of items from a next page link.
*
* @param nextPageLink the link to get the next page of items.
* @return the {@link Page} object storing a page of items and a link to the next page.
* @throws RestException thrown if an error is raised from Azure.
* @throws IOException thrown if there's any failure in deserialization.
*/
public abstract Page<E> nextPage(String nextPageLink) throws RestException, IOException;
/**
* If there are more pages available.
*
* @return true if there are more pages to load. False otherwise.
*/
public boolean hasNextPage() {
return this.cachedPage != null && this.cachedPage.getItems() != null && !this.cachedPage.getItems().isEmpty();
}
/**
* Loads a page from next page link.
* The exceptions are wrapped into Java Runtime exceptions.
*/
public void loadNextPage() {
this.currentPage = cachedPage;
cachedPage = null;
this.items.addAll(currentPage.getItems());
cachePage(currentPage.getNextPageLink());
}
/**
* Keep loading the next page from the next page link until all items are loaded.
*/
public void loadAll() {
while (hasNextPage()) {
loadNextPage();
}
}
/**
* Gets the latest page fetched.
*
* @return the latest page.
*/
public Page<E> currentPage() {
return currentPage;
}
/**
* Sets the current page.
*
* @param currentPage the current page.
*/
protected void setCurrentPage(Page<E> currentPage) {
this.currentPage = currentPage;
List<E> retrievedItems = currentPage.getItems();
if (retrievedItems != null) {
items.addAll(retrievedItems);
}
cachePage(currentPage.getNextPageLink());
}
/**
* The implementation of {@link ListIterator} for PagedList.
*/
private class ListItr implements ListIterator<E> {
/** The list iterator for the actual list of items. */
private ListIterator<E> itemsListItr;
/**
* Creates an instance of the ListIterator.
*
* @param index the position in the list to start.
*/
ListItr(int index) {
itemsListItr = items.listIterator(index);
}
@Override
public boolean hasNext() {
return itemsListItr.hasNext() || hasNextPage();
}
@Override
public E next() {
if (!itemsListItr.hasNext()) {
if (!hasNextPage()) {
throw new NoSuchElementException();
} else {
int size = items.size();
loadNextPage();
itemsListItr = items.listIterator(size);
}
}
return itemsListItr.next();
}
@Override
public void remove() {
itemsListItr.remove();
}
@Override
public boolean hasPrevious() {
return itemsListItr.hasPrevious();
}
@Override
public E previous() {
return itemsListItr.previous();
}
@Override
public int nextIndex() {
return itemsListItr.nextIndex();
}
@Override
public int previousIndex() {
return itemsListItr.previousIndex();
}
@Override
public void set(E e) {
itemsListItr.set(e);
}
@Override
public void add(E e) {
itemsListItr.add(e);
}
}
@Override
public int size() {
loadAll();
return items.size();
}
@Override
public boolean isEmpty() {
return items.isEmpty() && !hasNextPage();
}
@Override
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
@Override
public Iterator<E> iterator() {
return new ListItr(0);
}
@Override
public Object[] toArray() {
loadAll();
return items.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
loadAll();
return items.toArray(a);
}
@Override
public boolean add(E e) {
return items.add(e);
}
@Override
public boolean remove(Object o) {
return items.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object e : c) {
if (!contains(e)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends E> c) {
return items.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
return items.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
return items.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return items.retainAll(c);
}
@Override
public void clear() {
items.clear();
}
@Override
public E get(int index) {
while (index >= items.size() && hasNextPage()) {
loadNextPage();
}
return items.get(index);
}
@Override
public E set(int index, E element) {
return items.set(index, element);
}
@Override
public void add(int index, E element) {
items.add(index, element);
}
@Override
public E remove(int index) {
return items.remove(index);
}
@Override
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (E item : this) {
if (item == null) {
return index;
}
++index;
}
} else {
for (E item : this) {
if (item == o) {
return index;
}
++index;
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
loadAll();
return items.lastIndexOf(o);
}
@Override
public ListIterator<E> listIterator() {
return new ListItr(0);
}
@Override
public ListIterator<E> listIterator(int index) {
while (index >= items.size() && hasNextPage()) {
loadNextPage();
}
return new ListItr(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
while ((fromIndex >= items.size()
|| toIndex >= items.size())
&& hasNextPage()) {
loadNextPage();
}
return items.subList(fromIndex, toIndex);
}
}
|
package com.github.vignesh_iopex.oplog;
import org.bson.Document;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
public class Runner {
/** Filter non empty name space and process document to return Json string */
public static Observable<String> applyOperators(Observable<Document> observable) {
return observable.filter(new Func1<Document, Boolean>() {
@Override public Boolean call(Document document) {
return document.getString("ns").equals("safetraxV2.trips");
}
}).map(new Func1<Document, String>() {
@Override public String call(Document o) {
return o.toJson();
}
});
}
public static void main(String[] args) {
Observable<String> tailable = applyOperators(RxOplog.connect("localhost", 27017).tail());
tailable.subscribe(new Subscriber<String>() {
@Override public void onCompleted() {
System.out.println("Job listening to oplog is terminated");
}
@Override public void onError(Throwable e) {
e.printStackTrace();
}
@Override public void onNext(String s) {
System.out.println(s);
}
});
}
}
|
package com.idogfooding.backbone.browser;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.idogfooding.backbone.utils.StrKit;
/**
* BrowserUtils
*
* @author Charles
*/
public class BrowserUtils {
public static void openUri(Context context, String uri) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(Uri.parse(uri));
context.startActivity(intent);
}
public static boolean isVideoUrl(String uri) {
return StrKit.notEmpty(uri) && (uri.toLowerCase().endsWith(".mp4")
|| uri.toLowerCase().startsWith(".avi")
|| uri.toLowerCase().startsWith(".rmvb"));
}
public static boolean isImgUrl(String uri) {
return StrKit.notEmpty(uri) && (uri.toLowerCase().endsWith(".jpg")
|| uri.toLowerCase().startsWith(".png")
|| uri.toLowerCase().startsWith(".jpeg")
|| uri.toLowerCase().startsWith(".gif")
|| uri.toLowerCase().startsWith(".bmp"));
}
public static boolean isApk(String uri) {
return StrKit.notEmpty(uri) && (uri.toLowerCase().endsWith(".apk"));
}
}
|
package liquibase.util;
import java.util.*;
import java.util.regex.Pattern;
/**
* Various utility methods for working with strings.
*/
public class StringUtils {
private static final Pattern upperCasePattern = Pattern.compile(".*[A-Z].*");
private static final Pattern lowerCasePattern = Pattern.compile(".*[a-z].*");
public static String trimToEmpty(String string) {
if (string == null) {
return "";
}
return string.trim();
}
public static String trimToNull(String string) {
if (string == null) {
return null;
}
String returnString = string.trim();
if (returnString.length() == 0) {
return null;
} else {
return returnString;
}
}
/**
* Removes any comments from multiple line SQL using {@link #stripComments(String)}
* and then extracts each individual statement using {@link #splitSQL(String, String)}.
*
* @param multiLineSQL A String containing all the SQL statements
* @param stripComments If true then comments will be stripped, if false then they will be left in the code
*/
public static String[] processMutliLineSQL(String multiLineSQL, boolean stripComments, boolean splitStatements, String endDelimiter) {
StringClauses parsed = SqlParser.parse(multiLineSQL, true, !stripComments);
List<String> returnArray = new ArrayList<String>();
StringBuilder currentString = new StringBuilder();
String previousPiece = null;
boolean previousDelimiter = false;
for (Object piece : parsed.toArray(true)) {
if (splitStatements && piece instanceof String && isDelimiter((String) piece, previousPiece, endDelimiter)) {
String trimmedString = StringUtils.trimToNull(currentString.toString());
if (trimmedString != null) {
returnArray.add(trimmedString);
}
currentString = new StringBuilder();
previousDelimiter = true;
} else {
if (!previousDelimiter || StringUtils.trimToNull((String) piece) != null) { //don't include whitespace after a delimiter
if (!currentString.equals("") || StringUtils.trimToNull((String) piece) != null) { //don't include whitespace before the statement
currentString.append(piece);
}
}
previousDelimiter = false;
}
previousPiece = (String) piece;
}
String trimmedString = StringUtils.trimToNull(currentString.toString());
if (trimmedString != null) {
returnArray.add(trimmedString);
}
return returnArray.toArray(new String[returnArray.size()]);
}
protected static boolean isDelimiter(String piece, String previousPiece, String endDelimiter) {
if (endDelimiter == null) {
return piece.equals(";") || ((piece.equalsIgnoreCase("go") || piece.equals("/")) && (previousPiece == null || previousPiece.endsWith("\n")));
} else {
if (endDelimiter.length() == 1) {
return piece.toLowerCase().equalsIgnoreCase(endDelimiter.toLowerCase());
} else {
return piece.toLowerCase().matches(endDelimiter.toLowerCase()) || (previousPiece+piece).toLowerCase().matches("[.\n\r]*"+endDelimiter.toLowerCase());
}
}
}
/**
* Splits a (possible) multi-line SQL statement along ;'s and "go"'s.
*/
public static String[] splitSQL(String multiLineSQL, String endDelimiter) {
return processMutliLineSQL(multiLineSQL, false, true, endDelimiter);
}
* any comments that are between \/**\/ or anything that matches
* SP--SP<text>\n (to support the ANSI standard commenting of --
* at the end of a line).
*
* @return The String without the comments in
*/
public static String stripComments(String multiLineSQL) {
return SqlParser.parse(multiLineSQL, true, false).toString().trim();
}
public static String join(Object[] array, String delimiter, StringUtilsFormatter formatter) {
if (array == null) {
return null;
}
return join(Arrays.asList(array), delimiter, formatter);
}
public static String join(String[] array, String delimiter) {
return join(Arrays.asList(array), delimiter);
}
public static String join(Collection<String> collection, String delimiter) {
return join(collection, delimiter, new ToStringFormatter());
}
public static String join(Collection collection, String delimiter, StringUtilsFormatter formatter) {
if (collection == null) {
return null;
}
if (collection.size() == 0) {
return "";
}
StringBuffer buffer = new StringBuffer();
for (Object val : collection) {
buffer.append(formatter.toString(val)).append(delimiter);
}
String returnString = buffer.toString();
return returnString.substring(0, returnString.length() - delimiter.length());
}
public static String join(Collection collection, String delimiter, StringUtilsFormatter formatter, boolean sorted) {
if (sorted) {
TreeSet<String> sortedSet = new TreeSet<String>();
for (Object obj : collection) {
sortedSet.add(formatter.toString(obj));
}
return join(sortedSet, delimiter);
}
return join(collection, delimiter, formatter);
}
public static String join(Collection<String> collection, String delimiter, boolean sorted) {
if (sorted) {
return join(new TreeSet<String>(collection), delimiter);
} else {
return join(collection, delimiter);
}
}
public static String join(Map map, String delimiter) {
return join(map, delimiter, new ToStringFormatter());
}
public static String join(Map map, String delimiter, StringUtilsFormatter formatter) {
List<String> list = new ArrayList<String>();
for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
list.add(entry.getKey().toString()+"="+formatter.toString(entry.getValue()));
}
return join(list, delimiter);
}
public static List<String> splitAndTrim(String s, String regex) {
if (s == null) {
return null;
}
List<String> returnList = new ArrayList<String>();
for (String string : s.split(regex)) {
returnList.add(string.trim());
}
return returnList;
}
public static String repeat(String string, int times) {
String returnString = "";
for (int i=0; i<times; i++) {
returnString += string;
}
return returnString;
}
public static String join(Integer[] array, String delimiter) {
if (array == null) {
return null;
}
int[] ints = new int[array.length];
for (int i=0; i < ints.length; i++)
{
ints[i] = array[i];
}
return StringUtils.join(ints, delimiter);
}
public static String join(int[] array, String delimiter) {
if (array == null) {
return null;
}
if (array.length == 0) {
return "";
}
StringBuffer buffer = new StringBuffer();
for (int val : array) {
buffer.append(val).append(delimiter);
}
String returnString = buffer.toString();
return returnString.substring(0, returnString.length() - delimiter.length());
}
public static String indent(String string) {
return indent(string, 4);
}
public static String indent(String string, int padding) {
String pad = StringUtils.repeat(" ", padding);
return pad+(string.replaceAll("\n", "\n" + pad));
}
public static String lowerCaseFirst(String string) {
return string.substring(0, 1).toLowerCase()+string.substring(1);
}
public static String upperCaseFirst(String string) {
return string.substring(0, 1).toUpperCase()+string.substring(1);
}
public static boolean hasUpperCase(String string) {
return upperCasePattern.matcher(string).matches();
}
public static boolean hasLowerCase(String string) {
return lowerCasePattern.matcher(string).matches();
}
public static String standardizeLineEndings(String string) {
if (string == null) {
return null;
}
return string.replace("\r\n", "\n").replace("\r", "\n");
}
public static boolean isAscii(String string) {
if (string == null) {
return true;
}
for (char c : string.toCharArray()) {
if (!isAscii(c)) {
return false;
}
}
return true;
}
public static boolean isAscii(char ch) {
return ch < 128;
}
public static String escapeHtml(String str) {
StringBuilder out = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c > 0x7F) {
out.append("&
out.append(Integer.toString(c, 10));
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
public static String pad(String value, int length) {
value = StringUtils.trimToEmpty(value);
if (value.length() >= length) {
return value;
}
return value + StringUtils.repeat(" ", length - value.length());
}
/**
* Null-safe check if string is empty.
*
* @param value String to be checked
* @return true if String is null or empty
*/
public static boolean isEmpty(String value) {
return value == null || value.length() == 0;
}
/**
* Null-safe check if string is not empty
*
* @param value String to be checked
* @return true if string is not null and not empty (length > 0)
*/
public static boolean isNotEmpty(String value) {
return !isEmpty(value);
}
/**
* Checks if <code>value</code> starts with <code>startsWith</code>.
* @param value
* @param startsWith
* @return true if <code>value</code> starts with <code>startsWith</code>, otherwise false. If any of arguments is null returns false
*/
public static boolean startsWith(String value, String startsWith) {
if(value == null || startsWith == null){
return false;
}
return value.startsWith(startsWith);
}
public static boolean isWhitespace(CharSequence string) {
if (string == null) {
return true;
}
return StringUtils.trimToNull(string.toString()) == null;
}
public static interface StringUtilsFormatter<Type> {
public String toString(Type obj);
}
public static class ToStringFormatter implements StringUtilsFormatter {
@Override
public String toString(Object obj) {
if (obj == null) {
return null;
}
return obj.toString();
}
}
public static String limitSize(String string, int maxLength) {
if (string.length() > maxLength) {
return string.substring(0, maxLength - 3) + "...";
}
return string;
}
}
|
package org.opensim.view.nodes;
import java.awt.Image;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.Action;
import javax.swing.ImageIcon;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.PropertySupport;
import org.openide.nodes.Sheet;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.opensim.modeling.CustomJoint;
import org.opensim.modeling.Joint;
import org.opensim.modeling.OpenSimObject;
import org.opensim.modeling.SpatialTransform;
import org.opensim.modeling.TransformAxis;
import org.opensim.view.editors.BodyNameEditor;
/**
*
* @author Ayman Habib
*/
public class OneJointNode extends OpenSimObjectNode {
private static ResourceBundle bundle = NbBundle.getBundle(OneJointNode.class);
/** Creates a new instance of OneMuscleNode */
public OneJointNode(OpenSimObject j) {
super(j);
setShortDescription(bundle.getString("HINT_JointNode"));
Joint joint = Joint.safeDownCast(j);
CustomJoint cj = CustomJoint.safeDownCast(joint);
if (cj != null) {
SpatialTransform spt = cj.getSpatialTransform();
for (int i = 0; i < 6; i++) {
TransformAxis ta = spt.getTransformAxis(i);
getChildren().add(new Node[] { new OneDofNode(ta) });
}
} else {
setChildren(Children.LEAF);
}
}
public Image getIcon(int i) {
URL imageURL = this.getClass().getResource("icons/jointNode.png");
if (imageURL != null) {
return new ImageIcon(imageURL, "Joint").getImage();
} else {
return null;
}
}
public Action[] getActions(boolean b) {
Action[] superActions = (Action[]) super.getActions(b);
// Arrays are fixed size, onvert to a List
List<Action> actions = java.util.Arrays.asList(superActions);
// Create new Array of proper size
Action[] retActions = new Action[actions.size()+2];
actions.toArray(retActions);
try {
// append new command to the end of the list of actions
retActions[actions.size()] = (JointToggleChildFrameAction) JointToggleChildFrameAction.findObject(
(Class)Class.forName("org.opensim.view.nodes.JointToggleChildFrameAction"), true);
retActions[actions.size()+1] = (JointToggleParentFrameAction) JointToggleParentFrameAction.findObject(
(Class)Class.forName("org.opensim.view.nodes.JointToggleParentFrameAction"), true);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return retActions;
}
@Override
public Sheet createSheet() {
Sheet sheet = super.createSheet();
Sheet.Set set = sheet.get(Sheet.PROPERTIES);
try {
set.remove("parent_body");
PropertySupport.Reflection nextNodeProp2;
nextNodeProp2 = new PropertySupport.Reflection(this, String.class, "getParentBodyName", "setParentBodyName");
nextNodeProp2.setPropertyEditorClass(BodyNameEditor.class);
nextNodeProp2.setName("parent_body");
set.put(nextNodeProp2);
} catch (NoSuchMethodException ex) {
Exceptions.printStackTrace(ex);
}
return sheet;
}
public void setParentBodyName(String newParentName) {
new PropertyEditorAdaptor("parent_body", this).setValueString(newParentName);
}
public String getParentBodyName() {
return new PropertyEditorAdaptor("parent_body", this).getValueString();
}
}
|
package com.ehpefi.iforgotthat;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class ListElementHelper extends SQLiteOpenHelper {
// Important constants for handling the database
private static final int VERSION = 1;
private static final String DATABASE_NAME = "ift.db";
private static final String TABLE_NAME = "items";
// Column names in the database
public static final String COL_ID = "_id";
public static final String COL_LIST_ID = "list_id";
public static final String COL_DESCRIPTION = "description";
public static final String COL_CREATED_TIMESTAMP = "created_timestamp";
public static final String COL_ALARM_TIMESTAMP = "alarm_timestamp";
public static final String COL_COMPLETED = "completed";
private static final String COL_IMAGE = "image";
// Specify which class that logs messages
private static final String TAG = "ListElementHelper";
/**
* Constructs a new instance of the ListElementHelper class
*
* @param context The context in which the new instance should be created, usually 'this'.
* @since 1.0
*/
public ListElementHelper(Context context) {
// Call the super class' constructor
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate() was called. Creating the table '" + TABLE_NAME + "'...");
// SQL to create the 'items' table
// TODO: Mark image BLOB NOT NULL when everything is good to go :)
String createItemsSQL = String
.format("CREATE TABLE %s (%s integer PRIMARY KEY AUTOINCREMENT NOT NULL, %s integer NOT NULL, "
+ "%s varchar(255), %s DATETIME DEFAULT CURRENT_TIMESTAMP, %s DATETIME, %s integer(1) NOT NULL DEFAULT(0), "
+ "%s blob,FOREIGN KEY(%s) REFERENCES list(_id))", TABLE_NAME, COL_ID, COL_LIST_ID,
COL_DESCRIPTION, COL_CREATED_TIMESTAMP, COL_ALARM_TIMESTAMP, COL_COMPLETED, COL_IMAGE,
COL_LIST_ID);
// Create the table
try {
db.execSQL(createItemsSQL);
Log.i(TAG, "The table '" + TABLE_NAME + "' was successfully created");
} catch (SQLException sqle) {
Log.e(TAG, "Invalid SQL detected", sqle);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "onUpgrade() was called, but nothing to upgrade...");
}
@Override
public void onOpen(SQLiteDatabase db) {
// Maybe somewhat hacky, but SQLiteOpenHelper doesn't call onCreate() for a new
// table, just a new database completely
// Ask the database if the table 'items' exist
Cursor cursor = db.rawQuery(
String.format("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='%s'", TABLE_NAME), null);
cursor.moveToFirst();
// If not, create it
if (cursor.getInt(0) == 0) {
onCreate(db);
}
cursor.close();
}
@Override
public void onConfigure(SQLiteDatabase db) {
// Enable foreign keys
db.setForeignKeyConstraintsEnabled(true);
}
/**
* Inserts a new list element into the database
*
* @param listId The list that should contain this list element
* @param description The user's description of this reminder
* @param alarm Date and time in the following format: YYYY-MM-DD HH:MM:SS
* @param image A raw image
* @return The id of the inserted list element on success, 0 on failure
* @since 1.0
*/
public int createNewListElement(int listId, String description, String alarm, byte[] image) {
// Create a pointer to the database
SQLiteDatabase db = getWritableDatabase();
// Create the data to insert
ContentValues values = new ContentValues();
values.put(COL_LIST_ID, listId);
values.put(COL_DESCRIPTION, description);
values.put(COL_ALARM_TIMESTAMP, alarm);
values.put(COL_IMAGE, image);
// Try to save the list element
try {
// Check for success
// Runs the query and stores the id
long returnId = db.insertOrThrow(TABLE_NAME, null, values);
if (returnId != -1) {
// Success
Log.i(TAG, "The list element with description '" + description + "' was successfully saved");
// Close the database connection
db.close();
return (int) returnId;
}
// Failure
Log.e(TAG, "Could not save the list element with description '" + description + "'. That's all I know...");
// Close the database connection
db.close();
return 0;
} catch (SQLiteConstraintException sqlce) {
Log.e(TAG, "Error in inserting the list element with description " + description
+ " due to a database constraint. Are you sure that the provided list ID exists?");
// Close the database connection
db.close();
return 0;
} catch (SQLException sqle) {
// Something wrong with the SQL
Log.e(TAG, "Error in inserting the list element with description '" + description + "'", sqle);
// Close the database connection
db.close();
return 0;
}
}
/**
* Deletes a list element
*
* @param id The list element's identifier
* @return True on success, otherwise false
* @since 1.0
*/
public boolean deleteListElement(int id) {
// Create a pointer to the database
SQLiteDatabase db = getWritableDatabase();
// Log that we are deleting a list element
Log.i(TAG, "Deletion of list element with id " + id + " requested");
// Try to delete the list element
if (db.delete(TABLE_NAME, COL_ID + "=?", new String[] { Integer.toString(id) }) == 1) {
Log.i(TAG, "List element with id " + id + " was successfully deleted");
// Close the database connection
db.close();
return true;
}
// Couldn't delete list element
Log.e(TAG, "Could not delete list element with id " + id);
// Close the database connection
db.close();
return false;
}
/**
* Marks a list element as completed/done
*
* @param id The element's identifier
* @param status True for completed, false for not completed
* @return True if successfull, false otherwise
* @since 1.0
*/
public boolean setListElementComplete(int id, boolean status) {
// Create a pointer to the database
SQLiteDatabase db = getWritableDatabase();
// Also convert boolean to an integer for database purposes
int statusInt = (status) ? 1 : 0;
// Log that we are changing the status of an id
Log.i(TAG, "Setting the status of id: " + id + " to " + status);
// Provide new data
ContentValues values = new ContentValues();
values.put(COL_COMPLETED, statusInt);
if (db.update(TABLE_NAME, values, COL_ID + "=?", new String[] { Integer.toString(id) }) == 1) {
Log.i(TAG, "The status of id " + id + " was successfully changed to " + status);
// Close the database connection
db.close();
return true;
}
// Error
Log.e(TAG, "Could not change status of the list element with id " + id + " to " + status
+ ". Does the list element exist?");
// Close the database connection
db.close();
return false;
}
/**
* Retrieves one list element from the database based on the input id
*
* @param id The identifier of a list element
* @return A ListElementObject on success, null on failure
* @since 1.0
*/
public ListElementObject getListElement(int id) {
// Create a pointer to the database
SQLiteDatabase db = getReadableDatabase();
// The SQL for selecting one list from the database
String sql = String.format("SELECT %s, %s, %s, %s, %s, %s, %s FROM %s WHERE %s = %d", COL_ID, COL_LIST_ID,
COL_DESCRIPTION, COL_COMPLETED, COL_CREATED_TIMESTAMP, COL_ALARM_TIMESTAMP, COL_IMAGE, TABLE_NAME,
COL_ID, id);
// Cursor who points at the result
Cursor cursor = db.rawQuery(sql, null);
// As long as we have exactly one result
if (cursor.getCount() == 1) {
// Move to the only record
cursor.moveToFirst();
// Get completion status -> convert to boolean
boolean completed = (cursor.getInt(3) == 1 ? true : false);
// Create the list object
ListElementObject listElement = new ListElementObject(cursor.getInt(0), cursor.getInt(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5), completed, cursor.getBlob(6));
// Close the database connection
db.close();
// Return the list
return listElement;
}
Log.e(TAG, "The cursor in getListElement() contains an unexpected value: " + cursor.getCount()
+ ". Returning a null object!");
// Close the database connection
db.close();
// Fail
return null;
}
/**
* Gets all list elements for a given list id
*
* @param id The list id
* @param OrderBy A static string from the ListElementHelper class (COL_ID, COL_LIST_ID, COL_DESCRIPTION,
* COL_COMPLETED, COL_CREATED_TIMESTAMP, COL_ALARM_TIMESTAMP)
* @return An ArrayList of ListElementObject on success, an empty list of these on failure
* @since 1.0
*/
public ArrayList<ListElementObject> getListElementsForListId(int id, String OrderBy) {
// Create an ArrayList to hold our list elements
ArrayList<ListElementObject> listElements = new ArrayList<ListElementObject>();
// Create a pointer to the database
SQLiteDatabase db = getReadableDatabase();
// The SQL for selecting list elements matching the list id
String sql = String.format("SELECT %s, %s, %s, %s, %s, %s, %s FROM %s WHERE %s = %d", COL_ID, COL_LIST_ID,
COL_DESCRIPTION, COL_COMPLETED, COL_CREATED_TIMESTAMP, COL_ALARM_TIMESTAMP, COL_IMAGE, TABLE_NAME,
COL_LIST_ID, id);
// Cursor who points at the current record
Cursor cursor = db.rawQuery(sql, null);
// Iterate over the results
while (cursor.moveToNext()) {
// Get completion status -> convert to boolean
boolean completed = (cursor.getInt(3) == 1 ? true : false);
try {
listElements.add(new ListElementObject(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor
.getString(4), cursor.getString(5), completed, cursor.getBlob(6)));
} catch (Exception e) {
Log.e(TAG,
"Could not create ListElementObject in getListElementsForListId(), the following exception was thrown",
e);
}
}
// Close the database connection
db.close();
// Return the list
return listElements;
}
/**
* Gets all list elements which is marked as completed
*
* @return An ArrayList of ListElementObject which is marked as completed on success, an empty list of these on
* failure
* @since 1.0
*/
public ArrayList<ListElementObject> getCompletedItems() {
// Create an ArrayList to hold our list elements
ArrayList<ListElementObject> completedItems = new ArrayList<ListElementObject>();
// Create a pointer to the database
SQLiteDatabase db = getReadableDatabase();
// The SQL for selecting all list elements from the database which is completed
String sql = String.format("SELECT %s, %s, %s, %s, %s, %s, %s FROM %s WHERE %s = %d", COL_ID, COL_LIST_ID,
COL_DESCRIPTION, COL_COMPLETED, COL_CREATED_TIMESTAMP, COL_ALARM_TIMESTAMP, COL_IMAGE, TABLE_NAME,
COL_COMPLETED, 1);
// Cursor who points at the current record
Cursor cursor = db.rawQuery(sql, null);
// Iterate over the results
while (cursor.moveToNext()) {
// Get completion status -> convert to boolean
boolean completed = (cursor.getInt(3) == 1 ? true : false);
try {
completedItems.add(new ListElementObject(cursor.getInt(0), cursor.getInt(1), cursor.getString(2),
cursor
.getString(4), cursor.getString(5), completed, cursor.getBlob(6)));
} catch (Exception e) {
Log.e(TAG,
"Could not create ListElementObject in getCompletedItems(), the following exception was thrown",
e);
}
}
// Close the database connection
db.close();
// Return the list
return completedItems;
}
}
|
package com.bot;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.StringUtils;
import com.bot.Enum.MultiKeyMap;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linecorp.bot.client.LineMessagingService;
import com.linecorp.bot.model.event.Event;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.profile.UserProfileResponse;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
@SpringBootApplication
@LineMessageHandler
public class Oripyon_jr {
static HashMap<String, String[]> randomArrayCommand;
static HashMap<String, String> binaryCommand;
static HashMap<String, String> unaryCommand;
static{
try {
TypeReference<HashMap<String, String>> typeMapString = new TypeReference<HashMap<String,String>>(){};
TypeReference<HashMap<String, String[]>> typeMapArray = new TypeReference<HashMap<String, String[]>>(){};
ObjectMapper mapper = new ObjectMapper();
binaryCommand = mapper.readValue(Oripyon_jr.class.getResourceAsStream("/command/binary.json"), typeMapString);
unaryCommand = mapper.readValue(Oripyon_jr.class.getResourceAsStream("/command/unary.json"), typeMapString);
randomArrayCommand = mapper.readValue(Oripyon_jr.class.getResourceAsStream("/command/randomArray.json"), typeMapArray);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Autowired
private LineMessagingService lineMessagingService;
Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(Oripyon_jr.class, args);
}
@EventMapping
public Message handleTextMessageEvent(MessageEvent<TextMessageContent> event) {
String stringMessage = replyString(event);
if(!StringUtils.isEmpty(stringMessage)){
return new TextMessage(stringMessage);
}
return null;
}
@EventMapping
public void handleDefaultMessageEvent(Event event) {
System.out.println("event: " + event);
}
private String replyString(MessageEvent<TextMessageContent> event){
String message = event.getMessage().getText();
try {
if(message.startsWith("!")){
String key = message.split(" ")[0].substring(1);
String target = message.substring(key.length() + 1);
if(event.getSource().getUserId() != null){
UserProfileResponse sender = lineMessagingService.getProfile(event.getSource().getUserId()).execute().body();
if(binaryCommand.get(key) != null && !StringUtils.isEmpty(target)){
return binaryCommand.get(key).replace("@{}", target).replace("{}", sender.getDisplayName());
}
if(unaryCommand.get(key) != null){
return unaryCommand.get(key).replace("{}", sender.getDisplayName());
}
}
//keyvaluemultikey
if(randomArrayCommand.get(key) == null){
key = MultiKeyMap.getTrueKey(key);
}
String[] randomArray = randomArrayCommand.get(key);
if(randomArray != null){
int seed = probabilityControl(randomArray);
return randomArray[seed].split("%=")[0].trim();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//RandomArray
private int probabilityControl(String[] randomArray){
int withoutProbability = randomArray.length;
BigDecimal hundred = new BigDecimal(100);
double probabilityCount = 0;
BigDecimal probability;
for(String stringValue:randomArray){
if(stringValue.split("%=").length > 1){
probability = new BigDecimal(stringValue.split("%=")[1]).setScale(2, BigDecimal.ROUND_DOWN);
probabilityCount += probability.doubleValue();
withoutProbability
}
}
//100array
if(probabilityCount > 100){
return random.nextInt(randomArray.length);
}
// 100 - /
//100scope1-10000
int generalProbability = hundred.subtract(new BigDecimal(probabilityCount)).divide(new BigDecimal(withoutProbability), 2, BigDecimal.ROUND_HALF_UP).multiply(hundred).intValue();
int scopeSeed = random.nextInt(10000) + 1;
int scope = 0;
//scopeseedArray index
for(int i=0;i<randomArray.length;i++){
String stringValue = randomArray[i];
scope += stringValue.split("%=").length > 1 ?
new BigDecimal(stringValue.split("%=")[1]).setScale(2, BigDecimal.ROUND_DOWN).multiply(hundred).intValue():
generalProbability;
System.out.println("" + i + "" + scope);
if(scope >= scopeSeed){
System.out.println(scope);
System.out.println(scopeSeed);
System.out.println(i);
System.out.println(randomArray[i]);
return i;
}
}
return random.nextInt(randomArray.length);
}
}
|
package pl.tkowalcz.examples.ui;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.log4j.BasicConfigurator;
import pl.tkowalcz.twitter.ITwitterSearch;
import pl.tkowalcz.twitter.RetroTwitter;
import pl.tkowalcz.utils.WordUtils;
import rx.Observable;
import rx.apache.http.ObservableHttp;
import rx.apache.http.ObservableHttpResponse;
import rx.schedulers.JavaFxScheduler;
import java.io.ByteArrayInputStream;
import java.util.concurrent.TimeUnit;
import static pl.tkowalcz.utils.FxToRx.observe;
import static pl.tkowalcz.utils.FxToRx.observeKeyPress;
public class TwitterGui extends Application {
private final ITwitterSearch twitter = new CachingTwitterSearch(new RetroTwitter());
private final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
private TextArea textField;
private ListView<TwitterUserWithImage> listView;
public static void main(String[] args) {
BasicConfigurator.configure();
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane mainPane = new BorderPane();
mainPane.setPadding(new Insets(10, 25, 10, 25));
HBox content = new HBox();
HBox bottom = new HBox();
Scene scene = new Scene(mainPane, 500, 225);
textField = new TextArea();
textField.setWrapText(true);
textField.setFont(Font.font(24));
mainPane.setCenter(textField);
listView = new ListView<>();
listView.setCellFactory(TwitterUserCell::new);
content.getChildren().add(listView);
Label remainingChars = new Label("140");
Button tweet = new Button("Tweet");
tweet.setDefaultButton(true);
bottom.setPadding(new Insets(10, 0, 0, 0));
bottom.setSpacing(10);
bottom.setAlignment(Pos.BASELINE_RIGHT);
bottom.getChildren().addAll(remainingChars, tweet);
mainPane.setBottom(bottom);
PopupControl control = new PopupControl();
control.getScene().setRoot(content);
primaryStage.setTitle("Compose new Tweet");
primaryStage.setScene(scene);
primaryStage.show();
httpClient.start();
observe(textField.textProperty())
.map((text) -> 140 - text.length())
.doOnNext((remaining) -> remainingChars.setText(Integer.toString(remaining)))
.map((remaining) -> {
if (remaining <= 0) {
return Color.RED;
} else if (remaining < 20) {
return Color.YELLOW;
}
return Color.BLACK;
})
.subscribe(remainingChars::setTextFill);
Observable<KeyEvent> keyPressesFromWindow = observeKeyPress(mainPane);
Observable<KeyEvent> keyPressesFromList = observeKeyPress(listView);
Observable.merge(keyPressesFromWindow, keyPressesFromList)
.filter((KeyEvent keyEvent) -> keyEvent.getCode() == KeyCode.ESCAPE)
.subscribe((ignored) -> {
listView.getItems().clear();
control.hide();
});
Observable<Number> caretPositionObservable = observe(textField.caretPositionProperty());
caretPositionObservable
.map(Number::intValue)
.filter((position) -> position > 0)
.map((position) -> WordUtils.getWordAtIndex(textField.getText(), position))
.distinctUntilChanged()
.filter((word) -> word.startsWith("@") && word.length() > 3)
.throttleLast(250, TimeUnit.MILLISECONDS)
.flatMap((word) -> twitter.searchUsers(word).takeUntil(caretPositionObservable))
.flatMap((listOfUsers) ->
Observable.from(listOfUsers).map(TwitterUserWithImage::new).toList()
)
.filter((list) -> !list.isEmpty())
.observeOn(JavaFxScheduler.getInstance())
.subscribe((users) -> {
Point2D point2D = bottom.localToScreen(0, 10);
control.show(bottom, point2D.getX(), point2D.getY());
listView.getItems().clear();
listView.getItems().addAll(users);
Observable.from(users)
.takeUntil(caretPositionObservable)
.subscribe(
(user) ->
ObservableHttp
.createGet(user.getTwitterUser().getProfileImageUrl(), httpClient)
.toObservable()
.flatMap(ObservableHttpResponse::getContent)
.map(ByteArrayInputStream::new)
.map(Image::new)
.observeOn(JavaFxScheduler.getInstance())
.takeUntil(caretPositionObservable)
.subscribe((image) -> {
int currentIndex = listView.getItems().indexOf(user);
if (currentIndex >= 0) {
TwitterUserWithImage element = new TwitterUserWithImage(user.getTwitterUser());
element.setImage(image);
listView.getItems().set(currentIndex, element);
}
}, Throwable::printStackTrace));
}, Throwable::printStackTrace);
}
}
|
package arez.browser.extras;
import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.annotations.PreDispose;
import arez.browser.extras.Arez_BrowserLocation;
import elemental2.dom.DomGlobal;
import elemental2.dom.Event;
import elemental2.dom.EventListener;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import org.realityforge.anodoc.Unsupported;
/**
* This is a simple abstraction over browser location as a hash.
* The model exposes the observable values for the location as the application sees it via
* {@link #getLocation()}, the way the browser sees it via {@link #getBrowserLocation()}.
* The application code should define an autorun that monitors the location as the browser
* sees it and update the location as the application sees it via {@link #changeLocation(String)}
* if the browser location is valid. Otherwise the browser location should be reset to the application
* location.
*
* <p>It should be noted that this class is not a router but a primitive that can be used to
* implement a router. Observing the application location will allow the application to update
* the view. Observing the browser location will allow the application to decide whether the
* route should be updated.</p>
*/
@ArezComponent( nameIncludesId = false )
@Unsupported( "This is still considered experimental and will likely evolve over time" )
public class BrowserLocation
{
private final EventListener _listener = this::onHashChangeEvent;
/**
* The location according to the application.
*/
@Nonnull
private String _location = "";
/**
* The location according to the browser.
*/
@Nonnull
private String _browserLocation = "";
/**
* The location that the application is attempting to update the browser to.
*/
@Nonnull
private String _targetLocation = "";
/**
* Should we prevent the default action associated with hash change?
*/
private boolean _preventDefault = true;
/**
* Create the model object.
*
* @return the BrowserLocation instance.
*/
public static BrowserLocation create()
{
return new Arez_BrowserLocation();
}
BrowserLocation()
{
}
@PostConstruct
final void postConstruct()
{
DomGlobal.window.addEventListener( "hashchange", _listener, false );
_targetLocation = _browserLocation = _location = getHash();
}
@PreDispose
final void preDispose()
{
DomGlobal.window.removeEventListener( "hashchange", _listener, false );
}
/**
* Return true if component will prevent default actions when hash.
*
* @return true if component will prevent default actions when hash.
*/
public boolean shouldPreventDefault()
{
return _preventDefault;
}
/**
* Set a flag to determine whether events default action will be prevented.
*
* @param preventDefault true to prevent default action.
*/
public void setPreventDefault( final boolean preventDefault )
{
_preventDefault = preventDefault;
}
/**
* Change the target location to the specified parameter.
* This will ultimately result in a side-effect that updates the browsers location.
* This location parameter should not include "#" as the first character.
*
* @param targetLocation the location to change to.
*/
@Action
public void changeLocation( @Nonnull final String targetLocation )
{
_targetLocation = targetLocation;
if ( targetLocation.equals( getBrowserLocation() ) )
{
setLocation( targetLocation );
}
setHash( targetLocation );
/*
* setHash does not trigger a "hashchange" event so explicitly call the hook here
*/
updateBrowserLocation();
}
/**
* Revert the browsers location to the application location.
*/
@Action
public void resetBrowserLocation()
{
changeLocation( getLocation() );
}
/**
* Return the location as the application sees it.
* This return value does not include a "#" as the first character.
*
* @return the location.
*/
@Observable
@Nonnull
public String getLocation()
{
return _location;
}
@Observable
void setLocation( @Nonnull final String location )
{
_location = Objects.requireNonNull( location );
}
@Observable
@Nonnull
public String getBrowserLocation()
{
return _browserLocation;
}
void setBrowserLocation( @Nonnull final String browserLocation )
{
_browserLocation = Objects.requireNonNull( browserLocation );
}
@Action
void updateBrowserLocation()
{
final String location = getHash();
setBrowserLocation( location );
if ( _targetLocation.equals( location ) )
{
setLocation( location );
}
}
private void onHashChangeEvent( @Nonnull final Event e )
{
if ( _preventDefault )
{
e.preventDefault();
}
updateBrowserLocation();
}
@Nonnull
private String getHash()
{
final String hash = DomGlobal.window.location.getHash();
return null == hash ? "" : hash.substring( 1 );
}
private void setHash( @Nonnull final String hash )
{
if ( 0 == hash.length() )
{
final String url = DomGlobal.window.location.getPathname() + DomGlobal.window.location.getSearch();
DomGlobal.window.history.pushState( "", DomGlobal.document.title, url );
}
else
{
DomGlobal.window.location.setHash( hash );
}
}
}
|
package org.unitime.timetable.solver.exam.ui;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import net.sf.cpsolver.exam.model.ExamInstructor;
import net.sf.cpsolver.exam.model.ExamModel;
import net.sf.cpsolver.exam.model.ExamStudent;
import net.sf.cpsolver.ifs.model.Constraint;
import org.unitime.timetable.model.DepartmentalInstructor;
import org.unitime.timetable.model.Exam;
import org.unitime.timetable.model.ExamOwner;
import org.unitime.timetable.model.dao.DepartmentalInstructorDAO;
import org.unitime.timetable.model.dao.ExamDAO;
import org.unitime.timetable.model.dao.ExamOwnerDAO;
/**
* @author Tomas Muller
*/
public class ExamInfo implements Serializable, Comparable<ExamInfo> {
protected String iExamLabel = null;
protected Long iExamId = null;
protected transient Exam iExam = null;
protected int iExamType;
protected int iNrStudents;
protected int iLength;
protected int iMaxRooms;
protected int iSeatingType;
protected Vector<ExamSectionInfo> iSections = null;
protected Vector<ExamInstructorInfo> iInstructors = null;
public ExamInfo(net.sf.cpsolver.exam.model.Exam exam) {
iExamType = ((ExamModel)exam.getModel()).getProperties().getPropertyInt("Exam.Type", Exam.sExamTypeFinal);
iExamId = exam.getId();
iExamLabel = exam.getName();
iLength = exam.getLength();
iMaxRooms = exam.getMaxRooms();
iNrStudents = exam.getStudents().size();
iSeatingType = (exam.hasAltSeating()?Exam.sSeatingTypeExam:Exam.sSeatingTypeNormal);
if (!exam.getOwners().isEmpty()) {
iSections = new Vector();
for (Enumeration e=exam.getOwners().elements();e.hasMoreElements();) {
net.sf.cpsolver.exam.model.ExamOwner ecs = (net.sf.cpsolver.exam.model.ExamOwner)e.nextElement();
HashSet<Long> studentIds = new HashSet<Long>();
for (Iterator i=ecs.getStudents().iterator();i.hasNext();)
studentIds.add(((ExamStudent)i.next()).getId());
iSections.add(new ExamSectionInfo(ecs.getId(), ecs.getName(), studentIds));
}
}
iInstructors = new Vector();
for (Enumeration e=exam.constraints().elements();e.hasMoreElements();) {
Constraint c = (Constraint)e.nextElement();
if (c instanceof ExamInstructor) {
ExamInstructor instructor = (ExamInstructor)c;
iInstructors.add(new ExamInstructorInfo(instructor.getId(), null, instructor.getName()));
}
}
}
public ExamInfo(Exam exam) {
iExamType = exam.getExamType();
iExamId = exam.getUniqueId();
iExamLabel = exam.getLabel();
iMaxRooms = exam.getMaxNbrRooms();
iExam = exam;
iLength = exam.getLength();
iNrStudents = -1;
iSeatingType = exam.getSeatingType().intValue();
}
public int getExamType() {
return iExamType;
}
public String getExamTypeLabel() {
return Exam.sExamTypes[iExamType];
}
public Long getExamId() {
return iExamId;
}
public Exam getExam() {
if (iExam==null)
iExam = new ExamDAO().get(iExamId);
return iExam;
}
public Exam getExam(org.hibernate.Session hibSession) {
return new ExamDAO().get(iExamId, hibSession);
}
public String getExamName() {
return (iExamLabel==null?getExam().getLabel():iExamLabel);
}
public String getExamNameHtml() {
String name = getExamName();
if (name.length()>50)
return "<span title='"+name+"'>"+name.substring(0,50)+"...</span>";
else
return name;
}
public int getNrStudents() {
if (iNrStudents<0) iNrStudents = getExam().getSize();
return iNrStudents;
}
public int getSeatingType() {
return iSeatingType;
}
public String getSeatingTypeLabel() {
return Exam.sSeatingTypes[iSeatingType];
}
public int getLength() {
return iLength;
}
public int getMaxRooms() {
return iMaxRooms;
}
public Vector<ExamSectionInfo> getSections() {
if (iSections==null) {
iSections = new Vector();
for (Iterator i=new TreeSet(getExam().getOwners()).iterator();i.hasNext();)
iSections.add(new ExamSectionInfo((ExamOwner)i.next()));
}
return iSections;
}
public String getSectionName(String delim) {
String name = "";
for (Enumeration e=getSections().elements();e.hasMoreElements();) {
ExamSectionInfo info = (ExamSectionInfo)e.nextElement();
name += info.getName();
if (e.hasMoreElements()) name += delim;
}
return name;
}
public Vector<ExamInstructorInfo> getInstructors() {
if (iInstructors==null) {
iInstructors = new Vector();
for (Iterator i=new TreeSet(getExam().getInstructors()).iterator();i.hasNext();)
iInstructors.add(new ExamInstructorInfo((DepartmentalInstructor)i.next()));
}
return iInstructors;
}
public boolean hasInstructor(Long instructorId) {
if (iInstructors!=null) {
for (ExamInstructorInfo instructor : iInstructors)
if (instructor.getId().equals(instructorId)) return true;
} else {
for (Iterator i=getExam().getInstructors().iterator();i.hasNext();)
if (((DepartmentalInstructor)i.next()).getUniqueId().equals(instructorId)) return true;
}
return false;
}
public String getInstructorName(String delim) {
String name = "";
for (Enumeration e=getInstructors().elements();e.hasMoreElements();) {
ExamInstructorInfo info = (ExamInstructorInfo)e.nextElement();
name += info.getName();
if (e.hasMoreElements()) name += delim;
}
return name;
}
public int hashCode() {
return getExamId().hashCode();
}
public boolean equals(Object o) {
if (o==null || !(o instanceof ExamInfo)) return false;
return ((ExamInfo)o).getExamId().equals(getExamId());
}
public int compareTo(ExamInfo info) {
int cmp = getExamName().compareTo(info.getExamName());
if (cmp!=0) return cmp;
return getExamId().compareTo(info.getExamId());
}
public String toString() {
return getExamName();
}
public class ExamSectionInfo implements Serializable, Comparable<ExamSectionInfo> {
protected Long iId;
protected String iName;
protected int iNrStudents = -1;
protected transient ExamOwner iOwner = null;
protected Set<Long> iStudentIds = null;
public ExamSectionInfo(Long id, String name, Set<Long> studentIds) {
iId = id;
iName = name;
iNrStudents = studentIds.size();
iStudentIds = studentIds;
}
public ExamSectionInfo(ExamOwner owner) {
iOwner = owner;
iId = owner.getUniqueId();
iName = owner.getLabel();
iStudentIds = null;
}
public Set<Long> getStudentIds() {
if (iStudentIds==null) iStudentIds = new HashSet<Long>(getOwner().getStudentIds());
return iStudentIds;
}
public Long getId() { return iId; }
public Long getOwnerId() { return getOwner().getOwnerId(); }
public Integer getOwnerType() { return getOwner().getOwnerType(); }
public ExamOwner getOwner() {
if (iOwner==null)
iOwner = new ExamOwnerDAO().get(getId());
return iOwner;
}
public String getName() { return iName; }
public int getNrStudents() {
if (iNrStudents<0)
iNrStudents = getOwner().getSize();
return iNrStudents;
}
public ExamInfo getExam() {
return ExamInfo.this;
}
public ExamAssignment getExamAssignment() {
if (ExamInfo.this instanceof ExamAssignment)
return (ExamAssignment)ExamInfo.this;
return null;
}
public ExamAssignmentInfo getExamAssignmentInfo() {
if (ExamInfo.this instanceof ExamAssignmentInfo)
return (ExamAssignmentInfo)ExamInfo.this;
return null;
}
public String getSubject() {
return getOwner().getSubject();
}
public String getCourseNbr() {
return getOwner().getCourseNbr();
}
public String getItype() {
return getOwner().getItype();
}
public String getSection() {
return getOwner().getSection();
}
public int compareTo(ExamSectionInfo info) {
int cmp = getOwner().compareTo(getOwner());
if (cmp!=0) return cmp;
return getExam().compareTo(info.getExam());
}
public int hasCode() {
return getId().hashCode();
}
public boolean equals(Object o) {
if (o==null || !(o instanceof ExamSectionInfo)) return false;
return getId().equals(((ExamSectionInfo)o).getId());
}
}
public class ExamInstructorInfo implements Serializable, Comparable<ExamInstructorInfo> {
protected Long iId;
protected String iExternalUniqueId = null;
protected String iName = null;
protected transient DepartmentalInstructor iInstructor;
public ExamInstructorInfo(Long id, String externalUniqueId, String name) {
iId = id;
iExternalUniqueId = externalUniqueId;
iName = name;
}
public ExamInstructorInfo(DepartmentalInstructor instructor) {
iId = instructor.getUniqueId();
iName = instructor.getNameLastFirst();
iExternalUniqueId = instructor.getExternalUniqueId();
iInstructor = instructor;
}
public Long getId() { return iId; }
public String getName() { return iName; }
public String getExternalUniqueId() {
if (iExternalUniqueId==null && iInstructor==null)
iExternalUniqueId = getInstructor().getExternalUniqueId();
return iExternalUniqueId;
}
public DepartmentalInstructor getInstructor() {
if (iInstructor==null)
iInstructor = new DepartmentalInstructorDAO().get(getId());
return iInstructor;
}
public ExamInfo getExam() {
return ExamInfo.this;
}
public int compareTo(ExamInstructorInfo i) {
int cmp = getName().compareTo(i.getName());
if (cmp!=0) return cmp;
return getId().compareTo(i.getId());
}
public int hashCode() {
if (getExternalUniqueId()!=null) return getExternalUniqueId().hashCode();
return getId().hashCode();
}
public boolean equals(Object o) {
if (o==null || !(o instanceof ExamInstructorInfo)) return false;
ExamInstructorInfo i = (ExamInstructorInfo)o;
if (getExternalUniqueId()!=null && getExternalUniqueId().equals(i.getExternalUniqueId())) return true;
return getId().equals(i.getId());
}
}
}
|
package com.uber.okbuck.extension;
import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.tasks.Input;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("unused")
public class OkBuckExtension {
/**
* Build Tools Version
*/
@Input
public String buildToolVersion = "24.0.2";
/**
* Android target sdk version
*/
@Input
public String target = "android-24";
/**
* Annotation processor classes of project dependencies
*/
@Input
public Map<String, List<String>> annotationProcessors = new HashMap<>();
/**
* LinearAllocHardLimit used for multi-dex support.
*/
@Input
public Map<String, Integer> linearAllocHardLimit = new HashMap<>();
/**
* Primary dex class patterns.
*/
@Input
public Map<String, Set<String>> primaryDexPatterns = new HashMap<>();
/**
* Whether to enable exopackage.
*/
@Input
public Map<String, Boolean> exopackage = new HashMap<>();
/**
* Exopackage lib dependencies.
*/
@Input
public Map<String, Set<String>> appLibDependencies = new HashMap<>();
/**
* Proguard mapping file applied via applymapping
*/
@Input
public Map<String, File> proguardMappingFile = new HashMap<>();
/**
* List of build types/variant names for which to exclude generating lint rules
*/
@Input
public Map<String, Set<String>> lintExclude = new HashMap<>();
/**
* List of build types/variant names for which to exclude generating test rules
*/
@Input
public Map<String, Set<String>> testExclude = new HashMap<>();
/**
* Set of projects to generate buck configs for. Default is all subprojects of root project.
*/
@SuppressWarnings("CanBeFinal")
@Input
public Set<Project> buckProjects;
/**
* Extra buck options
*/
@Input
public Map<String, Map<String, Set<String>>> extraBuckOpts = new HashMap<>();
/**
* Extra buck defs
**/
@Input
public Set<File> extraDefs = new HashSet<>();
/**
* Whether to turn on buck's resource_union to reflect gradle's resource merging behavior
*/
@Input
public boolean resourceUnion = true;
/**
* Whether to generate android_build_config rules for library projects
*/
@Input
public boolean libraryBuildConfig = true;
/**
* List of exclude patterns for resources to be processed by aapt
*/
@Input
public Set<String> excludeResources = new HashSet<>();
/**
* Additional dependency caches.
* Every value "entry" will create a new configuration "entryExtraDepCache"
* that can be used to fetch and cache dependencies.
*/
@Input
public Set<String> extraDepCaches = new HashSet<>();
/**
* Forces okbuck to fail if the project is using dynamic or snapshot dependencies
*/
@Input
public boolean failOnChangingDependencies = false;
/**
* The prebult buck binary to use
*/
@Input
public String buckBinary = "com.github.facebook:buck:17aba06d14f0667460ee93953747421b01950dd7@pex";
public OkBuckExtension(Project project) {
buckProjects = project.getSubprojects();
}
private IntellijExtension intellijExtension = new IntellijExtension();
private ExperimentalExtension experimentalExtension = new ExperimentalExtension();
public void intellij(Action<IntellijExtension> container) {
container.execute(intellijExtension);
}
public IntellijExtension getIntellijExtension() {
return intellijExtension;
}
public void experimental(Action<ExperimentalExtension> container) {
container.execute(experimentalExtension);
}
public ExperimentalExtension getExperimentalExtension() {
return experimentalExtension;
}
}
|
package com.bustiblelemons.views;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.bustiblelemons.bustiblelibs.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
/**
* Created 5 Nov 2013
*/
public class LoadingImage extends RelativeLayout implements ImageLoadingListener {
private View rootView;
private String addresToLoad;
private String failbackAddress;
private ProgressBar progress;
private ImageView image;
private boolean showProgress;
private int noImageRes = R.drawable.lemons;
private Animation animationIn;
private boolean useAnimations;
public LoadingImage(Context context) {
super(context);
init(context, null);
}
public LoadingImage(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public LoadingImage(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
rootView = LayoutInflater.from(context).inflate(R.layout.loading_image, this, true);
image = (ImageView) rootView.findViewById(R.id.___image);
progress = (ProgressBar) rootView.findViewById(R.id.___progress);
if (attrs != null) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LoadingImage);
noImageRes = array.getResourceId(R.styleable.LoadingImage_no_image, R.drawable.lemons);
loadDefault();
showProgress = array.getBoolean(R.styleable.LoadingImage_show_progressbar, false);
if (showProgress) {
progress.setVisibility(View.VISIBLE);
}
setupAnimations(array);
array.recycle();
}
}
private void setupAnimations(TypedArray array) {
useAnimations = array.getBoolean(R.styleable.LoadingImage_use_animations, false);
if (useAnimations) {
int _in = array.getResourceId(R.styleable.LoadingImage_animationIn, R.anim.abc_fade_in);
setAnimationIn(_in);
int _out = array.getResourceId(R.styleable.LoadingImage_animationOut,
R.anim.abc_fade_out);
}
}
private void setAnimationIn(int resId) {
this.animationIn = getAnimation(resId);
}
private Animation getAnimation(int resId) {
return resId > 0 ? AnimationUtils.loadAnimation(getContext(), resId) : null;
}
public void loadFrom(String url) {
loadFrom(url, null);
}
public void loadFrom(String url, String fallbackUrl) {
if (url == null && fallbackUrl == null) {
loadDefault();
}
this.failbackAddress = fallbackUrl;
this.addresToLoad = !TextUtils.isEmpty(url) ? url : fallbackUrl;
if (!isSameUrl(addresToLoad)) {
rLoadUrl(addresToLoad);
}
}
private void rLoadUrl(String url) {
if (ImageLoader.getInstance().isInited()) {
ImageLoader.getInstance().loadImage(url, this);
}
}
private boolean isSameUrl(String url) {
String _tagUrl = (String) getTag(R.id.___tag_url);
return _tagUrl != null ? _tagUrl.equals(url) : false;
}
@Override
public void onLoadingStarted(String imageUri, View view) {
showProgressBar();
}
private void showProgressBar() {
if (showProgress) {
progress.setVisibility(VISIBLE);
}
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if (failbackAddress != null) {
rLoadUrl(failbackAddress);
} else {
loadDefault();
}
hideProgressbar();
}
private void hideProgressbar() {
if (showProgress) {
progress.setVisibility(GONE);
}
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
hideProgressbar();
setTag(R.id.___tag_url, imageUri);
loadBitmap(loadedImage);
}
private void loadBitmap(Bitmap loadedImage) {
if (useAnimations && animationIn != null) {
image.startAnimation(animationIn);
}
image.setImageBitmap(loadedImage);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
hideProgressbar();
loadDefault();
}
private void loadDefault() {
image.setImageResource(noImageRes);
}
}
|
package com.parse;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import bolts.Task;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
// For ParseExecutors.main()
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class ParseUserTest {
@Rule
public ExpectedException thrown= ExpectedException.none();
@Before
public void setUp() {
ParseObject.registerSubclass(ParseUser.class);
ParseObject.registerSubclass(ParseSession.class);
}
@After
public void tearDown() {
ParseObject.unregisterSubclass(ParseUser.class);
ParseObject.unregisterSubclass(ParseSession.class);
ParseCorePlugins.getInstance().reset();
ParsePlugins.reset();
Parse.disableLocalDatastore();
}
@Test
public void testImmutableKeys() {
ParseUser user = new ParseUser();
user.put("foo", "bar");
try {
user.put("sessionToken", "blah");
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Cannot modify"));
}
try {
user.remove("sessionToken");
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Cannot modify"));
}
try {
user.removeAll("sessionToken", Collections.emptyList());
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Cannot modify"));
}
}
//region SignUpAsync
@Test
public void testSignUpAsyncWithNoUserName() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Username cannot be missing or blank");
ParseTaskUtils.wait(user.signUpAsync(Task.<Void>forResult(null)));
}
@Test
public void testSignUpAsyncWithNoPassword() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
user.setUsername("userName");
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Password cannot be missing or blank");
ParseTaskUtils.wait(user.signUpAsync(Task.<Void>forResult(null)));
}
@Test
public void testSignUpAsyncWithObjectIdSetAndAuthDataNotSet() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser.State userState = new ParseUser.State.Builder()
.objectId("test")
.build();
ParseUser user = ParseObject.from(userState);
user.setUsername("userName");
user.setPassword("password");
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Cannot sign up a user that has already signed up.");
ParseTaskUtils.wait(user.signUpAsync(Task.<Void>forResult(null)));
}
@Test
public void testSignUpAsyncWithObjectIdSetAndAuthDataSet() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = mock(ParseUser.class);
when(currentUser.getSessionToken()).thenReturn("sessionToken");
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(currentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser.State userState = new ParseUser.State.Builder()
.objectId("test")
.putAuthData(ParseAnonymousUtils.AUTH_TYPE, null)
.build();
ParseUser user = ParseObject.from(userState);
user.setUsername("userName");
user.setPassword("password");
//TODO (mengyan): Avoid using partial mock after we have ParseObjectInstanceController
ParseUser partialMockUser = spy(user);
doReturn(Task.<Void>forResult(null))
.when(partialMockUser)
.saveAsync(anyString(), Matchers.<Task<Void>>any());
ParseTaskUtils.wait(partialMockUser.signUpAsync(Task.<Void>forResult(null)));
// Verify user is saved
verify(partialMockUser, times(1)).saveAsync(eq("sessionToken"), Matchers.<Task<Void>>any());
}
@Test
public void testSignUpAsyncWithAnotherSignUpAlreadyRunning() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
user.setUsername("userName");
user.setPassword("password");
user.startSave();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Cannot sign up a user that is already signing up.");
ParseTaskUtils.wait(user.signUpAsync(Task.<Void>forResult(null)));
}
@Test
public void testSignUpAsyncWithSignUpSameAnonymousUser() throws Exception {
ParseUser user = new ParseUser();
user.setUsername("userName");
user.setPassword("password");
Map<String, String> anonymousAuthData = new HashMap<>();
anonymousAuthData.put("key", "token");
user.putAuthData(ParseAnonymousUtils.AUTH_TYPE, anonymousAuthData);
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(user));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Attempt to merge currentUser with itself.");
ParseTaskUtils.wait(user.signUpAsync(Task.<Void>forResult(null)));
}
@Test
public void testSignUpAsyncWithMergeInDiskAnonymousUser() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = mock(ParseUser.class);
when(currentUser.getUsername()).thenReturn("oldUserName");
when(currentUser.getPassword()).thenReturn("oldPassword");
when(currentUser.isLinked(ParseAnonymousUtils.AUTH_TYPE)).thenReturn(true);
when(currentUser.getSessionToken()).thenReturn("oldSessionToken");
when(currentUser.getAuthData()).thenReturn(new HashMap<String, Map<String, String>>());
when(currentUser.saveAsync(anyString(), Matchers.<Task<Void>>any()))
.thenReturn(Task.<Void>forResult(null));
ParseUser.State state = new ParseUser.State.Builder()
.put("oldKey", "oldValue")
.build();
when(currentUser.getState()).thenReturn(state);
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(currentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
user.setUsername("userName");
user.setPassword("password");
Map<String, String> anonymousAuthData = new HashMap<>();
anonymousAuthData.put("key", "token");
user.putAuthData(ParseAnonymousUtils.AUTH_TYPE, anonymousAuthData);
Task<Void> signUpTask = user.signUpAsync(Task.<Void>forResult(null));
signUpTask.waitForCompletion();
// Make sure we checkForChangesToMutableContainers
verify(currentUser, times(1)).checkForChangesToMutableContainers();
// Make sure currentUser copy changes from user
verify(currentUser, times(1)).copyChangesFrom(user);
// Make sure we update currentUser username and password
verify(currentUser, times(1)).setUsername("userName");
verify(currentUser, times(1)).setPassword("password");
// Make sure we save currentUser
verify(currentUser, times(1)).saveAsync(eq("oldSessionToken"), Matchers.<Task<Void>>any());
// Make sure we merge currentUser with user after save
assertEquals("oldValue", user.get("oldKey"));
// Make sure set currentUser
verify(currentUserController, times(1)).setAsync(eq(user));
}
@Test
public void testSignUpAsyncWithMergeInDiskAnonymousUserSaveFailure() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
Map<String, String> oldAnonymousAuthData = new HashMap<>();
oldAnonymousAuthData.put("oldKey", "oldToken");
currentUser.putAuthData(ParseAnonymousUtils.AUTH_TYPE, oldAnonymousAuthData);
ParseUser partialMockCurrentUser = spy(currentUser);
when(partialMockCurrentUser.getUsername()).thenReturn("oldUserName");
when(partialMockCurrentUser.getPassword()).thenReturn("oldPassword");
when(partialMockCurrentUser.getSessionToken()).thenReturn("oldSessionToken");
ParseException saveException = new ParseException(ParseException.OTHER_CAUSE, "");
doReturn(Task.<Void>forError(saveException))
.when(partialMockCurrentUser)
.saveAsync(anyString(), Matchers.<Task<Void>>any());
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean()))
.thenReturn(Task.forResult(partialMockCurrentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
user.setUsername("userName");
user.setPassword("password");
Map<String, String> anonymousAuthData = new HashMap<>();
anonymousAuthData.put("key", "token");
user.putAuthData(ParseAnonymousUtils.AUTH_TYPE, anonymousAuthData);
Task<Void> signUpTask = user.signUpAsync(Task.<Void>forResult(null));
signUpTask.waitForCompletion();
// Make sure we checkForChangesToMutableContainers
verify(partialMockCurrentUser, times(1)).checkForChangesToMutableContainers();
// Make sure we update currentUser username and password
verify(partialMockCurrentUser, times(1)).setUsername("userName");
verify(partialMockCurrentUser, times(1)).setPassword("password");
// Make sure we sync user with currentUser
verify(partialMockCurrentUser, times(1)).copyChangesFrom(eq(user));
// Make sure we save currentUser
verify(partialMockCurrentUser, times(1))
.saveAsync(eq("oldSessionToken"), Matchers.<Task<Void>>any());
// Make sure we restore old username and password after save fails
verify(partialMockCurrentUser, times(1)).setUsername("oldUserName");
verify(partialMockCurrentUser, times(1)).setPassword("oldPassword");
// Make sure we restore anonymity
verify(partialMockCurrentUser, times(1)).putAuthData(
ParseAnonymousUtils.AUTH_TYPE, oldAnonymousAuthData);
// Make sure task is failed
assertTrue(signUpTask.isFaulted());
assertSame(saveException, signUpTask.getError());
}
@Test
public void testSignUpAsyncWithNoCurrentUserAndSignUpSuccess() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean()))
.thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.build();
when(userController.signUpAsync(
any(ParseUser.State.class), any(ParseOperationSet.class), anyString()))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
ParseUser user = new ParseUser();
user.setUsername("userName");
user.setPassword("password");
ParseTaskUtils.wait(user.signUpAsync(Task.<Void>forResult(null)));
// Make sure we sign up the user
verify(userController, times(1)).signUpAsync(
any(ParseUser.State.class), any(ParseOperationSet.class), anyString());
// Make sure user's data is correct
assertEquals("newSessionToken", user.getSessionToken());
assertEquals("newValue", user.getString("newKey"));
assertFalse(user.isLazy());
// Make sure we set the current user
verify(currentUserController, times(1)).setAsync(user);
}
@Test
public void testSignUpAsyncWithNoCurrentUserAndSignUpFailure() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean()))
.thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseException signUpException = new ParseException(ParseException.OTHER_CAUSE, "test");
when(userController.signUpAsync(
any(ParseUser.State.class), any(ParseOperationSet.class), anyString()))
.thenReturn(Task.<ParseUser.State>forError(signUpException));
ParseCorePlugins.getInstance().registerUserController(userController);
ParseUser user = new ParseUser();
user.put("key", "value");
user.setUsername("userName");
user.setPassword("password");
Task<Void> signUpTask = user.signUpAsync(Task.<Void>forResult(null));
// Make sure we sign up the user
verify(userController, times(1)).signUpAsync(
any(ParseUser.State.class), any(ParseOperationSet.class), anyString());
// Make sure user's data is correct
assertEquals("value", user.getString("key"));
// Make sure we never set the current user
verify(currentUserController, never()).setAsync(user);
// Make sure task is failed
assertTrue(signUpTask.isFaulted());
assertSame(signUpException, signUpTask.getError());
}
//endregion
//region testLogInWithAsync
@Test
public void testLoginWithAsyncWithLinkedLazyUser() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
currentUser.putAuthData(ParseAnonymousUtils.AUTH_TYPE, new HashMap<String, String>());
setLazy(currentUser);
ParseUser partialMockCurrentUser = spy(currentUser);
when(partialMockCurrentUser.getSessionToken()).thenReturn("oldSessionToken");
doReturn(Task.<ParseUser>forResult(null))
.when(partialMockCurrentUser)
.resolveLazinessAsync(Matchers.<Task<Void>>any());
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync()).thenReturn(Task.forResult(partialMockCurrentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
String authType = "facebook";
Map<String, String> authData = new HashMap<>();
authData.put("token", "123");
ParseUser userAfterLogin = ParseTaskUtils.wait(ParseUser.logInWithAsync(authType, authData));
// Make sure we stripAnonymity
assertNull(userAfterLogin.getAuthData().get(ParseAnonymousUtils.AUTH_TYPE));
// Make sure we update authData
assertEquals(authData, userAfterLogin.getAuthData().get("facebook"));
// Make sure we resolveLaziness
verify(partialMockCurrentUser, times(1)).resolveLazinessAsync(Matchers.<Task<Void>>any());
}
@Test
public void testLoginWithAsyncWithLinkedLazyUseAndResolveLazinessFailure() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
Map<String, String> oldAnonymousAuthData = new HashMap<>();
oldAnonymousAuthData.put("oldKey", "oldToken");
currentUser.putAuthData(ParseAnonymousUtils.AUTH_TYPE, oldAnonymousAuthData);
ParseUser partialMockCurrentUser = spy(currentUser);
when(partialMockCurrentUser.getSessionToken()).thenReturn("oldSessionToken");
doReturn(Task.<ParseUser>forError(new Exception()))
.when(partialMockCurrentUser)
.resolveLazinessAsync(Matchers.<Task<Void>>any());
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync()).thenReturn(Task.forResult(partialMockCurrentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
String authType = "facebook";
Map<String, String> authData = new HashMap<>();
authData.put("token", "123");
Task<ParseUser> loginTask = ParseUser.logInWithAsync(authType, authData);
loginTask.waitForCompletion();
// Make sure we try to resolveLaziness
verify(partialMockCurrentUser, times(1)).resolveLazinessAsync(Matchers.<Task<Void>>any());
// Make sure we do not save new authData
assertNull(partialMockCurrentUser.getAuthData().get("facebook"));
// Make sure we restore anonymity after resolve laziness failure
assertEquals(oldAnonymousAuthData, partialMockCurrentUser.getAuthData()
.get(ParseAnonymousUtils.AUTH_TYPE));
// Make sure task fails
assertTrue(loginTask.isFaulted());
}
@Test
public void testLoginWithAsyncWithLinkedNotLazyUser() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
currentUser.setObjectId("objectId"); // Make it not lazy.
currentUser.putAuthData(ParseAnonymousUtils.AUTH_TYPE, new HashMap<String, String>());
ParseUser partialMockCurrentUser = spy(currentUser);
when(partialMockCurrentUser.getSessionToken()).thenReturn("sessionToken");
doReturn(Task.<Void>forResult(null))
.when(partialMockCurrentUser)
.linkWithAsync(anyString(), Matchers.<Map<String, String>>any(), anyString());
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync()).thenReturn(Task.forResult(partialMockCurrentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
String authType = "facebook";
Map<String, String> authData = new HashMap<>();
authData.put("token", "123");
ParseUser userAfterLogin = ParseTaskUtils.wait(ParseUser.logInWithAsync(authType, authData));
// Make sure we link authData
verify(partialMockCurrentUser, times(1)).linkWithAsync(
eq("facebook"), eq(authData), eq("sessionToken"));
assertSame(partialMockCurrentUser, userAfterLogin);
}
@Test
public void testLoginWithAsyncWithLinkedNotLazyUserLinkFailure() throws Exception {
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.build();
when(userController.logInAsync(anyString(), Matchers.<Map<String, String>>any()))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
currentUser.putAuthData(ParseAnonymousUtils.AUTH_TYPE, new HashMap<String, String>());
currentUser.setObjectId("objectId"); // Make it not lazy.
ParseUser partialMockCurrentUser = spy(currentUser);
when(partialMockCurrentUser.getSessionToken()).thenReturn("sessionToken");
ParseException linkException =
new ParseException(ParseException.ACCOUNT_ALREADY_LINKED, "Account already linked");
doReturn(Task.<Void>forError(linkException))
.when(partialMockCurrentUser)
.linkWithAsync(anyString(), Matchers.<Map<String, String>>any(), anyString());
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync()).thenReturn(Task.forResult(partialMockCurrentUser));
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
String authType = "facebook";
Map<String, String> authData = new HashMap<>();
authData.put("token", "123");
ParseUser userAfterLogin = ParseTaskUtils.wait(ParseUser.logInWithAsync(authType, authData));
// Make sure we link authData
verify(partialMockCurrentUser, times(1)).linkWithAsync(
eq("facebook"), eq(authData), eq("sessionToken"));
// Make sure we login authData
verify(userController, times(1)).logInAsync("facebook", authData);
// Make sure we save the new created user as currentUser
verify(currentUserController, times(1)).setAsync(any(ParseUser.class));
// Make sure the new created user has correct data
assertEquals("newValue", userAfterLogin.get("newKey"));
assertEquals("newSessionToken", userAfterLogin.getSessionToken());
}
@Test
public void testLoginWithAsyncWithNoCurrentUser() throws Exception {
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.build();
when(userController.logInAsync(anyString(), Matchers.<Map<String, String>>any()))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync()).thenReturn(Task.<ParseUser>forResult(null));
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
String authType = "facebook";
Map<String, String> authData = new HashMap<>();
authData.put("token", "123");
ParseUser userAfterLogin = ParseTaskUtils.wait(ParseUser.logInWithAsync(authType, authData));
// Make sure we login authData
verify(userController, times(1)).logInAsync("facebook", authData);
// Make sure we save the new created user as currentUser
verify(currentUserController, times(1)).setAsync(any(ParseUser.class));
// Make sure the new created user has correct data
assertEquals("newValue", userAfterLogin.get("newKey"));
assertEquals("newSessionToken", userAfterLogin.getSessionToken());
}
//endregion
//region testLinkWithAsync
@Test
public void testLinkWithAsyncWithSaveAsyncSuccess() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getCurrentSessionTokenAsync())
.thenReturn(Task.<String>forResult(null));
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock authenticationProvider
ParseAuthenticationProvider provider = mock(ParseAuthenticationProvider.class);
when(provider.getAuthType()).thenReturn("facebook");
when(provider.restoreAuthentication(Matchers.<Map<String, String>>any())).thenReturn(true);
ParseUser.registerAuthenticationProvider(provider);
ParseUser user = new ParseUser();
// To make synchronizeAuthData work
user.setIsCurrentUser(true);
// To verify stripAnonymity
user.setObjectId("objectId");
user.putAuthData(ParseAnonymousUtils.AUTH_TYPE, new HashMap<String, String>());
ParseUser partialMockUser = spy(user);
doReturn(Task.<Void>forResult(null))
.when(partialMockUser)
.saveAsync(anyString(), Matchers.<Task<Void>>any());
String authType = "facebook";
Map<String, String> authData = new HashMap<>();
authData.put("token", "test");
ParseTaskUtils.wait(partialMockUser.linkWithAsync(authType, authData, "sessionTokenAgain"));
// Make sure we stripAnonymity
assertNull(partialMockUser.getAuthData().get(ParseAnonymousUtils.AUTH_TYPE));
// Make sure new authData is added
assertSame(authData, partialMockUser.getAuthData().get("facebook"));
// Make sure we save the user
verify(partialMockUser, times(1)).saveAsync(eq("sessionTokenAgain"), Matchers.<Task<Void>>any());
// Make sure synchronizeAuthData() is called
verify(provider, times(1)).restoreAuthentication(authData);
}
@Test
public void testLinkWithAsyncWithSaveAsyncFailure() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getCurrentSessionTokenAsync())
.thenReturn(Task.forResult("sessionToken"));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
Map<String, String> anonymousAuthData = new HashMap<>();
anonymousAuthData.put("anonymousToken", "anonymousTest");
// To verify stripAnonymity
user.setObjectId("objectId");
user.putAuthData(ParseAnonymousUtils.AUTH_TYPE, anonymousAuthData);
ParseUser partialMockUser = spy(user);
Exception saveException = new Exception();
doReturn(Task.<Void>forError(saveException))
.when(partialMockUser)
.saveAsync(anyString(), Matchers.<Task<Void>>any());
String facebookAuthType = "facebook";
Map<String, String> facebookAuthData = new HashMap<>();
facebookAuthData.put("facebookToken", "facebookTest");
Task<Void> linkTask =
partialMockUser.linkWithAsync(facebookAuthType, facebookAuthData, "sessionTokenAgain");
linkTask.waitForCompletion();
// Make sure new authData is added
assertSame(facebookAuthData, partialMockUser.getAuthData().get("facebook"));
// Make sure we save the user
verify(partialMockUser, times(1)).saveAsync(eq("sessionTokenAgain"), Matchers.<Task<Void>>any());
// Make sure old authData is restored
assertSame(anonymousAuthData, partialMockUser.getAuthData().get(ParseAnonymousUtils.AUTH_TYPE));
// Verify exception
assertSame(saveException, linkTask.getError());
}
//endregion
//region testResolveLazinessAsync
@Test
public void testResolveLazinessAsyncWithNotLazyUser() throws Exception {
ParseUser user = new ParseUser();
ParseTaskUtils.wait(user.resolveLazinessAsync(Task.<Void>forResult(null)));
}
@Test
public void testResolveLazinessAsyncWithAuthDataAndNotNewUser() throws Exception {
ParseUser user = new ParseUser();
setLazy(user);
user.putAuthData("facebook", new HashMap<String, String>());
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.isNew(false)
.build();
when(userController.logInAsync(any(ParseUser.State.class), any(ParseOperationSet.class)))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser userAfterResolveLaziness =
ParseTaskUtils.wait(user.resolveLazinessAsync(Task.<Void>forResult(null)));
// Make sure we logIn the lazy user
verify(userController, times(1)).logInAsync(
any(ParseUser.State.class), any(ParseOperationSet.class));
// Make sure we save currentUser
verify(currentUserController, times(1)).setAsync(any(ParseUser.class));
// Make sure user's data is correct
assertEquals("newSessionToken", userAfterResolveLaziness.getSessionToken());
assertEquals("newValue", userAfterResolveLaziness.get("newKey"));
// Make sure userAfterResolveLaziness is not lazy
assertFalse(userAfterResolveLaziness.isLazy());
// Make sure we create new user
assertNotSame(user, userAfterResolveLaziness);
}
@Test
public void testResolveLazinessAsyncWithAuthDataAndNewUser() throws Exception {
ParseUser user = new ParseUser();
setLazy(user);
user.putAuthData("facebook", new HashMap<String, String>());
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.objectId("objectId")
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.isNew(true)
.build();
when(userController.logInAsync(any(ParseUser.State.class), any(ParseOperationSet.class)))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
// Register a mock currentUserController to verify setAsync
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser userAfterResolveLaziness =
ParseTaskUtils.wait(user.resolveLazinessAsync(Task.<Void>forResult(null)));
// Make sure we logIn the lazy user
verify(userController, times(1)).logInAsync(
any(ParseUser.State.class), any(ParseOperationSet.class));
// Make sure we do not save currentUser
verify(currentUserController, never()).setAsync(any(ParseUser.class));
// Make sure userAfterResolveLaziness's data is correct
assertEquals("newSessionToken", userAfterResolveLaziness.getSessionToken());
assertEquals("newValue", userAfterResolveLaziness.get("newKey"));
// Make sure userAfterResolveLaziness is not lazy
assertFalse(userAfterResolveLaziness.isLazy());
// Make sure we do not create new user
assertSame(user, userAfterResolveLaziness);
}
@Test
public void testResolveLazinessAsyncWithAuthDataAndNotNewUserAndLDSEnabled() throws Exception {
ParseUser user = new ParseUser();
setLazy(user);
user.putAuthData("facebook", new HashMap<String, String>());
// To verify handleSaveResultAsync is not called
user.setPassword("password");
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.isNew(false)
.build();
when(userController.logInAsync(any(ParseUser.State.class), any(ParseOperationSet.class)))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
// Register a mock currentUserController to make getCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Enable LDS
Parse.enableLocalDatastore(null);
ParseUser userAfterResolveLaziness =
ParseTaskUtils.wait(user.resolveLazinessAsync(Task.<Void>forResult(null)));
// Make sure we logIn the lazy user
verify(userController, times(1)).logInAsync(
any(ParseUser.State.class), any(ParseOperationSet.class));
// Make sure handleSaveResultAsync() is not called, if handleSaveResultAsync is called, password
// field should be cleaned
assertEquals("password", user.getPassword());
// Make sure we do not save currentUser
verify(currentUserController, times(1)).setAsync(any(ParseUser.class));
// Make sure userAfterResolveLaziness's data is correct
assertEquals("newSessionToken", userAfterResolveLaziness.getSessionToken());
assertEquals("newValue", userAfterResolveLaziness.get("newKey"));
// Make sure userAfterResolveLaziness is not lazy
assertFalse(userAfterResolveLaziness.isLazy());
// Make sure we create new user
assertNotSame(user, userAfterResolveLaziness);
}
//endregion
//region testValidateSave
@Test
public void testValidateSaveWithNoObjectId() throws Exception {
ParseUser user = new ParseUser();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Cannot save a ParseUser until it has been signed up. Call signUp first.");
user.validateSave();
}
// TODO(mengyan): Add testValidateSaveWithIsAuthenticatedWithNotDirty
// TODO(mengyan): Add testValidateSaveWithIsAuthenticatedWithIsCurrentUser
@Test
public void testValidateSaveWithLDSNotEnabled() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
currentUser.setObjectId("test");
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(currentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
user.setObjectId("test");
// Make isDirty return true
user.put("key", "value");
// Make isCurrent return false
user.setIsCurrentUser(false);
user.validateSave();
}
@Test
public void testValidateSaveWithLDSNotEnabledAndCurrentUserNotMatch() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
currentUser.setObjectId("testAgain");
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(currentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
user.setObjectId("test");
// Make isDirty return true
user.put("key", "value");
// Make isCurrent return false
user.setIsCurrentUser(false);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Cannot save a ParseUser that is not authenticated.");
user.validateSave();
}
//endregion
//region testSaveAsync
@Test
public void testSaveAsyncWithLazyAndCurrentUser() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Set facebook authData to null to verify cleanAuthData()
ParseUser.State userState = new ParseUser.State.Builder()
.putAuthData("facebook", null)
.build();
ParseUser user = ParseObject.from(userState);
setLazy(user);
user.setIsCurrentUser(true);
ParseUser partialMockUser = spy(user);
doReturn(Task.<Void>forResult(null))
.when(partialMockUser)
.resolveLazinessAsync(Matchers.<Task<Void>>any());
ParseTaskUtils.wait(partialMockUser.saveAsync("sessionToken", Task.<Void>forResult(null)));
// Make sure we clean authData
assertFalse(partialMockUser.getAuthData().containsKey("facebook"));
// Make sure we save new currentUser
verify(currentUserController, times(1)).setAsync(partialMockUser);
}
@Test
public void testSaveAsyncWithLazyAndNotCurrentUser() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Set facebook authData to null to verify cleanAuthData()
ParseUser.State userState = new ParseUser.State.Builder()
.putAuthData("facebook", null)
.build();
ParseUser user = ParseObject.from(userState);
setLazy(user);
user.setIsCurrentUser(false);
ParseUser partialMockUser = spy(user);
doReturn(Task.<Void>forResult(null))
.when(partialMockUser)
.resolveLazinessAsync(Matchers.<Task<Void>>any());
ParseTaskUtils.wait(partialMockUser.saveAsync("sessionToken", Task.<Void>forResult(null)));
// Make sure we do not clean authData
assertTrue(partialMockUser.getAuthData().containsKey("facebook"));
// Make sure we do not save new currentUser
verify(currentUserController, never()).setAsync(partialMockUser);
}
// TODO(mengyan): Add testSaveAsyncWithNotLazyAndNotCurrentUser, right now we can not mock
// super.save()
//endregion
//region testLogOutAsync
@Test
public void testLogoutInternal() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock authenticationProvider
ParseAuthenticationProvider provider = mock(ParseAuthenticationProvider.class);
when(provider.getAuthType()).thenReturn("facebook");
when(provider.restoreAuthentication(Matchers.<Map<String, String>>any())).thenReturn(true);
ParseUser.registerAuthenticationProvider(provider);
// Set user initial state
String facebookAuthType = "facebook";
Map<String, String> facebookAuthData = new HashMap<>();
facebookAuthData.put("facebookToken", "facebookTest");
ParseUser.State userState = new ParseUser.State.Builder()
.objectId("test")
.putAuthData(facebookAuthType, facebookAuthData)
.sessionToken("oldSessionToken")
.build();
ParseUser user = ParseObject.from(userState);
String oldSessionToken = user.logOutInternal();
// Make sure user state is correct
assertFalse(user.isCurrentUser());
assertFalse(user.isNew());
assertNull(user.getSessionToken());
// Make sure provider is deauthenticate
verify(provider, times(1)).deauthenticate();
// Make sure return sessionToken is correct
assertSame("oldSessionToken", oldSessionToken);
}
@Test
public void testLogOutAsync() throws Exception {
// Register a mock sessionController to verify revokeAsync()
NetworkSessionController sessionController = mock(NetworkSessionController.class);
when(sessionController.revokeAsync(anyString())).thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerSessionController(sessionController);
// Set user initial state
String facebookAuthType = "facebook";
Map<String, String> facebookAuthData = new HashMap<>();
facebookAuthData.put("facebookToken", "facebookTest");
ParseUser.State userState = new ParseUser.State.Builder()
.objectId("test")
.putAuthData(facebookAuthType, facebookAuthData)
.sessionToken("r:oldSessionToken")
.build();
ParseUser user = ParseObject.from(userState);
ParseTaskUtils.wait(user.logOutAsync());
// Verify we revoke session
verify(sessionController, times(1)).revokeAsync("r:oldSessionToken");
}
//endregion
//region testEnable/UpgradeSessionToken
@Test
public void testEnableRevocableSessionInBackgroundWithCurrentUser() throws Exception {
// Register a mock ParsePlugins to make restClient() work
ParsePlugins mockPlugins = mock(ParsePlugins.class);
when(mockPlugins.restClient()).thenReturn(null);
ParsePlugins.set(mockPlugins);
// Register a mock currentUserController to verify setAsync
ParseUser mockUser = mock(ParseUser.class);
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(mockUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseTaskUtils.wait(ParseUser.enableRevocableSessionInBackground());
verify(currentUserController, times(1)).getAsync(false);
verify(mockUser, times(1)).upgradeToRevocableSessionAsync();
}
@Test
public void testEnableRevocableSessionInBackgroundWithNoCurrentUser() throws Exception {
// Register a mock ParsePlugins to make restClient() work
ParsePlugins mockPlugins = mock(ParsePlugins.class);
when(mockPlugins.restClient()).thenReturn(null);
ParsePlugins.set(mockPlugins);
// Register a mock currentUserController to verify setAsync
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseTaskUtils.wait(ParseUser.enableRevocableSessionInBackground());
verify(currentUserController, times(1)).getAsync(false);
}
@Test
public void testUpgradeToRevocableSessionAsync() throws Exception {
// Register a mock currentUserController to verify setAsync
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock sessionController to verify revokeAsync()
NetworkSessionController sessionController = mock(NetworkSessionController.class);
ParseSession.State state = new ParseSession.State.Builder("_Session")
.put("sessionToken", "r:newSessionToken")
.build();
when(sessionController.upgradeToRevocable(anyString()))
.thenReturn(Task.forResult(state));
ParseCorePlugins.getInstance().registerSessionController(sessionController);
// Set user initial state
ParseUser.State userState = new ParseUser.State.Builder()
.objectId("test")
.sessionToken("oldSessionToken")
.build();
ParseUser user = ParseObject.from(userState);
ParseTaskUtils.wait(user.upgradeToRevocableSessionAsync());
// Make sure we update to new sessionToken
assertEquals("r:newSessionToken", user.getSessionToken());
// Make sure we update currentUser
verify(currentUserController, times(1)).setAsync(user);
}
@Test
public void testDontOverwriteSessionTokenForCurrentUser() throws Exception {
ParseUser.State sessionTokenState = new ParseUser.State.Builder()
.sessionToken("sessionToken")
.put("key0", "value0")
.put("key1", "value1")
.isComplete(true)
.build();
ParseUser.State newState = new ParseUser.State.Builder()
.put("key0", "newValue0")
.put("key2", "value2")
.isComplete(true)
.build();
ParseUser.State emptyState = new ParseUser.State.Builder().isComplete(true).build();
ParseUser user = ParseObject.from(sessionTokenState);
user.setIsCurrentUser(true);
assertEquals(user.getSessionToken(), "sessionToken");
assertEquals(user.getString("key0"), "value0");
assertEquals(user.getString("key1"), "value1");
user.setState(newState);
assertEquals(user.getSessionToken(), "sessionToken");
assertEquals(user.getString("key0"), "newValue0");
assertNull(user.getString("key1"));
assertEquals(user.getString("key2"), "value2");
user.setIsCurrentUser(false);
user.setState(emptyState);
assertNull(user.getSessionToken());
assertNull(user.getString("key0"));
assertNull(user.getString("key1"));
assertNull(user.getString("key2"));
}
//endregion
//region testUnlinkFromAsync
@Test
public void testUnlinkFromAsyncWithAuthType() throws Exception {
// Register a mock currentUserController to make getAsync work
ParseUser mockUser = mock(ParseUser.class);
when(mockUser.getSessionToken()).thenReturn("sessionToken");
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync()).thenReturn(Task.forResult(mockUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Set user initial state
String facebookAuthType = "facebook";
Map<String, String> facebookAuthData = new HashMap<>();
facebookAuthData.put("facebookToken", "facebookTest");
ParseUser.State userState = new ParseUser.State.Builder()
.objectId("test")
.putAuthData(facebookAuthType, facebookAuthData)
.build();
ParseUser user = ParseObject.from(userState);
ParseUser partialMockUser = spy(user);
doReturn(Task.<Void>forResult(null))
.when(partialMockUser)
.saveAsync(anyString(), Matchers.<Task<Void>>any());
ParseTaskUtils.wait(partialMockUser.unlinkFromAsync("facebook"));
// Verify we delete authData
assertNull(user.getAuthData().get("facebook"));
// Verify we save the user
verify(partialMockUser, times(1)).saveAsync(eq("sessionToken"), Matchers.<Task<Void>>any());
}
@Test
public void testUnlinkFromAsyncWithNoAuthType() throws Exception {
// Register a mock currentUserController to make getAsync work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync()).thenReturn(Task.<ParseUser>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Set user initial state
String facebookAuthType = "facebook";
Map<String, String> facebookAuthData = new HashMap<>();
facebookAuthData.put("facebookToken", "facebookTest");
ParseUser.State userState = new ParseUser.State.Builder()
.objectId("test")
.putAuthData(facebookAuthType, facebookAuthData)
.build();
ParseUser user = ParseObject.from(userState);
ParseTaskUtils.wait(user.unlinkFromAsync(null));
// Verify we do not delete authData
assertEquals(facebookAuthData, user.getAuthData().get("facebook"));
}
//endregion
//region testLogin
@Test
public void testLogInInWithNoUserName() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Must specify a username for the user to log in with");
ParseTaskUtils.wait(ParseUser.logInInBackground(null, "password"));
}
@Test
public void testLogInWithNoPassword() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Must specify a password for the user to log in with");
ParseTaskUtils.wait(ParseUser.logInInBackground("userName", null));
}
@Test
public void testLogIn() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.build();
when(userController.logInAsync(anyString(), anyString()))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
ParseUser user = ParseUser.logIn("userName", "password");
// Make sure user is login
verify(userController, times(1)).logInAsync("userName", "password");
// Make sure we set currentUser
verify(currentUserController, times(1)).setAsync(user);
// Make sure user's data is correct
assertEquals("newSessionToken", user.getSessionToken());
assertEquals("newValue", user.get("newKey"));
}
@Test
public void testLogInWithCallback() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock userController to make logIn work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("newKey", "newValue")
.sessionToken("newSessionToken")
.build();
when(userController.logInAsync(anyString(), anyString()))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
final Semaphore done = new Semaphore(0);
ParseUser.logInInBackground("userName", "password", new LogInCallback() {
@Override
public void done(ParseUser user, ParseException e) {
done.release();
assertNull(e);
// Make sure user's data is correct
assertEquals("newSessionToken", user.getSessionToken());
assertEquals("newValue", user.get("newKey"));
}
});
assertTrue(done.tryAcquire(5, TimeUnit.SECONDS));
// Make sure user is login
verify(userController, times(1)).logInAsync("userName", "password");
// Make sure we set currentUser
verify(currentUserController, times(1)).setAsync(any(ParseUser.class));
}
//endregion
//region testBecome
@Test
public void testBecomeWithNoSessionToken() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Must specify a sessionToken for the user to log in with");
ParseUser.become(null);
}
@Test
public void testBecome() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock userController to make getUsreAsync work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("key", "value")
.sessionToken("sessionToken")
.build();
when(userController.getUserAsync(anyString()))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
ParseUser user = ParseUser.become("sessionToken");
// Make sure we call getUserAsync
verify(userController, times(1)).getUserAsync("sessionToken");
// Make sure we set currentUser
verify(currentUserController, times(1)).setAsync(user);
// Make sure user's data is correct
assertEquals("sessionToken", user.getSessionToken());
assertEquals("value", user.get("key"));
}
@Test
public void testBecomeWithCallback() throws Exception {
// Register a mock currentUserController to make setCurrentUser work
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.setAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock userController to make getUsreAsync work
ParseUserController userController = mock(ParseUserController.class);
ParseUser.State newUserState = new ParseUser.State.Builder()
.put("key", "value")
.sessionToken("sessionToken")
.build();
when(userController.getUserAsync(anyString()))
.thenReturn(Task.forResult(newUserState));
ParseCorePlugins.getInstance().registerUserController(userController);
final Semaphore done = new Semaphore(0);
ParseUser.becomeInBackground("sessionToken", new LogInCallback() {
@Override
public void done(ParseUser user, ParseException e) {
done.release();
assertNull(e);
// Make sure user's data is correct
assertEquals("sessionToken", user.getSessionToken());
assertEquals("value", user.get("key"));
}
});
// Make sure we call getUserAsync
verify(userController, times(1)).getUserAsync("sessionToken");
// Make sure we set currentUser
verify(currentUserController, times(1)).setAsync(any(ParseUser.class));
}
//endregion
//region testToRest
@Test
public void testToRest() throws Exception {
ParseUser user = new ParseUser();
user.setUsername("userName");
user.setPassword("password");
JSONObject json = user.toRest(user.getState(), user.operationSetQueue, PointerEncoder.get());
// Make sure we delete password operations
assertFalse(json.getJSONArray("__operations").getJSONObject(0).has("password"));
// Make sure we have username operations
assertEquals(
"userName", json.getJSONArray("__operations").getJSONObject(0).getString("username"));
}
//endregion
//region testValidateDelete
@Test
public void testValidDelete() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
currentUser.setObjectId("test");
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(currentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
user.setObjectId("test");
// Make isDirty return true
user.put("key", "value");
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Cannot delete a ParseUser that is not authenticated.");
user.validateDelete();
}
//endregion
//region testValidateDelete
@Test
public void testValidateSaveEventually() throws Exception {
ParseUser user = new ParseUser();
user.setPassword("password");
thrown.expect(ParseException.class);
thrown.expectMessage("Unable to saveEventually on a ParseUser with dirty password");
user.validateSaveEventually();
}
//endregion
//region testSynchronizeAuthData
@Test
public void testSynchronizeAuthData() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(currentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock authenticationProvider
ParseAuthenticationProvider provider = mock(ParseAuthenticationProvider.class);
when(provider.getAuthType()).thenReturn("facebook");
when(provider.restoreAuthentication(Matchers.<Map<String, String>>any())).thenReturn(true);
ParseUser.registerAuthenticationProvider(provider);
// Set user initial state
String facebookAuthType = "facebook";
Map<String, String> facebookAuthData = new HashMap<>();
facebookAuthData.put("facebookToken", "facebookTest");
ParseUser.State userState = new ParseUser.State.Builder()
.putAuthData(facebookAuthType, facebookAuthData)
.build();
ParseUser user = ParseObject.from(userState);
user.synchronizeAuthData(provider);
// Make sure we restore authentication
verify(provider, times(1)).restoreAuthentication(facebookAuthData);
}
@Test
public void testSynchronizeAllAuthData() throws Exception {
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenReturn(Task.forResult(currentUser));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
// Register a mock authenticationProvider
ParseAuthenticationProvider provider = mock(ParseAuthenticationProvider.class);
when(provider.getAuthType()).thenReturn("facebook");
when(provider.restoreAuthentication(Matchers.<Map<String, String>>any())).thenReturn(true);
ParseUser.registerAuthenticationProvider(provider);
// Set user initial state
String facebookAuthType = "facebook";
Map<String, String> facebookAuthData = new HashMap<>();
facebookAuthData.put("facebookToken", "facebookTest");
ParseUser.State userState = new ParseUser.State.Builder()
.putAuthData(facebookAuthType, facebookAuthData)
.build();
ParseUser user = ParseObject.from(userState);
user.setIsCurrentUser(true);
user.synchronizeAllAuthData();
// Make sure we restore authentication
verify(provider, times(1)).restoreAuthentication(facebookAuthData);
}
//endregion
//region testAutomaticUser
@Test
public void testAutomaticUser() throws Exception {
new ParseUser();
ParseUser.disableAutomaticUser();
assertFalse(ParseUser.isAutomaticUserEnabled());
ParseUser.enableAutomaticUser();
assertTrue(ParseUser.isAutomaticUserEnabled());
}
//endregion
//region testAutomaticUser
@Test
public void testPinCurrentUserIfNeededAsyncWithNoLDSEnabled() throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Method requires Local Datastore.");
ParseUser.pinCurrentUserIfNeededAsync(new ParseUser());
}
//endregion
//region testPinCurrentUserIfNeededAsync
@Test
public void testPinCurrentUserIfNeededAsync() throws Exception {
// Enable LDS
Parse.enableLocalDatastore(null);
// Register a mock currentUserController to make getCurrentUser work
ParseUser currentUser = new ParseUser();
currentUser.setObjectId("test");
CachedCurrentUserController currentUserController = mock(CachedCurrentUserController.class);
when(currentUserController.setIfNeededAsync(any(ParseUser.class)))
.thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
ParseUser user = new ParseUser();
ParseUser.pinCurrentUserIfNeededAsync(user);
// Make sure we pin the user
verify(currentUserController, times(1)).setIfNeededAsync(user);
}
//endregion
//region testRemove
@Test
public void testRemoveWithUserName() throws Exception {
ParseUser user = new ParseUser();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Can't remove the username key.");
user.remove("username");
}
//endregion
private static void setLazy(ParseUser user) {
Map<String, String> anonymousAuthData = new HashMap<>();
anonymousAuthData.put("anonymousToken", "anonymousTest");
user.putAuthData(ParseAnonymousUtils.AUTH_TYPE, anonymousAuthData);
}
}
|
package com.ibm.mil.cafejava;
import android.support.annotation.NonNull;
import android.support.annotation.StringDef;
import com.worklight.wlclient.api.WLResourceRequest;
import com.worklight.wlclient.api.WLResponseListener;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation for invoking a procedure from a Java based adapter.
*
* @see JSProcedureInvoker
*
* @author John Petitto (github @jpetitto)
* @author Tanner Preiss (github @t-preiss)
*/
public final class JavaProcedureInvoker implements ProcedureInvoker {
/** StringDef for basic HTTP method types: {@code GET, POST, PUT, DELETE}. */
@Retention(RetentionPolicy.SOURCE)
@StringDef({
GET,
POST,
PUT,
DELETE
})
public @interface HttpMethod {}
/** Annotated with the {@code HttpMethod} StringDef */
public static final String GET = WLResourceRequest.GET;
/** Annotated with the {@code HttpMethod} StringDef */
public static final String POST = WLResourceRequest.POST;
/** Annotated with the {@code HttpMethod} StringDef */
public static final String PUT = WLResourceRequest.PUT;
/** Annotated with the {@code HttpMethod} StringDef */
public static final String DELETE = WLResourceRequest.DELETE;
private final String adapterName;
private final String path;
private HashMap<String, String> pathParams;
private HashMap<String, String> queryParams;
private @HttpMethod String httpMethod;
private JavaProcedureInvoker(String adapterName, String path) {
this.adapterName = adapterName;
this.path = path;
}
@Override
public void invoke(WLResponseListener wlResponseListener) {
try {
URI uri = new URI("adapters/" + adapterName + "/" + path);
WLResourceRequest request = new WLResourceRequest(uri, httpMethod);
request.setQueryParameters(queryParams);
request.send(pathParams, wlResponseListener);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
/** Configures and instantiates a {@code JavaProcedureInvoker}. */
public static class Builder {
private final String adapterName;
private final String path;
private HashMap<String, String> pathParams = new HashMap<>();
private HashMap<String, String> queryParams = new HashMap<>();
private @HttpMethod String httpMethod = GET;
public Builder(String adapterName, String path) {
this.adapterName = adapterName;
this.path = path;
}
public Builder pathParam(@NonNull String name, @NonNull String value) {
pathParams.put(name, value);
return this;
}
public Builder pathParams(@NonNull Map<String, String> params) {
pathParams.putAll(params);
return this;
}
public Builder queryParam(@NonNull String name, @NonNull String value) {
queryParams.put(name, value);
return this;
}
public Builder queryParams(@NonNull Map<String, String> params) {
queryParams.putAll(params);
return this;
}
/** Expects an {@code HttpMethod} StringDef constant value. Default is {@code GET}. */
public Builder httpMethod(@NonNull @HttpMethod String httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public JavaProcedureInvoker build() {
JavaProcedureInvoker invoker = new JavaProcedureInvoker(adapterName, path);
invoker.pathParams = pathParams;
invoker.queryParams = queryParams;
invoker.httpMethod = httpMethod;
return invoker;
}
}
}
|
package com.m2stice.graphics;
public class Component {
public Component() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("oj");
}
}
|
package com.collective.celos.ci.mode;
import com.collective.celos.ScheduledTime;
import com.collective.celos.ci.config.CelosCiCommandLine;
import com.collective.celos.ci.config.deploy.CelosCiTarget;
import com.collective.celos.ci.config.deploy.CelosCiTargetParser;
import com.collective.celos.ci.mode.test.TestCase;
import com.collective.celos.ci.mode.test.TestConfigurationParser;
import com.collective.celos.ci.mode.test.TestRun;
import com.collective.celos.ci.mode.test.TestRunFailedException;
import com.collective.celos.ci.testing.fixtures.compare.RecursiveFsObjectComparer;
import com.collective.celos.ci.testing.fixtures.create.FixDirFromResourceCreator;
import com.collective.celos.ci.testing.fixtures.create.OutputFixDirFromHdfsCreator;
import com.collective.celos.ci.testing.fixtures.deploy.HdfsInputDeployer;
import com.google.common.collect.Lists;
import org.apache.hadoop.fs.Path;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.util.List;
import java.util.Set;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class TestTaskTest {
private TestRun testRun;
@Before
public void setUp() {
testRun = mock(TestRun.class);
doReturn(new File("testDir")).when(testRun).getTestCasesDir();
}
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
@Test
public void testTestRunsAreCreatedOk() throws Exception {
String hadoopCoreUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/core-site.xml").getFile();
String hadoopHdfsUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/hdfs-site.xml").getFile();
String targetFileStr = "{\n" +
" \"security.settings\": \"secsettings\",\n" +
" \"workflows.dir.uri\": \"celoswfdir\",\n" +
" \"hadoop.hdfs-site.xml\": \"" + hadoopHdfsUrl +"\",\n" +
" \"hadoop.core-site.xml\": \"" + hadoopCoreUrl +"\",\n" +
" \"defaults.dir.uri\": \"defdir\"\n" +
"}\n";
File targetFile = tempDir.newFile();
FileOutputStream stream = new FileOutputStream(targetFile);
stream.write(targetFileStr.getBytes());
stream.flush();
CelosCiTargetParser parser = new CelosCiTargetParser("");
CelosCiTarget target = parser.parse(targetFile.toURI());
File tmpDir = tempDir.newFolder();
String configJS = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/test.js").getFile();
CelosCiCommandLine commandLine = new CelosCiCommandLine(targetFile.toURI().toString(), "DEPLOY", "deploydir", "workflow", "testDir", "uname", false);
TestTask testTask = new TestTask(commandLine, new File(configJS), tmpDir);
String tempDirUri = tmpDir.toURI().toString();
Assert.assertTrue(testTask.getTestRuns().get(0).getCiContext().getTarget().getDefaultsDirUri().toString().startsWith(tempDirUri));
Assert.assertEquals(testTask.getTestRuns().get(0).getCiContext().getTarget().getPathToCoreSite(), target.getPathToCoreSite());
Assert.assertEquals(testTask.getTestRuns().get(0).getCiContext().getTarget().getPathToHdfsSite(), target.getPathToHdfsSite());
Assert.assertTrue(testTask.getTestRuns().get(0).getCiContext().getTarget().getWorkflowsDirUri().toString().startsWith(tempDirUri));
Assert.assertTrue(testTask.getTestRuns().get(0).getCiContext().getTarget().getWorkflowsDirUri().toString().length() > tempDirUri.length());
Assert.assertEquals(testTask.getTestRuns().get(0).getTestCase().getName(), "wordcount test case 1");
Assert.assertEquals(testTask.getTestRuns().get(0).getTestCase().getSampleTimeStart(), new ScheduledTime("2013-11-20T11:00Z"));
Assert.assertEquals(testTask.getTestRuns().get(0).getTestCase().getSampleTimeEnd(), new ScheduledTime("2013-11-20T18:00Z"));
HdfsInputDeployer deployer1 = (HdfsInputDeployer) testTask.getTestRuns().get(0).getTestCase().getInputs().get(0);
HdfsInputDeployer deployer2 = (HdfsInputDeployer) testTask.getTestRuns().get(0).getTestCase().getInputs().get(1);
Assert.assertEquals(deployer1.getPath(), new Path("input/wordcount1"));
Assert.assertEquals(deployer2.getPath(), new Path("input/wordcount11"));
RecursiveFsObjectComparer comparer = (RecursiveFsObjectComparer) testTask.getTestRuns().get(0).getTestCase().getOutputs().get(0);
OutputFixDirFromHdfsCreator hdfsCreator = (OutputFixDirFromHdfsCreator) comparer.getActualDataCreator();
Assert.assertEquals(hdfsCreator.getPath(), new Path("output/wordcount1"));
FixDirFromResourceCreator resourceDataCreator = (FixDirFromResourceCreator) comparer.getExpectedDataCreator();
Assert.assertEquals(resourceDataCreator.getPath(testRun), new File("testDir/src/test/celos-ci/test-1/output/plain/output/wordcount1"));
Assert.assertTrue(testTask.getTestRuns().get(1).getCiContext().getTarget().getDefaultsDirUri().toString().startsWith(tempDirUri));
Assert.assertEquals(testTask.getTestRuns().get(1).getCiContext().getTarget().getPathToCoreSite(), target.getPathToCoreSite());
Assert.assertEquals(testTask.getTestRuns().get(1).getCiContext().getTarget().getPathToHdfsSite(), target.getPathToHdfsSite());
Assert.assertTrue(testTask.getTestRuns().get(1).getCiContext().getTarget().getWorkflowsDirUri().toString().startsWith(tempDirUri));
Assert.assertTrue(testTask.getTestRuns().get(1).getCiContext().getTarget().getWorkflowsDirUri().toString().length() > tempDirUri.length());
Assert.assertEquals(testTask.getTestRuns().get(1).getTestCase().getName(), "wordcount test case 2");
Assert.assertEquals(testTask.getTestRuns().get(1).getTestCase().getSampleTimeStart(), new ScheduledTime("2013-12-20T16:00Z"));
Assert.assertEquals(testTask.getTestRuns().get(1).getTestCase().getSampleTimeEnd(), new ScheduledTime("2013-12-20T18:00Z"));
HdfsInputDeployer deployer21 = (HdfsInputDeployer) testTask.getTestRuns().get(1).getTestCase().getInputs().get(0);
Assert.assertEquals(deployer21.getPath(), new Path("input/wordcount2"));
RecursiveFsObjectComparer comparer2 = (RecursiveFsObjectComparer) testTask.getTestRuns().get(1).getTestCase().getOutputs().get(0);
OutputFixDirFromHdfsCreator hdfsCreator2 = (OutputFixDirFromHdfsCreator) comparer2.getActualDataCreator();
Assert.assertEquals(hdfsCreator2.getPath(), new Path("output/wordcount2"));
FixDirFromResourceCreator resourceDataCreator2 = (FixDirFromResourceCreator) comparer2.getExpectedDataCreator();
Assert.assertEquals(resourceDataCreator2.getPath(testRun), new File("testDir/src/test/celos-ci/test-1/output/plain/output/wordcount2"));
File logFile = new File(tmpDir, "celos.log");
Assert.assertArrayEquals(new File[]{ logFile }, tmpDir.listFiles());
Assert.assertTrue(logFile.length() > 0);
}
private class MockTestRun extends TestRun {
private boolean finished;
public MockTestRun(CelosCiTarget target, CelosCiCommandLine commandLine, TestCase testCase) throws Exception {
super(target, commandLine, testCase, tempDir.newFolder());
}
public void start() throws Exception {
finished = true;
}
public boolean isFinished() {
return finished;
}
}
@Test
public void testTest() throws Throwable {
String hadoopCoreUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/core-site.xml").getFile();
String hadoopHdfsUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/hdfs-site.xml").getFile();
String targetFileStr = "{\n" +
" \"security.settings\": \"secsettings\",\n" +
" \"celos.workflow.dir\": \"celoswfdir\",\n" +
" \"hadoop.hdfs-site.xml\": \"" + hadoopHdfsUrl +"\",\n" +
" \"hadoop.core-site.xml\": \"" + hadoopCoreUrl +"\",\n" +
" \"defaults.file.uri\": \"deffile\"\n" +
"}\n";
File targetFile = tempDir.newFile();
FileOutputStream stream = new FileOutputStream(targetFile);
stream.write(targetFileStr.getBytes());
stream.flush();
CelosCiCommandLine commandLine = new CelosCiCommandLine(targetFile.toURI().toString(), "DEPLOY", "deploydir", "workflow", "testDir", "uname", false);
String configJS = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/test.js").getFile();
TestConfigurationParser testConfigurationParser = mock(TestConfigurationParser.class);
CelosCiTargetParser parser = new CelosCiTargetParser("");
CelosCiTarget target = parser.parse(targetFile.toURI());
List<MockTestRun> runList = Lists.newArrayList(new MockTestRun(target, commandLine, null), new MockTestRun(target, commandLine, null));
doReturn(runList).when(testConfigurationParser).getTestCases();
TestTask testTask = new TestTask(commandLine, new File(configJS), tempDir.newFolder());
testTask.getTestRuns().clear();
testTask.getTestRuns().addAll(runList);
testTask.start();
int SLEEP_SECONDS_BEFORE_TEST_FAIL = 5;
int waitCount = 0;
while (!runList.get(0).isFinished() || !runList.get(1).isFinished()) {
if (waitCount ++ == SLEEP_SECONDS_BEFORE_TEST_FAIL) {
Assert.assertTrue(false);
}
Thread.sleep(1000);
}
}
private class MockTestRunException extends TestRun {
private final String testRunFailedText;
public MockTestRunException(String testRunFailedText, CelosCiTarget target, CelosCiCommandLine commandLine, TestCase testCase) throws Exception {
super(target, commandLine, testCase, tempDir.newFolder());
this.testRunFailedText = testRunFailedText;
}
public void start() throws Exception {
throw new TestRunFailedException(testRunFailedText);
}
}
@Test(expected = TestRunFailedException.class)
public void testTestException() throws Throwable {
String hadoopCoreUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/core-site.xml").getFile();
String hadoopHdfsUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/hdfs-site.xml").getFile();
String targetFileStr = "{\n" +
" \"security.settings\": \"secsettings\",\n" +
" \"celos.workflow.dir\": \"celoswfdir\",\n" +
" \"hadoop.hdfs-site.xml\": \"" + hadoopHdfsUrl +"\",\n" +
" \"hadoop.core-site.xml\": \"" + hadoopCoreUrl +"\",\n" +
" \"defaults.file.uri\": \"deffile\"\n" +
"}\n";
File targetFile = tempDir.newFile();
FileOutputStream stream = new FileOutputStream(targetFile);
stream.write(targetFileStr.getBytes());
stream.flush();
CelosCiCommandLine commandLine = new CelosCiCommandLine(targetFile.toURI().toString(), "DEPLOY", "deploydir", "workflow", "testDir", "uname", false);
String configJS = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/test.js").getFile();
TestConfigurationParser testConfigurationParser = mock(TestConfigurationParser.class);
CelosCiTargetParser parser = new CelosCiTargetParser("");
CelosCiTarget target = parser.parse(targetFile.toURI());
List<MockTestRunException> runList = Lists.newArrayList(new MockTestRunException("error2", target, commandLine, null));
doReturn(runList).when(testConfigurationParser).getTestCases();
TestTask testTask = new TestTask(commandLine, new File(configJS), tempDir.newFolder());
testTask.getTestRuns().clear();
testTask.getTestRuns().addAll(runList);
testTask.start();
}
@Test(expected = TestRunFailedException.class)
public void testTestTwoExceptions() throws Throwable {
String hadoopCoreUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/core-site.xml").getFile();
String hadoopHdfsUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/hdfs-site.xml").getFile();
String targetFileStr = "{\n" +
" \"security.settings\": \"secsettings\",\n" +
" \"celos.workflow.dir\": \"celoswfdir\",\n" +
" \"hadoop.hdfs-site.xml\": \"" + hadoopHdfsUrl +"\",\n" +
" \"hadoop.core-site.xml\": \"" + hadoopCoreUrl +"\",\n" +
" \"defaults.file.uri\": \"deffile\"\n" +
"}\n";
File targetFile = tempDir.newFile();
FileOutputStream stream = new FileOutputStream(targetFile);
stream.write(targetFileStr.getBytes());
stream.flush();
CelosCiCommandLine commandLine = new CelosCiCommandLine(targetFile.toURI().toString(), "DEPLOY", "deploydir", "workflow", "testDir", "uname", false);
String configJS = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/test.js").getFile();
TestConfigurationParser testConfigurationParser = mock(TestConfigurationParser.class);
CelosCiTargetParser parser = new CelosCiTargetParser("");
CelosCiTarget target = parser.parse(targetFile.toURI());
List<MockTestRunException> runList = Lists.newArrayList(new MockTestRunException("error1", target, commandLine, null), new MockTestRunException("error2", target, commandLine, null));
doReturn(runList).when(testConfigurationParser).getTestCases();
TestTask testTask = new TestTask(commandLine, new File(configJS), tempDir.newFolder());
testTask.getTestRuns().clear();
testTask.getTestRuns().addAll(runList);
testTask.start();
}
@Test
public void testTempDirIsWorldReadable() throws IOException {
File tempDir = TestTask.getTempDir();
Set<PosixFilePermission> perms = Files.getPosixFilePermissions(tempDir.toPath());
Assert.assertTrue(perms.contains(PosixFilePermission.OTHERS_READ));
Assert.assertTrue(perms.contains(PosixFilePermission.OTHERS_EXECUTE));
Assert.assertTrue(perms.contains(PosixFilePermission.OWNER_READ));
Assert.assertTrue(perms.contains(PosixFilePermission.OWNER_EXECUTE));
Assert.assertTrue(perms.contains(PosixFilePermission.OWNER_WRITE));
tempDir.delete();
}
}
|
package main.java.rest.resource;
import java.io.InputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import main.java.controller.MediaController;
@Path("/media")
public class MediaService {
private MediaController controller = new MediaController();
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response postMedia(@FormDataParam("file") InputStream file,
@FormDataParam("file") FormDataContentDisposition fileDisposition) {
boolean succes = controller.postMedia(file,fileDisposition);
if(succes) {
return Response.status(200).entity("succes").build();
} else {
return Response.status(500).entity("something went wrong").build();
}
}
}
|
import lejos.hardware.lcd.LCD;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.port.MotorPort;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.EV3TouchSensor;
import lejos.robotics.RegulatedMotor;
//Farbsensor 4
// Touchs 1
// Motoren r. A
// Motor l. D
// Kopfmotor C
import lejos.utility.Delay;
public class Main {
private static RegulatedMotor m = new EV3LargeRegulatedMotor(MotorPort.D);
private static RegulatedMotor m1 = new EV3LargeRegulatedMotor(MotorPort.A);
private static RegulatedMotor m2 = new EV3LargeRegulatedMotor(MotorPort.C);
/**
* @param args
*/
public static void main(String[] args){
new Tamagotchi();
//testUltrasonicSensor();
//testEmotion();
finishAfterButtonPress();
}
private static void finishAfterButtonPress(){
EV3TouchSensor sensor = new EV3TouchSensor(SensorPort.S1);
SimpleTouch touch=new SimpleTouch(sensor);
while (true) {
if (touch.isPressed()){
break;
}
}
}
private static void testEmotion(){
EV3TouchSensor sensor = new EV3TouchSensor(SensorPort.S1);
SimpleTouch touch=new SimpleTouch(sensor);
Emotion em = new Emotion(m,m1,m2);
em.start();
while (true) {
if (touch.isPressed()){
em.terminate();
break;
}
}
}
private static void testUltrasonicSensor(){
UltrasonicSensor us = new UltrasonicSensor("S2");
us.start();
us.setActive(true);
while(true){
LCD.drawString("UltraSonic"+us.getData(), 0, 1);
Delay.msDelay(1000);
}
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.BitSet;
import java.security.SecureRandom;
import java.lang.Math;
import java.math.BigInteger;
import gnu.getopt.Getopt;
// TODO: key expansion
// TODO: f function
// TODO: CBC mode debug
public class DES {
/**
* S-Box for Initial Permutation
*/
private static int[] IP = {
58, 50, 42, 34, 26, 18, 10, 2
, 60, 52, 44, 36, 28, 20, 12, 4
, 62, 54, 46, 38, 30, 22, 14, 6
, 64, 56, 48, 40, 32, 24, 16, 8
, 57, 49, 41, 33, 25, 17, 9, 1
, 59, 51, 43, 35, 27, 19, 11, 3
, 61, 53, 45, 37, 29, 21, 13, 5
, 63, 55, 47, 39, 31, 23, 15, 7
};
/**
* S-Box for Final Permutation
*/
private static int[] FP = {
40, 8, 48, 16, 56, 24, 64, 32
, 39, 7, 47, 15, 55, 23, 63, 31
, 38, 6, 46, 14, 54, 22, 62, 30
, 37, 5, 45, 13, 53, 21, 61, 29
, 36, 4, 44, 12, 52, 20, 60, 28
, 35, 3, 43, 11, 51, 19, 59, 27
, 34, 2, 42, 10, 50, 18, 58, 26
, 33, 1, 41, 9, 49, 17, 57, 25
};
public static void main(String[] args) {
StringBuilder inputFile = new StringBuilder();
StringBuilder outputFile = new StringBuilder();
StringBuilder keyStr = new StringBuilder();
StringBuilder encrypt = new StringBuilder();
pcl(args, inputFile, outputFile, keyStr, encrypt);
if(keyStr.toString() != "" && encrypt.toString().equals("e")){
encrypt(keyStr, inputFile, outputFile);
} else if(keyStr.toString() != "" && encrypt.toString().equals("d")){
decrypt(keyStr, inputFile, outputFile);
}
}
//public static void main(String[] args){
//BitSet bset = StringtoBitSet("BC6D211577A50B74");
//System.out.println(BitSettoAscii(bset));
//public static void main(String[] args){
//BitSet plainBlock = StringtoBitSet("bbbbbbb");//generating 56 bits, no effect for now, waiting for DESf to be implemented
//BitSet[] keys = new BitSet[2];
//keys[0] = plainBlock; keys[1] = plainBlock;
//String cipher = feistelNetwork(1,"aaaaaaaa",keys);//testing feistelNetwork
//System.out.println(cipher);
private static void decrypt(StringBuilder keyStr, StringBuilder inputFile,
StringBuilder outputFile) {
try {
PrintWriter writer = new PrintWriter(outputFile.toString(), "UTF-8");
List<String> lines = Files.readAllLines(Paths.get(inputFile.toString()), Charset.defaultCharset());
String IVStr = lines.get(0);
BitSet lastCBC = StringtoBitSet(IVStr);
System.out.println(BitSettoHex(lastCBC));
BitSet decrypted;
for (int i = 1; i < lines.size(); i ++) {
String line = lines.get(i);
if(line.length() != 16) {
throw new IllegalArgumentException("Decrypt block size should be 64 bits.");
}
BitSet block = HextoBitSet(line);
BitSet tmp = block;
decrypted = DES_decrypt(block, keyStr);
decrypted.xor(lastCBC);
lastCBC = tmp;
writer.print(BitSettoAscii(decrypted));
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* DES encryption
* @param block One block of the cyphertext. It should be 64 bits as the requirement
* @param keyStr Decryption key
*/
private static BitSet DES_decrypt(BitSet block, StringBuilder keyStr) {
BitSet[] keys = keyExpansion(keyStr, "d");
permutation(block, DES.FP); // Initial permutation
BitSet result = feistelNetwork(16, block, keys);
permutation(result, DES.IP); // Final permutation
return result;
}
//for debugging, transform a bitset to hex formation
private static String BitSettoHex(BitSet block){
StringBuilder hex = new StringBuilder();
for(int k = 0; k < block.toByteArray().length; k++){
String result = String.format("%02X",block.toByteArray()[k]);
hex.append(result);
}
return hex.toString();
}
//for debugging, transform a bitset to ascii formation
private static String BitSettoAscii(BitSet block){
byte[] b = block.toByteArray();
String str = new String(b);
return str;
}
// Transform Hex string to BitSet
private static BitSet HextoBitSet(String input){
//choose input length carefully so that it fits in 64 bits
BigInteger bigint = new BigInteger(input, 16);
byte[] content = bigint.toByteArray();
if(content.length == 9) {
content = Arrays.copyOfRange(content, 1, content.length);
}
BitSet bits = BitSet.valueOf(content);
return bits;
}
//StringtoBitset: transforms ascii text to bits representation
//to be used in transforming a plaintext block
private static BitSet StringtoBitSet(String input){
//choose input length carefully so that it fits in 64 bits
byte[] bytes = input.getBytes();
BitSet plainBlock = new BitSet(64);
plainBlock.clear();
int i = 0;
for(byte b:bytes){
//System.out.println(b);
int j = 0;
while(j < 8){
if(b%2 == 1)plainBlock.set(i);
i++;j++;
b >>= 1;
}
}
return plainBlock;
}
//DESf: the f function used by feistel Network
//todo: now it just returns all 0
private static BitSet DESf(BitSet tmp0, BitSet key){
BitSet ans = new BitSet(32);
ans.clear();
ans.set(1);
ans.set(2);
return ans;
}
//feistelnetwork: turns plain(64 bits) into cipher(64 bits), should be called with rounds=16 in DES
//keys should be 56 bits BitSet
private static BitSet feistelNetwork(int rounds, BitSet plainBlock, BitSet keys[]){
BitSet tmp1 = plainBlock.get(0,31);
BitSet tmp2 = plainBlock.get(32,63);
BitSet tmp3;
int i = 0;
while(i < rounds){
tmp3 = DESf(tmp2, keys[i]);
tmp3.xor(tmp1);
tmp1 = tmp2;
tmp2 = tmp3;
i++;
}
tmp3 = tmp1;
tmp1 = tmp2;
tmp2 = tmp3;
BitSet cipher = new BitSet(64);
for(i = 0; i < 32; i ++){
if(tmp1.get(i) == true){
cipher.set(i);
}
}
for(i = 0; i < 32; i ++){
if(tmp2.get(i) == true){
cipher.set(i+32);
}
}
return cipher;
}
private static void encrypt(StringBuilder keyStr, StringBuilder inputFile,
StringBuilder outputFile) {
try {
PrintWriter writer = new PrintWriter(outputFile.toString(), "UTF-8");
String encryptedText;
// read input as a single string
String plaintext = new String(Files.readAllBytes(Paths.get(inputFile.toString())));
encryptedText = DES_encrypt(plaintext, keyStr);
writer.print(encryptedText);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Generate key for each round based on encryption or decryption
* @param keyStr The key string
* @param type Encryption or Decryption. Values are 'e' or 'd'.
* @return BitSet[] A list of keys for each round
*/
private static BitSet[] keyExpansion(StringBuilder keyStr, String type) {
BitSet[] keys = new BitSet[16];
BitSet fakeKey = StringtoBitSet("bbbbbbb");
for(int i = 0; i < 16; i ++){
keys[i] = fakeKey;
}
return keys;
}
/**
* Print BitSet as 1s and 0s
*/
private static void printBitSet(BitSet bset){
for(int i = 0; i < bset.size(); i ++) {
if(i % 8 == 0) {
System.out.print(" ");
}
if(bset.get(i) == true) {
System.out.print("1");
} else {
System.out.print("0");
}
}
System.out.print("\n");
}
/**
* Initial or Final Permutation
*/
private static void permutation(BitSet original, int[] sbox) {
if(original.size() != 64) {
throw new IllegalArgumentException("Block size is not 64 bit.");
}
BitSet permuted = new BitSet(64);
for(int i = 0; i < 64; i ++) {
if(original.get(sbox[i]-1) == true) {
permuted.set(i);
}
}
original = permuted;
}
/**
* Generate IV for CBC mode
*/
private static BitSet getCBC_IV() {
BitSet CBC_IV = new BitSet(64);
SecureRandom generator = new SecureRandom();
generator.setSeed(System.currentTimeMillis());
for(int i = 0; i < 64; i ++) {
CBC_IV.set(i, generator.nextBoolean());
}
return CBC_IV;
}
/**
* Use PKCS5 padding algorithm to pad block
* @param block The block to be padded
* @return String Padded block
*/
private static String Padding_PKCS5(String block) {
BitSet block_bit = StringtoBitSet(block);
int padding_length = 8 - block.length()%8;
char padding_char = (char)padding_length;
for(int i = 0; i < padding_length; i ++) {
block = block+padding_char;
}
return block;
}
/**
* The DES encryption function
* @param line The input plaintext
* @return String The encrypted cyphertext
*/
private static String DES_encrypt(String line, StringBuilder keyStr) {
int blockSize = 8; // 8 bytes = 64 bits
int batch = (int)Math.ceil(line.length()*1.0 / blockSize);
BitSet[] EncryptKeys = keyExpansion(keyStr, "e");
String line_padded = Padding_PKCS5(line);
StringBuilder ciphertext = new StringBuilder();
BitSet lastCBC = getCBC_IV();
ciphertext.append(BitSettoHex(lastCBC)+"\n");
System.out.println(BitSettoHex(lastCBC));
for(int i = 0; i < batch; i++){
BitSet block = StringtoBitSet(line_padded.substring(i*blockSize,i*blockSize+blockSize));
// Using CBC mode
block.xor(lastCBC);
// Encrypt
permutation(block, DES.IP); // Initial permutation
BitSet result = feistelNetwork(16, block, EncryptKeys);
permutation(result, DES.FP); // Final permutation
lastCBC = result;
ciphertext.append(BitSettoHex(result)+"\n");
}
return ciphertext.toString();
}
static void genDESkey(){
System.out.println("New key goes here");
return;
}
/**
* This function Processes the Command Line Arguments.
*/
private static void pcl(String[] args, StringBuilder inputFile,
StringBuilder outputFile, StringBuilder keyString,
StringBuilder encrypt) {
Getopt g = new Getopt("Chat Program", args, "hke:d:i:o:");
int c;
String arg;
while ((c = g.getopt()) != -1){
switch(c){
case 'o':
arg = g.getOptarg();
outputFile.append(arg);
break;
case 'i':
arg = g.getOptarg();
inputFile.append(arg);
break;
case 'e':
arg = g.getOptarg();
keyString.append(arg);
encrypt.append("e");
break;
case 'd':
arg = g.getOptarg();
keyString.append(arg);
encrypt.append("d");
break;
case 'k':
genDESkey();
break;
case 'h':
callUseage(0);
case '?':
break; // getopt() already printed an error
default:
break;
}
}
}
private static void callUseage(int exitStatus) {
String useage =
" -h List all command line options\n" +
" -k Generate a DES key\n" +
" -e <key> Specify the key used to encrypt the file\n" +
" -d <key> Specify the key used to decrypt the file\n" +
" -i <path> Specify the input file\n" +
" -o <path> Specify the output file\n";
System.err.println(useage);
System.exit(exitStatus);
}
}
|
package playn.java;
import org.eclipse.swt.SWT;
import playn.core.Events;
import playn.core.Key;
import playn.core.Touch;
import playn.core.util.Callback;
public class SWTKeyboard extends JavaKeyboard {
private SWTPlatform platform;
public SWTKeyboard(SWTPlatform platform) {
this.platform = platform;
}
// TODO
@Override
public void getText(TextType textType, String label, String initVal, Callback<String> callback) {
callback.onFailure(new Exception("TODO"));
}
void init(Touch touch) {
super.init(touch);
platform.display.addFilter(SWT.KeyDown, new org.eclipse.swt.widgets.Listener() {
public void handleEvent (org.eclipse.swt.widgets.Event event) {
Key key = translateKey(event.keyCode);
if (key != null) {
dispatch(new Event.Impl(new Events.Flags.Impl(), event.time, key), down);
} else {
System.err.println("KEY? " + event.keyCode + " / " + event.character);
}
char keyChar = event.character;
if (Character.isISOControl(keyChar)) {
dispatch(new TypedEvent.Impl(new Events.Flags.Impl(), event.time, keyChar), typed);
}
}
});
platform.display.addFilter(SWT.KeyUp, new org.eclipse.swt.widgets.Listener() {
public void handleEvent (org.eclipse.swt.widgets.Event event) {
Key key = translateKey(event.keyCode);
if (key != null) {
dispatch(new Event.Impl(new Events.Flags.Impl(), event.time, key), up);
}
}
});
}
public Key translateKey(int keyCode) {
switch (keyCode) {
case SWT.ALT : return Key.ALT;
case SWT.ARROW_DOWN : return Key.DOWN;
case SWT.ARROW_LEFT : return Key.LEFT;
case SWT.ARROW_RIGHT : return Key.RIGHT;
case SWT.ARROW_UP : return Key.UP;
case SWT.BREAK : return Key.BREAK;
case SWT.CAPS_LOCK : return Key.CAPS_LOCK;
case SWT.COMMAND : return Key.META;
case SWT.CONTROL : return Key.CONTROL;
case SWT.DEL : return Key.DELETE;
case SWT.END : return Key.END;
case SWT.ESC : return Key.ESCAPE;
case SWT.F1 : return Key.F1;
case SWT.F10 : return Key.F10;
case SWT.F11 : return Key.F11;
case SWT.F12 : return Key.F12;
case SWT.F2 : return Key.F2;
case SWT.F3 : return Key.F3;
case SWT.F4 : return Key.F4;
case SWT.F5 : return Key.F5;
case SWT.F6 : return Key.F6;
case SWT.F7 : return Key.F7;
case SWT.F8 : return Key.F8;
case SWT.F9 : return Key.F9;
case SWT.HOME : return Key.HOME;
case SWT.INSERT : return Key.INSERT;
case SWT.KEYPAD_0 : return Key.NP0;
case SWT.KEYPAD_1 : return Key.NP1;
case SWT.KEYPAD_2 : return Key.NP2;
case SWT.KEYPAD_3 : return Key.NP3;
case SWT.KEYPAD_4 : return Key.NP4;
case SWT.KEYPAD_5 : return Key.NP5;
case SWT.KEYPAD_6 : return Key.NP6;
case SWT.KEYPAD_7 : return Key.NP7;
case SWT.KEYPAD_8 : return Key.NP8;
case SWT.KEYPAD_9 : return Key.NP9;
case SWT.KEYPAD_CR : return Key.ENTER;
case SWT.KEYPAD_DECIMAL : return Key.NP_DECIMAL;
case SWT.KEYPAD_DIVIDE : return Key.NP_DIVIDE;
// case SWT.KEYPAD_EQUAL : return Key.NP_EQUAL;
case SWT.KEYPAD_MULTIPLY : return Key.NP_MULTIPLY;
case SWT.KEYPAD_SUBTRACT : return Key.NP_SUBTRACT;
case SWT.NUM_LOCK : return Key.NP_NUM_LOCK;
case SWT.PAGE_DOWN : return Key.PAGE_DOWN;
case SWT.PAGE_UP : return Key.PAGE_UP;
case SWT.PAUSE : return Key.PAUSE;
case SWT.PRINT_SCREEN : return Key.PRINT_SCREEN;
case SWT.SCROLL_LOCK : return Key.SCROLL_LOCK;
case SWT.SHIFT : return Key.SHIFT;
case SWT.TAB : return Key.TAB;
// case SWT.KEY_SYSRQ : return Key.SYSRQ;
// case SWT.KEY_FUNCTION : return Key.FUNCTION;
// case SWT.KEY_DELETE : return Key.DELETE;
// case SWT.KEY_CLEAR : return Key.CLEAR;
// case SWT.KEY_POWER : return Key.POWER;
// printing keys are just their ASCII equivalents
case 'a': return Key.A;
case 'b': return Key.B;
case 'c': return Key.C;
case 'd': return Key.D;
case 'e': return Key.E;
case 'f': return Key.F;
case 'g': return Key.G;
case 'h': return Key.H;
case 'i': return Key.I;
case 'j': return Key.J;
case 'k': return Key.K;
case 'l': return Key.L;
case 'm': return Key.M;
case 'n': return Key.N;
case 'o': return Key.O;
case 'p': return Key.P;
case 'q': return Key.Q;
case 'r': return Key.R;
case 's': return Key.S;
case 't': return Key.T;
case 'u': return Key.U;
case 'v': return Key.V;
case 'w': return Key.W;
case 'x': return Key.X;
case 'y': return Key.Y;
case 'z': return Key.Z;
case '0': return Key.K0;
case '1': return Key.K1;
case '2': return Key.K2;
case '3': return Key.K3;
case '4': return Key.K4;
case '5': return Key.K5;
case '6': return Key.K6;
case '7': return Key.K7;
case '8': return Key.K8;
case '9': return Key.K9;
case '`': return Key.BACKQUOTE;
case '-': return Key.MINUS;
case ' ': return Key.SPACE;
case '=': return Key.EQUALS;
case '[': return Key.LEFT_BRACKET;
case ']': return Key.RIGHT_BRACKET;
case ';': return Key.SEMICOLON;
case '/': return Key.SLASH;
case ',': return Key.COMMA;
case '.': return Key.PERIOD;
case '~': return Key.TILDE;
case 8: return Key.BACKSPACE;
case '\'': return Key.QUOTE;
case '\\': return Key.BACKSLASH;
case '\n': return Key.ENTER;
case '\r': return Key.ENTER;
// TODO: other printables that aren't "unshifted" on US QWERTY?
}
return null;
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.Random;
import java.util.Scanner;
/**
* Test
*
* @author APCSA2014-15
* @version 2015-03-06
*/
public class Zoo
{
public static void main(String[] args) throws InterruptedException
{
List<Random> animals = new ArrayList<Random>();
System.out.println("Welcome to the Zoo!\n");
System.out.print("Building the cages");
delayDots();
System.out.print("Populating the animals");
populateAnimals(animals);
delayDots();
System.out.print("Hiring zookeepers");
delayDots();
Scanner in = new Scanner(System.in);
System.out.println("\nYou are standing in a wondrous zoo. What would you like to do?");
System.out.println("Type help to find out what you can do.\n");
String text = in.nextLine();
String msg = "";
while(!text.equals("leave"))
{
switch(text)
{
case "help" : msg = "So far we can only leave and ask for help.";
break;
default : msg = "You flail helplessly with indecision.";
}
System.out.println("\n" + msg);
System.out.println("\nYou are standing in a wondrous zoo. What would you like to do?\n");
text = in.nextLine();
}
System.out.println(Math.random() < .8 ? "\nHave a nice day! Hope you come back!" : "\nAn escaped lion eats you on your way out. Sorry!");
}
/**
* This prints an ellipses with 1 second between each period
* It then moves to the next line.
*/
public static void delayDots(int dotAmount) throws InterruptedException
{
for (int i=0; i<dotAmount; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.print(".");
}
System.out.println();
}
/**
* This prints an ellipses with 1 second between each period
* It then moves to the next line.
*/
public static void delayDots(int dotAmount) throws InterruptedException
{
delayDots(3);
}
/**
* This is where we will all collaborate.
* Construct your animal and add it to the List
* @param animals the list containing all the zoo animals
*/
public static void populateAnimals(List<Random> animals)
{
Random r = new Random();
Random q = new Random();
animals.add(r);
animals.add(q);
}
}
|
package com.wegas.core.ejb;
import com.fasterxml.jackson.databind.JsonNode;
import com.wegas.core.Helper;
import com.wegas.core.exception.client.WegasErrorMessage;
import com.wegas.core.exception.internal.WegasNoResultException;
import com.wegas.core.jcr.content.AbstractContentDescriptor;
import com.wegas.core.jcr.content.ContentConnector;
import com.wegas.core.jcr.content.DescriptorFactory;
import com.wegas.core.jcr.content.DirectoryDescriptor;
import com.wegas.core.jcr.jta.JCRConnectorProvider;
import com.wegas.core.merge.patch.WegasEntityPatch;
import com.wegas.core.merge.patch.WegasPatch;
import com.wegas.core.merge.utils.MergeHelper;
import com.wegas.core.persistence.AbstractEntity;
import com.wegas.core.persistence.game.GameModel;
import com.wegas.core.persistence.game.GameModel.GmType;
import com.wegas.core.persistence.game.GameModelContent;
import com.wegas.core.persistence.variable.DescriptorListI;
import com.wegas.core.persistence.variable.ModelScoped;
import com.wegas.core.persistence.variable.VariableDescriptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jcr.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author maxence
*/
@Stateless
@LocalBean
public class ModelFacade {
private static final Logger logger = LoggerFactory.getLogger(ModelFacade.class);
@Inject
private GameModelFacade gameModelFacade;
@Inject
private VariableDescriptorFacade variableDescriptorFacade;
@Inject
private RequestManager requestManager;
@Inject
private JCRConnectorProvider jCRConnectorProvider;
/**
* return a new list of managed scenarios
*
* @param scenarios
*
* @return scenarios copy, ensuring its content is managed
*/
private List<GameModel> loadGameModels(List<GameModel> scenarios) {
List<GameModel> scens = new ArrayList<>();
for (GameModel gm : scenarios) {
scens.add(gameModelFacade.find(gm.getId()));
}
return scens;
}
/**
*
* @param modelName
* @param scenarioIds
*
* @return
*/
public GameModel createModelFromCommonContentFromIds(String modelName, List<Long> scenarioIds) {
return createModelFromCommonContent(modelName, loadGameModelsFromIds(scenarioIds));
}
/**
*
* @param scenarioIds
*
* @return
*/
private List<GameModel> loadGameModelsFromIds(List<Long> scenarioIds) {
List<GameModel> scenarios = new ArrayList<>();
for (Long id : scenarioIds) {
scenarios.add(gameModelFacade.find(id));
}
return scenarios;
}
/**
* Create a gameModel which contains only the content which is shared among all gameModels
* The structure, as well as gameModel properties, will be the same as the first scenario in the list
* The returned scenario is not persisted. Caller may personalize the model (changing descriptors visibility).
* <p>
* To eventually create and persist the model, method {@link #createModel(com.wegas.core.persistence.game.GameModel, java.util.List) createModel} must be called
*
*
* @param modelName name of the new model
* @param scenarios list of gameModel to model, the first acts as reference for descriptors structure
*
* @return a game model which contains what all given scenario have in common
*/
public GameModel createModelFromCommonContent(String modelName, List<GameModel> scenarios) {
logger.info("Extract Common Content");
GameModel model = null;
if (!scenarios.isEmpty()) {
try {
// get a copy
List<GameModel> allScenarios = loadGameModels(scenarios);
scenarios = loadGameModels(scenarios);
// extract the first scenario to act as reference
logger.info("Create model, based on first scenario");
GameModel srcModel = scenarios.remove(0);
model = (GameModel) srcModel.duplicate();
model.setName(modelName);
/**
* Filter gameModelContents
*/
logger.info("Filter Libraries");
Map<String, Map<String, GameModelContent>> libraries = model.getLibraries();
List<Map<String, Map<String, GameModelContent>>> otherLibraries = new ArrayList<>();
for (GameModel other : scenarios) {
otherLibraries.add(other.getLibraries());
}
for (Entry<String, Map<String, GameModelContent>> libEntry : libraries.entrySet()) {
String libraryName = libEntry.getKey();
logger.info(" Process {}", libraryName);
Map<String, GameModelContent> library = libEntry.getValue();
for (Iterator<Entry<String, GameModelContent>> it = library.entrySet().iterator(); it.hasNext();) {
Entry<String, GameModelContent> entry = it.next();
String key = entry.getKey();
GameModelContent content = entry.getValue();
boolean exists = true;
for (Map<String, Map<String, GameModelContent>> otherLibs : otherLibraries) {
Map<String, GameModelContent> otherLib = otherLibs.get(libraryName);
if (!otherLib.containsKey(key)) {
exists = false;
// at least on scenrios which doesn't define the entry
break;
}
}
if (exists) {
content.setVisibility(ModelScoped.Visibility.INHERITED);
logger.info(" -> keep {}", key);
} else {
logger.info(" -> evict {}", key);
it.remove();
}
}
}
model.setLibraries(libraries);
List<VariableDescriptor> vdQueue = new ArrayList<>();
vdQueue.addAll(model.getChildVariableDescriptors());
List<VariableDescriptor> exclusionCandidates = new ArrayList<>();
/**
* Select variable descriptor to keep
*/
logger.info("Process variables");
while (vdQueue.size() > 0) {
VariableDescriptor vd = vdQueue.remove(0);
logger.info(" Process {}", vd);
boolean exists = true;
// does the descriptor exists in all gameModel ?
for (GameModel other : scenarios) {
try {
variableDescriptorFacade.find(other, vd.getName());
} catch (WegasNoResultException ex) {
exists = false;
break;
}
}
// queue all children even if the current descriptor doesn't exists in all scenarios
// becaus such a children may exists in all scenarios
if (vd instanceof DescriptorListI) {
DescriptorListI list = (DescriptorListI) vd;
vdQueue.addAll(list.getItems());
}
if (exists) {
logger.debug("Descriptor {} exists in all scenarios", vd);
// vd exists is all scenarios -> keep
vd.setVisibility(ModelScoped.Visibility.INHERITED);
} else {
logger.debug("Descriptor {} does NOT exists in all scenarios", vd);
if (vd instanceof DescriptorListI) {
//vd does not exists is all scenarios but may contains a child which is
exclusionCandidates.add(vd);
} else {
// exclude descriptor from model
DescriptorListI parent = vd.getParent();
parent.remove(vd);
}
}
}
/*
* go through exclusionCanditates to detemintate which of them should be kept
* a candidate is a descriptor which is not shared among all scenarios, but it may contains children which are.
* When it's the case, the descriptor must be kept.
* If the descriptor doesn't contains any children, it can be removed
*/
boolean restart;
do {
restart = false;
for (Iterator<VariableDescriptor> it = exclusionCandidates.iterator(); it.hasNext();) {
VariableDescriptor vd = it.next();
logger.debug("Should keep {} ?", vd);
DescriptorListI list = (DescriptorListI) vd;
if (list.size() == 0) {
// list descriptor doesnt's have any children -> remove
logger.debug(" -> NO (is empty)");
it.remove();
vd.getParent().remove(vd);
// since the structure has changed, another iteration is required because vd.getParent() may now be empty
restart = true;
} else {
// vd has children -> keep
vd.setVisibility(ModelScoped.Visibility.INHERITED);
}
}
} while (restart);
/*
* Persist GameModel
*/
model.setType(GameModel.GmType.MODEL);
model.setBasedOn(null);
gameModelFacade.createWithDebugGame(model);
for (GameModel scenario : allScenarios) {
logger.info("Register Implementation {} to {}", scenario, model);
//model.getImplementations().add(scenario);
scenario.setBasedOn(model);
}
/*
* JCR REPOSITORY
*/
gameModelFacade.duplicateRepository(model, srcModel);
// Open the brand new model repository
try {
ContentConnector modelRepo = jCRConnectorProvider.getContentConnector(model, ContentConnector.WorkspaceType.FILES);
logger.error("JCR FILES");
// open all other repositories but the one whose modelRepo is a copy of
List<ContentConnector> repositories = new ArrayList<>(scenarios.size());
for (GameModel scenario : scenarios) {
repositories.add(jCRConnectorProvider.getContentConnector(scenario, ContentConnector.WorkspaceType.FILES));
}
List<AbstractContentDescriptor> fileQueue = new LinkedList<>();
fileQueue.add(DescriptorFactory.getDescriptor("/", modelRepo));
while (!fileQueue.isEmpty()) {
AbstractContentDescriptor item = fileQueue.remove(0);
logger.error("Process {}", item);
String path = item.getFullPath();
boolean exists = true;
for (ContentConnector otherRepository : repositories) {
logger.error(" other repo: path {}", path);
AbstractContentDescriptor descriptor = DescriptorFactory.getDescriptor(path, otherRepository);
if (!descriptor.exist() || !descriptor.getClass().equals(item.getClass())) {
logger.error("BREAK");
exists = false;
break;
}
}
if (exists) {
logger.error(" item exists");
item.setVisibility(ModelScoped.Visibility.INHERITED);
item.setContentToRepository();
item.getContentFromRepository();
if (item instanceof DirectoryDescriptor) {
// directory exists in all scenarios: process children
fileQueue.addAll(((DirectoryDescriptor) item).list());
}
} else {
// item does not exists in all scenario -> delete
logger.error(" item does not exist");
item.delete(true);
}
}
} catch (RepositoryException ex) {
java.util.logging.Logger.getLogger(ModelFacade.class.getName()).log(Level.SEVERE, null, ex);
}
logger.info("Process variables");
} catch (CloneNotSupportedException ex) {
logger.error("Exception while creating model", ex);
}
}
return model;
}
/**
*
* @param vd
*
* @return
*/
private String getParentRef(VariableDescriptor vd) {
DescriptorListI parent = vd.getParent();
if (parent instanceof AbstractEntity) {
return ((AbstractEntity) parent).getRefId();
} else {
return null; //throw error ?
}
}
public GameModel getReference(GameModel model) {
Collection<GameModel> implementations = gameModelFacade.getImplementations(model);
for (GameModel gm : implementations) {
if (gm.getType().equals(GmType.REFERENCE)) {
return gm;
}
}
return null;
}
/**
* Attach all scenarios to the given model
*
* @param model the model
* @param scenarios scenario to attach to model
*/
public void integrateScenario(GameModel model, List<GameModel> scenarios) throws RepositoryException {
if (model != null) {
if (GmType.MODEL.equals(model.getType())) {
GameModel reference = this.getReference(model);
scenarios = loadGameModels(scenarios);
// set scenarios refId to model refId
for (GameModel scenario : scenarios) {
scenario.forceRefId(model.getRefId());
if (scenario.getType().equals(GmType.SCENARIO)) {
scenario.setOnGoingPropagation(Boolean.TRUE);
}
}
/*
* override scenearios pages
*/
Map<String, JsonNode> pages = reference.getPages();
for (GameModel scenario : scenarios) {
scenario.setPages(pages);
}
Map<VariableDescriptor, VariableDescriptor> toMove = new HashMap<>();
Map<GameModel, List<VariableDescriptor>> toCreate = new HashMap<>();
logger.info("Assert variables structure match structure in the model and override refIds");
for (VariableDescriptor modelVd : model.getVariableDescriptors()) {
// iterate over all model's descriptors
String modelParentRef = this.getParentRef(modelVd);
String name = modelVd.getName();
for (GameModel scenario : scenarios) {
try {
// get corresponding descriptor in the scenrio
VariableDescriptor vd = variableDescriptorFacade.find(scenario, name);
MergeHelper.resetRefIds(vd, modelVd); // make sure corresponding descriptors share the same refId
String parentRef = this.getParentRef(vd);
if (!parentRef.equals(modelParentRef)) {
logger.info("Descriptor {} will be moved from {} to {}", vd, vd.getParent(), modelVd.getParent());
// Parents differs
toMove.put(vd, modelVd); //key : the descriptor to move; value: corresponding descriptor within the model
}
} catch (WegasNoResultException ex) {
// corresponding descriptor not found -> it has to be created
logger.info("Descriptor {} will be created in {}", modelVd, modelVd.getParent());
if (modelVd instanceof DescriptorListI) {
toCreate.putIfAbsent(scenario, new ArrayList<>());
toCreate.get(scenario).add(modelVd);
}
}
}
}
// Create missing descriptors (DescriptorListI) to ensure all scenarios have the correct struct
for (GameModel scenario : toCreate.keySet()) {
List<VariableDescriptor> vdToCreate = toCreate.get(scenario);
logger.info("Create missing descriptor for {}", scenario);
boolean restart;
do {
restart = false;
for (Iterator<VariableDescriptor> it = vdToCreate.iterator(); it.hasNext();) {
VariableDescriptor vd = it.next();
try {
logger.info(" - missing descriptor is {}", vd);
DescriptorListI modelParent = vd.getParent();
if (modelParent instanceof VariableDescriptor) {
String parentName = ((VariableDescriptor) modelParent).getName();
try {
VariableDescriptor parent = variableDescriptorFacade.find(scenario, parentName);
VariableDescriptor clone;
clone = (VariableDescriptor) vd.shallowClone();
variableDescriptorFacade.createChild(scenario, (DescriptorListI<VariableDescriptor>) parent, clone);
logger.info(" CREATE AT as {} child", parent);
it.remove();
restart = true;
} catch (WegasNoResultException ex) {
logger.info(" PARENT {} NOT FOUND -> POSTPONE", modelParent);
}
} else {
logger.info(" CREATE AT ROOL LEVEL");
VariableDescriptor clone = (VariableDescriptor) vd.shallowClone();
variableDescriptorFacade.createChild(scenario, scenario, clone);
clone.setName(vd.getName());
it.remove();
restart = true;
}
} catch (CloneNotSupportedException ex) {
logger.error("Error while cloning {}", vd);
}
}
} while (restart);
}
logger.info("Move misplaced descriptors");
for (Entry<VariableDescriptor, VariableDescriptor> entry : toMove.entrySet()) {
logger.info("Process : {}", entry);
//key : the descriptor to move; value: corresponding descriptor within the model
this.move(entry.getKey(), entry.getValue());
}
// generate initial patch agains model
WegasEntityPatch initialPatch = new WegasEntityPatch(reference, reference, true);
logger.info("InitialPatch: {}", initialPatch);
// apply patch to all scenarios
for (GameModel scenario : scenarios) {
//initialPatch.apply(scenario, null, WegasPatch.PatchMode.OVERRIDE);
logger.info("Patch {}", scenario);
initialPatch.apply(scenario, scenario);
// revive
scenario.setBasedOn(model);
logger.info("Revive {}", scenario);
//scenario.propagateGameModel();
logger.debug(Helper.printGameModel(scenario));
variableDescriptorFacade.reviveItems(scenario, scenario, false);
gameModelFacade.reset(scenario);
}
this.syncRepository(model);
for (GameModel scenario : scenarios) {
if (scenario.getType().equals(GmType.SCENARIO)) {
scenario.setOnGoingPropagation(Boolean.FALSE);
}
}
logger.info("PROCESS COMPLETED");
}
}
}
/**
*
* @param model
*/
private void syncRepository(GameModel model) throws RepositoryException {
if (model.getType().equals(GmType.MODEL)) {
GameModel reference = this.getReference(model);
Collection<GameModel> implementations = gameModelFacade.getImplementations(model);
if (reference != null) {
ContentConnector modelRepo = jCRConnectorProvider.getContentConnector(model, ContentConnector.WorkspaceType.FILES);
ContentConnector refRepo = jCRConnectorProvider.getContentConnector(reference, ContentConnector.WorkspaceType.FILES);
AbstractContentDescriptor modelRoot = DescriptorFactory.getDescriptor("/", modelRepo);
AbstractContentDescriptor refRoot = DescriptorFactory.getDescriptor("/", refRepo);
//diff from ref to model files
WegasPatch patch = new WegasEntityPatch(refRoot, modelRoot, Boolean.TRUE);
for (GameModel scenario : implementations) {
if (scenario.getType().equals(GmType.SCENARIO)) {
// apply patch to each implementations
ContentConnector repo = jCRConnectorProvider.getContentConnector(scenario, ContentConnector.WorkspaceType.FILES);
AbstractContentDescriptor root = DescriptorFactory.getDescriptor("/", repo);
patch.apply(scenario, root);
}
}
// and patch the reference
patch.apply(reference, refRoot);
}
} else {
throw WegasErrorMessage.error("GameModel " + model + " is not a model (sic)");
}
}
/**
* Move vd according to the position of the corresponding modelVd
*
* @param vd the misplaced descriptor
* @param modelVd the correpsonding descriptor in the model
*/
private void move(VariableDescriptor vd, VariableDescriptor modelVd) {
// should move find to according to model structure before patching
DescriptorListI from = vd.getParent();
DescriptorListI modelParent = modelVd.getParent();
logger.info("Move {} from {} to {}", vd, from, modelParent);
from.remove(vd);
DescriptorListI newParent;
if (modelParent instanceof VariableDescriptor) {
// original parent is a descriptor
String parentName = ((VariableDescriptor) modelParent).getName();
try {
newParent = (DescriptorListI) variableDescriptorFacade.find(vd.getGameModel(), parentName);
} catch (WegasNoResultException ex) {
logger.error("Parent not found within scenario -> should never occurs");
newParent = null;
}
} else {
// Root-level descriptor -> parent is the gameModel;
newParent = vd.getGameModel();
}
if (newParent != null) {
newParent.addItem(vd); // order will be restored later
} else {
throw WegasErrorMessage.error("ORPHAN DESCRIPTOR");
}
}
/**
* Propagate mode to all implementations
*
* @param gameModelId
*
* @return
*
* @throws javax.jcr.RepositoryException
*
*/
public GameModel propagateModel(Long gameModelId) throws RepositoryException {
return this.propagateModel(gameModelFacade.find(gameModelId));
}
/**
* Propagate mode to all implementations
*
* @param gameModel
*
* @return
*
*/
private GameModel propagateModel(GameModel gameModel) throws RepositoryException {
if (gameModel.getType().equals(GmType.MODEL)) {
GameModel reference = this.getReference(gameModel);
if (reference == null) {
/*
* create reference
*/
logger.info("Create Reference");
try {
reference = (GameModel) gameModel.duplicate();
} catch (CloneNotSupportedException ex) {
throw WegasErrorMessage.error("Could not create reference by cloning " + gameModel);
}
reference.setType(GameModel.GmType.REFERENCE);
reference.setBasedOn(gameModel);
gameModelFacade.create(reference);
// flush to force pages to be stored
gameModelFacade.flush();
gameModelFacade.duplicateRepository(reference, gameModel);
List<GameModel> implementations = gameModelFacade.getImplementations(gameModel);
this.integrateScenario(gameModel, implementations);
} else {
WegasPatch patch = new WegasEntityPatch(reference, gameModel, Boolean.TRUE);
logger.info("PropagatePatch: {}", patch);
Collection<GameModel> implementations = gameModelFacade.getImplementations(gameModel);
for (GameModel scenario : implementations) {
// avoid propagating to game's scenarios or to the model
if (scenario.getType().equals(GmType.SCENARIO)) {
scenario.setOnGoingPropagation(Boolean.TRUE);
patch.apply(scenario, scenario);
logger.info("Revive {}", scenario);
//scenario.propagateGameModel();
variableDescriptorFacade.reviveItems(scenario, scenario, false);
gameModelFacade.reset(scenario);
}
}
patch.apply(reference, reference);
//reference.propagateGameModel();
this.syncRepository(gameModel);
for (GameModel scenario : implementations) {
// avoid propagating to game's scenarios or to the model
if (scenario.getType().equals(GmType.SCENARIO)) {
scenario.setOnGoingPropagation(Boolean.FALSE);
}
}
}
return gameModel;
} else {
throw WegasErrorMessage.error("GameModel " + gameModel + " is not a model (sic)");
}
}
}
|
package com.base.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.base.contants.Contants;
import com.base.po.AllPlan;
import com.base.po.ApplyDept;
import com.base.po.BaseCheckList;
import com.base.po.ExportBase;
import com.base.po.PlanList;
import com.base.service.PlanMaintainService;
import com.base.service.baseApplyService;
import com.base.serviceImpl.AdminManageServiceImpl;
import com.base.serviceImpl.InputExcelServiceImpl;
import com.base.utils.ExcelReport;
import com.base.utils.WeekTransformToTime;
@Controller("planMaintainController")
@RequestMapping("/jsp")
public class PlanMaintainController {
@Autowired
private PlanMaintainService planMaintainService;
@Autowired
private AdminManageServiceImpl adminManageServiceImpl;
@Autowired
private baseApplyService baseapplyservice;
@RequestMapping("/displayPlanInfo.do")
public String displayPlanInfo(HttpServletRequest request,
HttpServletResponse response) {
String semester = request.getParameter("semester");
System.out.println("semester:"+semester);
if (semester.equals("")) {
semester = null;
}
String searchValue = request.getParameter("search[value]");
if (searchValue.equals("")) {
searchValue = null;
}
Integer size = Integer.parseInt(request.getParameter("length"));
Integer startIndex = Integer.parseInt(request.getParameter("start"));
Integer draw = Integer.parseInt(request.getParameter("draw"));
int order = Integer.valueOf(request.getParameter("order[0][column]"));
String orderDir = request.getParameter("order[0][dir]");// asc or
// // desc
Integer pageindex = (startIndex / size + 1);
int recordsTotal=0;
List<AllPlan> list=new ArrayList<AllPlan>();
if(semester!=null){
PlanList pl = null;
pl = planMaintainService.getPlanInfo(semester, pageindex, size, order,
orderDir, searchValue);
list=pl.getData();
recordsTotal=pl.getRecordsTotal();
}
JSONObject getObj = new JSONObject();
getObj.put("draw", draw);
getObj.put("recordsFiltered", recordsTotal);
getObj.put("recordsTotal", recordsTotal);
getObj.put("data", list);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/exportPlanInfo.do")
public String exportPlanInfo(HttpServletRequest request,
HttpServletResponse response) {
String semester =request.getParameter("semester");
String college = request.getParameter("college");
if(college.equals("-1")){
college=null;
}
List<AllPlan> list = planMaintainService
.getPlanTable(semester, college);
if (CollectionUtils.isNotEmpty(list)) {
String path = request.getSession().getServletContext()
.getRealPath("/upload/");
/* String path = ExcelReport.getWebRootUrl(request,"/upload/"); */
String fullFileName = path + "/PracticePlanInfo.xlsx";
ExcelReport export = new ExcelReport();
export.exportPracticePlanInfo(list, fullFileName);
String filename = ".xlsx";
response.setContentType("application/octet-stream;charset=UTF-8");
try {
response.setContentType("application/octet-stream");
boolean isMSIE = ExcelReport.isMSBrowser(request);
if (isMSIE) {
filename = URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"),
"ISO-8859-1");
}
response.setHeader("Content-disposition",
"attachment;filename=\"" + filename + "\"");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(fullFileName);
out = response.getOutputStream();
int b = 0;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
return "practicePlanMaintain";
}
@RequestMapping("/checkIsThisUser.do")
public String checkIsThisUser(HttpServletRequest request,
HttpServletResponse response) {
String id = request.getParameter("id");
boolean flag=planMaintainService.checkIsUser(id);
JSONObject getObj = new JSONObject();
getObj.put("flag", flag);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/checkIsThisMid.do")
public String checkIsThisMid(HttpServletRequest request,
HttpServletResponse response) {
String aid = request.getParameter("aid");
boolean flag=planMaintainService.checkIsMid(aid);
JSONObject getObj = new JSONObject();
getObj.put("flag", flag);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/addOnePlanInfo.do")
public String addOnePlanInfo(HttpServletRequest request,
HttpServletResponse response) {
String str = request.getParameter("str");
System.out.println(str);
str = "insert into baseweb.coursearrange(semester,college,cid,count,selectedCount,composition,coursename,weekClassify,credit,courseNature,courseCategory,tid,tname,"
+ "Week,checkMethod,mid,major_oriented) values" + str;
planMaintainService.addOnePlanInfo(str);
JSONObject getObj = new JSONObject();
getObj.put("flag", true);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/getPlanMaintainInfo.do")
public String getPlanMaintainInfo(HttpServletRequest request,
HttpServletResponse response) {
List<ApplyDept> list1 = baseapplyservice.getDept(1);
List<String> list2=planMaintainService.getSemester();
JSONObject getObj = new JSONObject();
getObj.put("college", list1);
getObj.put("semester", list2);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/getReadyCollege.do")
public String getReadyCollege(HttpServletRequest request,
HttpServletResponse response) {
String semester=request.getParameter("semester");
List<String> list=planMaintainService.getPlanCollege(semester);
JSONObject getObj = new JSONObject();
getObj.put("college", list);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/importPlanInfo.do")
public String importPlanInfo(HttpServletRequest request,
HttpServletResponse response) throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mFile = multipartRequest.getFile("fileResource");
String path = request.getSession().getServletContext()
.getRealPath("/upload/");
String fileName = mFile.getOriginalFilename();
String filename = "";
if (!fileName.isEmpty()) {
filename = new Date().getTime() + "$" + fileName;
InputStream inputStream = mFile.getInputStream();
byte[] b = new byte[1048576];
int length = inputStream.read(b);
path += "\\" + filename;
File tempFile = new File(path);
FileOutputStream outputStream = new FileOutputStream(tempFile);
outputStream.write(b, 0, length);
filename = path;
// list
Workbook wb = (Workbook) InputExcelServiceImpl.getWb(path);
List<List<String>> list = InputExcelServiceImpl.getPlanExcelRows(InputExcelServiceImpl.getSheet(wb, 0), -1, -1);
// System.out.println("");
// list
if (CollectionUtils.isNotEmpty(list)) {
String prefix = "INSERT IGNORE INTO baseweb.coursearrange(count,selectedCount,composition,"
+ "college,cid,coursename,"
+ "weekClassify,credit,courseNature,courseCategory,"
+ "siteRepuire,tid,tname,"
+ "technicalTitle,semester,week,checkMethod,mid,major_oriented,checkTime) "
+ "values";
StringBuffer suffix = new StringBuffer();
for (int i = 1; i < list.size(); i++) {
String resultStr = "";
// sheet
List<String> row = list.get(i);
// System.out.println(row.size());
System.out.println("row size is " + row.size());
if (row != null && row.size() > 0) {
String value = null;
String termYear=null;
int week=0;
for (int j = 0; j < row.size(); j++) {
value = row.get(j);
if (j == 6) {
if(value.length()==0){
value="0";
}else{
value = value.substring(1);
}
} else if (j == 7) {
if(value.length()==0){
value="0";
}
}else if (j == 15) {
if(value.length()!=0){
week=Integer.valueOf(value.substring(0,value.indexOf('-')));
}
}else if (j == 14) {
value = value.substring(value.indexOf('(') + 1,
value.lastIndexOf(')'));
termYear=value;
}
resultStr = resultStr + '"' + value + '"' + ',';
}
/*resultStr = resultStr.substring(0,
resultStr.length() - 1);*/
resultStr=resultStr+WeekTransformToTime.weekTransformToTime(termYear, week);
suffix.append("(" + resultStr + "),");
}
}
// sql
String sql = prefix
+ suffix.substring(0, suffix.length() - 1)
+ " on duplicate key update count=values(count),selectedCount=values(selectedCount),composition=values(composition),college=values(college)"
+ ",cid=values(cid),coursename=values(coursename),weekClassify=values(weekClassify),credit=values(credit)"
+ ",courseNature=values(courseNature),courseCategory=values(courseCategory),siteRepuire=values(siteRepuire),tid=values(tid)"
+ ",tname=values(tname),technicalTitle=values(technicalTitle),semester=values(semester),week=values(week),checkMethod=values(checkMethod),mid=values(mid),major_oriented=values(major_oriented),checkTime=values(checkTime)";
System.out.println(sql);
adminManageServiceImpl.setAdminFunction(sql);
}
wb.close();
outputStream.close();
inputStream.close();
tempFile.delete();
}
return "redirect:practicePlanMaintain.jsp";
}
@RequestMapping("/checkIsSave.do")
public String checkIsSave(HttpServletRequest request,
HttpServletResponse response) {
String semester = "2016-2017-1";// request.getParameter("semester");
if (semester.equals("")) {
semester = null;
}
String searchValue = request.getParameter("search[value]");
if (searchValue.equals("")) {
searchValue = null;
}
Integer size = Integer.parseInt(request.getParameter("length"));
Integer startIndex = Integer.parseInt(request.getParameter("start"));
Integer draw = Integer.parseInt(request.getParameter("draw"));
int order = Integer.valueOf(request.getParameter("order[0][column]"));
String orderDir = request.getParameter("order[0][dir]");// asc or
// // desc
Integer pageindex = (startIndex / size + 1);
PlanList pl = null;
int status = 0;
pl = planMaintainService.checkIsSave(semester, status, pageindex, size,
order, orderDir, searchValue);
JSONObject getObj = new JSONObject();
getObj.put("draw", draw);
getObj.put("recordsFiltered", pl.getRecordsTotal());
getObj.put("recordsTotal", pl.getRecordsTotal());
getObj.put("data", pl.getData());
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/deletePlanInfo.do")
public String deletePlanInfo(HttpServletRequest request,
HttpServletResponse response) {
String recordstr = request.getParameter("deletstr");
planMaintainService.deletePlanInfo(recordstr);
JSONObject getObj = new JSONObject();
getObj.put("msg", "");
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/callAttention.do")
public String callAttention(HttpServletRequest request,
HttpServletResponse response) {
String recordstr = request.getParameter("recordstr");
planMaintainService.callAttention(recordstr);
JSONObject getObj = new JSONObject();
getObj.put("msg", "");
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@RequestMapping("/saveSemesterTime.do")
public String saveSemesterTime(HttpServletRequest request,
HttpServletResponse response) {
String teamYearw = request.getParameter("teamYearw");
String oneSemesterTime = request.getParameter("oneSemesterTime");
String twoSemesterTime = request.getParameter("twoSemesterTime");
System.out.println(":"+teamYearw+",:"+oneSemesterTime+",:"+twoSemesterTime);
Contants.map.put(teamYearw+"-1", oneSemesterTime);
Contants.map.put(teamYearw+"-2", twoSemesterTime);
JSONObject getObj = new JSONObject();
getObj.put("msg", true);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(getObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
|
package com.intellij.refactoring.util;
import com.intellij.ant.PsiAntElement;
import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInspection.redundantCast.RedundantCastUtil;
import com.intellij.lang.StdLanguages;
import com.intellij.lang.properties.psi.Property;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.controlFlow.ControlFlowUtil;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.jsp.WebDirectoryElement;
import com.intellij.psi.search.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlElementDecl;
import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.PackageWrapper;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.RefactoringSettings;
import com.intellij.refactoring.ui.InfoDialog;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.HashMap;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.util.*;
public class RefactoringUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.util.RefactoringUtil");
public static final int EXPR_COPY_SAFE = 0;
public static final int EXPR_COPY_UNSAFE = 1;
public static final int EXPR_COPY_PROHIBITED = 2;
private RefactoringUtil() {}
public static void showInfoDialog(String info, Project project) {
RefactoringSettings settings = RefactoringSettings.getInstance();
if (settings.IS_SHOW_ACTION_INFO) {
InfoDialog usagesWarning = new InfoDialog(info, project);
usagesWarning.show();
settings.IS_SHOW_ACTION_INFO = usagesWarning.isToShowInFuture();
}
}
public static boolean isSourceRoot(final PsiDirectory directory) {
if (directory.getManager() == null) return false;
final Project project = directory.getProject();
final VirtualFile virtualFile = directory.getVirtualFile();
final VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(virtualFile);
return Comparing.equal(virtualFile, sourceRootForFile);
}
public static boolean isInStaticContext(PsiElement element) {
return PsiUtil.getEnclosingStaticElement(element, null) != null;
}
public static boolean isResolvableType(PsiType type) {
return type.accept(new PsiTypeVisitor<Boolean>() {
public Boolean visitPrimitiveType(PsiPrimitiveType primitiveType) {
return Boolean.TRUE;
}
public Boolean visitArrayType(PsiArrayType arrayType) {
return arrayType.getComponentType().accept(this);
}
public Boolean visitClassType(PsiClassType classType) {
if (classType.resolve() == null) return Boolean.FALSE;
PsiType[] parameters = classType.getParameters();
for (PsiType parameter : parameters) {
if (parameter != null && !parameter.accept(this).booleanValue()) return Boolean.FALSE;
}
return Boolean.TRUE;
}
public Boolean visitWildcardType(PsiWildcardType wildcardType) {
if (wildcardType.getBound() != null) return wildcardType.getBound().accept(this);
return Boolean.TRUE;
}
}).booleanValue();
}
public static PsiElement replaceOccurenceWithFieldRef(PsiExpression occurrence, PsiField newField, PsiClass destinationClass)
throws IncorrectOperationException {
final PsiManager manager = occurrence.getManager();
final String fieldName = newField.getName();
final PsiVariable psiVariable = manager.getResolveHelper().resolveReferencedVariable(fieldName, occurrence);
final PsiElementFactory factory = manager.getElementFactory();
if (psiVariable != null && psiVariable.equals(newField)) {
return occurrence.replace(factory.createExpressionFromText(fieldName, null));
}
else {
final PsiReferenceExpression ref = (PsiReferenceExpression)factory.createExpressionFromText("this." + fieldName, null);
if (newField.hasModifierProperty(PsiModifier.STATIC)) {
ref.setQualifierExpression(factory.createReferenceExpression(destinationClass));
}
return occurrence.replace(ref);
}
}
/**
* @see com.intellij.psi.codeStyle.CodeStyleManager#suggestUniqueVariableName(String, com.intellij.psi.PsiElement, boolean)
* Cannot use method from code style manager: a collision with fieldToReplace is not a collision
*/
public static String suggestUniqueVariableName(String baseName, PsiElement place, PsiField fieldToReplace) {
int index = 0;
while (true) {
final String name = index > 0 ? baseName + index : baseName;
index++;
final PsiManager manager = place.getManager();
PsiResolveHelper helper = manager.getResolveHelper();
PsiVariable refVar = helper.resolveReferencedVariable(name, place);
if (refVar != null && !manager.areElementsEquivalent(refVar, fieldToReplace)) continue;
class CancelException extends RuntimeException {}
try {
place.accept(new PsiRecursiveElementVisitor() {
public void visitClass(PsiClass aClass) {
}
public void visitVariable(PsiVariable variable) {
if (name.equals(variable.getName())) {
throw new CancelException();
}
}
});
}
catch (CancelException e) {
continue;
}
return name;
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static boolean isValidName(final Project project, final PsiElement psiElement, final String newName) {
if (newName == null) {
return false;
}
if (psiElement instanceof PsiAntElement) {
return newName.trim().matches("[\\d\\w\\_\\.\\-]*");
}
if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) {
return newName.indexOf(File.separatorChar) < 0 && newName.indexOf('/') < 0;
}
if (psiElement instanceof WebDirectoryElement) {
return newName.indexOf('/') < 0;
}
if (psiElement instanceof XmlTag ||
psiElement instanceof XmlAttribute ||
psiElement instanceof XmlElementDecl
) {
return newName.trim().matches("([\\d\\w\\_\\.\\-]+:)?[\\d\\w\\_\\.\\-]+");
}
if (psiElement instanceof XmlAttributeValue) {
return true; // ask meta data
}
if (psiElement instanceof Property) {
return true;
}
return psiElement.getLanguage().getNamesValidator().isIdentifier(newName.trim(), project);
}
//order of usages accross different files is irrelevant
public static void sortDepthFirstRightLeftOrder(final UsageInfo[] usages) {
Arrays.sort(usages, new Comparator<UsageInfo>() {
public int compare(final UsageInfo usage1, final UsageInfo usage2) {
final PsiElement element1 = usage1.getElement();
final PsiElement element2 = usage2.getElement();
if (element1 == null || element2 == null) return 0;
return element2.getTextRange().getStartOffset() - element1.getTextRange().getStartOffset();
}
});
}
public static interface UsageInfoFactory {
UsageInfo createUsageInfo(PsiElement usage, int startOffset, int endOffset);
}
public static void addUsagesInStringsAndComments(PsiElement element, String stringToSearch, List<UsageInfo> results,
UsageInfoFactory factory) {
PsiManager manager = element.getManager();
PsiSearchHelper helper = manager.getSearchHelper();
SearchScope scope = element.getUseScope();
scope = scope.intersectWith(GlobalSearchScope.projectScope(manager.getProject()));
int index = stringToSearch.lastIndexOf('.');
String identifierToSearch = index >= 0 ? stringToSearch.substring(index + 1) : stringToSearch;
PsiLiteralExpression[] literals = helper.findStringLiteralsContainingIdentifier(identifierToSearch, scope);
for (PsiLiteralExpression literal : literals) {
processStringOrComment(literal, stringToSearch, results, factory);
}
PsiElement[] comments = helper.findCommentsContainingIdentifier(identifierToSearch, scope);
for (PsiElement comment : comments) {
processStringOrComment(comment, stringToSearch, results, factory);
}
}
public static boolean isSearchTextOccurencesEnabled(PsiElement element) {
return element instanceof PsiPackage || (element instanceof PsiClass && ((PsiClass)element).getQualifiedName() != null) ||
(element instanceof PsiFile && !StdLanguages.JAVA.equals(element.getLanguage()));
}
public static PsiElement getVariableScope(PsiLocalVariable localVar) {
if (!(localVar instanceof ImplicitVariable)) {
return localVar.getParent().getParent();
}
else {
return ((ImplicitVariable)localVar).getDeclarationScope();
}
}
public static void addTextOccurences(PsiElement element, String stringToSearch, GlobalSearchScope searchScope,
final List<UsageInfo> results, final UsageInfoFactory factory) {
processTextOccurences(element, stringToSearch, searchScope, new Processor<UsageInfo>() {
public boolean process(UsageInfo t) {
results.add(t);
return true;
}
}, factory);
}
public static void processTextOccurences(PsiElement element, String stringToSearch, GlobalSearchScope searchScope,
final Processor<UsageInfo> processor, final UsageInfoFactory factory) {
PsiSearchHelper helper = element.getManager().getSearchHelper();
helper.processUsagesInNonJavaFiles(element, stringToSearch,
new PsiNonJavaFileReferenceProcessor() {
public boolean process(PsiFile psiFile, int startOffset, int endOffset) {
UsageInfo usageInfo = factory.createUsageInfo(psiFile, startOffset, endOffset);
if (usageInfo != null) {
if (!processor.process(usageInfo)) return false;
}
return true;
}
},
searchScope);
}
private static void processStringOrComment(PsiElement element, String stringToSearch, List<UsageInfo> results,
UsageInfoFactory factory) {
String elementText = element.getText();
for (int index = 0; index < elementText.length(); index++) {
index = elementText.indexOf(stringToSearch, index);
if (index < 0) break;
final PsiReference referenceAt = element.findReferenceAt(index);
if (referenceAt != null && referenceAt.resolve() != null) continue;
if (index > 0) {
char c = elementText.charAt(index - 1);
if (Character.isJavaIdentifierPart(c) && c != '$') {
continue;
}
}
if (index + stringToSearch.length() < elementText.length()) {
char c = elementText.charAt(index + stringToSearch.length());
if (Character.isJavaIdentifierPart(c) && c != '$') {
continue;
}
}
UsageInfo usageInfo = factory.createUsageInfo(element, index, index + stringToSearch.length());
if (usageInfo != null) {
results.add(usageInfo);
}
index += stringToSearch.length();
}
}
public static void renameNonCodeUsages(final Project project, final UsageInfo[] usages) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
HashMap<PsiFile,ArrayList<UsageOffset>> filesToOffsetsMap = new HashMap<PsiFile, ArrayList<UsageOffset>>();
for (UsageInfo usage : usages) {
final PsiElement element = usage.getElement();
if (element == null || !element.isValid()) continue;
if (usage instanceof NonCodeUsageInfo) {
final PsiFile containingFile = element.getContainingFile();
int fileOffset = element.getTextRange().getStartOffset() + usage.startOffset;
ArrayList<UsageOffset> list = filesToOffsetsMap.get(containingFile);
if (list == null) {
list = new ArrayList<UsageOffset>();
filesToOffsetsMap.put(containingFile, list);
}
list.add(new UsageOffset(fileOffset, fileOffset + usage.endOffset - usage.startOffset,
((NonCodeUsageInfo)usage).newText));
}
}
for (PsiFile file : filesToOffsetsMap.keySet()) {
final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
final Document editorDocument = psiDocumentManager.getDocument(file);
psiDocumentManager.doPostponedOperationsAndUnblockDocument(editorDocument);
ArrayList<UsageOffset> list = filesToOffsetsMap.get(file);
UsageOffset[] offsets = list.toArray(new UsageOffset[list.size()]);
Arrays.sort(offsets);
for (int i = offsets.length - 1; i >= 0; i
UsageOffset usageOffset = offsets[i];
editorDocument.replaceString(usageOffset.startOffset, usageOffset.endOffset, usageOffset.newText);
}
PsiDocumentManager.getInstance(project).commitDocument(editorDocument);
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
}
private static class UsageOffset implements Comparable {
final int startOffset;
final int endOffset;
final String newText;
public UsageOffset(int startOffset, int endOffset, String newText) {
this.startOffset = startOffset;
this.endOffset = endOffset;
this.newText = newText;
}
public int compareTo(Object o) {
return startOffset - ((UsageOffset)o).startOffset;
}
}
public static PsiReturnStatement[] findReturnStatements(PsiMethod method) {
ArrayList<PsiElement> vector = new ArrayList<PsiElement>();
PsiCodeBlock body = method.getBody();
if (body != null) {
addReturnStatements(vector, body);
}
return vector.toArray(new PsiReturnStatement[vector.size()]);
}
private static void addReturnStatements(ArrayList<PsiElement> vector, PsiElement element) {
if (element instanceof PsiReturnStatement) {
vector.add(element);
}
else if (element instanceof PsiClass) {
return;
}
else {
PsiElement[] children = element.getChildren();
for (PsiElement child : children) {
addReturnStatements(vector, child);
}
}
}
public static PsiElement getParentStatement(PsiElement place, boolean skipScopingStatements) {
PsiElement parent = place;
while (true) {
if (parent instanceof PsiStatement) break;
parent = parent.getParent();
if (parent == null) return null;
}
PsiElement parentStatement = parent;
parent = parentStatement instanceof PsiStatement ? parentStatement : parentStatement.getParent();
while (parent instanceof PsiStatement) {
if (!skipScopingStatements &&
((parent instanceof PsiForStatement && parentStatement == ((PsiForStatement)parent).getBody())
|| (parent instanceof PsiForeachStatement && parentStatement == ((PsiForeachStatement)parent).getBody())
|| (parent instanceof PsiWhileStatement && parentStatement == ((PsiWhileStatement)parent).getBody())
|| (parent instanceof PsiIfStatement &&
(parentStatement == ((PsiIfStatement)parent).getThenBranch() || parentStatement == ((PsiIfStatement)parent).getElseBranch())))
) {
return parentStatement;
}
parentStatement = parent;
parent = parent.getParent();
}
return parentStatement;
}
public static PsiElement getParentExpressionAnchorElement(PsiElement place) {
PsiElement parent = place;
while (true) {
if (isExpressionAnchorElement(parent)) return parent;
parent = parent.getParent();
if (parent == null) return null;
}
}
public static boolean isExpressionAnchorElement(PsiElement element) {
return element instanceof PsiStatement || element instanceof PsiClassInitializer
|| element instanceof PsiField || element instanceof PsiMethod;
}
/**
* @param expression
* @return loop body if expression is part of some loop's condition or for loop's increment part
* null otherwise
*/
public static PsiElement getLoopForLoopCondition(PsiExpression expression) {
PsiExpression outermost = expression;
while (outermost.getParent() instanceof PsiExpression) {
outermost = (PsiExpression)outermost.getParent();
}
if (outermost.getParent() instanceof PsiForStatement) {
final PsiForStatement forStatement = (PsiForStatement)outermost.getParent();
if (forStatement.getCondition() == outermost) {
return forStatement;
}
else {
return null;
}
}
if (outermost.getParent() instanceof PsiExpressionStatement && outermost.getParent().getParent() instanceof PsiForStatement) {
final PsiForStatement forStatement = (PsiForStatement)outermost.getParent().getParent();
if (forStatement.getUpdate() == outermost.getParent()) {
return forStatement;
}
else {
return null;
}
}
if (outermost.getParent() instanceof PsiWhileStatement) {
return outermost.getParent();
}
if (outermost.getParent() instanceof PsiDoWhileStatement) {
return outermost.getParent();
}
return null;
}
public static PsiClass getThisClass(PsiElement place) {
PsiElement parent = place.getContext();
if (parent == null) return null;
PsiElement prev = null;
while (true) {
if (parent instanceof PsiClass) {
if (!(parent instanceof PsiAnonymousClass && ((PsiAnonymousClass)parent).getArgumentList() == prev)) {
return (PsiClass)parent;
}
}
prev = parent;
parent = parent.getContext();
if (parent == null) return null;
}
}
public static PsiClass getThisResolveClass(final PsiReferenceExpression place) {
final JavaResolveResult resolveResult = place.advancedResolve(false);
final PsiElement scope = resolveResult.getCurrentFileResolveScope();
if (scope instanceof PsiClass) {
return (PsiClass)scope;
}
return null;
/*
PsiElement parent = place.getContext();
PsiElement prev = null;
while (true) {
if (parent instanceof PsiClass) {
if (!(parent instanceof PsiAnonymousClass && ((PsiAnonymousClass)parent).getArgumentList() == prev))
return (PsiClass)parent;
}
prev = parent;
parent = parent.getContext();
if (parent == null) return null;
}
*/
}
public static PsiCall getEnclosingConstructorCall (PsiJavaCodeReferenceElement ref) {
PsiElement parent = ref.getParent();
if (ref instanceof PsiReferenceExpression && parent instanceof PsiMethodCallExpression) return (PsiCall)parent;
if (parent instanceof PsiAnonymousClass) {
parent = parent.getParent();
}
return parent instanceof PsiNewExpression ? (PsiNewExpression)parent : null;
}
public static PsiMethod getEnclosingMethod (PsiElement element) {
final PsiElement container = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class);
return container instanceof PsiMethod ? ((PsiMethod)container) : null;
}
public static void renameVariableReferences(PsiVariable variable, String newName, SearchScope scope)
throws IncorrectOperationException {
for (PsiReference reference : ReferencesSearch.search(variable, scope).findAll()) {
reference.handleElementRename(newName);
}
}
public static boolean canBeDeclaredFinal(PsiVariable variable) {
LOG.assertTrue(variable instanceof PsiLocalVariable || variable instanceof PsiParameter);
final boolean isReassigned = HighlightControlFlowUtil.isReassigned(variable, new THashMap<PsiElement, Collection<ControlFlowUtil.VariableInfo>>(), new THashMap<PsiParameter, Boolean>());
return !isReassigned;
}
public static PsiExpression inlineVariable(PsiLocalVariable variable, PsiExpression initializer,
PsiJavaCodeReferenceElement ref) throws IncorrectOperationException {
PsiManager manager = initializer.getManager();
PsiClass thisClass = RefactoringUtil.getThisClass(initializer);
PsiClass refParent = RefactoringUtil.getThisClass(ref);
initializer = convertInitializerToNormalExpression(initializer, variable.getType());
ChangeContextUtil.encodeContextInfo(initializer, false);
PsiExpression expr = (PsiExpression)ref.replace(initializer);
PsiType exprType = expr.getType();
if (exprType != null && !variable.getType().equals(exprType)) {
PsiTypeCastExpression cast = (PsiTypeCastExpression)manager.getElementFactory().createExpressionFromText("(t)a", null);
PsiTypeElement castTypeElement = cast.getCastType();
LOG.assertTrue(castTypeElement != null);
castTypeElement.replace(variable.getTypeElement());
cast.getOperand().replace(expr);
PsiExpression exprCopy = (PsiExpression)expr.copy();
cast = (PsiTypeCastExpression)expr.replace(cast);
if (!RedundantCastUtil.isCastRedundant(cast)) {
expr = cast;
} else {
PsiElement toReplace = cast;
while (toReplace.getParent() instanceof PsiParenthesizedExpression) {
toReplace = toReplace.getParent();
}
expr = (PsiExpression)toReplace.replace(exprCopy);
}
}
ChangeContextUtil.clearContextInfo(initializer);
PsiThisExpression thisAccessExpr = null;
if (Comparing.equal(thisClass, refParent)) {
thisAccessExpr = createThisExpression(manager, null);
}
else {
if (!(thisClass instanceof PsiAnonymousClass)) {
thisAccessExpr = createThisExpression(manager, thisClass);
}
}
return (PsiExpression)ChangeContextUtil.decodeContextInfo(expr, thisClass, thisAccessExpr);
}
public static PsiThisExpression createThisExpression(PsiManager manager, PsiClass qualifierClass)
throws IncorrectOperationException {
PsiElementFactory factory = manager.getElementFactory();
if (qualifierClass != null) {
PsiThisExpression qualifiedThis = (PsiThisExpression)factory.createExpressionFromText("q.this", null);
qualifiedThis = (PsiThisExpression)CodeStyleManager.getInstance(manager.getProject()).reformat(qualifiedThis);
PsiJavaCodeReferenceElement thisQualifier = qualifiedThis.getQualifier();
LOG.assertTrue(thisQualifier != null);
thisQualifier.bindToElement(qualifierClass);
return qualifiedThis;
}
else {
return (PsiThisExpression)factory.createExpressionFromText("this", null);
}
}
/**
* removes a reference to the specified class from the reference list given
*
* @return if removed - a reference to the class or null if there were no references to this class in the reference list
*/
public static PsiJavaCodeReferenceElement removeFromReferenceList(PsiReferenceList refList, PsiClass aClass)
throws IncorrectOperationException {
PsiJavaCodeReferenceElement[] refs = refList.getReferenceElements();
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.isReferenceTo(aClass)) {
PsiJavaCodeReferenceElement refCopy = (PsiJavaCodeReferenceElement)ref.copy();
ref.delete();
return refCopy;
}
}
return null;
}
public static PsiJavaCodeReferenceElement findReferenceToClass(PsiReferenceList refList, PsiClass aClass) {
PsiJavaCodeReferenceElement[] refs = refList.getReferenceElements();
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.isReferenceTo(aClass)) {
return ref;
}
}
return null;
}
public static PsiType getTypeByExpressionWithExpectedType(PsiExpression expr) {
PsiType type = getTypeByExpression(expr);
if (type != null) return type;
ExpectedTypeInfo[] expectedTypes = ExpectedTypesProvider.getInstance(expr.getProject()).getExpectedTypes(expr, false);
if (expectedTypes.length == 1) {
type = expectedTypes[0].getType();
if (!type.equalsToText("java.lang.Object")) return type;
}
return null;
}
public static PsiType getTypeByExpression(PsiExpression expr) {
PsiElementFactory factory = expr.getManager().getElementFactory();
return getTypeByExpression(expr, factory);
}
private static PsiType getTypeByExpression(PsiExpression expr, final PsiElementFactory factory) {
PsiType type = expr.getType();
if (type == null) {
if (expr instanceof PsiArrayInitializerExpression) {
PsiExpression[] initializers = ((PsiArrayInitializerExpression)expr).getInitializers();
if (initializers.length > 0) {
PsiType initType = getTypeByExpression(initializers[0]);
if (initType == null) return null;
return initType.createArrayType();
}
}
return null;
}
PsiClass refClass = PsiUtil.resolveClassInType(type);
if (refClass instanceof PsiAnonymousClass) {
type = ((PsiAnonymousClass)refClass).getBaseClassType();
}
if (type == PsiType.NULL) {
ExpectedTypeInfo[] infos = ExpectedTypesProvider.getInstance(expr.getProject()).getExpectedTypes(expr, false);
if (infos.length == 1) {
type = infos[0].getType();
}
else {
type = factory.createTypeByFQClassName("java.lang.Object", expr.getResolveScope());
}
}
return GenericsUtil.getVariableTypeByExpressionType(type);
}
public static boolean isAssignmentLHS(PsiElement element) {
PsiElement parent = element.getParent();
return parent instanceof PsiAssignmentExpression && element.equals(((PsiAssignmentExpression)parent).getLExpression()) ||
isPlusPlusOrMinusMinus(parent);
}
public static boolean isPlusPlusOrMinusMinus(PsiElement element) {
if (element instanceof PsiPrefixExpression) {
PsiJavaToken operandSign = ((PsiPrefixExpression)element).getOperationSign();
return operandSign.getTokenType() == JavaTokenType.PLUSPLUS
|| operandSign.getTokenType() == JavaTokenType.MINUSMINUS;
}
else if (element instanceof PsiPostfixExpression) {
PsiJavaToken operandSign = ((PsiPostfixExpression)element).getOperationSign();
return operandSign.getTokenType() == JavaTokenType.PLUSPLUS
|| operandSign.getTokenType() == JavaTokenType.MINUSMINUS;
}
else {
return false;
}
}
public static void removeFinalParameters(PsiMethod method)
throws IncorrectOperationException {
// Remove final parameters
PsiParameterList paramList = method.getParameterList();
PsiParameter[] params = paramList.getParameters();
for (PsiParameter param : params) {
if (param.hasModifierProperty(PsiModifier.FINAL)) {
param.getModifierList().setModifierProperty(PsiModifier.FINAL, false);
}
}
}
public static PsiElement getAnchorElementForMultipleExpressions(PsiExpression[] occurrences, PsiElement scope) {
PsiElement anchor = null;
for (PsiExpression occurrence : occurrences) {
if (scope != null && !PsiTreeUtil.isAncestor(scope, occurrence, false)) {
continue;
}
PsiElement anchor1 = getParentExpressionAnchorElement(occurrence);
if (anchor1 == null) return null;
if (anchor == null) {
anchor = anchor1;
}
else {
PsiElement commonParent = PsiTreeUtil.findCommonParent(anchor, anchor1);
if (commonParent == null || anchor.getTextRange() == null || anchor1.getTextRange() == null) return null;
PsiElement firstAnchor = anchor.getTextRange().getStartOffset() < anchor1.getTextRange().getStartOffset() ?
anchor : anchor1;
if (commonParent.equals(firstAnchor)) {
anchor = firstAnchor;
}
else {
if (commonParent instanceof PsiStatement) {
anchor = commonParent;
}
else {
PsiElement parent = firstAnchor;
while (!parent.getParent().equals(commonParent)) {
parent = parent.getParent();
}
final PsiElement newAnchor = getParentExpressionAnchorElement(parent);
if (newAnchor != null) {
anchor = newAnchor;
}
else {
anchor = parent;
}
}
}
}
}
if (occurrences.length > 1 && anchor.getParent().getParent() instanceof PsiSwitchStatement) {
PsiSwitchStatement switchStatement = (PsiSwitchStatement)anchor.getParent().getParent();
if (switchStatement.getBody().equals(anchor.getParent())) {
int startOffset = occurrences[0].getTextRange().getStartOffset();
int endOffset = occurrences[occurrences.length - 1].getTextRange().getEndOffset();
PsiStatement[] statements = switchStatement.getBody().getStatements();
boolean isInDifferentCases = false;
for (PsiStatement statement : statements) {
if (statement instanceof PsiSwitchLabelStatement) {
int caseOffset = statement.getTextRange().getStartOffset();
if (startOffset < caseOffset && caseOffset < endOffset) {
isInDifferentCases = true;
break;
}
}
}
if (isInDifferentCases) {
anchor = switchStatement;
}
}
}
return anchor;
}
public static void setVisibility(PsiModifierList modifierList, String newVisibility)
throws IncorrectOperationException {
modifierList.setModifierProperty(PsiModifier.PRIVATE, false);
modifierList.setModifierProperty(PsiModifier.PUBLIC, false);
modifierList.setModifierProperty(PsiModifier.PROTECTED, false);
modifierList.setModifierProperty(newVisibility, true);
}
public static boolean isMethodUsage(PsiElement element) {
if (!(element instanceof PsiJavaCodeReferenceElement)) return false;
PsiElement parent = element.getParent();
if (parent instanceof PsiCall) {
return true;
}
else if (parent instanceof PsiAnonymousClass) {
return element.equals(((PsiAnonymousClass)parent).getBaseClassReference());
}
return false;
}
public static PsiExpressionList getArgumentListByMethodReference(PsiElement ref) {
if (ref instanceof PsiEnumConstant) return ((PsiEnumConstant)ref).getArgumentList();
PsiElement parent = ref.getParent();
if (parent instanceof PsiCall) {
return ((PsiCall)parent).getArgumentList();
}
else if (parent instanceof PsiAnonymousClass) {
return ((PsiNewExpression)parent.getParent()).getArgumentList();
}
LOG.assertTrue(false);
return null;
}
public static PsiCallExpression getCallExpressionByMethodReference(PsiJavaCodeReferenceElement ref) {
PsiElement parent = ref.getParent();
if (parent instanceof PsiMethodCallExpression) {
return (PsiMethodCallExpression)parent;
}
else if (parent instanceof PsiNewExpression) {
return (PsiNewExpression)parent;
}
else if (parent instanceof PsiAnonymousClass) {
return (PsiNewExpression)parent.getParent();
}
else {
LOG.assertTrue(false);
return null;
}
}
/**
* @return List of highlighters
*/
public static ArrayList<RangeHighlighter> highlightAllOccurences(Project project, PsiElement[] occurences, Editor editor) {
ArrayList<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
HighlightManager highlightManager = HighlightManager.getInstance(project);
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
highlightManager.addOccurrenceHighlights(editor, occurences, attributes, true, highlighters);
return highlighters;
}
public static ArrayList<RangeHighlighter> highlightOccurences(Project project, PsiElement[] occurences, Editor editor) {
if (occurences.length > 1) {
return highlightAllOccurences(project, occurences, editor);
}
return new ArrayList<RangeHighlighter>();
}
public static String createTempVar(PsiExpression expr, PsiElement context, boolean declareFinal)
throws IncorrectOperationException {
PsiElement anchorStatement = getParentStatement(context, true);
LOG.assertTrue(anchorStatement != null && anchorStatement.getParent() != null);
Project project = expr.getProject();
String[] suggestedNames =
CodeStyleManager.getInstance(project).suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expr, null).names;
final String prefix = suggestedNames[0];
final String id = CodeStyleManager.getInstance(project).suggestUniqueVariableName(prefix, context, true);
PsiElementFactory factory = expr.getManager().getElementFactory();
if (expr instanceof PsiParenthesizedExpression) {
PsiExpression expr1 = ((PsiParenthesizedExpression)expr).getExpression();
if (expr1 != null) {
expr = expr1;
}
}
PsiDeclarationStatement decl =
factory.createVariableDeclarationStatement(id, expr.getType(), expr);
if (declareFinal) {
((PsiLocalVariable)decl.getDeclaredElements()[0]).getModifierList().setModifierProperty(PsiModifier.FINAL, true);
}
anchorStatement.getParent().addBefore(decl, anchorStatement);
return id;
}
public static int verifySafeCopyExpression(PsiElement expr) {
return verifySafeCopyExpressionSubElement(expr);
}
private static int verifySafeCopyExpressionSubElement(PsiElement element) {
int result = EXPR_COPY_SAFE;
if (element == null) return result;
if (element instanceof PsiThisExpression
|| element instanceof PsiSuperExpression
|| element instanceof PsiIdentifier
) {
return EXPR_COPY_SAFE;
}
if (element instanceof PsiMethodCallExpression) {
result = EXPR_COPY_UNSAFE;
}
if (element instanceof PsiNewExpression) {
return EXPR_COPY_PROHIBITED;
}
if (element instanceof PsiAssignmentExpression) {
return EXPR_COPY_PROHIBITED;
}
if (isPlusPlusOrMinusMinus(element)) {
return EXPR_COPY_PROHIBITED;
}
PsiElement[] children = element.getChildren();
for (PsiElement child : children) {
int childResult = verifySafeCopyExpressionSubElement(child);
result = Math.max(result, childResult);
}
return result;
}
public static PsiExpression convertInitializerToNormalExpression(PsiExpression expression,
PsiType forcedReturnType)
throws IncorrectOperationException {
PsiExpression returnValue;
if (expression instanceof PsiArrayInitializerExpression) {
returnValue =
createNewExpressionFromArrayInitializer((PsiArrayInitializerExpression)expression,
forcedReturnType);
}
else {
returnValue = expression;
}
return returnValue;
}
public static PsiExpression createNewExpressionFromArrayInitializer(PsiArrayInitializerExpression initializer,
PsiType forcedType)
throws IncorrectOperationException {
PsiType initializerType = null;
if (initializer != null) {
// initializerType = myExpresssion.getType();
if (forcedType != null) {
initializerType = forcedType;
}
else {
initializerType = getTypeByExpression(initializer);
}
}
if (initializerType == null) {
return initializer;
}
LOG.assertTrue(initializerType instanceof PsiArrayType);
PsiElementFactory factory = initializer.getManager().getElementFactory();
PsiNewExpression result =
(PsiNewExpression)factory.createExpressionFromText("new " + initializerType.getPresentableText() + "{}", null);
result = (PsiNewExpression)CodeStyleManager.getInstance(initializer.getProject()).reformat(result);
PsiArrayInitializerExpression arrayInitializer = result.getArrayInitializer();
LOG.assertTrue(arrayInitializer != null);
arrayInitializer.replace(initializer);
return result;
}
public static void abstractizeMethod(PsiClass targetClass, PsiMethod method) throws IncorrectOperationException {
PsiCodeBlock body = method.getBody();
if (body != null) {
body.delete();
}
method.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, true);
method.getModifierList().setModifierProperty(PsiModifier.FINAL, false);
method.getModifierList().setModifierProperty(PsiModifier.SYNCHRONIZED, false);
method.getModifierList().setModifierProperty(PsiModifier.NATIVE, false);
if (!targetClass.isInterface()) {
targetClass.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, true);
}
removeFinalParameters(method);
}
public static boolean isInsideAnonymous(PsiElement element, PsiElement upTo) {
for (PsiElement current = element;
current != null && current != upTo;
current = current.getParent()) {
if (current instanceof PsiAnonymousClass) return true;
}
return false;
}
public static PsiExpression unparenthesizeExpression(PsiExpression expression) {
while (expression instanceof PsiParenthesizedExpression) {
final PsiExpression innerExpression = ((PsiParenthesizedExpression)expression).getExpression();
if (innerExpression == null) return expression;
expression = innerExpression;
}
return expression;
}
public static PsiExpression outermostParenthesizedExpression(PsiExpression expression) {
while (expression.getParent() instanceof PsiParenthesizedExpression) {
expression = (PsiParenthesizedExpression)expression.getParent();
}
return expression;
}
public static String getStringToSearch(PsiElement element, boolean nonJava) {
if (element instanceof PsiDirectory) { // normalize a directory to a corresponding package
final PsiPackage aPackage = ((PsiDirectory)element).getPackage();
if (aPackage != null) element = aPackage;
}
if (element instanceof PsiPackage) {
return nonJava ? ((PsiPackage)element).getQualifiedName() : ((PsiPackage)element).getName();
}
else if (element instanceof PsiClass) {
return nonJava ? ((PsiClass)element).getQualifiedName() : ((PsiClass)element).getName();
}
else if (element instanceof XmlTag) {
return ((XmlTag)element).getValue().getTrimmedText();
}
else if (element instanceof XmlAttribute) {
return ((XmlAttribute)element).getValue();
}
else if (element instanceof PsiMember) {
PsiMember member = (PsiMember) element;
String name = member.getName();
if (name == null) return null;
if (!nonJava) {
return name;
}
PsiClass containingClass = member.getContainingClass();
if (containingClass == null || containingClass.getQualifiedName() == null) return null;
return containingClass.getQualifiedName() + "." + name;
}
else if (element instanceof PsiNamedElement) {
return ((PsiNamedElement)element).getName();
}
else {
LOG.error("Unknown element type");
return null;
}
}
public static String getInnerClassNameForClassLoader(PsiClass aClass) {
final String qName = aClass.getQualifiedName();
if (qName == null) return null;
return replaceDotsWithDollars(qName, aClass);
}
public static String replaceDotsWithDollars(final String qName, PsiClass aClass) {
StringBuffer qNameBuffer = new StringBuffer(qName);
int fromIndex = qNameBuffer.length();
PsiElement parent = aClass.getParent();
while (parent instanceof PsiClass) {
final int dotIndex = qNameBuffer.lastIndexOf(".", fromIndex);
if (dotIndex < 0) break;
qNameBuffer.replace(dotIndex, dotIndex + 1, "$");
fromIndex = dotIndex - 1;
parent = parent.getParent();
}
return qNameBuffer.toString();
}
public static String getNewInnerClassName(PsiClass aClass, String oldInnerClassName, String newName) {
if (!oldInnerClassName.endsWith(aClass.getName())) return newName;
StringBuffer buffer = new StringBuffer(oldInnerClassName);
buffer.replace(buffer.length() - aClass.getName().length(), buffer.length(), newName);
return buffer.toString();
}
public static boolean isSuperOrThisCall(PsiStatement statement, boolean testForSuper, boolean testForThis) {
if (!(statement instanceof PsiExpressionStatement)) return false;
PsiExpression expression = ((PsiExpressionStatement)statement).getExpression();
if (!(expression instanceof PsiMethodCallExpression)) return false;
final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)expression).getMethodExpression();
if (testForSuper) {
if ("super".equals(methodExpression.getText())) return true;
}
if (testForThis) {
if ("this".equals(methodExpression.getText())) return true;
}
return false;
}
public static void visitImplicitConstructorUsages(PsiClass aClass,
final ImplicitConstructorUsageVisitor implicitConstructorUsageVistor) {
PsiManager manager = aClass.getManager();
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
final PsiClass[] inheritors = manager.getSearchHelper().findInheritors(aClass, projectScope, false);
for (PsiClass inheritor : inheritors) {
visitImplicitSuperConstructorUsages(inheritor, implicitConstructorUsageVistor, aClass);
}
}
public static void visitImplicitSuperConstructorUsages(PsiClass subClass,
final ImplicitConstructorUsageVisitor implicitConstructorUsageVistor,
PsiClass superClass) {
final PsiMethod baseDefaultConstructor = findDefaultConstructor (superClass);
final PsiMethod[] constructors = subClass.getConstructors();
if (constructors.length > 0) {
for (PsiMethod constructor : constructors) {
final PsiStatement[] statements = constructor.getBody().getStatements();
if (statements.length < 1 || !isSuperOrThisCall(statements[0], true, true)) {
implicitConstructorUsageVistor.visitConstructor(constructor, baseDefaultConstructor);
}
}
}
else {
implicitConstructorUsageVistor.visitClassWithoutConstructors(subClass);
}
}
private static PsiMethod findDefaultConstructor(final PsiClass aClass) {
final PsiMethod[] constructors = aClass.getConstructors();
for (PsiMethod constructor : constructors) {
if (constructor.getParameterList().getParameters().length == 0) return constructor;
}
return null;
}
public static interface ImplicitConstructorUsageVisitor {
void visitConstructor(PsiMethod constructor, PsiMethod baseConstructor);
void visitClassWithoutConstructors(PsiClass aClass);
}
public interface Graph<T> {
Set<T> getVertices();
Set<T> getTargets(T source);
}
/**
* Returns subset of <code>graph.getVertices()</code> that is a tranistive closure (by <code>graph.getTargets()<code>)
* of the following property: initialRelation.value() of vertex or <code>graph.getTargets(vertex)</code> is true.
* <p/>
* Note that <code>graph.getTargets()</code> is not neccesrily a subset of <code>graph.getVertex()</code>
*
* @param graph
* @param initialRelation
* @return subset of graph.getVertices()
*/
public static <T> Set<T> transitiveClosure(Graph<T> graph, Condition<T> initialRelation) {
Set<T> result = new HashSet<T>();
final Set<T> vertices = graph.getVertices();
boolean anyChanged;
do {
anyChanged = false;
for (T currentVertex : vertices) {
if (!result.contains(currentVertex)) {
if (!initialRelation.value(currentVertex)) {
Set<T> targets = graph.getTargets(currentVertex);
for (T currentTarget : targets) {
if (result.contains(currentTarget) || initialRelation.value(currentTarget)) {
result.add(currentVertex);
anyChanged = true;
break;
}
}
}
else {
result.add(currentVertex);
}
}
}
}
while (anyChanged);
return result;
}
public static boolean equivalentTypes(PsiType t1, PsiType t2, PsiManager manager) {
while (t1 instanceof PsiArrayType) {
if (!(t2 instanceof PsiArrayType)) return false;
t1 = ((PsiArrayType)t1).getComponentType();
t2 = ((PsiArrayType)t2).getComponentType();
}
if (t1 instanceof PsiPrimitiveType) {
return t2 instanceof PsiPrimitiveType && t1.equals(t2);
}
return manager.areElementsEquivalent(PsiUtil.resolveClassInType(t1), PsiUtil.resolveClassInType(t2));
}
public static List<PsiVariable> collectReferencedVariables(PsiElement scope) {
final List<PsiVariable> result = new ArrayList<PsiVariable>();
scope.accept(new PsiRecursiveElementVisitor() {
public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement element = expression.resolve();
if (element instanceof PsiVariable) {
result.add((PsiVariable)element);
}
final PsiExpression qualifier = expression.getQualifierExpression();
if (qualifier != null) {
qualifier.accept(this);
}
}
});
return result;
}
public static boolean isModifiedInScope(PsiVariable variable, PsiElement scope) {
for (PsiReference reference : ReferencesSearch.search(variable, new LocalSearchScope(scope), false).findAll()) {
if (isAssignmentLHS(reference.getElement())) return true;
}
return false;
}
public static String getNameOfReferencedParameter(PsiDocTag tag) {
LOG.assertTrue("param".equals(tag.getName()));
final PsiElement[] dataElements = tag.getDataElements();
if (dataElements.length < 1) return null;
return dataElements[0].getText();
}
public static void fixJavadocsForParams(PsiMethod method, Set<PsiParameter> newParameters) throws IncorrectOperationException {
final PsiDocComment docComment = method.getDocComment();
if (docComment == null) return;
final PsiParameter[] parameters = method.getParameterList().getParameters();
final PsiDocTag[] paramTags = docComment.findTagsByName("param");
if (parameters.length > 0 && newParameters.size() < parameters.length && paramTags.length == 0) return;
Map<PsiParameter, PsiDocTag> tagForParam = new HashMap<PsiParameter, PsiDocTag>();
for (PsiParameter parameter : parameters) {
boolean found = false;
for (PsiDocTag paramTag : paramTags) {
if (parameter.getName().equals(getNameOfReferencedParameter(paramTag))) {
tagForParam.put(parameter, paramTag);
found = true;
break;
}
}
if (!found && !newParameters.contains(parameter)) {
tagForParam.put(parameter, null);
}
}
List<PsiDocTag> newTags = new ArrayList<PsiDocTag>();
for (PsiParameter parameter : parameters) {
if (tagForParam.containsKey(parameter)) {
final PsiDocTag psiDocTag = tagForParam.get(parameter);
if (psiDocTag != null) {
newTags.add((PsiDocTag)psiDocTag.copy());
}
}
else {
newTags.add(method.getManager().getElementFactory().createParamTag(parameter.getName(), ""));
}
}
PsiDocTag anchor = paramTags.length > 0 ? paramTags[paramTags.length - 1] : null;
for (PsiDocTag psiDocTag : newTags) {
anchor = (PsiDocTag)docComment.addAfter(psiDocTag, anchor);
}
for (PsiDocTag paramTag : paramTags) {
paramTag.delete();
}
}
public static PsiDirectory createPackageDirectoryInSourceRoot(PackageWrapper aPackage, final VirtualFile sourceRoot)
throws IncorrectOperationException {
final PsiDirectory[] directories = aPackage.getDirectories();
for (PsiDirectory directory : directories) {
if (VfsUtil.isAncestor(sourceRoot, directory.getVirtualFile(), false)) {
return directory;
}
}
String qNameToCreate = qNameToCreateInSourceRoot(aPackage, sourceRoot);
final String[] shortNames = qNameToCreate.split("\\.");
PsiDirectory current = aPackage.getManager().findDirectory(sourceRoot);
LOG.assertTrue(current != null);
for (String shortName : shortNames) {
PsiDirectory subdirectory = current.findSubdirectory(shortName);
if (subdirectory == null) {
subdirectory = current.createSubdirectory(shortName);
}
current = subdirectory;
}
return current;
}
public static String qNameToCreateInSourceRoot(PackageWrapper aPackage, final VirtualFile sourceRoot)
throws IncorrectOperationException {
String targetQName = aPackage.getQualifiedName();
String sourceRootPackage = ProjectRootManager.getInstance(aPackage.getManager().getProject()).getFileIndex().getPackageNameByDirectory(sourceRoot);
if (sourceRootPackage == null || !targetQName.startsWith(sourceRootPackage)) {
throw new IncorrectOperationException("Cannot create package '" + targetQName + "' in source folder " + sourceRoot.getPresentableUrl());
}
String result = targetQName.substring(sourceRootPackage.length());
if (StringUtil.startsWithChar(result, '.')) result = result.substring(1); // remove initial '.'
return result;
}
public static PsiDirectory findPackageDirectoryInSourceRoot(PackageWrapper aPackage, final VirtualFile sourceRoot) {
final PsiDirectory[] directories = aPackage.getDirectories();
for (PsiDirectory directory : directories) {
if (VfsUtil.isAncestor(sourceRoot, directory.getVirtualFile(), false)) {
return directory;
}
}
String qNameToCreate;
try {
qNameToCreate = qNameToCreateInSourceRoot(aPackage, sourceRoot);
}
catch (IncorrectOperationException e) {
return null;
}
final String[] shortNames = qNameToCreate.split("\\.");
PsiDirectory current = aPackage.getManager().findDirectory(sourceRoot);
LOG.assertTrue(current != null);
for (String shortName : shortNames) {
PsiDirectory subdirectory = current.findSubdirectory(shortName);
if (subdirectory == null) {
return null;
}
current = subdirectory;
}
return current;
}
public static String calculatePsiElementDescriptionList(PsiElement[] elements) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < elements.length; i++) {
if (i > 0) buffer.append(", ");
buffer.append(UsageViewUtil.getType(elements[i]));
buffer.append(" ");
buffer.append(UsageViewUtil.getDescriptiveName(elements[i]));
}
return buffer.toString();
}
public static class ConditionCache <T> implements Condition<T> {
private final Condition<T> myCondition;
private final HashSet<T> myProcessedSet = new HashSet<T>();
private final HashSet<T> myTrueSet = new HashSet<T>();
public ConditionCache(Condition<T> condition) {
myCondition = condition;
}
public boolean value(T object) {
if (!myProcessedSet.contains(object)) {
myProcessedSet.add(object);
final boolean value = myCondition.value(object);
if (value) {
myTrueSet.add(object);
return true;
}
return false;
}
return myTrueSet.contains(object);
}
}
public static class IsInheritorOf implements Condition<PsiClass> {
private final PsiClass myClass;
private final ConditionCache<PsiClass> myConditionCache;
public IsInheritorOf(PsiClass aClass) {
myClass = aClass;
myConditionCache = new ConditionCache<PsiClass>(new MyCondition());
}
public boolean value(PsiClass object) {
return myConditionCache.value(object);
}
private class MyCondition implements Condition<PsiClass> {
public boolean value(PsiClass aClass) {
return aClass.isInheritor(myClass, true);
}
}
}
public static class IsDescendantOf implements Condition<PsiClass> {
private final PsiClass myClass;
private final ConditionCache<PsiClass> myConditionCache;
public IsDescendantOf(PsiClass aClass) {
myClass = aClass;
myConditionCache = new ConditionCache<PsiClass>(new Condition<PsiClass>() {
public boolean value(PsiClass aClass) {
return InheritanceUtil.isInheritorOrSelf(aClass, myClass, true);
}
});
}
public boolean value(PsiClass aClass) {
return myConditionCache.value(aClass);
}
}
public static void processIncorrectOperation(final Project project, IncorrectOperationException e) {
@NonNls final String message = e.getMessage();
final int index = message != null ? message.indexOf("java.io.IOException") : -1;
if (index >= 0) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
Messages.showMessageDialog(project, message.substring(index + "java.io.IOException".length()),
RefactoringBundle.message("error.title"),
Messages.getErrorIcon());
}
});
}
else {
LOG.error(e);
}
}
public static void analyzeModuleConflicts(Project project,
Collection<? extends PsiElement> scope,
final UsageInfo[] usages,
PsiElement target,
final Collection<String> conflicts) {
if (scope == null) return;
final VirtualFile vFile = PsiUtil.getVirtualFile(target);
if (vFile == null) return;
analyzeModuleConflicts(project, scope, usages, vFile, conflicts);
}
public static void analyzeModuleConflicts(Project project,
final Collection<? extends PsiElement> scopes,
final UsageInfo[] usages,
final VirtualFile vFile,
final Collection<String> conflicts) {
if (scopes == null) return;
for (final PsiElement scope : scopes) {
if (scope instanceof PsiPackage || scope instanceof PsiDirectory) return;
}
final Module targetModule = VfsUtil.getModuleForFile(project, vFile);
if (targetModule == null) return;
final GlobalSearchScope resolveScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(targetModule);
final HashSet<PsiElement> reported = new HashSet<PsiElement>();
for (final PsiElement scope : scopes) {
scope.accept(new PsiRecursiveElementVisitor() {
public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
super.visitReferenceElement(reference);
final PsiElement resolved = reference.resolve();
if (resolved != null && !reported.contains(resolved)
&& !isAncestor(resolved, scopes)
&& !PsiSearchScopeUtil.isInScope(resolveScope, resolved)) {
final String scopeDescription = CommonRefactoringUtil.htmlEmphasize(ConflictsUtil.getDescription(ConflictsUtil.getContainer(reference),
true));
final String message =
RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.in.module.2",
ConflictsUtil.capitalize(CommonRefactoringUtil.htmlEmphasize(ConflictsUtil.getDescription(resolved, true))),
scopeDescription, CommonRefactoringUtil.htmlEmphasize(targetModule.getName()));
conflicts.add(message);
reported.add(resolved);
}
}
});
}
NextUsage:
for (UsageInfo usage : usages) {
if (usage instanceof MoveRenameUsageInfo) {
final MoveRenameUsageInfo moveRenameUsageInfo = ((MoveRenameUsageInfo)usage);
final PsiElement element = usage.getElement();
if (element != null &&
PsiTreeUtil.getParentOfType(element, PsiImportStatement.class, false) == null) {
for (PsiElement scope : scopes) {
if (PsiTreeUtil.isAncestor(scope, element, false)) continue NextUsage;
}
final GlobalSearchScope resolveScope1 = element.getResolveScope();
if (!resolveScope1.isSearchInModuleContent(targetModule)) {
final PsiFile file = element.getContainingFile();
final PsiElement container;
if (file instanceof PsiJavaFile) {
container = ConflictsUtil.getContainer(element);
LOG.assertTrue(container != null);
}
else {
container = file;
}
final String scopeDescription = CommonRefactoringUtil.htmlEmphasize(ConflictsUtil.getDescription(container, true));
Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(file.getVirtualFile());
final String message =
RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.from.module.2", ConflictsUtil.capitalize(
CommonRefactoringUtil.htmlEmphasize(ConflictsUtil.getDescription(moveRenameUsageInfo.getReferencedElement(), true))),
scopeDescription,
CommonRefactoringUtil.htmlEmphasize(module.getName()));
conflicts.add(message);
}
}
}
}
}
private static boolean isAncestor(final PsiElement resolved, final Collection<? extends PsiElement> scopes) {
for (final PsiElement scope : scopes) {
if (PsiTreeUtil.isAncestor(scope, resolved, false)) return true;
}
return false;
}
}
|
package com.ecyrd.jspwiki.plugin;
import java.util.Collection;
import java.util.Properties;
import org.apache.jspwiki.api.PluginException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.ecyrd.jspwiki.TestEngine;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.plugin.PluginManager.WikiPluginInfo;
public class PluginIndexPluginTest extends TestCase
{
Properties props = new Properties();
TestEngine engine;
WikiContext context;
PluginManager manager;
Collection<WikiPluginInfo> m_requiredPlugins;
public static final String[] REQUIRED_COLUMNS = { "Name", "Class Name", "alias's", "author", "minVersion", "maxVersion",
"adminBean Class" };
public PluginIndexPluginTest( String s )
{
super( s );
}
public void setUp() throws Exception
{
props.load( TestEngine.findTestProperties() );
engine = new TestEngine( props );
manager = new PluginManager( engine, props );
context = engine.getWikiContextFactory().newViewContext( engine.createPage( "TestPage" ) );
m_requiredPlugins = context.getEngine().getPluginManager().modules();
}
public void tearDown()
{
TestEngine.emptyWorkDir();
}
public static Test suite()
{
return new TestSuite( PluginIndexPluginTest.class );
}
/**
* Test for the presence of all core plugins
*
* @throws PluginException
*/
public void testCorePluginsPresent() throws PluginException
{
String result = manager.execute( context, "{PluginIndexPlugin details=false}" );
// test for the presence of each core plugin (this list can be expanded
// as new plugins are added)
for( WikiPluginInfo pluginInfo : m_requiredPlugins )
{
String name = pluginInfo.getName();
assertTrue( "plugin '" + name + "' missing", result.contains( name ) );
}
}
/**
* Test for : PluginIndexPlugin details=true Shows the plugin names
* including all attributes
*
* @throws PluginException
*/
public void testDetails() throws PluginException
{
String result = manager.execute( context, "{PluginIndexPlugin details=true}" );
// check for the presence of all required columns:
for( int i = 0; i < REQUIRED_COLUMNS.length; i++ )
{
assertTrue( "plugin '" + REQUIRED_COLUMNS[i] + "' missing", result.contains( REQUIRED_COLUMNS[i] ) );
}
}
/**
* Test for the number of rows returned (should be equal to the number of
* plugins found)
*
* @throws PluginException
*/
public void testNumberOfRows() throws PluginException
{
String result = manager.execute( context, "{PluginIndexPlugin details=true}" );
String row = "<tr";
String[] pieces = result.split( row );
int numRows = pieces.length - 2;
assertEquals( "unexpected number of rows", m_requiredPlugins.size(), numRows );
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2007 Dec 08: Code formatting. - dj@opennms.org
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.core.resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import org.opennms.core.resource.db.DbConnectionFactory;
public class Vault extends Object {
/**
* Holds all the application configuration properties.
*/
protected static Properties properties = new Properties(System.getProperties());
/**
* Stores the directory where the OpenNMS configuration files can be found.
* The default is <em>/opt/OpenNMS</em>.
*/
protected static String homeDir = "/opt/opennms/";
/**
* A delegate object that encapsulates the JDBC database connection
* allocation management. For example, some factories might preallocate
* connections into pools, or some might allocate connections only when
* requested.
*/
protected static DbConnectionFactory dbConnectionFactory;
/**
* Private, empty constructor so that this class cannot be instantiated.
*/
private Vault() {
}
/**
* Set the delegate class for managing JDBC database connection pools. This
* interface allows us to deploy <code>Vault</code> in different
* environments and using different database connection pooling models.
*/
public static void setDbConnectionFactory(DbConnectionFactory factory) {
if (factory == null) {
throw new IllegalArgumentException("Cannot take null parameters.");
}
dbConnectionFactory = factory;
}
public static Connection getDbConnection() throws SQLException {
if (dbConnectionFactory == null) {
throw new IllegalStateException("You must set a DbConnectionFactory before requesting a database connection.");
}
return dbConnectionFactory.getConnection();
}
public static void releaseDbConnection(Connection connection) throws SQLException {
if (dbConnectionFactory == null) {
throw new IllegalStateException("You must set a DbConnectionFactory before releasing a database connection.");
}
dbConnectionFactory.releaseConnection(connection);
}
/**
* Set the application configuration properties.
*/
public static void setProperties(Properties properties) {
if (properties == null) {
throw new IllegalArgumentException("Cannot take null parameters.");
}
Vault.properties = properties;
/*
* For backwards compatibility; put all these
* properties into the system properties.
*/
Enumeration keys = properties.keys();
Properties sysProps = System.getProperties();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
sysProps.put(key, properties.get(key));
}
}
/**
* Return the entire set of application configuration properties.
*/
public static Properties getProperties() {
return properties;
}
/**
* Return property from the configuration parameter list.
*/
public static String getProperty(String key) {
return properties.getProperty(key);
}
/**
* Set the directory so we will know where we can get the OpenNMS
* configuration files.
*/
public static void setHomeDir(String homeDir) {
if (homeDir == null) {
throw new IllegalArgumentException("Cannot take null parameters.");
}
Vault.homeDir = homeDir;
Vault.properties.setProperty("opennms.home", homeDir);
System.setProperty("opennms.home", homeDir);
}
/**
* Get the directory that holds the OpenNMS configuration files.
*/
public static String getHomeDir() {
return homeDir;
}
/**
* <P>
* Adds new keys to the system properties using the passed key name a the
* properties location instance. The passed key is used as a key to the
* system {@link java.util.Properties#getPropertyget property} to find the
* supplementary property information. The returned value should be in the
* form of a list of file names, each separated by the system
* {@link java.io.File#pathSeparatorCharpath separator} character.
* </P>
*
* <P>
* Once the list of files is recovered, each file is visited and loaded into
* the system properties. If any file cannot be loaded due to an I/O error
* then it is skipped as a whole. No partial key sets are loaded into the
* system properties. Also, this method will not overwrite an existing key
* in the currently loaded properties.
* </P>
*
* @param key
* The key name used to lookup the property path values.
*
* @return True if all properties loaded correctly, false if any property
* file failed to load.
*/
public static boolean supplementSystemPropertiesFromKey(String key) {
boolean loadedOK = true;
String path = System.getProperty(key);
if (path != null) {
StringTokenizer files = new StringTokenizer(path, File.pathSeparator);
while (files.hasMoreTokens()) {
try {
File pfile = new File(files.nextToken());
if (pfile.exists() && pfile.isFile()) {
Properties p = new Properties();
InputStream is = new FileInputStream(pfile);
try {
p.load(is);
} catch (IOException ioE) {
throw ioE;
} finally {
try {
is.close();
} catch (IOException ioE) { /* do nothing */
}
}
Iterator i = p.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
if (System.getProperty((String) e.getKey()) == null)
System.setProperty((String) e.getKey(), (String) e.getValue());
}
}
} catch (IOException ioE) {
loadedOK = false;
}
} // end while more files to be processed
} // end if property path no null
return loadedOK;
}
}
|
// Decompiler options: packimports(3)
// Source File Name: Data.java
package com.middleearthgames.orderchecker.io;
import com.middleearthgames.orderchecker.Nation;
import java.awt.Dimension;
import java.awt.Point;
import java.io.*;
import java.util.Vector;
import javax.swing.JCheckBox;
// Referenced classes of package com.middleearthgames.orderchecker.io:
// OCWindows, GameData
public class Data
{
public Data()
{
this.turnPath = "";
this.ordersPath = "";
this.gameType = 1;
this.exportFormat = 0;
this.sortFormat = 0;
this.endOfTurnInfo = true;
this.showCharInfo = true;
this.showAllResults = false;
this.gameData = new Vector();
this.windowSizes = new OCWindows();
}
public static JCheckBox isDuplicateRequest(Vector list, JCheckBox request)
{
for(int i = 0; i < list.size(); i++)
{
JCheckBox box = (JCheckBox)list.get(i);
if(request.getText().equals(box.getText()))
return box;
}
return null;
}
public void writeObject(ObjectOutputStream out)
throws IOException
{
out.writeInt(7);
out.writeUTF(this.turnPath);
out.writeUTF(this.ordersPath);
out.writeInt(this.gameType);
out.writeInt(this.gameData.size());
for(int i = 0; i < this.gameData.size(); i++)
{
GameData data = (GameData)this.gameData.get(i);
data.writeObject(out);
}
this.windowSizes.writeObject(out);
out.writeInt(this.exportFormat);
out.writeInt(this.sortFormat);
out.writeBoolean(this.endOfTurnInfo);
out.writeBoolean(this.showCharInfo);
out.writeBoolean(this.showAllResults);
}
public void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
int version = in.readInt();
this.turnPath = in.readUTF();
this.ordersPath = in.readUTF();
if(version < 6)
{
@SuppressWarnings("unused")
String rulesPath = in.readUTF();
String terrainPath = in.readUTF();
for(int i = 0; i < terrainFiles.length; i++)
if(terrainPath.equalsIgnoreCase(terrainFiles[i]))
this.gameType = i;
} else
{
this.gameType = in.readInt();
}
int count = in.readInt();
for(int i = 0; i < count; i++)
{
GameData data = new GameData();
data.readObject(in);
this.gameData.add(data);
}
this.windowSizes.readObject(in);
if(version >= 2)
this.exportFormat = in.readInt();
if(version >= 7)
this.sortFormat = in.readInt();
if(version >= 3)
this.endOfTurnInfo = in.readBoolean();
if(version >= 4)
this.showCharInfo = in.readBoolean();
if(version >= 5)
this.showAllResults = in.readBoolean();
}
public GameData findGame(Nation nation)
{
for(int i = 0; i < this.gameData.size(); i++)
{
GameData data = (GameData)this.gameData.get(i);
if(data.getGame() == nation.getGame())
{
if((data.getGameType() == null) || (data.getGameType().length() == 0))
data.setGameType(nation.getGameType());
return data;
}
}
GameData newGame = new GameData(nation);
this.gameData.add(newGame);
return newGame;
}
public String getTurnResultsPath()
{
return this.turnPath;
}
public String getOrdersPath()
{
return this.ordersPath;
}
public int getGameType()
{
return this.gameType;
}
public String[] getGameDescriptions()
{
return gameDesc;
}
public String getGameDescription()
{
return gameDesc[this.gameType];
}
public String getRulesPath()
{
return dataDirectory + rulesFile;
}
public String getTerrainPath()
{
return dataDirectory + terrainFiles[this.gameType];
}
public static String getDataDirectory() {
return dataDirectory;
}
public static void setDataDirectory(String dataDirectory) {
Data.dataDirectory = dataDirectory;
}
public Vector getGames()
{
return this.gameData;
}
public int getNationAlignment(int number, Nation nation)
{
GameData data = findGame(nation);
return data.getNationAlignment(number);
}
public Vector getCheckBoxes(Nation nation)
{
GameData data = findGame(nation);
return data.getCheckBoxes();
}
public String getCharacterNotes(Nation nation, String name)
{
GameData data = findGame(nation);
return data.getCharacterNotes(name);
}
public int getExportFormat()
{
return this.exportFormat;
}
public int getSortFormat()
{
return this.sortFormat;
}
public boolean getEndOfTurnInfo()
{
return this.endOfTurnInfo;
}
public boolean getShowCharNotes()
{
return this.showCharInfo;
}
public boolean getShowAllInfo()
{
return this.showAllResults;
}
public void setTurnResultsPath(String path)
{
this.turnPath = path;
}
public void setOrdersPath(String path)
{
this.ordersPath = path;
}
public void setGameType(String type)
{
for(int i = 0; i < gameDesc.length; i++)
if(type.equals(gameDesc[i]))
this.gameType = i;
}
public void setNationAlignment(int number, int alignment, Nation nation)
{
GameData data = findGame(nation);
data.setNationAlignment(number, alignment);
}
public void setCheckBoxes(Vector checkBoxes, Nation nation)
{
GameData data = findGame(nation);
data.setCheckBoxes(checkBoxes, nation.getTurn());
}
public void setCharacterNotes(Nation nation, String name, String notes)
{
GameData data = findGame(nation);
data.setCharacterNotes(name, notes);
}
public void setExportFormat(int format)
{
this.exportFormat = format;
}
public void setSortFormat(int format)
{
this.sortFormat = format;
}
public void setEndOfTurnInfo(boolean value)
{
this.endOfTurnInfo = value;
}
public void setShowCharNotes(boolean value)
{
this.showCharInfo = value;
}
public void setShowAllInfo(boolean value)
{
this.showAllResults = value;
}
public static Point getScreenLocation(Dimension d)
{
return OCWindows.getScreenLocation(d);
}
public static void checkScreenSize(Dimension d)
{
OCWindows.checkScreenSize(d);
}
public Dimension getWindowSize(int w)
{
return this.windowSizes.getWindowSize(w);
}
public Point getWindowLocation(int w)
{
return this.windowSizes.getWindowLocation(w);
}
public void setWindowSize(int w, Dimension d)
{
this.windowSizes.setWindowSize(w, d);
}
public void setWindowLocation(int w, Point p)
{
this.windowSizes.setWindowLocation(w, p);
}
@SuppressWarnings("unused")
private static final int VERSION = 7;
public static final int NEUTRAL = 0;
public static final int FREE_PEOPLE = 1;
public static final int DARK_SERVANT = 2;
public static final int TOTAL_NATIONS = 25;
//private static final int GAME_TYPES = 4;
public static final int GAME_1650 = 0;
public static final int GAME_2950 = 1;
public static final int GAME_1000 = 2;
public static final int GAME_BOFA = 3;
public static final int GAME_UW = 4;
public static final int GAME_KS = 5;
public static final int GAME_CME= 6;
private static String gameDesc[] = {
"1650", "2950", "Fourth Age", "BOFA", "Untold War", "Kin Strife","Champions of Middle-Earth"
};
public static final int NORMAL_FORMAT = 0;
public static final int HTML_FORMAT = 1;
public static final int BBCODE_FORMAT = 2;
public static final int SORT_BY_NAME = 0;
public static final int SORT_BY_LOCATION = 1;
static final int OC_WINDOWS = 4;
public static final int MAIN_WINDOW = 0;
public static final int FILE_EXPORT_WINDOW = 1;
public static final int HELP_INFO_WINDOW = 2;
public static final int CHAR_NOTES_WINDOW = 3;
private static String dataDirectory = "bin/metadata/orderchecker/";
private static String rulesFile = "ruleset.csv";
private static String terrainFiles[] = {
"1650.game", "2950.game", "fa.game", "bofa.game", "uw.game", "ks.game","cme.game"
};
private String turnPath;
private String ordersPath;
private int gameType;
private int exportFormat;
private int sortFormat;
private boolean endOfTurnInfo;
private boolean showCharInfo;
private boolean showAllResults;
private Vector gameData;
private OCWindows windowSizes;
}
|
package me.calebjones.spacelaunchnow.content.jobs;
import android.support.annotation.NonNull;
import com.evernote.android.job.Job;
import com.evernote.android.job.JobRequest;
import me.calebjones.spacelaunchnow.content.models.Constants;
import me.calebjones.spacelaunchnow.content.services.LaunchDataService;
public class NextLaunchJob extends Job {
public static final String TAG = Constants.ACTION_CHECK_NEXT_LAUNCH_TIMER;
@NonNull
@Override
protected Result onRunJob(Params params) {
if (LaunchDataService.getNextLaunches(getContext())) {
return Result.SUCCESS;
} else {
return Result.RESCHEDULE;
}
}
@Override
protected void onReschedule(int newJobId) {
// the rescheduled job has a new ID
}
public static void scheduleJob(long interval, int launchId) {
JobRequest.Builder builder = new JobRequest.Builder(NextLaunchJob.TAG + launchId)
.setExact(interval);
builder.setUpdateCurrent(true);
builder.build().schedule();
}
}
|
package org.frc4931.robot;
import org.frc4931.robot.commandnew.Scheduler;
import org.frc4931.robot.commandnew.auto.GrabAndGoAuto;
import org.frc4931.robot.commandnew.auto.TransferTote;
import org.frc4931.robot.commandnew.grabber.ToggleGrabber;
import org.frc4931.robot.commandnew.grabber.ToggleGrabberLift;
import org.frc4931.robot.commandnew.grabber.ToggleGrabberStep;
import org.frc4931.robot.commandnew.guardrail.ToggleGuardrail;
import org.frc4931.robot.commandnew.kicker.ToggleKickerGuardrail;
import org.frc4931.robot.commandnew.kicker.ToggleKickerTransfer;
import org.frc4931.robot.commandnew.ramplifter.ToggleRamp;
import org.frc4931.robot.component.DataStream;
import org.frc4931.robot.component.Motor;
import org.frc4931.robot.component.MotorWithAngle;
import org.frc4931.robot.component.Relay;
import org.frc4931.robot.component.Solenoid;
import org.frc4931.robot.component.Switch;
import org.frc4931.robot.subsystem.DriveSystem;
import org.frc4931.robot.subsystem.LoaderArm;
import org.frc4931.robot.subsystem.Ramp;
import org.frc4931.robot.subsystem.StackIndicatorLight;
import org.frc4931.robot.subsystem.VisionSystem;
import org.frc4931.robot.system.Robot;
import org.frc4931.robot.system.RobotBuilder;
import org.frc4931.utils.Lifecycle;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class RobotManager extends IterativeRobot {
private static final long START_TIME = System.currentTimeMillis();
public static final int NUMBER_OF_ADC_BITS = 12;
private static Robot robot;
private boolean home = false;
private Scheduler scheduler;
public Robot get() {
return robot;
}
@Override
public void robotInit() {
robot = RobotBuilder.buildRobot();
scheduler = new Scheduler();
Executor.getInstance().register(scheduler);
SwitchListener listener = new SwitchListener();
Logger logger = new Logger();
listener.onTriggered(robot.operator.toggleClaw, ()->scheduler.add(new ToggleGrabber(robot.structure.grabber)));
listener.onTriggered(robot.operator.toggleRails, ()->scheduler.add(new ToggleGuardrail(robot.structure.ramp.rail)));
listener.onTriggered(robot.operator.toggleRamp, ()->scheduler.add(new ToggleRamp(robot.structure.ramp.lifter)));
listener.onTriggered(robot.operator.transferTote, ()->scheduler.add(new TransferTote(robot)));
listener.onTriggered(robot.operator.writeData, logger::shutdown);
listener.onTriggered(robot.operator.writeData, ()->System.out.println("DATA SAVED"));
listener.whileUntriggered(()->robot.compressor.isPressurized(), ()->robot.compressor.activate());
listener.whileTriggered(()->robot.compressor.isPressurized(), ()->robot.compressor.deactivate());
listener.onTriggered(robot.operator.resetCounter, robot.toteCounter::reset);
listener.onTriggered(robot.operator.increaseCounter, robot.toteCounter::increase);
listener.onTriggered(robot.operator.grabberToStep, ()->scheduler.add(new ToggleGrabberStep(robot.structure.grabber)));
listener.onTriggered(robot.operator.grabberToTransfer, ()->scheduler.add(new ToggleGrabberLift(robot.structure.grabber)));
listener.onTriggered(robot.operator.kickerToTransfer, ()->scheduler.add(new ToggleKickerTransfer(robot.structure.kickerSystem.kicker)));
listener.onTriggered(robot.operator.kickerToGuardrail, ()->scheduler.add(new ToggleKickerGuardrail(robot.structure.kickerSystem.kicker)));
Executor.getInstance().register(listener);
logger.register("Drive Speed", ()->(short)(robot.operator.driveSpeed.read()*1000));
logger.register("Turn Speed", ()->(short)(robot.operator.turnSpeed.read()*1000));
logger.register("Throttle", ()->(short)(robot.operator.throttle.read()*1000));
logger.register("Guardrail Status", ()->robot.componets.guardrailGrabber.isExtending() ? 1 : 0);
logger.register("Left Grabber Status", ()->robot.componets.grabberLeftGrabber.isExtending() ? 1 : 0);
logger.register("Right Grabber Status", ()->robot.componets.grabberRightGrabber.isExtending() ? 1 : 0);
logger.register("Ramp Lifter Status", ()->robot.componets.rampLifter.isExtending() ? 1 : 0);
logger.register("Kicker Position", ()->(short)(Math.round(robot.componets.kickerEncoder.getAngle()*100)));
logger.register("Kicker Current", ()->(short)(robot.componets.kickerCurrent.getCurrent()*1000));
logger.register("Kicker Speed", ()->(short)(robot.componets.kickerMotor.getSpeed()*1000));
logger.register("Totes", ()->(short)robot.toteCounter.get());
logger.register("Grabber Position", ()->(short)Math.round(robot.componets.grabberEncoder.getAngle()*100));
logger.register("X Accel", ()->(short)(robot.componets.builtInAccel.getXacceleration()*1000));
logger.register("Y Accel", ()->(short)(robot.componets.builtInAccel.getYacceleration()*1000));
logger.register("Z Accel", ()->(short)(robot.componets.builtInAccel.getZacceleration()*1000));
logger.startup();
Executor.getInstance().start();
}
public void robotPeriodic() {
}
public void activePeriodic() {
robotPeriodic();
SmartDashboard.putNumber("Tote Count", robot.toteCounter.get());
SmartDashboard.putNumber("Front Distance", robot.frontDistance.getDistance() - 6);
}
@Override
public void disabledInit() {
scheduler.killAll();
robot.toteCounter.reset();
}
@Override
public void disabledPeriodic() {
robotPeriodic();
}
// Active code starts here
@Override
public void autonomousInit() {
robot.structure.ramp.lifter.raise();
robot.structure.ramp.rail.open();
robot.structure.grabber.open();
if(!home) {
robot.structure.kickerSystem.kicker.home();
robot.structure.grabber.home();
home = true;
}
scheduler.add(new GrabAndGoAuto(robot.drive, robot.structure));
}
@Override
public void autonomousPeriodic() {
activePeriodic();
}
@Override
public void teleopInit() {
scheduler.killAll();
if(!home) {
robot.structure.kickerSystem.kicker.home();
robot.structure.grabber.home();
home = true;
}
}
@Override
public void teleopPeriodic() {
activePeriodic();
double driveSpeed = robot.operator.driveSpeed.read();
double turnSpeed = robot.operator.turnSpeed.read()*-1;
// Map throttle from [-1.0, 1.0] to [0.0, 1.0]
double throttle = (robot.operator.throttle.read() - 1)/1.5;
robot.drive.arcade(driveSpeed * throttle, turnSpeed * throttle);
}
public static long time() {
return System.currentTimeMillis() - START_TIME;
}
@Deprecated
public static final class Systems implements Lifecycle {
public final DriveSystem drive;
public final LoaderArm grabber;
public final Ramp ramp;
public final VisionSystem vision;
public final StackIndicatorLight stackIndicator;
public Systems(DriveSystem drive, LoaderArm arm, Ramp ramp, VisionSystem vision, StackIndicatorLight stackIndicator) {
this.drive = drive;
this.grabber = arm;
this.ramp = ramp;
this.vision = vision;
this.stackIndicator = stackIndicator;
}
@Override
public void startup() {
drive.startup();
grabber.startup();
ramp.startup();
vision.startup();
stackIndicator.startup();
}
@Override
public void shutdown() {
try {
drive.shutdown();
} finally {
try {
grabber.shutdown();
} finally {
try {
ramp.shutdown();
} finally {
try {
vision.shutdown();
} finally {
stackIndicator.shutdown();
}
}
}
}
}
}
@Deprecated
public static interface Components {
Relay shifter();
Motor leftDriveMotor();
Motor rightDriveMotor();
Motor armLifterActuator();
Switch armLifterLowerSwitch();
Switch armLifterUpperSwitch();
Solenoid grabberActuator();
Switch capturableSwitch();
Switch capturedSwitch();
MotorWithAngle kickerMotor();
Solenoid rampLifterActuator();
Motor guardRailActuator();
Switch guardRailOpenSwitch();
Switch guardRailClosedSwitch();
String frontCameraName();
String rearCameraName();
DataStream rioDuinoDataStream();
}
}
|
package com.drew.metadata.apple;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.drew.lang.annotations.NotNull;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.makernotes.AppleMakernoteDirectory;
import com.drew.metadata.exif.makernotes.AppleRunTimeMakernoteDirectory;
import com.drew.metadata.plist.BplistReader;
/**
* Reads the <tt>AppleRunTime</tt> data and adds {@link AppleRunTimeMakernoteDirectory} to the
* parent {@link AppleMakernoteDirectory} if it can be parsed with no errors.
*/
public class AppleRunTimeReader
{
public void extract(@NotNull byte[] bytes, @NotNull final Metadata metadata, @NotNull final Directory parentDirectory)
{
parentDirectory.setByteArray(AppleMakernoteDirectory.TAG_RUN_TIME, bytes);
if (!BplistReader.isValid(bytes)) {
parentDirectory.addError("Input array is not a bplist");
return;
}
AppleRunTimeMakernoteDirectory directory = new AppleRunTimeMakernoteDirectory();
directory.setParent(parentDirectory);
try {
processAppleRunTime(directory, bytes);
if (directory.getTagCount() > 0) {
metadata.addDirectory(directory);
}
} catch (IOException e) {
parentDirectory.addError("Error processing TAG_RUN_TIME: " + e.getMessage());
}
}
/**
* Process the BPLIST containing the RUN_TIME tag. The directory will only be populated with values
* if the <tt>flag</tt> indicates that the CMTime structure is "valid".
*
* @param directory The <tt>AppleRunTimeMakernoteDirectory</tt> to set values onto.
* @param bplist The BPLIST
* @throws IOException Thrown if an error occurs parsing the BPLIST as a CMTime structure.
*/
private static void processAppleRunTime(@NotNull final AppleRunTimeMakernoteDirectory directory, @NotNull final byte[] bplist) throws IOException
{
final BplistReader.PropertyListResults results = BplistReader.parse(bplist);
final Set<Map.Entry<Byte, Byte>> entrySet = results.getEntrySet();
if (entrySet != null) {
HashMap<String, Object> values = new HashMap<String, Object>(entrySet.size());
for (Map.Entry<Byte, Byte> entry : entrySet) {
String key = (String)results.getObjects().get(entry.getKey());
Object value = results.getObjects().get(entry.getValue());
values.put(key, value);
}
Object flagsObject = values.get("flags");
if (flagsObject instanceof Byte) {
byte flags = (Byte) flagsObject;
if ((flags & 0x1) == 0x1) {
directory.setInt(AppleRunTimeMakernoteDirectory.CMTimeFlags, flags);
directory.setInt(AppleRunTimeMakernoteDirectory.CMTimeEpoch, (Byte) values.get("epoch"));
directory.setLong(AppleRunTimeMakernoteDirectory.CMTimeScale, (Long) values.get("timescale"));
directory.setLong(AppleRunTimeMakernoteDirectory.CMTimeValue, (Long) values.get("value"));
}
} else if (flagsObject instanceof String) {
byte flags = Byte.parseByte((String) flagsObject);
if ((flags & 0x1) == 0x1) {
directory.setInt(AppleRunTimeMakernoteDirectory.CMTimeFlags, flags);
directory.setInt(AppleRunTimeMakernoteDirectory.CMTimeEpoch, Byte.parseByte((String) values.get("epoch")));
directory.setLong(AppleRunTimeMakernoteDirectory.CMTimeScale, Long.parseLong((String) values.get("timescale")));
directory.setLong(AppleRunTimeMakernoteDirectory.CMTimeValue, Long.parseLong((String) values.get("value")));
}
}
}
}
}
|
package tpe.fruh_razzaq_jando.pue1;
/**
* Diese Klasse implementiert einen Bruch
*
* @author TPE_UIB_01
*/
public class Bruch implements Cloneable {
public static final int HASHSHIFT = 32;
// Properties
private long nenner, zaehler, ganze;
// Constructors
Bruch(long zaehler, long nenner) {
if (nenner == 0)
throw new RuntimeException(
"Bruch(zaehler, nenner) - nenner darf nicht 0 sein!");
else {
checkDoppelMinus(zaehler, nenner);
kuerze();
}
}
Bruch(long ganze, long zaehler, long nenner) {
if (nenner == 0)
throw new RuntimeException(
"Bruch(zaehler, nenner, ganze) - nenner darf nicht 0 sein!");
else {
checkDoppelMinus(zaehler, nenner);
this.ganze = ganze;
kuerze();
}
}
// Accessors
public long getNenner() {
return nenner;
}
public long getZaehler() {
return zaehler;
}
public long getGanze() {
return ganze;
}
// Methods
/**
* Methode welche aus einem doppelten Minusbruch z.B. -3/-2 3/2 wird
*
* @param zaehler Vom Bruch der Zaehler
* @param nenner Vom Bruch der Nenner
*/
private void checkDoppelMinus(long zaehler, long nenner) {
if (zaehler < 0 && nenner < 0) {
this.zaehler = Math.abs(zaehler);
this.nenner = Math.abs(nenner);
} else {
this.zaehler = zaehler;
this.nenner = nenner;
}
}
/**
* Methode implementiert die Rechnung eines Bruches mit einer Potenz
*
* @param potenz - Gibt die Potenz an , mit welcher der Bruch potenziert werden soll
* @return Einen neuen Bruch nachdem die Potenz darauf angewendet wurde
*/
public Bruch potenziere(long potenz) {
boolean warEcht = false;
Bruch tempBruch = (Bruch) this.clone();
if (isEcht()) {
tempBruch = tempBruch.unechterBruch();
warEcht = true;
}
long zaehler = (long) Math.pow(tempBruch.zaehler, potenz);
long nenner = (long) Math.pow(tempBruch.nenner, potenz);
Bruch newBruch = new Bruch(zaehler, nenner);
if (warEcht) {
newBruch = newBruch.echterBruch();
}
return newBruch;
}
public boolean isEcht() {
// Nur wenn der Bruch einen ganzzahligen Anteil besitzt ist er echt
return (this.ganze != 0);
}
/**
* Methode liefert zu einem Bruch den Kehrwert Bsp (1/2 = 2/1)
*
* @return einen neuen Bruch mit des Kehrwertes des alten Bruchs
*/
public Bruch kehrwert() {
if (this.isEcht()) {
return (new Bruch(this.ganze, this.nenner, this.zaehler));
} else {
return new Bruch(this.nenner, this.zaehler);
}
}
public Bruch addiere(Bruch zweiterBruch) {
return rechenOperation(zweiterBruch, '+');
}
public Bruch subtrahiere(Bruch zweiterBruch) {
return rechenOperation(zweiterBruch, '-');
}
public Bruch multipliziere(Bruch zweiterBruch) {
return rechenOperation(zweiterBruch, '*');
}
public Bruch multipliziere(long wert) {
return rechenOperation(new Bruch(wert, 1L), '*');
}
public Bruch dividiere(Bruch zweiterBruch) {
return rechenOperation(zweiterBruch, ':');
}
public Bruch dividiere(long wert) {
return rechenOperation(new Bruch(wert, 1), ':');
}
private Bruch rechenOperation(Bruch zweiterBruch, char operation) {
boolean echt = false;
Bruch tmpBruch1 = this.unechterBruch();
Bruch tmpBruch2 = zweiterBruch.unechterBruch();
Bruch ergebnisBruch;
if (this.isEcht() || zweiterBruch.isEcht()) {
echt = true;
}
long zaehler = tmpBruch1.neuerZaehler(operation, tmpBruch2);
long nenner;
// Die Operation geteilt, wird gesondert behandelt aufgrund des
// Kehrwertes
if (operation != ':') {
nenner = tmpBruch1.nenner * tmpBruch2.nenner;
} else {
nenner = tmpBruch1.nenner * tmpBruch2.kehrwert().nenner;
}
ergebnisBruch = new Bruch(zaehler, nenner);
ergebnisBruch = ergebnisBruch.rechenKuerzen();
if (echt) {
ergebnisBruch = ergebnisBruch.echterBruch();
}
return ergebnisBruch;
}
private long neuerZaehler(char operation, Bruch tmpBruch2) {
switch (operation) {
case '+':
return (this.zaehler * tmpBruch2.nenner)
+ (tmpBruch2.zaehler * this.nenner);
case '-':
return (this.zaehler * tmpBruch2.nenner)
- (tmpBruch2.zaehler * this.nenner);
case '*':
return (this.zaehler * tmpBruch2.zaehler);
case ':':
Bruch kehrwertBruch = tmpBruch2.kehrwert();
return (this.zaehler * kehrwertBruch.zaehler);
}
return 0;
}
/**
* Methode, welche aus einem echten/unechten Bruch einen unechten Bruch
* macht.
*
* @return Unechter Bruch z.B. 7/4
*/
public Bruch unechterBruch() {
if (isEcht()) {
return (new Bruch(0, (this.ganze * this.nenner) + this.zaehler,
this.nenner));
} else {
return (new Bruch(this.zaehler, this.nenner));
}
}
/**
* Methode, welche aus einem echten/unechten Bruch einen unechten Bruch
* macht.
*
* @return Echter Bruch z.B. 1 3/4
*/
public Bruch echterBruch() {
Bruch neuerBruch = (Bruch) this.clone();
while (neuerBruch.zaehler > neuerBruch.nenner) {
neuerBruch.ganze++;
neuerBruch.zaehler -= neuerBruch.nenner;
}
return neuerBruch;
}
/**
* Methode, welche von einem Bruch den Dezimalwert berechnet.
*
* @return Einen neuen Double-Wert mit dem Ergebnis
*/
public double getDezimalzahl() {
return ganze + ((double) zaehler / (double) nenner);
}
private void kuerze() {
if (this.zaehler != 0) {
long ggt = getGGT(Math.abs(Math.min(this.zaehler, this.nenner)));
this.zaehler = this.zaehler / ggt;
this.nenner = this.nenner / ggt;
}
}
private Bruch rechenKuerzen() {
if (this.zaehler != 0) {
long ggt = getGGT(Math.min(this.zaehler, this.nenner));
return (new Bruch(this.ganze, this.zaehler / ggt, this.nenner / ggt));
}
return (new Bruch(this.ganze, this.zaehler, this.nenner));
}
private long getGGT(long aktuelleZahl) {
// Zahl haben wir unseren GGT gefunden
if (zaehler % aktuelleZahl == 0 && nenner % aktuelleZahl == 0)
return aktuelleZahl;
else
// Rekursiver Aufruf, mache das Problem kleiner
return getGGT(aktuelleZahl - 1);
}
@Override
public String toString() {
if (ganze == 0)
return zaehler + "/" + nenner;
else if (zaehler == 0 && nenner == 0)
return ganze + "";
else
return ganze + " " + zaehler + "/" + nenner;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// does not happen
return null;
}
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Bruch bruch = (Bruch) o;
if (ganze != bruch.ganze)
return false;
if (nenner != bruch.nenner)
return false;
return zaehler == bruch.zaehler;
}
@Override
public int hashCode() {
int result = (int) (nenner ^ (nenner >>> HASHSHIFT));
result = 31 * result + (int) (zaehler ^ (zaehler >>> HASHSHIFT));
result = 31 * result + (int) (ganze ^ (ganze >>> HASHSHIFT));
return result;
}
}
|
/* -*- mode: Java; c-basic-offset: 2; -*- */
/**
* LZX Function representation
* @author steele@osteele.com
*/
package org.openlaszlo.sc;
public class Function {
public String name;
private final String args;
private final String body;
private final String sourceLocation;
public Function(String body) {
this("", body);
}
public Function(String args, String body) {
this("", args, body);
}
public Function(String name, String args, String body) {
this(name, args, body, null);
}
public Function(String name, String args, String body, String loc) {
this.name = name;
this.args = args;
this.body = body;
this.sourceLocation = loc;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "function " + name + "\n(" + args + "\n) {" +
"\n" + (sourceLocation != null?(sourceLocation + "\n"):"") + body + "\n}";
}
}
|
package jodd.util;
import java.io.File;
/**
* Various system utilities.
*/
public class SystemUtil {
/**
* Calculates and returns java system timer resolution in miliseconds.
* Resolution of a timer depends on platform and java version.
*/
public static double systemTimerResolution() {
long t1, t2;
int sumres = 0;
//noinspection CallToSystemGC
System.gc();
int loops = 20;
for (int i = 0; i < loops; ++i) {
t1 = System.currentTimeMillis();
while (true) {
t2 = System.currentTimeMillis();
if (t2 != t1) {
sumres += (int) (t2 - t1);
break;
}
}
}
return (sumres / (double) loops);
}
public static final String USER_DIR = "user.dir";
public static final String USER_NAME = "user.name";
public static final String USER_HOME = "user.home";
public static final String JAVA_HOME = "java.home";
public static final String TEMP_DIR = "java.io.tmpdir";
public static final String OS_NAME = "os.name";
public static final String OS_VERSION = "os.version";
public static final String JAVA_VERSION = "java.version";
public static final String JAVA_SPECIFICATION_VERSION = "java.specification.version";
public static final String JAVA_VENDOR = "java.vendor";
public static final String JAVA_CLASSPATH = "java.class.path";
public static final String PATH_SEPARATOR = "path.separator";
public static final String HTTP_PROXY_HOST = "http.proxyHost";
public static final String HTTP_PROXY_PORT = "http.proxyPort";
public static final String HTTP_PROXY_USER = "http.proxyUser";
public static final String HTTP_PROXY_PASSWORD = "http.proxyPassword";
public static final String FILE_ENCODING = "file.encoding";
public static final String SUN_BOOT_CLASS_PATH = "sun.boot.class.path";
/**
* Returns current working folder.
*/
public static String getUserDir() {
return System.getProperty(USER_DIR);
}
/**
* Returns current user.
*/
public static String getUserName() {
return System.getProperty(USER_NAME);
}
/**
* Returns user home folder.
*/
public static String getUserHome() {
return System.getProperty(USER_HOME);
}
/**
* Returns current working folder.
* Just a better name for {@link #getUserDir()}.
*/
public static String getWorkingFolder() {
return System.getProperty(USER_DIR);
}
/**
* Returns JRE home.
*/
public static String getJavaJreHome() {
return System.getProperty(JAVA_HOME);
}
/**
* Returns JAVA_HOME which is not equals to "java.home" property
* since it points to JAVA_HOME/jre folder.
*/
public static String getJavaHome() {
String home = System.getProperty(JAVA_HOME);
if (home == null) {
return null;
}
int i = home.lastIndexOf('\\');
int j = home.lastIndexOf('/');
if (j > i) {
i = j;
}
return home.substring(0, i);
}
/**
* Returns system temp dir.
*/
public static String getTempDir() {
return System.getProperty(TEMP_DIR);
}
/**
* Returns OS name.
*/
public static String getOsName() {
return System.getProperty(OS_NAME);
}
/**
* Returns OS version.
*/
public static String getOsVersion() {
return System.getProperty(OS_VERSION);
}
/**
* Returns Java version.
* @see #getJavaSpecificationVersion()
*/
public static String getJavaVersion() {
return System.getProperty(JAVA_VERSION);
}
/**
* Retrieves the version of the currently running JVM.
*/
public static double getJavaSpecificationVersion() {
return Double.parseDouble(System.getProperty(JAVA_SPECIFICATION_VERSION));
}
/**
* Returns Java vendor.
*/
public static String getJavaVendor() {
return System.getProperty(JAVA_VENDOR);
}
/**
* Returns system class path.
*/
public static String getClassPath() {
return System.getProperty(JAVA_CLASSPATH);
}
/**
* Returns path separator.
*/
public static String getPathSeparator() {
return System.getProperty(PATH_SEPARATOR);
}
/**
* Returns file encoding.
*/
public static String getFileEncoding() {
return System.getProperty(FILE_ENCODING);
}
/**
* Checks if the currently running JVM is at least compliant with JDK 1.5.
*/
public static boolean isAtLeastJdk15() {
return getJavaSpecificationVersion() >= 1.5;
}
/**
* Checks if the currently running JVM is at least compliant with JDK 1.6.
*/
public static boolean isAtLeastJdk16() {
return getJavaSpecificationVersion() >= 1.6;
}
/**
* Returns <code>true</code> if host is Windows.
*/
public static boolean isHostWindows() {
return getOsName().toUpperCase().startsWith("WINDOWS");
}
/**
* Returns <code>true</code> if host is Linux.
*/
public static boolean isHostLinux() {
return getOsName().toUpperCase().startsWith("LINUX");
}
/**
* Returns <code>true</code> if host is a general unix.
*/
public static boolean isHostUnix() {
return File.pathSeparator.equals(StringPool.COLON);
}
/**
* Returns <code>true</code> if host is Mac.
*/
public static boolean isHostMac() {
return getOsName().toUpperCase().startsWith("MAC OS X");
}
/**
* Returns <code>true</code> if host is Solaris.
*/
public static boolean isHostSolaris() {
return getOsName().toUpperCase().startsWith("SUNOS");
}
/**
* Returns <code>true<</code> if host is AIX.
*/
public static boolean isHostAix() {
return getOsName().toUpperCase().equals("AIX");
}
/**
* Returns sun bootstrap class path.
*/
public static String getSunBoothClassPath() {
return System.getProperty(SUN_BOOT_CLASS_PATH);
}
/**
* Sets HTTP proxy settings.
*/
public static void setHttpProxy(String host, String port, String username, String password) {
System.getProperties().put(HTTP_PROXY_HOST, host);
System.getProperties().put(HTTP_PROXY_PORT, port);
System.getProperties().put(HTTP_PROXY_USER, username);
System.getProperties().put(HTTP_PROXY_PASSWORD, password);
}
/**
* Sets HTTP proxy settings.
*/
public static void setHttpProxy(String host, String port) {
System.getProperties().put(HTTP_PROXY_HOST, host);
System.getProperties().put(HTTP_PROXY_PORT, port);
}
}
|
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.eperson.AccountManager;
import org.dspace.eperson.EPerson;
/**
* Servlet for handling user registration and forgotten passwords.
* <P>
* This servlet handles both forgotten passwords and initial registration of
* users. Which it handles depends on the initialisation parameter
* "register" - if it's "true", it is treated as an initial registration
* and the user is asked to input their personal information.
* <P>
* The sequence of events is this: The user clicks on "register" or "I forgot
* my password." This servlet then displays the relevant "enter your e-mail"
* form. An e-mail address is POSTed back, and if this is valid, a token
* is created and e-mailed, otherwise an error is displayed, with another
* "enter your e-mail" form.
* <P>
* When the user clicks on the token URL mailed to them, this servlet receives
* a GET with the token as the parameter "KEY". If this is a valid token,
* the servlet then displays the "edit profile" or "edit password" screen
* as appropriate.
*/
public class RegisterServlet extends DSpaceServlet
{
/** Logger */
private static Logger log = Logger.getLogger(RegisterServlet.class);
/** The "enter e-mail" step */
public static final int ENTER_EMAIL_PAGE = 1;
/** The "enter personal info" page */
public static final int PERSONAL_INFO_PAGE = 2;
/** The simple "enter new password" page */
public static final int NEW_PASSWORD_PAGE = 3;
/** true = registering users, false = forgotten passwords */
private boolean registering;
public void init()
{
registering = getInitParameter("register").equalsIgnoreCase("true");
}
protected void doDSGet(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
/* Respond to GETs. A simple GET with no parameters will display
* the relevant "type in your e-mail" form. A GET with a "key"
* parameter will go to the "enter personal info" or "enter new
* password" page as appropriate.
*/
// Get the key
String key = request.getParameter("token");
if (key == null)
{
// Simple "enter your e-mail" page
if (registering)
{
// Registering a new user
JSPManager.showJSP(request, response, "/register/new-user.jsp");
}
else
{
// User forgot their password
JSPManager.showJSP(request,
response,
"/register/forgot-password.jsp");
}
}
else
{
// Find out who the key is for
EPerson eperson = AccountManager.getEPerson(context, key);
/* Display an error if it's:
* An invalid token
* An active eperson is trying to register
* An active eperson who needs to use certs is trying to set a p/w
* An inactive (unregistered) eperson is trying to set a new p/w
*/
if (eperson == null ||
(eperson.getActive() && registering) ||
(eperson.getActive() && eperson.getRequireCertificate() && registering) ||
(!registering && !eperson.getActive()))
{
// Invalid token
JSPManager.showJSP(request,
response,
"/register/invalid-token.jsp");
return;
}
// Both forms need an EPerson object
request.setAttribute("eperson", eperson);
// And the token
request.setAttribute("key", key);
// Put up the relevant form
if (registering)
{
JSPManager.showJSP(request,
response,
"/register/registration-form.jsp");
}
else
{
JSPManager.showJSP(request,
response,
"/register/new-password.jsp");
}
}
}
protected void doDSPost(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
/*
* POSTs are the result of entering an e-mail in the
* "forgot my password" or "new user" forms, or the "enter profile
* information" or "enter new password" forms.
*/
// First get the step
int step = UIUtil.getIntParameter(request, "step");
switch (step)
{
case ENTER_EMAIL_PAGE:
processEnterEmail(context, request, response);
break;
case PERSONAL_INFO_PAGE:
processPersonalInfo(context, request, response);
break;
case NEW_PASSWORD_PAGE:
processNewPassword(context, request, response);
break;
default:
log.warn(LogManager.getHeader(context,
"integrity_error",
UIUtil.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
}
}
/**
* Process information from the "enter e-mail" page. If the e-mail
* corresponds to a valid user of the system, a token is generated
* and sent to that user.
*
* @param context current DSpace context
* @param request current servlet request object
* @param response current servlet response object
*/
private void processEnterEmail(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
String email = request.getParameter("email");
EPerson eperson = EPerson.findByEmail(context, email);
if (eperson != null)
{
// Can't register an already active user
if (eperson.getActive() && registering)
{
log.info(LogManager.getHeader(context,
"already_registered",
"email=" + email));
JSPManager.showJSP(request,
response,
"/register/already-registered.jsp");
return;
}
// Can't give new password to inactive user
if (!eperson.getActive() && !registering)
{
log.info(LogManager.getHeader(context,
"unregistered_forgot_password",
"email=" + email));
JSPManager.showJSP(request,
response,
"/register/inactive-account.jsp");
return;
}
// User that requires certificate can't get password
if (eperson.getRequireCertificate() && !registering)
{
log.info(LogManager.getHeader(context,
"certificate_user_forgot_password",
"email=" + email));
JSPManager.showJSP(request,
response,
"/error/require-certificate.jsp");
return;
}
// Now send info.
try
{
if (registering)
{
log.info(LogManager.getHeader(context,
"sendtoken_register",
"email=" + email));
AccountManager.sendRegistrationInfo(context, email);
JSPManager.showJSP(request,
response,
"/register/registration-sent.jsp");
}
else
{
log.info(LogManager.getHeader(context,
"sendtoken_forgotpw",
"email=" + email));
AccountManager.sendForgotPasswordInfo(context, email);
JSPManager.showJSP(request,
response,
"/register/password-token-sent.jsp");
}
// Context needs completing to write registration data
context.complete();
}
catch (MessagingException me)
{
log.info(LogManager.getHeader(context,
"error_emailing",
"email=" + email),
me);
JSPManager.showInternalError(request, response);
}
}
else
{
log.info(LogManager.getHeader(context,
"unknown_email",
"email=" + email));
request.setAttribute("retry", new Boolean(true));
if (registering)
{
JSPManager.showJSP(request,
response,
"/register/new-user.jsp");
}
else
{
JSPManager.showJSP(request,
response,
"/register/forgot-password.jsp");
}
}
}
/**
* Process information from "Personal information page"
*
* @param context current DSpace context
* @param request current servlet request object
* @param response current servlet response object
*/
private void processPersonalInfo(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
// Get the key
String key = request.getParameter("key");
// Get the eperson associated with the registration
EPerson eperson = AccountManager.getEPerson(context, key);
// If the token isn't valid, show an error
if (eperson == null)
{
log.info(LogManager.getHeader(context,
"invalid_token",
"token=" + key));
// Invalid token
JSPManager.showJSP(request,
response,
"/register/invalid-token.jsp");
return;
}
// If the token is valid, we set the current user of the context
// to the user associated with the token, so they can update their
// info
context.setCurrentUser(eperson);
// Set the user profile info
boolean infoOK = EditProfileServlet.updateUserProfile(eperson, request);
boolean passwordOK = true;
if (eperson.getRequireCertificate() == false)
{
passwordOK = EditProfileServlet.confirmAndSetPassword(eperson,
request);
}
if (!infoOK)
{
request.setAttribute("missing.fields", new Boolean(true));
}
if (!passwordOK)
{
request.setAttribute("password.problem", new Boolean(true));
}
request.setAttribute("eperson", eperson);
// Forward to appropriate page
if (infoOK && passwordOK)
{
log.info(LogManager.getHeader(context,
"usedtoken_register",
"email=" + eperson.getEmail()));
// delete the token
AccountManager.deleteToken(context, key);
// Set the user as active
eperson.setActive(true);
eperson.update();
JSPManager.showJSP(request, response, "/register/registered.jsp");
context.complete();
}
else
{
request.setAttribute("key", key);
JSPManager.showJSP(request,
response,
"/register/registration-form.jsp");
}
}
/**
* Process information from "enter new password"
*
* @param context current DSpace context
* @param request current servlet request object
* @param response current servlet response object
*/
private void processNewPassword(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
// Get the key
String key = request.getParameter("key");
// Get the eperson associated with the password change
EPerson eperson = AccountManager.getEPerson(context, key);
// If the token isn't valid, show an error
if (eperson == null)
{
log.info(LogManager.getHeader(context,
"invalid_token",
"token=" + key));
// Invalid token
JSPManager.showJSP(request,
response,
"/register/invalid-token.jsp");
return;
}
// If the token is valid, we set the current user of the context
// to the user associated with the token, so they can update their
// info
context.setCurrentUser(eperson);
// Confirm and set the password
boolean passwordOK = EditProfileServlet.confirmAndSetPassword(
eperson, request);
if (passwordOK)
{
log.info(LogManager.getHeader(context,
"usedtoken_forgotpw",
"email=" + eperson.getEmail()));
eperson.update();
AccountManager.deleteToken(context, key);
JSPManager.showJSP(request,
response,
"/register/password-changed.jsp");
context.complete();
}
else
{
request.setAttribute("password.problem", new Boolean(true));
request.setAttribute("key", key);
request.setAttribute("eperson", eperson);
JSPManager.showJSP(request,
response,
"/register/new-password.jsp");
}
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.HierarchyEvent;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public final class MainPanel extends JPanel {
private final JTextArea logger = new JTextArea();
private final FileModel model = new FileModel();
private final transient TableRowSorter<? extends TableModel> sorter = new TableRowSorter<>(model);
private final Set<Integer> deleteRowSet = new TreeSet<>();
private MainPanel() {
super(new BorderLayout());
JTable table = new JTable(model);
table.setRowSorter(sorter);
table.setFillsViewportHeight(true);
table.setComponentPopupMenu(new TablePopupMenu());
TableColumn col = table.getColumnModel().getColumn(0);
col.setMinWidth(30);
col.setMaxWidth(30);
col.setResizable(false);
Path dir = Paths.get(System.getProperty("java.io.tmpdir"));
SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
Thread worker = new Thread(() -> {
try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
append("register: " + dir);
processEvents(dir, watcher);
loop.exit();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
});
worker.start();
if (!loop.enter()) {
append("Error");
}
addHierarchyListener(e -> {
boolean isDisplayableChanged = (e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0;
if (isDisplayableChanged && !e.getComponent().isDisplayable()) {
worker.interrupt();
}
});
JButton button = new JButton("createTempFile");
button.addActionListener(e -> {
try {
Path path = Files.createTempFile("_", ".tmp");
path.toFile().deleteOnExit();
} catch (IOException ex) {
append(ex.getMessage());
}
});
JPanel p = new JPanel();
p.add(button);
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setTopComponent(new JScrollPane(table));
sp.setBottomComponent(new JScrollPane(logger));
sp.setResizeWeight(.5f);
add(p, BorderLayout.NORTH);
add(sp);
setPreferredSize(new Dimension(320, 240));
}
// Process all events for keys queued to the watcher
public void processEvents(Path dir, WatchService watcher) {
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
EventQueue.invokeLater(() -> append("Interrupted"));
Thread.currentThread().interrupt();
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
// This key is registered only for ENTRY_CREATE events,
// but an OVERFLOW event can occur regardless if events
// are lost or discarded.
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
// The filename is the context of the event.
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path filename = ev.context();
Path child = dir.resolve(filename);
EventQueue.invokeLater(() -> {
append(String.format("%s: %s", kind, child));
updateTable(kind, child);
});
}
// Reset the key -- this step is critical if you want to
// receive further watch events. If the key is no longer valid,
// the directory is inaccessible so exit the loop.
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
public void updateTable(WatchEvent.Kind<?> kind, Path child) {
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
model.addPath(child);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
for (int i = 0; i < model.getRowCount(); i++) {
Object value = model.getValueAt(i, 2);
String path = Objects.toString(value, "");
if (path.equals(child.toString())) {
deleteRowSet.add(i);
// model.removeRow(i);
break;
}
}
sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
@Override public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
return !isDeleteRow(entry.getIdentifier());
}
});
}
}
public boolean isDeleteRow(int row) {
return deleteRowSet.contains(row);
}
public void append(String str) {
logger.append(str + "\n");
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class FileModel extends DefaultTableModel {
private static final ColumnContext[] COLUMN_ARRAY = {
new ColumnContext("No.", Integer.class, false),
new ColumnContext("Name", String.class, false),
new ColumnContext("Full Path", String.class, false)
};
private int number;
public void addPath(Path path) {
Object[] obj = {number, path.getFileName(), path.toAbsolutePath()};
super.addRow(obj);
number++;
}
@Override public boolean isCellEditable(int row, int col) {
return COLUMN_ARRAY[col].isEditable;
}
@Override public Class<?> getColumnClass(int column) {
return COLUMN_ARRAY[column].columnClass;
}
@Override public int getColumnCount() {
return COLUMN_ARRAY.length;
}
@Override public String getColumnName(int column) {
return COLUMN_ARRAY[column].columnName;
}
private static class ColumnContext {
public final String columnName;
public final Class<?> columnClass;
public final boolean isEditable;
protected ColumnContext(String columnName, Class<?> columnClass, boolean isEditable) {
this.columnName = columnName;
this.columnClass = columnClass;
this.isEditable = isEditable;
}
}
}
class TablePopupMenu extends JPopupMenu {
private final JMenuItem delete;
protected TablePopupMenu() {
super();
delete = add("delete");
delete.addActionListener(e -> {
JTable table = (JTable) getInvoker();
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] selection = table.getSelectedRows();
for (int i = selection.length - 1; i >= 0; i
int idx = table.convertRowIndexToModel(selection[i]);
Path path = Paths.get(Objects.toString(model.getValueAt(idx, 2)));
try {
Files.delete(path);
} catch (IOException ex) {
Toolkit.getDefaultToolkit().beep();
}
}
});
}
@Override public void show(Component c, int x, int y) {
if (c instanceof JTable) {
delete.setEnabled(((JTable) c).getSelectedRowCount() > 0);
super.show(c, x, y);
}
}
}
|
package dynamake.dragndrop;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import dynamake.commands.DejectTransaction;
import dynamake.commands.DualCommand;
import dynamake.commands.DualCommandPair;
import dynamake.commands.InjectTransaction;
import dynamake.menubuilders.ActionRunner;
import dynamake.menubuilders.CompositeMenuBuilder;
import dynamake.models.CompositeModelLocation;
import dynamake.models.Location;
import dynamake.models.Model;
import dynamake.models.ModelComponent;
import dynamake.models.ModelLocation;
import dynamake.models.LiveModel.LivePanel;
import dynamake.tools.InteractionPresenter;
import dynamake.tools.TargetPresenter;
import dynamake.transcription.Collector;
import dynamake.transcription.Connection;
import dynamake.transcription.DualCommandFactory2;
import dynamake.transcription.Trigger;
public class DragDragDropPopupBuilder implements DragDropPopupBuilder {
private Connection<Model> connection;
private TargetPresenter targetPresenter;
private InteractionPresenter interactionPresenter;
public DragDragDropPopupBuilder(Connection<Model> connection, TargetPresenter targetPresenter, InteractionPresenter interactionPresenter) {
this.connection = connection;
this.targetPresenter = targetPresenter;
this.interactionPresenter = interactionPresenter;
}
@Override
public void buildFromSelectionAndTarget(ModelComponent livePanel,
JPopupMenu popup, ModelComponent selection,
ModelComponent target, Point dropPointOnTarget, Rectangle dropBoundsOnTarget) {
if(target == null || target == selection) {
// Build popup menu for dropping onto selection
buildFromSelectionToSelection(livePanel, popup, selection);
} else {
// Build popup menu for dropping onto other
buildFromSelectionToOther(livePanel, popup, selection, target, dropPointOnTarget, dropBoundsOnTarget);
}
}
private void buildFromSelectionToSelection(final ModelComponent livePanel, JPopupMenu popup, ModelComponent selection) {
ActionRunner runner = new ActionRunner() {
@Override
public void run(final Object action) {
connection.trigger(new Trigger<Model>() {
@SuppressWarnings("unchecked")
@Override
public void run(Collector<Model> collector) {
targetPresenter.reset(collector);
interactionPresenter.reset(collector);
((Trigger<Model>)action).run(collector);
collector.commit();
}
});
}
};
ModelComponent parentModelComponent = ModelComponent.Util.closestModelComponent(((JComponent)selection).getParent());
CompositeMenuBuilder containerTransactionMapBuilder = new CompositeMenuBuilder();
// Assume only TranscriberRunnable<Model> to be added as actions for menus
if(parentModelComponent != null)
parentModelComponent.appendContainerTransactions((LivePanel)livePanel, containerTransactionMapBuilder, selection);
CompositeMenuBuilder transactionSelectionMapBuilder = new CompositeMenuBuilder();
selection.appendTransactions(livePanel, transactionSelectionMapBuilder);
containerTransactionMapBuilder.appendTo(popup, runner, "Container");
if(!containerTransactionMapBuilder.isEmpty() && !transactionSelectionMapBuilder.isEmpty())
popup.addSeparator();
transactionSelectionMapBuilder.appendTo(popup, runner, "Selection");
}
private void buildFromSelectionToOther(final ModelComponent livePanel, JPopupMenu popup, final ModelComponent selection, final ModelComponent target, final Point dropPointOnTarget, final Rectangle dropBoundsOnTarget) {
ActionRunner runner = new ActionRunner() {
@Override
public void run(final Object action) {
connection.trigger(new Trigger<Model>() {
@SuppressWarnings("unchecked")
@Override
public void run(Collector<Model> collector) {
targetPresenter.reset(collector);
interactionPresenter.reset(collector);
((Trigger<Model>)action).run(collector);
collector.commit();
}
});
}
};
CompositeMenuBuilder transactionSelectionGeneralMapBuilder = new CompositeMenuBuilder();
if(selection.getModelBehind().isObservedBy(target.getModelBehind())) {
transactionSelectionGeneralMapBuilder.addMenuBuilder("Unforward to", new Trigger<Model>() {
@Override
public void run(Collector<Model> collector) {
Model.executeRemoveObserver(collector, selection, target);
}
});
} else {
transactionSelectionGeneralMapBuilder.addMenuBuilder("Forward to", new Trigger<Model>() {
@Override
public void run(Collector<Model> collector) {
Model.executeAddObserver(collector, selection, target);
}
});
}
transactionSelectionGeneralMapBuilder.addMenuBuilder("Inject", new Trigger<Model>() {
@Override
public void run(Collector<Model> collector) {
collector.execute(new DualCommandFactory2<Model>() {
ModelComponent referenceMC;
@Override
public Model getReference() {
referenceMC = ModelComponent.Util.closestCommonAncestor(selection, target);
return referenceMC.getModelBehind();
}
@Override
public void createDualCommands(Location location, List<DualCommand<Model>> dualCommands) {
ModelLocation locationOfSelection = new CompositeModelLocation(
(ModelLocation)location,
ModelComponent.Util.locationFromAncestor(referenceMC, selection)
);
ModelLocation locationOfTarget = new CompositeModelLocation(
(ModelLocation)location,
ModelComponent.Util.locationFromAncestor(referenceMC, target)
);
dualCommands.add(new DualCommandPair<Model>(
new InjectTransaction(locationOfSelection, locationOfTarget),
new DejectTransaction(locationOfSelection, locationOfTarget)
));
}
});
}
});
CompositeMenuBuilder transactionTargetMapBuilder = new CompositeMenuBuilder();
target.appendDropTargetTransactions(livePanel, selection, dropBoundsOnTarget, dropPointOnTarget, transactionTargetMapBuilder);
transactionSelectionGeneralMapBuilder.appendTo(popup, runner, "General");
if(!transactionSelectionGeneralMapBuilder.isEmpty() && !transactionTargetMapBuilder.isEmpty())
popup.addSeparator();
transactionTargetMapBuilder.appendTo(popup, runner, "Target");
CompositeMenuBuilder transactionDroppedMapBuilder = new CompositeMenuBuilder();
selection.appendDroppedTransactions(livePanel, target, dropBoundsOnTarget, transactionDroppedMapBuilder);
if(!transactionTargetMapBuilder.isEmpty() && !transactionDroppedMapBuilder.isEmpty())
popup.addSeparator();
transactionDroppedMapBuilder.appendTo(popup, runner, "Dropped");
}
@Override
public void cancelPopup(LivePanel livePanel) {
connection.trigger(new Trigger<Model>() {
public void run(Collector<Model> collector) {
targetPresenter.reset(collector);
interactionPresenter.reset(collector);
collector.reject();
}
});
}
}
|
package io.spacedog.services;
import java.util.stream.Stream;
import org.elasticsearch.action.support.QuerySourceBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import io.spacedog.services.Credentials.Level;
import io.spacedog.services.CredentialsResource.SignUp;
import io.spacedog.utils.Backends;
import io.spacedog.utils.Exceptions;
import io.spacedog.utils.Internals;
import io.spacedog.utils.SpaceParams;
import net.codestory.http.Context;
import net.codestory.http.annotations.Delete;
import net.codestory.http.annotations.Get;
import net.codestory.http.annotations.Post;
import net.codestory.http.payload.Payload;
public class BackendResource extends Resource {
private static final String TYPE = "backend";
// Routes
@Get("")
@Get("/")
public Payload ping() {
return JsonPayload.success();
}
@Post("")
@Post("/")
@Post("/1")
@Post("/1/")
public Payload post(String body, Context context) {
Credentials credentials = SpaceContext.getCredentials();
if (credentials.isRootBackend())
throw Exceptions.illegalArgument("[api] not available to identify a new backend");
return post(credentials.backendId(), body, context);
}
@Post("/1/backend/:id")
@Post("/1/backend/:id/")
public Payload post(String backendId, String body, Context context) {
Backends.checkIfIdIsValid(backendId);
if (existsBackend(backendId))
return JsonPayload.invalidParameters("backendId", backendId,
String.format("backend id [%s] not available", backendId));
SignUp backendSignUp = new SignUp(backendId, Level.SUPER_ADMIN, body);
CredentialsResource.get().create(backendSignUp);
// after backend is created, new admin credentials are valid
// and can be set in space context if none are set
SpaceContext.setCredentials(
new Credentials(backendId, backendSignUp.credentials.name(),
backendSignUp.credentials.email().get(), Level.SUPER_ADMIN));
if (!SpaceContext.isTest())
Internals.get().notify(
Start.get().configuration().superdogAwsNotificationTopic(),
String.format("New backend (%s)", spaceRootUrl(backendId).toString()),
String.format("backend id = %s\nadmin email = %s", backendId,
backendSignUp.credentials.email().get()));
return JsonPayload.saved(true, backendId, "/1/backend", TYPE, backendId, true);
}
@Get("/1/backend")
@Get("/1/backend/")
public Payload getAll(Context context) {
Credentials credentials = SpaceContext.checkAdminCredentials(false);
boolean refresh = context.query().getBoolean(SpaceParams.REFRESH, false);
if (credentials.isRootBackend()) {
if (credentials.isSuperDog())
return CredentialsResource.get().getAllSuperAdmins(refresh);
throw new AuthorizationException("no backend subdomain found");
}
return CredentialsResource.get().getAllSuperAdmins(credentials.backendId(), refresh);
}
@Delete("/1/backend")
@Delete("/1/backend/")
public Payload delete(Context context) {
Credentials credentials = SpaceContext.checkSuperAdminCredentials();
CredentialsResource.get().deleteAll(credentials.backendId());
Start.get().getElasticClient().deleteAllIndices(credentials.backendId());
if (!SpaceContext.isTest() && !Start.get().configuration().isOffline()) {
FileResource.get().deleteAll();
ShareResource.get().deleteAll();
}
return JsonPayload.success();
}
@Get("/v1/admin/login")
@Get("/v1/admin/login/")
@Get("/1/admin/login")
@Get("/1/admin/login/")
public Payload getLogin() {
SpaceContext.checkAdminCredentials();
return JsonPayload.success();
}
// Implementation
public boolean existsBackend(String backendId) {
ElasticClient elastic = Start.get().getElasticClient();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.filter(QueryBuilders.termQuery(BACKEND_ID, backendId));
elastic.refreshType(SPACEDOG_BACKEND, CredentialsResource.TYPE);
long totalHits = elastic.prepareSearch(SPACEDOG_BACKEND, CredentialsResource.TYPE)
.setQuery(new QuerySourceBuilder().setQuery(boolQueryBuilder).toString())
.setSize(0)
.get()
.getHits()
.getTotalHits();
if (totalHits > 0)
return true;
return getAllBackendIndices().anyMatch(index -> index[0].equals(backendId));
}
public Stream<String[]> getAllBackendIndices() {
return Start.get().getElasticClient().indices().map(index -> index.split("-", 2));
}
// Singleton
private static BackendResource singleton = new BackendResource();
static BackendResource get() {
return singleton;
}
private BackendResource() {
}
}
|
package uk.ac.bournemouth.darwin.auth;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import android.accounts.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ScrollView;
import android.widget.TextView;
public class AccountInfoActivity extends Activity {
private TextView aTextView;
@Override
protected void onCreate(Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
ScrollView scrollview = new ScrollView(this);
aTextView = new TextView(this);
scrollview.addView(aTextView);
StringBuilder text=new StringBuilder();
{
for (Provider p: Security.getProviders()) {
TreeMap<String,List<String>> types = new TreeMap<String, List<String>>();
text.append("Provider: ").append(p.getName()).append('\n');
for(Service s: p.getServices()) {
final String type = s.getType();
List<String> list = types.get(type);
if (list==null) {
list = new ArrayList<String>();
types.put(s.getType(), list);
}
list.add(s.getAlgorithm());
}
for(Entry<String, List<String>> type: types.entrySet()) {
for (String algorithm: type.getValue()) {
text.append(" Service type:").append(type.getKey())
.append(" algorithm:").append(algorithm).append('\n');
}
}
}
}
aTextView.setText(text);
setContentView(scrollview);
}
@SuppressWarnings("deprecation")
@Override
protected void onResume() {
super.onResume();
final AccountManager am=AccountManager.get(this);
Account[] accounts = am.getAccountsByType(DarwinAuthenticator.ACCOUNT_TYPE);
if (accounts.length>0) {
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> pFuture) {
try {
final Bundle result = pFuture.getResult();
CharSequence newText = null;
if (result.containsKey(AccountManager.KEY_ERROR_CODE)|| result.containsKey(AccountManager.KEY_ERROR_MESSAGE)) {
newText = "error ("+result.getString(AccountManager.KEY_ERROR_CODE)+"): "+result.getString(AccountManager.KEY_ERROR_MESSAGE);
} else if (result.containsKey(AccountManager.KEY_INTENT)){
newText = "received an intent";
Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
startActivity(intent);
} else if (result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
final String token = result.getString(AccountManager.KEY_AUTHTOKEN);
if (token!=null) {
newText = "Got an auth token: "+token;
Log.v("ACCOUNTINFO", newText.toString());
am.invalidateAuthToken(DarwinAuthenticator.ACCOUNT_TOKEN_TYPE, token);
}
}
if (newText!=null) {
aTextView.setText(newText);
}
} catch (AccountsException e) {
reportException(e);
} catch (IOException e) {
reportException(e);
}
}
};
am.getAuthToken(accounts[0], DarwinAuthenticator.ACCOUNT_TOKEN_TYPE, false, callback , null);
} else {
am.addAccount(DarwinAuthenticator.ACCOUNT_TYPE, DarwinAuthenticator.ACCOUNT_TOKEN_TYPE, null, null, this, null, null);
}
}
private void reportException(Throwable pThrowable) {
StringWriter writer = new StringWriter();
pThrowable.printStackTrace(new PrintWriter(writer));
aTextView.setText("Cancelled: "+writer.toString());
Log.w("ACCOUNTINFO", pThrowable);
}
@Override
protected void onPause() {
super.onPause();
aTextView.setText("Getting auth token");
}
}
|
package org.simplity.tp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.simplity.kernel.Application;
import org.simplity.kernel.ApplicationError;
import org.simplity.kernel.FormattedMessage;
import org.simplity.kernel.Tracer;
import org.simplity.kernel.comp.ComponentManager;
import org.simplity.kernel.comp.ValidationContext;
import org.simplity.kernel.data.DataSheet;
import org.simplity.kernel.data.FieldsInterface;
import org.simplity.kernel.data.FlatFileRowType;
import org.simplity.kernel.db.DbAccessType;
import org.simplity.kernel.db.DbDriver;
import org.simplity.kernel.dm.Record;
import org.simplity.kernel.expr.Expression;
import org.simplity.kernel.util.TextUtil;
import org.simplity.kernel.value.Value;
import org.simplity.service.ServiceContext;
/**
* @author simplity.org
*
*/
public class FileProcessor extends Block {
/**
* folder in which we look for files to process
*/
String inFolderName;
/**
* folder in which we look for files to process
*/
String outFolderName;
/**
* example *.txt
*/
String inFileNamePattern;
/**
* if we are to create an output file. file name can contain parts of input
* file name as part of it. example if input file name is a.txt
* {name}{ext}.out will translate to a.txt.out and {fileName}.out
* will translate to a.out
*/
String outFileName;
/**
* Similar to outFileName that can be based on input file name
*/
String renameInFileTo;
/**
* should the input file be deleted after processing it? Not relevant if
* rename attribute is specified.
*/
boolean deleteInFileAfterProcessing;
/**
* record that describes the structure of this file
*/
String inRecordName;
/**
* record that describes the structure of this file
*/
String outRecordName;
/**
* format of the data in input file
*/
FlatFileRowType inDataFormat;
/**
* format of the data in output file
*/
FlatFileRowType outDataFormat;
/**
* What action do we take in case the input row fails data-type validation?
*/
Action actionOnInvalidInputRow;
/**
* action to be executed of the row processing generates error
*/
Action actionOnErrorWhileProcessing;
/**
* is there a conditional based on which we have to decide whether to write
* output or not? Null means we write always. If specified, output row is
* written for this row only if it evaluates to true.
*/
Expression conditionForOutput;
/**
* filter corresponding to the input file
*/
private FilenameFilter filter;
private File inbox;
/*
* (non-Javadoc)
*
* @see org.simplity.tp.Action#delegate(org.simplity.service.ServiceContext,
* org.simplity.kernel.db.DbDriver)
*/
@Override
protected Value delegate(ServiceContext ctx, DbDriver driver) {
Tracer.trace("Going to process files in folder " + this.inFolderName
+ " that exists = " + this.inbox.exists());
int nbrFiles = 0;
Record record = ComponentManager.getRecord(this.inRecordName);
Record outRecord = null;
if (this.outRecordName != null) {
outRecord = ComponentManager.getRecord(this.outRecordName);
}
BlockWorker worker = new BlockWorker(this.actions, this.indexedActions, ctx);
for (File file : this.inbox.listFiles(this.filter)) {
Tracer.trace("File " + file.getAbsolutePath());
if (this.processOneFile(file, ctx, driver, record, outRecord, worker)) {
nbrFiles++;
}
}
return Value.newIntegerValue(nbrFiles);
}
/**
* @param file
* @throws IOException
*/
private boolean processOneFile(File file, ServiceContext ctx, DbDriver driver,
Record record, Record outRecord, BlockWorker worker) {
BufferedReader reader = null;
BufferedWriter writer = null;
try {
/*
* create input/output streams
*/
String inName = file.getName();
Tracer.trace("Processing " + inName + "....");
reader = new BufferedReader(new FileReader(file));
if (this.outFileName != null) {
String outName = TextUtil.getFileName(this.outFileName, inName);
File outFile = new File(this.outFolderName + outName);
writer = new BufferedWriter(new FileWriter(outFile));
}
String inText;
/*
* loop on each row in input file. Note that the ctx is not reset
* per row. However, error status is reset because we manage
* transactions at row level
*/
List<FormattedMessage> errors = new ArrayList<FormattedMessage>();
while ((inText = reader.readLine()) != null) {
/*
* Absolved of all past sins. Start life afresh :-)
*/
ctx.resetMessages();
errors.clear();
record.extractFromFlatRow(inText, this.inDataFormat, ctx, errors);
/*
* above method validates input as per data type specification.
* Was there any trouble?
*/
if (errors.size() > 0) {
collectErrors(ctx, inText, errors);
if (this.actionOnInvalidInputRow == null) {
Tracer.trace(
"Invalid row received as input. Row is not processed.");
} else {
this.actionOnInvalidInputRow.act(ctx, driver);
}
continue;
}
/*
* now that the input is fine, let us process the row
*/
worker.execute(driver);
/*
* any trouble while processing?
*/
if (ctx.isInError()) {
collectErrors(ctx, inText, errors);
if (this.actionOnErrorWhileProcessing == null) {
Tracer.trace(
"Invalid row received as input. Row is not processed.");
} else {
this.actionOnErrorWhileProcessing.act(ctx, driver);
}
continue;
}
/*
* are we to write output row?
*/
if (writer != null) {
if (this.conditionForOutput != null) {
if (this.conditionForOutput.evaluate(ctx).toBoolean() == false) {
Tracer.trace(
"Output not written because the condition for the same is not satisfied.");
continue;
}
}
String outText = outRecord.formatFlatRow(this.outDataFormat, ctx);
writer.write(outText);
writer.newLine();
}
}
/*
* important to close the stream before trying to delete/rename
*/
reader.close();
if (this.renameInFileTo != null) {
String arcName = this.inFolderName + TextUtil.getFileName(
this.renameInFileTo, inName);
Tracer.trace("Renaming to " + arcName);
file.renameTo(new File(arcName));
} else if (this.deleteInFileAfterProcessing) {
if (file.delete() == false) {
throw new ApplicationError("Unable to delete file " + file.getPath());
}
}
reader = null;
return true;
} catch (Exception e) {
Application.getExceptionListener().listen(null, e);
return false;
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception ignore) {
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception ignore) {
}
}
}
}
private void collectErrors(ServiceContext ctx, String inText, List<FormattedMessage> errors) {
ctx.addMessages(errors);
DataSheet tempErrorSheet = ctx.getMessagesAsDS();
tempErrorSheet.addColumn("errorRow", Value.newTextValue(inText));
DataSheet errorSheet = ctx.getDataSheet("error");
if(errorSheet!=null){
errorSheet.appendRows(tempErrorSheet);
}
else{
ctx.putDataSheet("error", tempErrorSheet);
}
}
/*
* (non-Javadoc)
*
* @see org.simplity.tp.Action#getReady(int)
*/
@Override
public void getReady(int idx) {
super.getReady(idx);
if (this.actionOnErrorWhileProcessing != null) {
this.actionOnErrorWhileProcessing.getReady(0);
}
if (this.actionOnInvalidInputRow != null) {
this.actionOnInvalidInputRow.getReady(0);
}
this.filter = TextUtil.getFileNameFilter(this.inFileNamePattern);
this.inbox = new File(this.inFolderName);
if (this.inFolderName != null && this.inFolderName.endsWith("/") == false) {
this.inFolderName += '/';
}
if (this.outFolderName != null && this.outFolderName.endsWith("/") == false) {
this.outFolderName += '/';
}
}
/*
* (non-Javadoc)
*
* @see org.simplity.tp.Block#validate(org.simplity.kernel.comp.
* ValidationContext, org.simplity.tp.Service)
*/
@Override
public int validate(ValidationContext vtx, Service service) {
int count = 0;
count = super.validate(vtx, service);
if (this.inFolderName == null) {
vtx.addError("inFolderName is required for file processor");
count++;
}
if (this.inFileNamePattern == null) {
vtx.addError("inFileNamePattern is required for file processor");
count++;
}
if (this.inDataFormat == null) {
vtx.addError("inDataFormat is required for file processor");
count++;
}
if (this.inRecordName == null) {
vtx.addError("inRecordName is required for file processor");
count++;
}
if (this.outFolderName != null) {
if (this.outDataFormat == null) {
vtx.addError("outDataFormat is required when outFolderName is specified");
count++;
}
if (this.outRecordName == null) {
vtx.addError("outRecordName is required when outFolderName is specified");
count++;
}
if (this.outFileName == null) {
vtx.addError("outFileName is required when outFolderName is specified");
count++;
}
} else if (this.outDataFormat != null || this.outRecordName != null
|| this.outFileName != null) {
vtx.reportUnusualSetting(
"Since outFolderName is not specified, no output is going to be written, and other output related attributes are ignored.");
}
if (this.renameInFileTo == null) {
if (this.deleteInFileAfterProcessing == false) {
vtx.reportUnusualSetting(
"Input file is neither deleted, nor renamed. This may result in the file being processed again.");
}
} else if (this.deleteInFileAfterProcessing) {
vtx.reportUnusualSetting(
"since rename is specified, we ignore delete directive.");
}
/*
* If db updates re involved, file-processor requires that the service
* delegates commits to sub-service
*/
if (this.dbAccess == DbAccessType.READ_WRITE) {
count += this.validateDbAccess(service, vtx);
}
return count;
}
private int validateDbAccess(Service service, ValidationContext vtx) {
int count = 0;
/*
* There must be one sub-service action that manages its own
* transaction, and rest of the actions should not do any updates
*/
if (service.dbAccessType != DbAccessType.SUB_SERVICE) {
vtx.addError(
"File-processor is designed to update data base. Service should delegate transaction processing to sub-service.");
count++;
}
if(this.actionOnErrorWhileProcessing.getDataAccessType().updatesDb()){
if(this.actionOnErrorWhileProcessing instanceof SubService == false){
vtx.addError("actionOnErrorWhileProcessing is designed for db update. For such a requirement, you should convert this to a subService action.");
count++;
}
}
if(this.actionOnInvalidInputRow.getDataAccessType().updatesDb()){
if(this.actionOnInvalidInputRow instanceof SubService == false){
vtx.addError("actionOnInvalidInputRow is designed for db update. For such a requirement, you should convert this to a subService action.");
count++;
}
}
for(Action action : this.actions){
if(action instanceof SubService == false && action.getDataAccessType().updatesDb()){
vtx.addError("actions of a file-processor is designed for a bb update. You should re-factor this into sub-service so that the db updates can be managed within separate transaction.");
count++;
}
}
return count;
}
}
|
package org.nusco.narjillos.views;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Shape;
import javafx.scene.transform.Translate;
import org.nusco.narjillos.shared.physics.Vector;
import org.nusco.narjillos.shared.things.FoodPiece;
class FoodView extends RoundObjectView {
private static final double MINIMUM_ZOOM_LEVEL = 0.035;
private final Shape circle;
public FoodView(FoodPiece food) {
super(food, 7);
circle = new Circle(getRadius());
}
public Node toNode(double zoomLevel, boolean infraredOn) {
if (zoomLevel < MINIMUM_ZOOM_LEVEL)
return null;
circle.setFill(getColor(infraredOn));
if (infraredOn) {
circle.setStroke(Color.WHITE);
circle.setStrokeWidth(3);
} else {
circle.setStrokeWidth(0);
}
circle.getTransforms().clear();
circle.getTransforms().add(moveToStartPoint());
circle.setEffect(getEffects(zoomLevel, infraredOn));
return circle;
}
private Color getColor(boolean infraredOn) {
if (infraredOn)
return Color.RED;
return Color.BROWN;
}
private Translate moveToStartPoint() {
Vector position = getThing().getPosition();
return new Translate(position.x, position.y);
}
}
|
package com.greensnow25.start;
/**
* public class StartUI run TRACKER.
* @author grensnow25.
* @since 28.12.16.
* @version 1.0.
*/
public class StartUI {
/**
* method init run the aplication
*/
public void init() throws Exception {
ConsoleInput input = new ConsoleInput();
input.choise();
input.close();
}
/**
* main.
* @param args string array.
*/
public static void main(String[] args) throws Exception {
new StartUI().init();
}
}
|
package owltools.gaf;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
/**
*
* @author Shahid Manzoor
*
*/
public class GAFParser {
private static final String GAF_COMMENT = "!";
private static final String GAF_VERSION = GAF_COMMENT + "gaf-version:";
protected static Logger LOG = Logger.getLogger(GAFParser.class);
private static boolean DEBUG = LOG.isDebugEnabled();
public final static int DB = 0;
public final static int DB_OBJECT_ID = 1;
public final static int DB_OBJECT_SYMBOL = 2;
public final static int QUALIFIER = 3;
public final static int GOID = 4;
public final static int REFERENCE = 5;
public final static int EVIDENCE = 6;
public final static int WITH = 7;
public final static int ASPECT = 8;
public final static int DB_OBJECT_NAME = 9;
public final static int DB_OBJECT_SYNONYM = 10;
public final static int DB_OBJECT_TYPE = 11;
public final static int TAXON = 12;
public final static int DATE = 13;
public final static int ASSIGNED_BY = 14;
public final static int ANNOTATION_XP = 15;
public final static int GENE_PRODUCT_ISOFORM = 16;
private double gafVersion;
private BufferedReader reader;
private String currentRow;
private String currentCols[];
private int expectedNumCols;
private int lineNumber;
private List<Object> voilations;
private List<GafParserListener> parserListeners;
public List<Object> getAnnotationRuleViolations(){
return this.voilations;
}
/**
* Try to parse a next line, may skip lines until a line is parsed successfully or the file ends.
*
* @return true, if there is a next line.
* @throws IOException
*/
public boolean next() throws IOException{
while (true) {
ReadState state = loadNext();
if (state == ReadState.success) {
return true;
}
else if (state == ReadState.no) {
return false;
}
// default ReadState.next
// continue loop
}
}
/**
* Using a recursive call to check if a next line exists, may lead to an over flow.
* Use a while loop with a function call, which has a tri-state return value.
*
* @return ReadState
* @throws IOException
*/
private ReadState loadNext() throws IOException{
if(reader != null){
currentRow = reader.readLine();
if(currentRow == null){
return ReadState.no;
}
lineNumber++;
if(DEBUG)
LOG.debug("Parsing Row: " +lineNumber + " -- " +currentRow);
final String trimmedLine = StringUtils.trimToEmpty(currentRow);
if (trimmedLine.length() == 0) {
LOG.warn("Blank Line");
return ReadState.next;
}else if (trimmedLine.startsWith(GAF_COMMENT)) {
if(gafVersion<1){
if (isFormatDeclaration(trimmedLine)) {
gafVersion = parseGafVersion(trimmedLine);
if (gafVersion == 2.0) {
expectedNumCols = 17;
}
}
}
return ReadState.next;
}else{
fireParsing();
// use more efficient implementation to split line
// this.currentRow.split("\\t", -1);
this.currentCols = StringUtils.splitPreserveAllTokens(this.currentRow, '\t');
if (expectedNumCols == 17 && currentCols.length == 16) {
LOG.warn("Fix missing tab for GAF 2.0 format in line: "+lineNumber);
// repair
// add an empty "" to the array
this.currentCols = Arrays.copyOf(currentCols, 17);
this.currentCols[16] = "";
fireParsingWarning("Fix missing tab for GAF 2.0 format, expected 17 columns but found only 16.");
}
if (expectedNumCols == 17 && currentCols.length == 15) {
LOG.warn("Fix missing tabs for GAF 2.0 format in line: "+lineNumber);
// repair
// add two empty "" to the array
this.currentCols = Arrays.copyOf(currentCols, 17);
this.currentCols[15] = "";
this.currentCols[16] = "";
fireParsingWarning("Fix missing tab for GAF 2.0 format, expected 17 columns but found only 15.");
}
if (currentCols.length != expectedNumCols) {
String error = "Got invalid number of columns for row '"+lineNumber+"' (expected "
+ expectedNumCols
+ ", got "
+ currentCols.length
+ ")";
if(currentCols.length<expectedNumCols){
String v =error;
voilations.add(v);
fireParsingError(error);
LOG.error(error + " The row is ignored: " + this.currentRow);
return ReadState.next;
}else{
fireParsingWarning(error);
LOG.warn(error + " : " + this.currentRow);
}
}
return ReadState.success;
}
}
return ReadState.no;
}
private enum ReadState {
success,
no,
next
}
private void fireParsing(){
for(GafParserListener listner: parserListeners){
listner.parsing(this.currentRow, lineNumber);
}
}
private void fireParsingError(String message){
for(GafParserListener listner: parserListeners){
listner.parserError(message, this.currentRow, lineNumber);
}
}
private void fireParsingWarning(String message){
for(GafParserListener listner: parserListeners){
if (listner.reportWarnings()) {
listner.parserWarning(message, this.currentRow, lineNumber);
}
}
}
public String getCurrentRow(){
return this.currentRow;
}
public GAFParser(){
init();
}
public void init(){
this.gafVersion = 0;
this.reader = null;
this.expectedNumCols = 15;
voilations = new Vector<Object>();
lineNumber = 0;
if(parserListeners == null){
parserListeners = new Vector<GafParserListener>();
}
}
public void addParserListener(GafParserListener listener){
if(listener == null)
return;
if(!parserListeners.contains(listener))
parserListeners.add(listener);
}
public void remoteParserListener(GafParserListener listener){
if(listener == null)
return;
parserListeners.remove(listener);
}
public void parse(Reader reader){
init();
if (DEBUG)
LOG.debug("Parsing Start");
this.reader = new BufferedReader(reader);
}
/**
*
* @param file is the location of the gaf file. The location
* could be http url, absolute path and uri. The could refer to a gaf file or compressed gaf (gzip fle).
* @throws IOException
* @throws URISyntaxException
*/
public void parse(String file) throws IOException, URISyntaxException{
if(file == null){
throw new IOException("File '" + file + "' file not found");
}
//LOG.info("ends with: " + Boolean.toString(file.endsWith(file)));
//LOG.info("is: [" + file.toString() + "]");
InputStream is = null;
if(file.startsWith("http:
URL url = new URL(file);
is = url.openStream();
LOG.info("Open stream as URL");
}else if(file.startsWith("file:/")){
is = new FileInputStream(new File(new URI(file)));
LOG.info("Open stream as file URI");
}else{
is = new FileInputStream(file);
LOG.info("Open stream as file");
}
if(file.endsWith(".gz")){
is = new GZIPInputStream(is);
LOG.info("Will decompress (.gz)");
}
InputStreamReader isr = new InputStreamReader(is);
parse(isr);
}
public void parse(File gaf_file)
throws IOException {
// String message = "Importing GAF data";
try {
parse(gaf_file.getAbsoluteFile().toString());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void checkNext(){
if(this.currentCols == null){
throw new IllegalStateException("Error occured becuase either there is no further " +
"record in the file or parse method is not called yet");
}
}
// Col. 1
public String getDb(){
checkNext();
return this.currentCols[DB];
}
// Col. 2
public String getDbObjectId(){
checkNext();
return this.currentCols[DB_OBJECT_ID];
}
// Col. 3
public String getDbObjectSymbol(){
checkNext();
return this.currentCols[DB_OBJECT_SYMBOL];
}
// Col. 4
public String getQualifier(){
checkNext();
return this.currentCols[QUALIFIER];
}
// Col. 5
public String getGOId(){
checkNext();
return this.currentCols[GOID];
}
// Col. 6
public String getReference(){
checkNext();
return this.currentCols[REFERENCE];
}
// Col. 7
public String getEvidence(){
checkNext();
return this.currentCols[EVIDENCE];
}
// Col. 8
public String getWith(){
checkNext();
return this.currentCols[WITH];
}
// Col. 9
public String getAspect(){
checkNext();
return this.currentCols[ASPECT];
}
// Col. 10
public String getDbObjectName(){
checkNext();
String s = this.currentCols[DB_OBJECT_NAME];
s = s.replace("\\", "\\\\");
return s;
}
// Col. 11
public String getDbObjectSynonym(){
checkNext();
return this.currentCols[DB_OBJECT_SYNONYM];
}
// Col. 12
public String getDBObjectType(){
checkNext();
return this.currentCols[DB_OBJECT_TYPE];
}
// Col. 13
public String getTaxon(){
checkNext();
return this.currentCols[TAXON];
}
// Col. 14
public String getDate(){
checkNext();
return this.currentCols[DATE];
}
// Col. 15
public String getAssignedBy(){
checkNext();
return this.currentCols[ASSIGNED_BY];
}
// Col. 16
public String getAnnotationExtension(){
checkNext();
if(this.currentCols.length>15){
return this.currentCols[ANNOTATION_XP];
}
return null;
}
// Col. 17
public String getGeneProjectFormId(){
checkNext();
if(this.currentCols.length>16){
return this.currentCols[GENE_PRODUCT_ISOFORM];
}
return null;
}
private boolean isFormatDeclaration(String line) {
return line.startsWith(GAF_VERSION);
}
private double parseGafVersion(String line) {
Pattern p = Pattern.compile(GAF_VERSION + "\\s*(\\d+\\.*\\d+)");
Matcher m = p.matcher(line);
if (m.matches()) {
return Double.parseDouble(m.group(1));
}
return 0;
}
public int getLineNumber() {
return lineNumber;
}
}
|
package ru.osetsky.tracker.start;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.Matchers.nullValue;
public class StunInputTest {
/**
* Method is testStunInputHowUser.
*/
@Test
public void testStunInputHowUser() {
Tracker tracker = new Tracker();
String[] parametr = {"0", "name", "desc", "6"};
Input input = new StunInput(parametr);
StartUi sU = new StartUi(input, tracker).init();
assertThat(tracker.getAll()[0].getName(), is("name"));
}
/**
* Method is testHowUserAddItem.
*/
@Test
public void testHowUserAddItem() {
Tracker tracker = new Tracker();
String[] parametr = {"0", "Alex", "coder", "6"};
Input input = new StunInput(parametr);
StartUi sAdd = new StartUi(input, tracker).init();
assertThat(tracker.getAll()[0].getDescription(), is("coder"));
}
/**
* Method is testHowUserAddAndDeleteItem.
*/
@Test
public void testHowUserAddAndDeleteItem() {
Tracker tracker = new Tracker();
String[] parametr = {"0", "Lala", "coder", "3", "6"};
Input input = new StunInput(parametr);
StartUi sDelete = new StartUi(input, tracker).init();
assertThat(tracker.getAll()[0].getDescription(), is(nullValue()));
}
/**
* Method is testHowUserAddAndDeleteItem2.
*/
@Test
public void testHowUserAddAndDeleteItem2() {
Tracker tracker = new Tracker();
String[] parametr = {"0", "Petr", "teacher", "3", "6"};
Input input = new StunInput(parametr);
StartUi sAdd = new StartUi(input, tracker).init();
assertThat(tracker.getAll()[0].getDescription(), is(nullValue()));
}
}
|
package vg.civcraft.mc.namelayer.listeners;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import vg.civcraft.mc.namelayer.NameLayerPlugin;
import vg.civcraft.mc.namelayer.database.GroupManagerDao;
import vg.civcraft.mc.namelayer.group.Group;
public class PlayerListener implements Listener{
private static Map<UUID, List<Group>> notifications = new HashMap<UUID, List<Group>>();
@EventHandler(priority=EventPriority.LOWEST)
public void playerJoinEvent(PlayerJoinEvent event){
Player p = event.getPlayer();
UUID uuid = p.getUniqueId();
if (!notifications.containsKey(uuid) || notifications.get(uuid).isEmpty())
return;
String x = null;
GroupManagerDao db = NameLayerPlugin.getGroupManagerDao();
boolean shouldAutoAccept = db.shouldAutoAcceptGroups(uuid);
if(shouldAutoAccept){
x = "You have auto-accepted invitation from the following groups while you were away: ";
}
else{
x = "You have been invited to the following groups while you were away: ";
}
for (Group g:notifications .get(uuid)){
x += g.getName() + ", ";
}
x = x.substring(0, x.length()- 2);
x += ".";
p.sendMessage(ChatColor.YELLOW + x);
}
public static void addNotification(UUID u, Group g){
if (!notifications.containsKey(u))
notifications.put(u, new ArrayList<Group>());
notifications.get(u).add(g);
}
public static List<Group> getNotifications(UUID player) {
return notifications.get(player);
}
public static void removeNotification(UUID u, Group g){
if (!notifications.containsKey(u))
notifications.put(u, new ArrayList<Group>());
notifications.get(u).remove(g);
}
public static String getNotificationsInStringForm(UUID u){
if (!notifications.containsKey(u))
notifications.put(u, new ArrayList<Group>());
String groups = "";
for (Group g: notifications.get(u))
groups += g.getName() + ", ";
if (groups.length() == 0)
return ChatColor.GREEN + "You have no notifications.";
groups = groups.substring(0, groups.length()- 2);
groups = ChatColor.GREEN + "Your current groups are: " + groups + ".";
return groups;
}
}
|
package org.slf4j.event;
import java.util.Queue;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.helpers.SubstituteLogger;
public class EventRecodingLogger implements Logger {
String name;
SubstituteLogger logger;
Queue<SubstituteLoggingEvent> eventQueue;
public EventRecodingLogger(SubstituteLogger logger, Queue<SubstituteLoggingEvent> eventQueue) {
this.logger = logger;
this.name = logger.getName();
this.eventQueue = eventQueue;
}
public String getName() {
return name;
}
private void recordEvent(Level level, String msg, Object[] args, Throwable throwable) {
recordEvent(level, null, msg, args, throwable);
}
private void recordEvent(Level level, Marker marker, String msg, Object[] args, Throwable throwable) {
// System.out.println("recording logger:"+name+", msg:"+msg);
SubstituteLoggingEvent loggingEvent = new SubstituteLoggingEvent();
loggingEvent.setTimeStamp(System.currentTimeMillis());
loggingEvent.setLevel(level);
loggingEvent.setLogger(logger);
loggingEvent.setLoggerName(name);
loggingEvent.addMarker(marker);
loggingEvent.setMessage(msg);
loggingEvent.setArgumentArray(args);
loggingEvent.setThrowable(throwable);
loggingEvent.setThreadName(Thread.currentThread().getName());
eventQueue.add(loggingEvent);
}
public boolean isTraceEnabled() {
return true;
}
public void trace(String msg) {
recordEvent(Level.TRACE, msg, null, null);
}
public void trace(String format, Object arg) {
recordEvent(Level.TRACE, format, new Object[] { arg }, null);
}
public void trace(String format, Object arg1, Object arg2) {
recordEvent(Level.TRACE, format, new Object[] { arg1, arg2 }, null);
}
public void trace(String format, Object... arguments) {
recordEvent(Level.TRACE, format, arguments, null);
}
public void trace(String msg, Throwable t) {
recordEvent(Level.TRACE, msg, null, t);
}
public boolean isTraceEnabled(Marker marker) {
return true;
}
public void trace(Marker marker, String msg) {
recordEvent(Level.TRACE, marker, msg, null, null);
}
public void trace(Marker marker, String format, Object arg) {
recordEvent(Level.TRACE, marker, format, new Object[] { arg }, null);
}
public void trace(Marker marker, String format, Object arg1, Object arg2) {
recordEvent(Level.TRACE, marker, format, new Object[] { arg1, arg2 }, null);
}
public void trace(Marker marker, String format, Object... argArray) {
recordEvent(Level.TRACE, marker, format, argArray, null);
}
public void trace(Marker marker, String msg, Throwable t) {
recordEvent(Level.TRACE, marker, msg, null, t);
}
public boolean isDebugEnabled() {
return true;
}
public void debug(String msg) {
recordEvent(Level.DEBUG, msg, null, null);
}
public void debug(String format, Object arg) {
recordEvent(Level.DEBUG, format, new Object[] { arg }, null);
}
public void debug(String format, Object arg1, Object arg2) {
recordEvent(Level.DEBUG, format, new Object[] { arg1, arg2 }, null);
}
public void debug(String format, Object... arguments) {
recordEvent(Level.DEBUG, format, arguments, null);
}
public void debug(String msg, Throwable t) {
recordEvent(Level.DEBUG, msg, null, t);
}
public boolean isDebugEnabled(Marker marker) {
return true;
}
public void debug(Marker marker, String msg) {
recordEvent(Level.DEBUG, marker, msg, null, null);
}
public void debug(Marker marker, String format, Object arg) {
recordEvent(Level.DEBUG, marker, format, new Object[] { arg }, null);
}
public void debug(Marker marker, String format, Object arg1, Object arg2) {
recordEvent(Level.DEBUG, marker, format, new Object[] { arg1, arg2 }, null);
}
public void debug(Marker marker, String format, Object... arguments) {
recordEvent(Level.DEBUG, marker, format, arguments, null);
}
public void debug(Marker marker, String msg, Throwable t) {
recordEvent(Level.DEBUG, marker, msg, null, t);
}
public boolean isInfoEnabled() {
return true;
}
public void info(String msg) {
recordEvent(Level.INFO, msg, null, null);
}
public void info(String format, Object arg) {
recordEvent(Level.INFO, format, new Object[] { arg }, null);
}
public void info(String format, Object arg1, Object arg2) {
recordEvent(Level.INFO, format, new Object[] { arg1, arg2 }, null);
}
public void info(String format, Object... arguments) {
recordEvent(Level.INFO, format, arguments, null);
}
public void info(String msg, Throwable t) {
recordEvent(Level.INFO, msg, null, t);
}
public boolean isInfoEnabled(Marker marker) {
return true;
}
public void info(Marker marker, String msg) {
recordEvent(Level.INFO, marker, msg, null, null);
}
public void info(Marker marker, String format, Object arg) {
recordEvent(Level.INFO, marker, format, new Object[] { arg }, null);
}
public void info(Marker marker, String format, Object arg1, Object arg2) {
recordEvent(Level.INFO, marker, format, new Object[] { arg1, arg2 }, null);
}
public void info(Marker marker, String format, Object... arguments) {
recordEvent(Level.INFO, marker, format, arguments, null);
}
public void info(Marker marker, String msg, Throwable t) {
recordEvent(Level.INFO, marker, msg, null, t);
}
public boolean isWarnEnabled() {
return true;
}
public void warn(String msg) {
recordEvent(Level.WARN, msg, null, null);
}
public void warn(String format, Object arg) {
recordEvent(Level.WARN, format, new Object[] { arg }, null);
}
public void warn(String format, Object arg1, Object arg2) {
recordEvent(Level.WARN, format, new Object[] { arg1, arg2 }, null);
}
public void warn(String format, Object... arguments) {
recordEvent(Level.WARN, format, arguments, null);
}
public void warn(String msg, Throwable t) {
recordEvent(Level.WARN, msg, null, t);
}
public boolean isWarnEnabled(Marker marker) {
return true;
}
public void warn(Marker marker, String msg) {
recordEvent(Level.WARN, marker, msg, null, null);
}
public void warn(Marker marker, String format, Object arg) {
recordEvent(Level.WARN, marker, format, new Object[] { arg }, null);
}
public void warn(Marker marker, String format, Object arg1, Object arg2) {
recordEvent(Level.WARN, marker, format, new Object[] { arg1, arg2 }, null);
}
public void warn(Marker marker, String format, Object... arguments) {
recordEvent(Level.WARN, marker, format, arguments, null);
}
public void warn(Marker marker, String msg, Throwable t) {
recordEvent(Level.WARN, marker, msg, null, t);
}
public boolean isErrorEnabled() {
return true;
}
public void error(String msg) {
recordEvent(Level.ERROR, msg, null, null);
}
public void error(String format, Object arg) {
recordEvent(Level.ERROR, format, new Object[] { arg }, null);
}
public void error(String format, Object arg1, Object arg2) {
recordEvent(Level.ERROR, format, new Object[] { arg1, arg2 }, null);
}
public void error(String format, Object... arguments) {
recordEvent(Level.ERROR, format, arguments, null);
}
public void error(String msg, Throwable t) {
recordEvent(Level.ERROR, msg, null, t);
}
public boolean isErrorEnabled(Marker marker) {
return true;
}
public void error(Marker marker, String msg) {
recordEvent(Level.ERROR, marker, msg, null, null);
}
public void error(Marker marker, String format, Object arg) {
recordEvent(Level.ERROR, marker, format, new Object[] { arg }, null);
}
public void error(Marker marker, String format, Object arg1, Object arg2) {
recordEvent(Level.ERROR, marker, format, new Object[] { arg1, arg2 }, null);
}
public void error(Marker marker, String format, Object... arguments) {
recordEvent(Level.ERROR, marker, format, arguments, null);
}
public void error(Marker marker, String msg, Throwable t) {
recordEvent(Level.ERROR, marker, msg, null, t);
}
}
|
package rjsv.circularview;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import rjsv.circularview.enumerators.AnimationStyle;
import rjsv.circularview.utils.CircleViewAnimationListener;
import rjsv.circularview.utils.Disposable;
/**
* Description
*
* @author <a href="mailto:ricardo.vieira@xpand-it.com">RJSV</a>
* @version $Revision : 1 $
*/
public class CircleViewAnimation extends Animation implements Disposable {
private CircleView circleView;
private float startValue;
private float endValue;
private float currentValue;
private long duration;
private boolean isAnimationRunning = false;
private AnimationStyle circleViewAnimationStyle;
private Interpolator circleViewInterpolator;
private CircleViewAnimationListener circleViewAnimationListener;
private Handler timerManager;
private Runnable timerOperation;
// Constructor
public CircleViewAnimation() {
this.startValue = 0;
this.endValue = 0;
this.circleViewAnimationStyle = AnimationStyle.PERIODIC;
this.circleViewAnimationListener = new CircleViewAnimationListener();
this.timerManager = new Handler();
this.timerOperation = new Runnable() {
public void run() {
}
};
setInterpolator(new LinearInterpolator());
}
public CircleViewAnimation setCircleView(CircleView circleView) {
this.circleView = circleView;
return this;
}
public CircleViewAnimation setDuration(float durationInSeconds) {
setDuration((long) durationInSeconds);
return this;
}
public CircleViewAnimation setDuration(int durationInSeconds) {
setDuration((long) durationInSeconds);
return this;
}
public CircleViewAnimation setAnimationStyle(AnimationStyle style) {
this.circleViewAnimationStyle = style;
return this;
}
public CircleViewAnimation setCustomAnimationListener(AnimationListener listener) {
this.circleViewAnimationListener.registerAnimationListener(listener);
setAnimationListener(listener != null ? circleViewAnimationListener : null);
return this;
}
public CircleViewAnimation setCustomInterpolator(Interpolator i) {
this.circleViewInterpolator = i;
super.setInterpolator(circleViewInterpolator);
return this;
}
public CircleViewAnimation setTimerOperationOnFinish(Runnable r) {
if (r != null) {
timerOperation = r;
}
return this;
}
// Overridden values
public void start(float startValue, float endValue) {
if (circleView != null && !isAnimationRunning) {
this.startValue = startValue;
this.endValue = endValue;
setDuration(startValue - endValue);
isAnimationRunning = true;
circleView.startAnimation(this);
timerManager.postDelayed(timerOperation, duration * 1000);
}
}
public void stop() {
if (circleView != null && isAnimationRunning) {
isAnimationRunning = false;
timerManager.removeCallbacks(timerOperation);
circleView.clearAnimation();
}
}
@Override
public void start() {
start(circleView.getProgressValue(), 0);
}
@Override
public void setDuration(long durationInSeconds) {
duration = durationInSeconds;
super.setDuration(duration * 1000);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation transformation) {
if (interpolatedTime == 1.0) {
stop();
}
currentValue = startValue + ((endValue - startValue) * interpolatedTime);
float changingValue = currentValue;
if (AnimationStyle.PERIODIC.equals(circleViewAnimationStyle)) {
changingValue = (int) changingValue;
}
circleView.setProgressValue(changingValue);
}
@Override
public void disposeData() {
this.setInterpolator(null);
circleViewInterpolator = null;
if (circleViewAnimationListener != null) {
circleViewAnimationListener.unregisterAnimationListeners();
circleViewAnimationListener = null;
}
if (timerManager != null) {
if (timerOperation != null) {
timerManager.removeCallbacks(timerOperation);
}
timerOperation = null;
timerManager = null;
}
}
}
|
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.TokenMgrError;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSQuery;
/**
* Servlet for handling a simple search.
* <P>
* All metadata is search for the value contained in the "query" parameter.
* If the "location" parameter is present, the user's location is switched
* to that location using a redirect. Otherwise, the user's current
* location is used to constrain the query; i.e., if the user is "in" a
* collection, only results from the collection will be returned.
* <P>
* The value of the "location" parameter should be ALL (which means no location),
* a the ID of a community (e.g. "123"), or a community ID, then a slash, then
* a collection ID, e.g. "123/456".
*
* @author Robert Tansley
* @version $Id$
*/
public class SimpleSearchServlet extends DSpaceServlet
{
/** log4j category */
private static Logger log = Logger.getLogger(SimpleSearchServlet.class);
protected void doDSGet(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
// Get the query
String query = request.getParameter("query");
// Get the location parameter, if any
String location = request.getParameter("location");
String newURL;
// If there is a location parameter, we should redirect to
// do the search with the correct location.
if (location != null && !location.equals(""))
{
String url = "";
if (!location.equals("/"))
{
// Location is a Handle
url = "/handle/" + location;
}
// Do the redirect
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + url +
"/simple-search?query=" + query));
return;
}
// Build log information
String logInfo = "";
// Get our location
Community community = UIUtil.getCommunityLocation(request);
Collection collection = UIUtil.getCollectionLocation(request);
// handles for the search results or the results
List itemHandles = null;
List communityHandles = null;
List collectionHandles = null;
// 'de-handled' search results
Item[] resultsItems;
Community[] resultsCommunities;
Collection[] resultsCollections;
// Perform the search
try
{
if (collection != null)
{
logInfo = "collection_id=" + collection.getID() + ",";
// Values for drop-down box
request.setAttribute("community", community);
request.setAttribute("collection", collection);
// we're in a collection, only display item results
itemHandles = DSQuery.getItemResults(DSQuery.doQuery(query, collection));
collectionHandles = new ArrayList();
communityHandles = new ArrayList();
}
else if (community != null)
{
logInfo = "community_id=" + community.getID() + ",";
request.setAttribute("community", community);
// Get the collections within the community for the dropdown box
request.setAttribute("collection.array",
community.getCollections());
HashMap results = DSQuery.doQuery(query, community);
// we're in a community, display item and collection results
itemHandles = DSQuery.getItemResults(results);
collectionHandles = DSQuery.getCollectionResults(results);
communityHandles = new ArrayList();
}
else
{
// Get all communities for dropdown box
Community[] communities = Community.findAll(context);
request.setAttribute("community.array", communities);
HashMap results = DSQuery.doQuery(query);
// searching everything, return all results
itemHandles = DSQuery.getItemResults(results);
communityHandles = DSQuery.getCommunityResults(results);
collectionHandles= DSQuery.getCollectionResults(results);
}
// limit search results to 50 or fewer items - no limit on
// number of communities and collections
int numItems = (itemHandles.size() > 50 ? 50 : itemHandles.size() );
// Make objects from the handles - make arrays, fill them out
resultsItems = new Item [numItems ];
resultsCommunities = new Community [communityHandles.size() ];
resultsCollections = new Collection[collectionHandles.size()];
for (int i = 0; i < numItems; i++)
{
String myhandle = (String) itemHandles.get(i);
Object o = HandleManager.resolveToObject(context, myhandle);
resultsItems[i] = (Item)o;
if (resultsItems[i] == null)
{
throw new SQLException("Query \"" + query +
"\" returned unresolvable handle: " + myhandle);
}
}
for (int i = 0; i < collectionHandles.size(); i++)
{
String myhandle = (String) collectionHandles.get(i);
Object o = HandleManager.resolveToObject(context, myhandle);
resultsCollections[i] = (Collection)o;
if (resultsCollections[i] == null)
{
throw new SQLException("Query \"" + query +
"\" returned unresolvable handle: " + myhandle);
}
}
for (int i = 0; i < communityHandles.size(); i++)
{
String myhandle = (String) communityHandles.get(i);
Object o = HandleManager.resolveToObject(context, myhandle);
resultsCommunities[i] = (Community)o;
if (resultsCommunities[i] == null)
{
throw new SQLException("Query \"" + query +
"\" returned unresolvable handle: " + myhandle);
}
}
// Log
log.info(LogManager.getHeader(context,
"search",
logInfo + "query=\"" + query + "\",results=(" + resultsCommunities.length + "," + resultsCollections.length + "," + resultsItems.length + ")"));
}
catch (ParseException pe)
{
/*
* A parse exception means there were some weird characters in
* the query we couldn't resolve. We'll pretend the search went
* OK but with no results for the user, but log the error, since
* this shouldn't really happen.
*/
log.warn(LogManager.getHeader(context,
"search_exception",
logInfo + "query=\"" + query + "\""),
pe);
// Empty results
resultsItems = new Item[0];
resultsCommunities = new Community[0];
resultsCollections = new Collection[0];
}
catch (TokenMgrError tme)
{
// Similar to parse exception
log.warn(LogManager.getHeader(context,
"search_exception",
logInfo + "query=\"" + query + "\""),
tme);
// Empty results
resultsItems = new Item[0];
resultsCommunities = new Community[0];
resultsCollections = new Collection[0];
}
// Pass the results to the display JSP
request.setAttribute("items", resultsItems );
request.setAttribute("communities", resultsCommunities);
request.setAttribute("collections", resultsCollections);
// And the original query string
request.setAttribute("query", query);
JSPManager.showJSP(request, response, "/search/results.jsp");
}
}
|
package com.hsalf.smilerating;
import android.animation.Animator;
import android.animation.ArgbEvaluator;
import android.animation.FloatEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.annotation.ColorInt;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import java.util.HashMap;
import java.util.Map;
public class SmileRating extends BaseRating {
private static final String TAG = "RatingView";
private int mPlaceHolderSmileColor = Color.WHITE;
private int mAngryColor = Color.parseColor("#f29a68");
private int mNormalColor = Color.parseColor("#f2dd68");
private int mDrawingColor = Color.parseColor("#353431");
private int mTextSelectedColor = Color.BLACK;
private int mTextNonSelectedColor = Color.parseColor("#AEB3B5");
private int mPlaceholderBackgroundColor = Color.parseColor("#e6e8ed");
private String[] mNames = new String[]{
"Terrible", "Bad", "Okay", "Good", "Great"
};
private Face[] mFaces = new Face[SMILES_LIST.length];
private Map<Integer, Point> mTouchPoints = new HashMap<>();
private float mSmileGap;
private Paint mPathPaint = new Paint();
private Paint mBackgroundPaint = new Paint();
private Paint mPointPaint1 = new Paint();
private Paint mPointPaint2 = new Paint();
// private Path mEyePathLeft = new Path();
// private Path mEyePathRight = new Path();
private Point mFaceCenter = new Point();
private Path mSmilePath = new Path();
private Paint mPlaceHolderFacePaint = new Paint();
private Paint mPlaceholderLinePaint = new Paint();
private Paint mPlaceHolderCirclePaint = new Paint();
private float divisions;
private ValueAnimator mValueAnimator = new ValueAnimator();
private FloatEvaluator mFloatEvaluator = new FloatEvaluator();
private ArgbEvaluator mColorEvaluator = new ArgbEvaluator();
private ClickAnalyser mClickAnalyser;
private Matrix mScaleMatrix = new Matrix();
private RectF mScaleRect = new RectF();
private RectF mTouchBounds = new RectF();
private Path mDummyDrawPah = new Path();
private Paint mTextPaint = new Paint();
@Smiley
private int mSelectedSmile = OKAY;
@Smiley
private int mPreviousSmile = -1;
@Smiley
private int mNearestSmile = OKAY;
@Smiley
private int mPendingActionSmile = OKAY;
private Smileys mSmileys;
// private float mTranslation = 0;
private float mWidth;
private float mHeight;
private float mCenterY;
private float mFromRange;
private float mToRange;
private float mPrevX;
private boolean mFaceClickEngaged = false;
private OnRatingSelectedListener mOnRatingSelectedListener = null;
private OnSmileySelectionListener mOnSmileySelectionListener = null;
private float mPlaceHolderScale = 1f;
public SmileRating(Context context) {
super(context);
init();
}
public SmileRating(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttrs(attrs);
init();
}
public SmileRating(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
parseAttrs(attrs);
init();
}
private void parseAttrs(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SmileRating);
mAngryColor = a.getColor(R.styleable.SmileRating_angryColor, mAngryColor);
mNormalColor = a.getColor(R.styleable.SmileRating_normalColor, mNormalColor);
mDrawingColor = a.getColor(R.styleable.SmileRating_drawingColor, mDrawingColor);
mPlaceHolderSmileColor = a.getColor(R.styleable.SmileRating_placeHolderSmileColor,
mPlaceHolderSmileColor);
mPlaceholderBackgroundColor = a.getColor(R.styleable.SmileRating_placeHolderBackgroundColor,
mPlaceholderBackgroundColor);
mTextSelectedColor = a.getColor(R.styleable.SmileRating_textSelectionColor,
mTextSelectedColor);
mTextNonSelectedColor = a.getColor(R.styleable.SmileRating_textNonSelectionColor,
mTextNonSelectedColor);
a.recycle();
}
}
private void init() {
mClickAnalyser = ClickAnalyser.newInstance(getResources().getDisplayMetrics().density);
mTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
mPathPaint.setAntiAlias(true);
mPathPaint.setStrokeWidth(3);
mPathPaint.setColor(mDrawingColor);
mPathPaint.setStyle(Paint.Style.FILL);
mPointPaint1.setColor(Color.RED);
mPointPaint1.setStyle(Paint.Style.FILL);
mPointPaint2.setColor(Color.BLUE);
mPointPaint2.setStyle(Paint.Style.STROKE);
mBackgroundPaint.setStyle(Paint.Style.FILL);
mPlaceHolderFacePaint.setColor(mPlaceHolderSmileColor);
mPlaceHolderFacePaint.setStyle(Paint.Style.FILL);
mPlaceHolderCirclePaint.setColor(mPlaceholderBackgroundColor);
mPlaceHolderCirclePaint.setStyle(Paint.Style.FILL);
mPlaceholderLinePaint.setColor(mPlaceholderBackgroundColor);
mPlaceholderLinePaint.setStyle(Paint.Style.STROKE);
mValueAnimator.setDuration(250);
mValueAnimator.addListener(mAnimatorListener);
mValueAnimator.addUpdateListener(mAnimatorUpdateListener);
mValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
}
private ValueAnimator.AnimatorUpdateListener mAnimatorUpdateListener
= new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float anim = (float) animation.getAnimatedValue();
moveSmile(anim);
}
};
private Animator.AnimatorListener mAnimatorListener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
notifyListener();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
};
private void notifyListener() {
boolean reselected = mPreviousSmile == getSelectedSmile();
mPreviousSmile = mSelectedSmile;
mPendingActionSmile = mSelectedSmile;
if (mOnSmileySelectionListener != null) {
mOnSmileySelectionListener.onSmileySelected(mSelectedSmile, reselected);
}
if (mOnRatingSelectedListener != null) {
mOnRatingSelectedListener.onRatingSelected(getRating(), reselected);
}
}
public void setOnSmileySelectionListener(OnSmileySelectionListener l) {
mOnSmileySelectionListener = l;
}
public void setOnRatingSelectedListener(OnRatingSelectedListener l) {
mOnRatingSelectedListener = l;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
// mHeight = mWidth / 5.3f;
mHeight = mWidth / (5.3f * 1.3f);
mCenterY = mHeight / 2f;
mFaceCenter.y = mCenterY;
divisions = (mHeight / 32f);
mTextPaint.setTextSize(mHeight / 4.5f);
mSmileys = Smileys.newInstance(Math.round(mWidth), Math.round(mHeight));
setMeasuredDimension(Math.round(mWidth), (int) Math.round(mHeight + (mHeight * 0.48)));
createTouchPoints();
mPlaceholderLinePaint.setStrokeWidth(mHeight * 0.05f);
/*getSmiley(mSmileys, 0.5f, divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);*/
setSelectedSmile(mPendingActionSmile, mTouchPoints.get(mPendingActionSmile), false, false);
Log.i(TAG, "Selected smile:" + getSmileName(mPendingActionSmile));
}
private void createTouchPoints() {
mTouchPoints.clear();
float divisions = mWidth / 5f;
float divCenter = divisions / 2f;
mSmileGap = (divisions - mHeight) / 2f;
mFromRange = mSmileGap + (mHeight / 2);
mToRange = mWidth - (mHeight / 2) - mSmileGap;
int count = SMILES_LIST.length;
for (int i = 0; i < count; i++) {
mFaces[i] = createFace(i, mCenterY);
mTouchPoints.put(SMILES_LIST[i], new Point((divisions * i) + divCenter, mCenterY));
}
}
private Face createFace(int index, float centerY) {
Face face = new Face();
face.smileType = index;
getSmiley(mSmileys, index * 0.25f, divisions, mFromRange, mToRange, face.place,
face.smile, centerY);
face.place.y = centerY;
return face;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Point start = mFaces[0].place;
Point end = mFaces[mFaces.length - 1].place;
canvas.drawLine(start.x, start.y, end.x, end.y, mPlaceholderLinePaint);
Log.i(TAG, "******************");
for (Face face : mFaces) {
if (!mSmilePath.isEmpty()) {
float scale = getScale(face.smileType);
canvas.drawCircle(face.place.x, face.place.y,
scale * (mHeight / 2), mPlaceHolderCirclePaint);
mScaleMatrix.reset();
face.smile.computeBounds(mScaleRect, true);
mScaleMatrix.setScale(scale, scale,
mScaleRect.centerX(), mScaleRect.centerY());
mDummyDrawPah.reset();
mDummyDrawPah.addPath(face.smile, mScaleMatrix);
canvas.drawPath(mDummyDrawPah, mPlaceHolderFacePaint);
float transY = 0.15f - (scale * 0.15f);
mTextPaint.setColor((int) mColorEvaluator.evaluate(((transY / 0.15f) - 0.2f) / 0.8f,
mTextNonSelectedColor, mTextSelectedColor));
drawTextCentered(getSmileName(face.smileType), face.place.x,
face.place.y + (mHeight * (0.70f + transY)), mTextPaint, canvas);
}
}
canvas.drawCircle(mFaceCenter.x, mFaceCenter.y, mHeight / 2f, mBackgroundPaint);
if (!mSmilePath.isEmpty()) {
canvas.drawPath(mSmilePath, mPathPaint);
}
}
private void drawTextCentered(String text, float x, float y, Paint paint, Canvas canvas) {
float xPos = x - (paint.measureText(text) / 2);
float yPos = (y - ((paint.descent() + paint.ascent()) / 2));
canvas.drawText(text, xPos, yPos, paint);
}
private float getScale(@Smiley int smile) {
if (smile == mNearestSmile) {
return mPlaceHolderScale;
}
return 0.80f;
}
public String getSmileName(int smile) {
if (smile >= mNames.length) {
return null;
}
return mNames[smile];
}
public void setNameForSmile(@Smiley int smile, String title) {
mNames[smile] = title != null ? title : "";
invalidate();
}
public void setAngryColor(@ColorInt int color) {
this.mAngryColor = color;
getSmiley(mSmileys, getFractionBySmiley(mSelectedSmile), divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);
}
public void setNormalColor(@ColorInt int color) {
this.mNormalColor = color;
getSmiley(mSmileys, getFractionBySmiley(mSelectedSmile), divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);
}
public void setDrawingColor(@ColorInt int color) {
this.mDrawingColor = color;
mPathPaint.setColor(mDrawingColor);
invalidate();
}
public void setTextSelectedColor(@ColorInt int color) {
this.mTextSelectedColor = color;
invalidate();
}
public void setTextNonSelectedColor(@ColorInt int color) {
this.mTextNonSelectedColor = color;
invalidate();
}
public void setPlaceHolderSmileColor(@ColorInt int color) {
this.mPlaceHolderSmileColor = color;
mPlaceHolderFacePaint.setColor(mPlaceHolderSmileColor);
invalidate();
}
public void setPlaceholderBackgroundColor(@ColorInt int color) {
this.mPlaceholderBackgroundColor = color;
mPlaceHolderCirclePaint.setColor(mPlaceholderBackgroundColor);
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
float x = event.getX();
float y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
mClickAnalyser.start(x, y);
mFaceClickEngaged = isSmileyBounds(mFaceCenter.x, mFaceCenter.y,
x, y, mCenterY);
mPrevX = x;
break;
case MotionEvent.ACTION_MOVE:
mClickAnalyser.move(x, y);
if (mClickAnalyser.isMoved() && mFaceClickEngaged) {
moveSmile(mFaceCenter.x - (mPrevX - x));
}
mPrevX = x;
break;
case MotionEvent.ACTION_UP:
mFaceClickEngaged = false;
mClickAnalyser.stop(x, y);
if (!mClickAnalyser.isMoved()) {
onClickView(x, y);
} else {
positionSmile();
}
break;
}
return true;
}
private void positionSmile() {
float currentPosition = mFaceCenter.x;
float distance = Integer.MAX_VALUE;
Point point = null;
@Smiley
int smile = GREAT;
for (Integer s : mTouchPoints.keySet()) {
Point p = mTouchPoints.get(s);
float d = Math.abs(p.x - currentPosition);
if (distance > d) {
point = p;
smile = s;
distance = d;
}
}
setSelectedSmile(smile, point, false, true);
}
private void moveSmile(float position) {
float fraction = (position - mFromRange) / (mToRange - mFromRange);
moveSmileByFraction(fraction);
}
private void moveSmileByFraction(float fraction) {
if (fraction >= 0f && fraction <= 1f) {
getSmiley(mSmileys, fraction, divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);
invalidate();
}
}
private void onClickView(float x, float y) {
for (Integer smile : mTouchPoints.keySet()) {
Point point = mTouchPoints.get(smile);
boolean touched = isSmileyBounds(point.x, point.y, x, y, mCenterY);
if (touched) {
if (smile == getSelectedSmile()) {
notifyListener();
} else {
setSelectedSmile(smile, point, true, true);
}
}
}
}
private boolean isSmileyBounds(float cx, float cy, float tx, float ty, float width) {
mTouchBounds.set(cx - width, 0, cx + width, getMeasuredHeight());
return mTouchBounds.contains(tx, ty);
}
/**
* Set the selected smiley
*
* @param smile is the smiley type you want this rating bar to show as selected smile
*/
public void setSelectedSmile(@Smiley int smile) {
setSelectedSmile(smile, false);
}
/**
* Set the selected smiley
*
* @param smile is the smiley type you want this rating bar to show as selected smile
* @param animate true if you want to set the selected smiley and animate it,
* false for no animation
*/
public void setSelectedSmile(@Smiley int smile, boolean animate) {
mPendingActionSmile = smile;
setSelectedSmile(smile, mTouchPoints.get(smile), true, animate);
}
/**
* @return the current selected smiley {@link #TERRIBLE} ,{@link #BAD},
* {@link #OKAY},{@link #GOOD},{@link #GREAT}
*/
@Smiley
public int getSelectedSmiley() {
return mSelectedSmile;
}
/**
* @return the selected rating level from range of 0 to 4
*/
public int getRatingLevel() {
return getRating();
}
private void setSelectedSmile(@Smiley int smile, Point point, boolean check, boolean animate) {
if (mSelectedSmile == smile && check) {
return;
}
mSelectedSmile = smile;
if (mFaceCenter == null || point == null) {
return;
}
mValueAnimator.setFloatValues(mFaceCenter.x, point.x);
if (animate) {
mValueAnimator.start();
} else {
moveSmile(point.x);
// notifyListener();
}
}
@Smiley
public int getSelectedSmile() {
return mSelectedSmile;
}
public int getRating() {
return getSelectedSmile() + 1;
}
/**
* Evaluates click actions using touch events
*/
protected static class ClickAnalyser {
private static final int MAX_CLICK_DISTANCE = 20;
private static final int MAX_CLICK_DURATION = 200;
private float mPressX;
private float mPressY;
private final float mDensity;
private long mPressStartTime;
private boolean mMoved = false;
private boolean mClickEventOccured = true;
public ClickAnalyser(float density) {
mDensity = density;
}
public static ClickAnalyser newInstance(float density) {
return new ClickAnalyser(density);
}
public void start(float x, float y) {
mPressX = x;
mPressY = y;
mMoved = false;
mClickEventOccured = true;
mPressStartTime = System.currentTimeMillis();
}
/**
* returns long press
*
* @param x
* @param y
* @return
*/
public void move(float x, float y) {
float dist = distance(mPressX, mPressY, x, y);
long time = System.currentTimeMillis() - mPressStartTime;
if (!mMoved && dist > MAX_CLICK_DISTANCE) {
mMoved = true;
}
if ((time) > MAX_CLICK_DURATION || mMoved) {
mClickEventOccured = false;
}
}
public boolean stop(float x, float y) {
move(x, y);
return mClickEventOccured;
}
private float distance(float x1, float y1, float x2, float y2) {
float dx = x1 - x2;
float dy = y1 - y2;
float distanceInPx = (float) Math.sqrt(dx * dx + dy * dy);
return pxToDp(distanceInPx);
}
public boolean isMoved() {
return mMoved;
}
private float pxToDp(float px) {
return px / mDensity;
}
}
private float getFractionBySmiley(@Smiley int smiley) {
switch (smiley) {
case BaseRating.BAD:
return 1f;
case BaseRating.GOOD:
return 0.75f;
case BaseRating.GREAT:
return 0.5f;
case BaseRating.OKAY:
return 0.25f;
case BaseRating.TERRIBLE:
return 0f;
}
return 0;
}
private void getSmiley(Smileys smileys, float fraction, float divisions, float fromRange,
float toRange, Point point, Path smilePath,
float centerY) {
if (smileys == null) {
return;
}
float actualTranslation = mFloatEvaluator.evaluate(fraction, fromRange, toRange);
point.x = actualTranslation;
float trans = actualTranslation - centerY;
if (fraction > 0.75f) {
fraction -= 0.75f;
fraction *= 4;
findNearestSmile(fraction, GOOD, GREAT);
mBackgroundPaint.setColor(mNormalColor);
transformSmile(trans, fraction, smilePath,
smileys.getSmile(GOOD), smileys.getSmile(GREAT), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, GREAT, smilePath, smilePath, centerY);
} else if (fraction > 0.50f) {
fraction -= 0.50f;
fraction *= 4;
findNearestSmile(fraction, OKAY, GOOD);
mBackgroundPaint.setColor(mNormalColor);
transformSmile(trans, fraction, smilePath,
smileys.getSmile(OKAY), smileys.getSmile(GOOD), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, GOOD, smilePath, smilePath, centerY);
} else if (fraction > 0.25f) {
fraction -= 0.25f;
fraction *= 4;
findNearestSmile(fraction, BAD, OKAY);
mBackgroundPaint.setColor(mNormalColor);
transformSmile(trans, fraction, smilePath,
smileys.getSmile(BAD), smileys.getSmile(OKAY), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, BAD, smilePath, smilePath, centerY);
} else {
fraction *= 4;
findNearestSmile(fraction, TERRIBLE, BAD);
mBackgroundPaint.setColor((Integer) mColorEvaluator.evaluate(fraction, mAngryColor, mNormalColor));
transformSmile(trans, fraction, smilePath,
smileys.getSmile(TERRIBLE), smileys.getSmile(BAD), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, TERRIBLE, smilePath, smilePath, centerY);
}
}
private void findNearestSmile(float fraction, @Smiley int leftSmile, @Smiley int rightSmile) {
if (fraction < 0.5f) {
mPlaceHolderScale = limitNumberInRange(fraction * 2);
mNearestSmile = leftSmile;
} else {
mPlaceHolderScale = limitNumberInRange(1f - (fraction - 0.5f) * 2);
mNearestSmile = rightSmile;
}
}
private float limitNumberInRange(float num) {
// The range is going to be in between 0 to 0.80
num *= 0.80f;
return num;
}
private void createEyeLocation(Smileys smileys, float divisions, float fraction, float actualTranslation, @Smiley int smile, Path leftEye, Path rightEye, float centerY) {
Eye eyeLeft = EyeEmotion.prepareEye(smileys.getEye(Eye.LEFT), mFloatEvaluator, fraction, smile);
Eye eyeRight = EyeEmotion.prepareEye(smileys.getEye(Eye.RIGHT), mFloatEvaluator, fraction, smile);
eyeLeft.radius = divisions * 2.5f;
eyeRight.radius = divisions * 2.5f;
eyeLeft.center.x = (divisions * 11f) + actualTranslation - centerY;
eyeLeft.center.y = centerY * 0.70f;
eyeRight.center.x = (divisions * 21f) + actualTranslation - centerY;
eyeRight.center.y = centerY * 0.70f;
eyeLeft.fillPath(leftEye);
eyeRight.fillPath(rightEye);
}
private static class Face {
Point place = new Point();
Path smile = new Path();
@Smiley
int smileType;
/*Path leftEye = new Path();
Path rightEye = new Path();*/
}
public interface OnSmileySelectionListener {
/**
* Called when a smiley is selected
*
* @param smiley is the type of smiley the user selected ({@link #GREAT}, {@link #BAD},
* {@link #OKAY},{@link #GOOD},{@link #GREAT})
* @param reselected is false when user selects different smiley that previously selected
* one true when the same smiley is selected. Except if it first time,
* then the value will be false.
*/
void onSmileySelected(@Smiley int smiley, boolean reselected);
}
public interface OnRatingSelectedListener {
/**
* Called when a smiley is selected
*
* @param level is the level of the rating (0 to 4)
* @param reselected is false when user selects different smiley that previously selected
* one true when the same smiley is selected. Except if it first time,
* then the value will be false.
*/
void onRatingSelected(int level, boolean reselected);
}
}
|
package org.jetel.interpreter;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.regex.Matcher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.primitive.CloverDouble;
import org.jetel.data.primitive.CloverInteger;
import org.jetel.data.primitive.CloverLong;
import org.jetel.data.primitive.DecimalFactory;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.TransformationGraph;
import org.jetel.interpreter.ASTnode.CLVFAddNode;
import org.jetel.interpreter.ASTnode.CLVFAnd;
import org.jetel.interpreter.ASTnode.CLVFAssignment;
import org.jetel.interpreter.ASTnode.CLVFBlock;
import org.jetel.interpreter.ASTnode.CLVFBreakStatement;
import org.jetel.interpreter.ASTnode.CLVFBreakpointNode;
import org.jetel.interpreter.ASTnode.CLVFCaseExpression;
import org.jetel.interpreter.ASTnode.CLVFComparison;
import org.jetel.interpreter.ASTnode.CLVFContinueStatement;
import org.jetel.interpreter.ASTnode.CLVFDate2NumNode;
import org.jetel.interpreter.ASTnode.CLVFDateAddNode;
import org.jetel.interpreter.ASTnode.CLVFDateDiffNode;
import org.jetel.interpreter.ASTnode.CLVFDivNode;
import org.jetel.interpreter.ASTnode.CLVFDoStatement;
import org.jetel.interpreter.ASTnode.CLVFForStatement;
import org.jetel.interpreter.ASTnode.CLVFForeachStatement;
import org.jetel.interpreter.ASTnode.CLVFFunctionCallStatement;
import org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration;
import org.jetel.interpreter.ASTnode.CLVFIfStatement;
import org.jetel.interpreter.ASTnode.CLVFIffNode;
import org.jetel.interpreter.ASTnode.CLVFImportSource;
import org.jetel.interpreter.ASTnode.CLVFInputFieldLiteral;
import org.jetel.interpreter.ASTnode.CLVFIsNullNode;
import org.jetel.interpreter.ASTnode.CLVFLiteral;
import org.jetel.interpreter.ASTnode.CLVFLookupNode;
import org.jetel.interpreter.ASTnode.CLVFMapping;
import org.jetel.interpreter.ASTnode.CLVFMinusMinusNode;
import org.jetel.interpreter.ASTnode.CLVFMinusNode;
import org.jetel.interpreter.ASTnode.CLVFModNode;
import org.jetel.interpreter.ASTnode.CLVFMulNode;
import org.jetel.interpreter.ASTnode.CLVFNVLNode;
import org.jetel.interpreter.ASTnode.CLVFOperator;
import org.jetel.interpreter.ASTnode.CLVFOr;
import org.jetel.interpreter.ASTnode.CLVFOutputFieldLiteral;
import org.jetel.interpreter.ASTnode.CLVFPlusPlusNode;
import org.jetel.interpreter.ASTnode.CLVFPostfixExpression;
import org.jetel.interpreter.ASTnode.CLVFPrintErrNode;
import org.jetel.interpreter.ASTnode.CLVFPrintLogNode;
import org.jetel.interpreter.ASTnode.CLVFPrintStackNode;
import org.jetel.interpreter.ASTnode.CLVFRaiseErrorNode;
import org.jetel.interpreter.ASTnode.CLVFRegexLiteral;
import org.jetel.interpreter.ASTnode.CLVFReturnStatement;
import org.jetel.interpreter.ASTnode.CLVFSequenceNode;
import org.jetel.interpreter.ASTnode.CLVFSizeNode;
import org.jetel.interpreter.ASTnode.CLVFStart;
import org.jetel.interpreter.ASTnode.CLVFStartExpression;
import org.jetel.interpreter.ASTnode.CLVFStatementExpression;
import org.jetel.interpreter.ASTnode.CLVFStr2NumNode;
import org.jetel.interpreter.ASTnode.CLVFSubNode;
import org.jetel.interpreter.ASTnode.CLVFSwitchStatement;
import org.jetel.interpreter.ASTnode.CLVFSymbolNameExp;
import org.jetel.interpreter.ASTnode.CLVFTruncNode;
import org.jetel.interpreter.ASTnode.CLVFUnaryExpression;
import org.jetel.interpreter.ASTnode.CLVFVarDeclaration;
import org.jetel.interpreter.ASTnode.CLVFVariableLiteral;
import org.jetel.interpreter.ASTnode.CLVFWhileStatement;
import org.jetel.interpreter.ASTnode.Node;
import org.jetel.interpreter.ASTnode.SimpleNode;
import org.jetel.interpreter.data.TLListVariable;
import org.jetel.interpreter.data.TLMapVariable;
import org.jetel.interpreter.data.TLValue;
import org.jetel.interpreter.data.TLValueType;
import org.jetel.interpreter.data.TLVariable;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.Compare;
import org.jetel.util.StringUtils;
/**
* Executor of FilterExpression parse tree.
*
* @author dpavlis
* @since 16.9.2004
*
* Executor of FilterExpression parse tree
*/
public class TransformLangExecutor implements TransformLangParserVisitor,
TransformLangParserConstants{
public static final int BREAK_BREAK=1;
public static final int BREAK_CONTINUE=2;
public static final int BREAK_RETURN=3;
protected Stack stack;
protected boolean breakFlag;
protected int breakType;
protected Properties globalParameters;
protected DataRecord[] inputRecords;
protected DataRecord[] outputRecords;
protected Node emptyNode; // used as replacement for empty statements
protected TransformationGraph graph;
protected Log runtimeLogger;
static Log logger = LogFactory.getLog(TransformLangExecutor.class);
/**
* Constructor
*/
public TransformLangExecutor(Properties globalParameters) {
stack = new Stack();
breakFlag = false;
this.globalParameters=globalParameters;
emptyNode = new SimpleNode(Integer.MAX_VALUE);
}
public TransformLangExecutor() {
this(null);
}
public TransformationGraph getGraph() {
return graph;
}
public void setGraph(TransformationGraph graph) {
this.graph = graph;
}
public Log getRuntimeLogger() {
return runtimeLogger;
}
public void setRuntimeLogger(Log runtimeLogger) {
this.runtimeLogger = runtimeLogger;
}
/**
* Set input data records for processing.<br>
* Referenced input data fields will be resolved from
* these data records.
*
* @param inputRecords array of input data records carrying values
*/
public void setInputRecords(DataRecord[] inputRecords){
this.inputRecords=inputRecords;
}
/**
* Set output data records for processing.<br>
* Referenced output data fields will be resolved from
* these data records - assignment (in code) to output data field
* will result in assignment to one of these data records.
*
* @param outputRecords array of output data records for setting values
*/
public void setOutputRecords(DataRecord[] outputRecords){
this.outputRecords=outputRecords;
}
/**
* Set global parameters which may be reference from within the
* transformation source code
*
* @param parameters
*/
public void setGlobalParameters(Properties parameters){
this.globalParameters=parameters;
}
/**
* Allows to store parameter/value on stack from
* where it can be read by executed script/function.
* @param obj Object/value to be stored
* @since 10.12.2006
*/
public void setParameter(String obj){
stack.push(new TLValue(TLValueType.STRING,obj));
}
/**
* Method which returns result of executing parse tree.<br>
* Basically, it returns whatever object was left on top of executor's
* stack (usually as a result of last executed expression/operation).<br>
* It can be called repetitively in order to read all objects from stack.
*
* @return Object saved on stack or NULL if no more objects are available
*/
public TLValue getResult() {
return stack.pop();
}
/**
* Return value of globally defined variable determined by slot number.
* Slot can be obtained by calling <code>TransformLangParser.getGlobalVariableSlot(<i>varname</i>)</code>
*
* @param varSlot
* @return Object - depending of Global variable type
* @since 6.12.2006
*/
public TLVariable getGlobalVariable(int varSlot){
return stack.getGlobalVar(varSlot);
}
/**
* Allows to set value of defined global variable.
*
* @param varSlot
* @param value
* @since 6.12.2006
*/
public void setGlobalVariable(int varSlot,TLVariable value){
stack.storeGlobalVar(varSlot,value);
}
/* implementation of visit methods for each class of AST node */
/* it seems to be necessary to define a visit() method for SimpleNode */
public Object visit(SimpleNode node, Object data) {
// throw new TransformLangExecutorRuntimeException(node,
// "Error: Call to visit for SimpleNode");
return data;
}
public Object visit(CLVFStart node, Object data) {
int i, k = node.jjtGetNumChildren();
for (i = 0; i < k; i++)
node.jjtGetChild(i).jjtAccept(this, data);
return data; // this value is ignored in this example
}
public Object visit(CLVFStartExpression node, Object data) {
int i, k = node.jjtGetNumChildren();
for (i = 0; i < k; i++)
node.jjtGetChild(i).jjtAccept(this, data);
return data; // this value is ignored in this example
}
public Object visit(CLVFOr node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a=stack.pop();
if (a.type!=TLValueType.BOOLEAN){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}else if (a.getBoolean()){
stack.push(Stack.TRUE_VAL);
return data;
}
node.jjtGetChild(1).jjtAccept(this, data);
a=stack.pop();
if (a.type!=TLValueType.BOOLEAN){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}
stack.push( a.getBoolean() ? Stack.TRUE_VAL : Stack.FALSE_VAL);
return data;
}
public Object visit(CLVFAnd node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a=stack.pop();
if (a.type!=TLValueType.BOOLEAN){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}else if (!a.getBoolean()){
stack.push(Stack.FALSE_VAL);
return data;
}
node.jjtGetChild(1).jjtAccept(this, data);
a=stack.pop();
if (a.type!=TLValueType.BOOLEAN){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}
stack.push(a.getBoolean() ? Stack.TRUE_VAL : Stack.FALSE_VAL);
return data;
}
public Object visit(CLVFComparison node, Object data) {
int cmpResult = 2;
boolean lValue = false;
// special handling for Regular expression
if (node.cmpType == REGEX_EQUAL) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue field1 = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue field2 = stack.pop();
if (field1.type == TLValueType.STRING
&& field2.getValue() instanceof Matcher) {
Matcher regex = (Matcher) field2.getValue();
regex.reset(field1.getCharSequence());
if (regex.matches()) {
lValue = true;
} else {
lValue = false;
}
} else {
Object[] arguments = { field1, field2 };
throw new TransformLangExecutorRuntimeException(node,
arguments, "regex equal - wrong type of literal(s)");
}
// other types of comparison
} else {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue b = stack.pop();
if (!a.type.isCompatible(b.type)) {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"compare - incompatible literals/expressions");
}
switch (a.type) {
case INTEGER:
case LONG:
case DOUBLE:
case DECIMAL:
cmpResult = a.getNumeric().compareTo(b.getNumeric());
break;
case DATE:
cmpResult = a.getDate().compareTo(b.getDate());
break;
case STRING:
cmpResult = Compare.compare(a.getCharSequence(), b
.getCharSequence());
break;
case BOOLEAN:
if (node.cmpType == EQUAL || node.cmpType == NON_EQUAL) {
cmpResult = a.getBoolean() == b.getBoolean() ? 0 : -1;
} else {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"compare - unsupported comparison operator ["
+ tokenImage[node.cmpType]
+ "] for literals/expressions");
}
break;
default:
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"compare - don't know how to compare literals/expressions");
}
switch (node.cmpType) {
case EQUAL:
if (cmpResult == 0) {
lValue = true;
}
break;// equal
case LESS_THAN:
if (cmpResult == -1) {
lValue = true;
}
break;// less than
case GREATER_THAN:
if (cmpResult == 1) {
lValue = true;
}
break;// grater than
case LESS_THAN_EQUAL:
if (cmpResult <= 0) {
lValue = true;
}
break;// less than equal
case GREATER_THAN_EQUAL:
if (cmpResult >= 0) {
lValue = true;
}
break;// greater than equal
case NON_EQUAL:
if (cmpResult != 0) {
lValue = true;
}
break;
default:
// this should never happen !!!
logger
.fatal("Internal error: Unsupported comparison operator !");
throw new RuntimeException(
"Internal error - Unsupported comparison operator !");
}
}
stack.push(lValue ? Stack.TRUE_VAL : Stack.FALSE_VAL);
return data;
}
public Object visit(CLVFAddNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue b = stack.pop();
if (a.isNull()|| b.isNull()) {
//TODO: (check) we allow empty strings to be concatenated
if (a.type!=TLValueType.STRING)
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"add - NULL value not allowed");
}
if (node.nodeVal==null) {
node.nodeVal= a.isNull() ? TLValue.create(a.type) : a.duplicate();
}
try {
if (a.type.isNumeric() && b.type.isNumeric()) {
node.nodeVal.getNumeric().setValue(a.getNumeric());
node.nodeVal.getNumeric().add(b.getNumeric());
stack.push(node.nodeVal);
} else if (a.type==TLValueType.DATE && b.type.isNumeric()) {
Calendar result = Calendar.getInstance();
result.setTime(a.getDate());
result.add(Calendar.DATE, b.getInt());
node.nodeVal.getDate().setTime(result.getTimeInMillis());
stack.push(node.nodeVal);
} else if (a.type==TLValueType.STRING) {
CharSequence a1 = a.getCharSequence();
StringBuilder buf=(StringBuilder)node.nodeVal.getValue();
buf.setLength(0);
StringUtils.strBuffAppend(buf,a1);
if (b.type==TLValueType.STRING) {
StringUtils.strBuffAppend(buf,b.getCharSequence());
} else {
buf.append(b);
}
stack.push(node.nodeVal);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"add - wrong type of literal(s)");
}
} catch (ClassCastException ex) {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"add - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFSubNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue b = stack.pop();
if (a.isNull()|| b.isNull()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"sub - NULL value not allowed");
}
if (!b.type.isNumeric()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"sub - wrong type of literal");
}
if (node.nodeVal==null) {
node.nodeVal=a.duplicate();
}
if(a.type.isNumeric()) {
node.nodeVal.getNumeric().setValue(a.getNumeric());
node.nodeVal.getNumeric().sub(b.getNumeric());
stack.push(node.nodeVal);
} else if (a.type==TLValueType.DATE) {
Calendar result = Calendar.getInstance();
result.setTime(a.getDate());
result.add(Calendar.DATE, b.getInt() * -1);
node.nodeVal.getDate().setTime(result.getTimeInMillis());
stack.push(node.nodeVal);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"sub - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFMulNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue b = stack.pop();
if (a.isNull()|| b.isNull()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"mul - NULL value not allowed");
}
if (!a.type.isNumeric() && !b.type.isNumeric()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b },
"mul - wrong type of literals");
}
if (node.nodeVal==null) {
node.nodeVal=a.duplicate();
}
node.nodeVal.getNumeric().setValue(a.getNumeric());
node.nodeVal.getNumeric().mul(b.getNumeric());
stack.push(node.nodeVal);
return data;
}
public Object visit(CLVFDivNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue b = stack.pop();
if (a.isNull()|| b.isNull()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"div - NULL value not allowed");
}
if (!a.type.isNumeric() && !b.type.isNumeric()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b },
"div - wrong type of literals");
}
if (node.nodeVal==null || node.nodeVal.type!=a.type) {
node.nodeVal=TLValue.create(a.type);
}
node.nodeVal.getNumeric().setValue(a.getNumeric());
try {
node.nodeVal.getNumeric().div(b.getNumeric());
}catch(ArithmeticException ex){
throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b },
"div - arithmetic exception",ex);
}catch (Exception ex) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b },
"div - error during operation",ex);
}
stack.push(node.nodeVal);
return data;
}
public Object visit(CLVFModNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue b = stack.pop();
if (a.isNull()|| b.isNull()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"mod - NULL value not allowed");
}
if (!a.type.isNumeric() && !b.type.isNumeric()) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"mod - wrong type of literals");
}
if (node.nodeVal==null) {
node.nodeVal=a.duplicate();
}
node.nodeVal.getNumeric().setValue(a.getNumeric());
node.nodeVal.getNumeric().mod(b.getNumeric());
stack.push(node.nodeVal);
return data;
}
/*
public Object visit(CLVFNegation node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue value = stack.pop();
if (value.type==TLValueType.BOOLEAN) {
stack.push(value.getBoolean() ? Stack.FALSE_VAL
: Stack.TRUE_VAL);
} else {
throw new TransformLangExecutorRuntimeException(node, new Object[] { value },
"logical condition does not evaluate to BOOLEAN value");
}
return data;
}
*/
public Object visit(CLVFIsNullNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue value = stack.pop();
if (value.isNull()) {
stack.push(Stack.TRUE_VAL);
} else {
if (value.type==TLValueType.STRING) {
stack.push( value.getCharSequence().length()==0 ? Stack.TRUE_VAL : Stack.FALSE_VAL);
}else {
stack.push(Stack.FALSE_VAL);
}
}
return data;
}
public Object visit(CLVFNVLNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue value = stack.pop();
if (value.isNull()) {
node.jjtGetChild(1).jjtAccept(this, data);
} else {
if (value.type==TLValueType.STRING && value.getCharSequence().length()==0) {
node.jjtGetChild(1).jjtAccept(this, data);
}else {
stack.push(value);
}
}
return data;
}
public Object visit(CLVFLiteral node, Object data) {
stack.push(node.valueTL);
return data;
}
public Object visit(CLVFInputFieldLiteral node, Object data) {
DataRecord record = inputRecords[node.recordNo];
if (record == null) {
stack.push(Stack.NULL_VAL);
} else {
DataField field = record.getField(node.fieldNo);
if (field.isNull())
stack.push(Stack.NULL_VAL);
else
stack.push(new TLValue(field));
}
// old
// stack.push(inputRecords[node.recordNo].getField(node.fieldNo).getValue());
// we return reference to DataField so we can
// perform extra checking in special cases
return node.field;
}
public Object visit(CLVFOutputFieldLiteral node, Object data) {
//stack.push(inputRecords[node.recordNo].getField(node.fieldNo));
// we return reference to DataField so we can
// perform extra checking in special cases
return data;
}
public Object visit(CLVFRegexLiteral node, Object data) {
stack.push(new TLValue(TLValueType.OBJECT,node.matcher));
return data;
}
public Object visit(CLVFDateAddNode node, Object data) {
int shiftAmount;
node.jjtGetChild(0).jjtAccept(this, data);
TLValue date = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue amount = stack.pop();
if (amount.type.isNumeric()) {
shiftAmount = amount.getInt();
} else {
Object arguments[] = { amount };
throw new TransformLangExecutorRuntimeException(node,arguments, "dateadd - amount is not a Numeric value");
}
if (date.type!=TLValueType.DATE) {
Object arguments[] = { date };
throw new TransformLangExecutorRuntimeException(node,arguments,
"dateadd - no Date expression");
}
if (node.nodeVal==null) {
node.nodeVal=date.duplicate();
}
node.calendar.setTime(date.getDate());
node.calendar.add(node.calendarField, shiftAmount);
node.nodeVal.getDate().setTime(node.calendar.getTimeInMillis());
stack.push(node.nodeVal);
return data;
}
public Object visit(CLVFDate2NumNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue date = stack.pop();
if (date.type==TLValueType.DATE) {
node.calendar.setTime(date.getDate());
stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(node.calendar.get(node.calendarField))));
} else {
Object arguments[] = { date };
throw new TransformLangExecutorRuntimeException(node,arguments,
"date2num - no Date expression");
}
return data;
}
public Object visit(CLVFDateDiffNode node, Object data) {
TLValue date1, date2;
node.jjtGetChild(0).jjtAccept(this, data);
date1 = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
date2 = stack.pop();
if (date1.type==TLValueType.DATE && date1.type==date2.type) {
long diffSec = (date1.getDate().getTime() - date2.getDate().getTime()) / 1000;
int diff = 0;
switch (node.calendarField) {
case Calendar.SECOND:
// we have the difference in seconds
diff = (int) diffSec;
break;
case Calendar.MINUTE:
// how many minutes'
diff = (int) diffSec / 60;
break;
case Calendar.HOUR_OF_DAY:
diff = (int) diffSec / 3600;
break;
case Calendar.DAY_OF_MONTH:
// how many days is the difference
diff = (int) diffSec / 86400;
break;
case Calendar.WEEK_OF_YEAR:
// how many weeks
diff = (int) diffSec / 604800;
break;
case Calendar.MONTH:
node.start.setTime(date1.getDate());
node.end.setTime(date2.getDate());
diff = (node.start.get(Calendar.MONTH) + node.start
.get(Calendar.YEAR) * 12)
- (node.end.get(Calendar.MONTH) + node.end
.get(Calendar.YEAR) * 12);
break;
case Calendar.YEAR:
node.start.setTime(date1.getDate());
node.end.setTime(date2.getDate());
diff = node.start.get(node.calendarField)
- node.end.get(node.calendarField);
break;
default:
Object arguments[] = { new Integer(node.calendarField) };
throw new TransformLangExecutorRuntimeException(node,arguments,
"datediff - wrong difference unit");
}
stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(diff)));
} else {
Object arguments[] = { date1, date2 };
throw new TransformLangExecutorRuntimeException(node,arguments,
"datediff - no Date expression");
}
return data;
}
public Object visit(CLVFMinusNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue value = stack.pop();
if (value.type.isNumeric()) {
TLValue newVal=value.duplicate();
newVal.getNumeric().mul(Stack.NUM_MINUS_ONE_P);
stack.push(newVal);
} else {
Object arguments[] = { value };
throw new TransformLangExecutorRuntimeException(node,arguments,
"minus - not a number");
}
return data;
}
public Object visit(CLVFStr2NumNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (a.type==TLValueType.STRING) {
try {
TLValue value = null;
switch (node.numType) {
case INT_VAR:
value = new TLValue(TLValueType.INTEGER,new CloverInteger(Integer.parseInt(
a.getString(), node.radix)));
break;
case LONG_VAR:
value = new TLValue(TLValueType.LONG,new CloverLong(Long.parseLong(a.getString(), node.radix)));
break;
case DECIMAL_VAR:
if (node.radix == 10) {
value = new TLValue(TLValueType.LONG,DecimalFactory.getDecimal(a.getString()));
} else {
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"str2num - can't convert string to decimal number using specified radix");
}
break;
default:
// get double/number type
switch (node.radix) {
case 10:
case 16:
value = new TLValue(TLValueType.DOUBLE,new CloverDouble(Double
.parseDouble(a.getString())));
break;
default:
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"str2num - can't convert string to number/double number using specified radix");
}
}
stack.push(value);
} catch (NumberFormatException ex) {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,
arguments, "str2num - can't convert \"" + a + "\"");
}
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node, arguments,
"str2num - wrong type of literal");
}
return data;
}
public Object visit(CLVFIffNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue condition = stack.pop();
if (condition.type==TLValueType.BOOLEAN) {
if (condition.getBoolean()) {
node.jjtGetChild(1).jjtAccept(this, data);
} else {
node.jjtGetChild(2).jjtAccept(this, data);
}
stack.push(stack.pop());
} else {
Object[] arguments = { condition };
throw new TransformLangExecutorRuntimeException(node,arguments,
"iif - condition does not evaluate to BOOLEAN value");
}
return data;
}
public Object visit(CLVFPrintErrNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (node.printLine){
StringBuilder buf=new StringBuilder((a != null ? a.toString() : "<null>"));
buf.append(" (on line: ").append(node.getLineNumber());
buf.append(" col: ").append(node.getColumnNumber()).append(")");
System.err.println(buf);
}else{
System.err.println(a != null ? a : "<null>");
}
return data;
}
public Object visit(CLVFPrintStackNode node, Object data) {
for (int i=stack.top;i>=0;i
System.err.println("["+i+"] : "+stack.stack[i]);
}
return data;
}
public Object visit(CLVFForStatement node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data); // set up of the loop
boolean condition = false;
Node loopCondition = node.jjtGetChild(1);
Node increment = node.jjtGetChild(2);
Node body;
try{
body=node.jjtGetChild(3);
}catch(ArrayIndexOutOfBoundsException ex){
body=emptyNode;
}
try {
loopCondition.jjtAccept(this, data); // evaluate the condition
condition = stack.pop().getBoolean();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// loop execution
while (condition) {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) {
return data;
}
}
increment.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = stack.pop().getBoolean();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}
}
return data;
}
public Object visit(CLVFForeachStatement node, Object data) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral)node.jjtGetChild(0);
CLVFVariableLiteral arrayNode=(CLVFVariableLiteral)node.jjtGetChild(1);
TLVariable variableToAssign = stack.getVar(varNode.localVar,
varNode.varSlot);
TLVariable arrayVariable=stack.getVar(arrayNode.localVar,
arrayNode.varSlot);
Node body;
try{
body=node.jjtGetChild(2);
}catch(ArrayIndexOutOfBoundsException ex){
body=emptyNode;
}
Iterator<TLValue> iter;
switch(arrayVariable.getType()) {
case LIST:
iter=((TLListVariable)arrayVariable).getList().iterator();
break;
case MAP:
iter=((TLMapVariable)arrayVariable).getMap().values().iterator();
break;
default:
throw new TransformLangExecutorRuntimeException(node,"not a Map or List variable");
}
while(iter.hasNext()) {
variableToAssign.setValue(iter.next());
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) {
return data;
}
}
}
return data;
}
public Object visit(CLVFWhileStatement node, Object data) {
boolean condition = false;
Node loopCondition = node.jjtGetChild(0);
Node body;
try{
body=node.jjtGetChild(1);
}catch(ArrayIndexOutOfBoundsException ex){
body=emptyNode;
}
try {
loopCondition.jjtAccept(this, data); // evaluate the condition
condition = stack.pop().getBoolean();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// loop execution
while (condition) {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data;
}
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = stack.pop().getBoolean();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}
}
return data;
}
public Object visit(CLVFIfStatement node, Object data) {
boolean condition = false;
try {
node.jjtGetChild(0).jjtAccept(this, data); // evaluate the
// condition
condition = stack.pop().getBoolean();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"condition does not evaluate to BOOLEAN value");
} catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// first if
if (condition) {
node.jjtGetChild(1).jjtAccept(this, data);
} else { // if else part exists
if (node.jjtGetNumChildren() > 2) {
node.jjtGetChild(2).jjtAccept(this, data);
}
}
return data;
}
public Object visit(CLVFDoStatement node, Object data) {
boolean condition = false;
Node loopCondition = node.jjtGetChild(1);
Node body = node.jjtGetChild(0);
// loop execution
do {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data;
}
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = stack.pop().getBoolean();
}catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
} while (condition);
return data;
}
public Object visit(CLVFSwitchStatement node, Object data) {
// get value of switch && push/leave it on stack
boolean match=false;
node.jjtGetChild(0).jjtAccept(this, data);
TLValue switchVal=stack.pop();
int numChildren = node.jjtGetNumChildren();
int numCases = node.hasDefaultClause ? numChildren-1 : numChildren;
// loop over remaining case statements
for (int i = 1; i < numCases; i++) {
stack.push(switchVal);
if (node.jjtGetChild(i).jjtAccept(this, data)==Stack.TRUE_VAL){
match=true;
}
if (breakFlag) {
if (breakType == BREAK_BREAK) {
breakFlag = false;
}
break;
}
}
// test whether execute default branch
if (node.hasDefaultClause && !match){
node.jjtGetChild(numChildren-1).jjtAccept(this, data);
}
return data;
}
public Object visit(CLVFCaseExpression node, Object data) {
// test if literal (as child 0) is equal to data on stack
// if so, execute block (child 1)
boolean match = false;
TLValue switchVal = stack.pop();
node.jjtGetChild(0).jjtAccept(this, data);
TLValue value = stack.pop();
try {
switch(switchVal.type) {
case INTEGER:
case LONG:
case DOUBLE:
case DECIMAL:
match = (value.getNumeric().compareTo(switchVal.getNumeric()) == 0);
break;
case STRING:
match = (Compare.compare(switchVal.getCharSequence(),
value.getCharSequence()) == 0);
break;
case DATE:
match = ( switchVal.getDate().compareTo(value.getDate()) == 0);
break;
case BOOLEAN:
match = (switchVal.getBoolean()==value.getBoolean());
break;
default:
}
} catch (ClassCastException ex) {
Object[] args=new Object[] {switchVal,value};
throw new TransformLangExecutorRuntimeException(node,args,"incompatible literals in case clause");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid case value");
}
if (match){
node.jjtGetChild(1).jjtAccept(this, data);
return Stack.TRUE_VAL;
}
return Stack.FALSE_VAL;
}
public Object visit(CLVFPlusPlusNode node, Object data) {
Node childNode = node.jjtGetChild(0);
if (node.statement) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode;
TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot);
if (var.getType().isNumeric()) {
var.getValue().getNumeric().add(Stack.NUM_ONE_P);
}else if (var.getType()==TLValueType.DATE) {
stack.calendar.setTime(var.getValue().getDate());
stack.calendar.add(Calendar.DATE, 1);
var.getValue().setValue(stack.calendar.getTime());
}else {
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
}
return data;
}
public Object visit(CLVFMinusMinusNode node, Object data) {
Node childNode = node.jjtGetChild(0);
if (node.statement) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode;
TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot);
if (var.getType().isNumeric()) {
var.getValue().getNumeric().sub(Stack.NUM_ONE_P);
}else if (var.getType()==TLValueType.DATE) {
stack.calendar.setTime(var.getValue().getDate());
stack.calendar.add(Calendar.DATE, -1);
var.getValue().setValue(stack.calendar.getTime());
}else {
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
}
return data;
}
public Object visit(CLVFBlock node, Object data) {
int childern = node.jjtGetNumChildren();
for (int i = 0; i < childern; i++) {
node.jjtGetChild(i).jjtAccept(this, data);
// have we seen contiue/break/return statement ??
if (breakFlag){
if (breakType!=BREAK_RETURN)
stack.pop();
return data;
}
stack.pop();
}
return data;
}
/*
* Loop & block & function control nodes
*/
public Object visit(CLVFBreakStatement node, Object data) {
breakFlag = true; // we encountered break statement;
breakType=BREAK_BREAK;
return data;
}
public Object visit(CLVFContinueStatement node, Object data) {
breakFlag = true; // we encountered continue statement;
breakType= BREAK_CONTINUE;
return data;
}
public Object visit(CLVFReturnStatement node, Object data) {
if (node.jjtHasChildren()){
node.jjtGetChild(0).jjtAccept(this, data);
}
breakFlag = true;
breakType = BREAK_RETURN;
return data;
}
public Object visit(CLVFBreakpointNode node, Object data) {
// list all variables
System.err.println("** list of global variables ***");
for (int i=0;i<stack.globalVarSlot.length;System.out.println(stack.globalVarSlot[i++]));
System.err.println("** list of local variables ***");
for (int i=0;i<stack.localVarCounter;i++)
System.out.println(stack.localVarSlot[stack.localVarSlotOffset+i]);
return data;
}
/*
* Variable declarations
*/
public Object visit(CLVFVarDeclaration node, Object data) {
TLValue value=null;
TLVariable variable=null;
// create global/local variable
switch (node.type) {
case INT_VAR:
value = new TLValue(TLValueType.INTEGER, new CloverInteger(0));
break;
case LONG_VAR:
value = new TLValue(TLValueType.LONG,new CloverLong(0));
break;
case DOUBLE_VAR:
value = new TLValue(TLValueType.DOUBLE, new CloverDouble(0));
break;
case DECIMAL_VAR:
if (node.length > 0) {
if (node.precision > 0) {
value = new TLValue(TLValueType.DECIMAL, DecimalFactory.getDecimal(node.length,
node.precision));
} else {
value = new TLValue(TLValueType.DECIMAL,DecimalFactory.getDecimal(node.length, 0));
}
} else {
value = new TLValue(TLValueType.DECIMAL,DecimalFactory.getDecimal());
}
break;
case STRING_VAR:
value = new TLValue(TLValueType.STRING,new StringBuilder());
break;
case DATE_VAR:
value = new TLValue(TLValueType.DATE,new Date());
break;
case BOOLEAN_VAR:
value = Stack.FALSE_VAL;
break;
case LIST_VAR:
if (node.length>0) {
variable = new TLListVariable(node.name,node.length);
((TLListVariable)variable).fill(Stack.NULL_VAL, node.length);
}else {
variable = new TLListVariable(node.name);
}
break;
case MAP_VAR:
if (node.length>0){
variable = new TLMapVariable(node.name,node.length);
}else {
variable = new TLMapVariable(node.name);
}
break;
default:
throw new TransformLangExecutorRuntimeException(node,
"variable declaration - "
+ "unknown type for variable \""
+ node.name + "\"");
}
if (variable==null)
variable=new TLVariable(node.name,value);
stack.storeVar(node.localVar, node.varSlot,variable );
if (node.jjtHasChildren()) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue initValue = stack.pop();
TLValueType type =variable.getType();
if (type.isStrictlyCompatible(initValue.type)) {
variable.setValue(initValue);
}else {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + initValue
+ "\" to variable \"" + node.name
+ "\" - incompatible data types");
}
}
return data;
}
public Object visit(CLVFVariableLiteral node, Object data) {
TLVariable var = stack.getVar(node.localVar, node.varSlot);
TLValue index = null;
if (node.indexSet) {
try {
switch (var.getType()) {
case LIST:
node.jjtGetChild(0).jjtAccept(this, data);
index = stack.pop();
stack.push(var.getValue(index.getInt()));
break;
case MAP:
node.jjtGetChild(0).jjtAccept(this, data);
index = stack.pop();
stack.push(var.getValue(index.getString()));
break;
}
} catch (Exception ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid index \"" + index + "\" of variable \""
+ var.getName() + "\" - type "
+ var.getType().toString(), ex);
}
}else {
stack.push(var.getValue());
}
return data;
}
public Object visit(CLVFAssignment node, Object data) {
CLVFVariableLiteral varNode = (CLVFVariableLiteral) node.jjtGetChild(0);
TLVariable variableToAssign = stack.getVar(varNode.localVar,
varNode.varSlot);
node.jjtGetChild(1).jjtAccept(this, data);
TLValue valueToAssign = stack.pop();
if (valueToAssign==null) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + valueToAssign
+ "\" to variable \"" + varNode.varName+"\"");
}
TLValue index = null;
switch (varNode.varType) {
case LIST_VAR:
try {
if (varNode.indexSet) {
varNode.jjtGetChild(0).jjtAccept(this, data);
index = stack.pop();
variableToAssign.setValue(index.getInt(), valueToAssign);
}else {
variableToAssign.setValue(-1,valueToAssign);
}
} catch (IndexOutOfBoundsException ex) {
throw new TransformLangExecutorRuntimeException(node,
"index \""+index+"\" is outside current limits of list/array \""
+ varNode.varName+"\"", ex);
} catch (Exception ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + valueToAssign
+ "\" to variable \"" + varNode.varName+"\"", ex);
}
break;
case MAP_VAR:
try {
varNode.jjtGetChild(0).jjtAccept(this, data);
index = stack.pop();
variableToAssign.setValue(index.getString(), valueToAssign);
} catch (Exception ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + valueToAssign
+ "\" to variable \"" + varNode.varName+"\"", ex);
}
break;
default:
TLValueType type=variableToAssign.getType();
if (type.isCompatible(valueToAssign.type)) {
variableToAssign.setValue(valueToAssign);
} else {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + valueToAssign
+ "[" + valueToAssign.type
+ "] \" to variable \""
+ variableToAssign.getName() + "\" ["
+ variableToAssign.getType()
+ "] \" - incompatible data types");
}
}
return data;
}
public Object visit(CLVFMapping node, Object data) {
DataField field=outputRecords[node.recordNo].getField(node.fieldNo);
int arity=node.jjtGetNumChildren(); // how many children we have defined
TLValue value=null;
try{
// we try till success or no more options
for (int i=0;i<arity;i++){
node.jjtGetChild(i).jjtAccept(this, data);
value=stack.pop();
try{
value.copyToDataField(field);
break; // success during assignment, finish looping
}catch(Exception ex){
if (i == arity-1)
throw ex;
}
}
}catch(BadDataFormatException ex){
if (!outputRecords[node.recordNo].getField(node.fieldNo).getMetadata().isNullable()){
throw new TransformLangExecutorRuntimeException(node,"can't assign NULL to \"" + node.fieldName + "\"");
}
throw new TransformLangExecutorRuntimeException(node,"data format exception when mapping \"" + node.fieldName + "\" - assigning \""
+ value + "\"");
}catch(TransformLangExecutorRuntimeException ex){
throw ex;
}catch(Exception ex){
String msg=ex.getMessage();
throw new TransformLangExecutorRuntimeException(node,
(msg!=null ? msg : "") +
" when mapping \"" + node.fieldName + "\" ("+DataFieldMetadata.type2Str(field.getType())
+") - assigning \"" + value + "\" ("+(value!=null ? value.getType().getName(): "unknown type" )+")");
}
return data;
}
/*
* Declaration & calling of Functions here
*/
public Object visit(CLVFFunctionCallStatement node, Object data) {
// EXTERNAL FUNCTION
if (node.externalFunction != null) {
// put call parameters on stack
node.childrenAccept(this, data);
// convert stack content into values
try {
TLValue returnVal = node.externalFunction.execute(stack.pop(
node.externalFunctionParams, node.jjtGetNumChildren()),
node.context);
stack.push(returnVal);
} catch (TransformLangExecutorRuntimeException ex) {
ex.setNode(node);
throw ex;
}
} else {
// INTERNAL FUNCTION
// put call parameters on stack
node.childrenAccept(this, data);
CLVFFunctionDeclaration executionNode = node.callNode;
// open call frame
stack.pushFuncCallFrame();
// store call parameters from stack as local variables
for (int i = executionNode.numParams - 1; i >= 0; stack
.storeLocalVar(i--, new TLVariable("local", stack.pop())))
;
// execute function body
// loop execution
TLValue returnData;
int numChildren = executionNode.jjtGetNumChildren();
for (int i = 0; i < numChildren; i++) {
executionNode.jjtGetChild(i).jjtAccept(this, data);
returnData = stack.pop(); // in case there is anything on top
// of stack
// check for break or continue statements
if (breakFlag) {
breakFlag = false;
if (breakType == BREAK_RETURN) {
if (returnData != null)
stack.push(returnData);
break;
}
}
}
stack.popFuncCallFrame();
}
return data;
}
public Object visit(CLVFFunctionDeclaration node, Object data) {
return data;
}
public Object visit(CLVFStatementExpression node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
return data;
}
public Object executeFunction(CLVFFunctionDeclaration executionNode, TLValue[] data) {
//put call parameters on stack
if (data==null){
data=new TLValue[0];
}
//TODO - check for function call parameter types
// open call frame
stack.pushFuncCallFrame();
// store call parameters from stack as local variables
for (int i=executionNode.numParams-1;i>=0; i
stack.storeLocalVar(i, new TLVariable(executionNode.varNames[i], data[i]));
}
// execute function body
// loop execution
TLValue returnData;
int numChildren=executionNode.jjtGetNumChildren();
for (int i=0;i<numChildren;i++){
executionNode.jjtGetChild(i).jjtAccept(this,data);
returnData=stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_RETURN){
if (returnData!=null)
stack.push(returnData);
break;
}
}
}
stack.popFuncCallFrame();
return data;
}
/*
* MATH functions log,log10,exp,pow,sqrt,round
*/
/*
public Object visit(CLVFSqrtNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (a.type.isNumeric()) {
try{
stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.sqrt(((Numeric)a).getDouble()) )));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing SQRT function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"sqrt - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFLogNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (a.type.isNumeric()) {
try{
stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.log(((Numeric)a).getDouble()) )));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"log - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFLog10Node node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (a.type.isNumeric()) {
try{
stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble( Math.log10(((Numeric)a).getDouble()))));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG10 function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"log10 - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFExpNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (a.type.isNumeric()) {
try{
stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble( Math.exp(((Numeric)a).getDouble()))));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing EXP function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"exp - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFRoundNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (a.type.isNumeric()) {
try{
stack.push(new TLValue(TLValueType.DOUBLE,new CloverLong(Math.round(((Numeric)a).getDouble()))));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing ROUND function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"round - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFPowNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
TLValue b = stack.pop();
if (a.type.isNumeric() && b.type.isNumeric()) {
try{
stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.pow(a.getDouble(),
b.getDouble()))));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing POW function",ex);
}
}else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"pow - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFPINode node, Object data) {
stack.push(Stack.NUM_PI);
return data;
}
*/
public Object visit(CLVFTruncNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
if (a.type==TLValueType.DATE ) {
stack.calendar.setTime(a.getDate());
stack.calendar.set(Calendar.HOUR_OF_DAY, 0);
stack.calendar.set(Calendar.MINUTE , 0);
stack.calendar.set(Calendar.SECOND , 0);
stack.calendar.set(Calendar.MILLISECOND , 0);
stack.push( new TLValue(TLValueType.DATE,stack.calendar.getTime() ));
}else if (a.type.isNumeric()){
stack.push(new TLValue(TLValueType.LONG,new CloverLong(a.getLong())));
}else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"trunc - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFRaiseErrorNode node,Object data){
node.jjtGetChild(0).jjtAccept(this, data);
TLValue a = stack.pop();
throw new TransformLangExecutorRuntimeException(node,null,
"!!! Exception raised by user: "+((a!=null) ? a.toString() : "no message"));
}
public Object visit(CLVFSequenceNode node,Object data){
Object seqVal=null;
TLValueType type=null;
if (node.sequence==null){
if (graph!=null){
node.sequence=graph.getSequence(node.sequenceName);
}else{
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain Sequence \""+node.sequenceName+
"\" from graph - graph is not assigned");
}
if (node.sequence==null){
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain Sequence \""+node.sequenceName+
"\" from graph \""+graph.getName()+"\"");
}
}
switch(node.opType){
case CLVFSequenceNode.OP_RESET:
node.sequence.reset();
seqVal=Stack.NUM_ZERO;
type=TLValueType.INTEGER;
break;
case CLVFSequenceNode.OP_CURRENT:
switch(node.retType){
case LONG_VAR:
seqVal=new CloverLong(node.sequence.currentValueLong());
type=TLValueType.LONG;
break;
case STRING_VAR:
seqVal=node.sequence.currentValueString();
type=TLValueType.STRING;
default:
seqVal=new CloverInteger(node.sequence.currentValueInt());
type=TLValueType.INTEGER;
}
default: // default is next value from sequence
switch(node.retType){
case LONG_VAR:
seqVal=new CloverLong(node.sequence.nextValueLong());
type=TLValueType.LONG;
break;
case STRING_VAR:
seqVal=node.sequence.nextValueString();
type=TLValueType.STRING;
default:
seqVal=new CloverInteger(node.sequence.nextValueInt());
}
}
stack.push(new TLValue(type,seqVal));
return data;
}
public Object visit(CLVFLookupNode node,Object data){
DataRecord record=null;
if (node.lookup==null){
node.lookup=graph.getLookupTable(node.lookupName);
if (node.lookup==null){
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain LookupTable \""+node.lookupName+
"\" from graph \""+graph.getName()+"\"");
}
node.fieldNum=node.lookup.getMetadata().getFieldPosition(node.fieldName);
if (node.fieldNum<0){
throw new TransformLangExecutorRuntimeException(node,
"Invalid field name \""+node.fieldName+"\" at LookupTable \""+node.lookupName+
"\" in graph \""+graph.getName()+"\"");
}
}
switch(node.opType){
case CLVFLookupNode.OP_INIT:
try{
node.lookup.init();
}catch(ComponentNotReadyException ex){
throw new TransformLangExecutorRuntimeException(node,
"Error when initializing lookup table \""+node.lookupName+"\" :",
ex);
}
return data;
case CLVFLookupNode.OP_FREE:
node.lookup.free();
return data;
case CLVFLookupNode.OP_NUM_FOUND:
stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(node.lookup.getNumFound())));
return data;
case CLVFLookupNode.OP_GET:
Object keys[]=new Object[node.jjtGetNumChildren()];
for(int i=0;i<node.jjtGetNumChildren();i++){
node.jjtGetChild(i).jjtAccept(this, data);
keys[i]=stack.pop();
}
record=node.lookup.get(keys);
break;
case CLVFLookupNode.OP_NEXT:
record=node.lookup.getNext();
}
if(record!=null){
stack.push(new TLValue(record.getField(node.fieldNum)));
}else{
stack.push(Stack.NULL_VAL);
}
return data;
}
public Object visit(CLVFPrintLogNode node, Object data) {
if (runtimeLogger == null) {
throw new TransformLangExecutorRuntimeException(node,
"Can NOT perform logging operation - no logger defined");
}
node.jjtGetChild(0).jjtAccept(this, data);
TLValue msg = stack.pop();
switch (node.level) {
case 1: //| "debug"
runtimeLogger.debug(msg);
break;
case 2: //| "info"
runtimeLogger.info(msg);
break;
case 3: //| "warn"
runtimeLogger.warn(msg);
break;
case 4: //| "error"
runtimeLogger.error(msg);
break;
case 5: //| "fatal"
runtimeLogger.fatal(msg);
break;
default:
runtimeLogger.trace(msg);
}
return data;
}
public Object visit(CLVFSizeNode node, Object data) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral) node.jjtGetChild(0);
TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot);
stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(var.getLength())));
return data;
}
public Object visit(CLVFImportSource node,Object data) {
node.childrenAccept(this, data);
return data;
}
public Object visit(CLVFSymbolNameExp node,Object data) {
stack.push(node.value);
return data;
}
public Object visit(CLVFOperator node,Object data) {
return data;
}
public Object visit(CLVFPostfixExpression node,Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
TLValue val=stack.pop();
int operatorType=((CLVFOperator)node.jjtGetChild(1)).kind;
if (operatorType==INCR) {
if (val.type.isNumeric()) {
val=val.duplicate();
val.getNumeric().add(Stack.NUM_ONE_P);
stack.push(val);
}else if (val.type==TLValueType.DATE) {
stack.calendar.setTime(val.getDate());
stack.calendar.add(Calendar.DATE, 1);
val.value=stack.calendar.getTime();
stack.push(val);
}else {
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
}else{
if (val.type.isNumeric()) {
val=val.duplicate();
val.getNumeric().sub(Stack.NUM_ONE_P);
stack.push(val);
}else if (val.type==TLValueType.DATE) {
stack.calendar.setTime(val.getDate());
stack.calendar.add(Calendar.DATE, -1);
val.value=stack.calendar.getTime();
stack.push(val);
}else {
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
}
return data;
}
public Object visit(CLVFUnaryExpression node,Object data) {
int operatorType=((CLVFOperator)node.jjtGetChild(0)).kind;
node.jjtGetChild(1).jjtAccept(this, data);
TLValue val=stack.pop();
switch(operatorType){
case INCR:
if (val.type.isNumeric()) {
val=val.duplicate();
val.getNumeric().add(Stack.NUM_ONE_P);
stack.push(val);
}else if (val.type==TLValueType.DATE) {
stack.calendar.setTime(val.getDate());
stack.calendar.add(Calendar.DATE, 1);
val.value=stack.calendar.getTime();
stack.push(val);
}else {
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
break;
case DECR:
if (val.type.isNumeric()) {
val=val.duplicate();
val.getNumeric().sub(Stack.NUM_ONE_P);
stack.push(val);
}else if (val.type==TLValueType.DATE) {
stack.calendar.setTime(val.getDate());
stack.calendar.add(Calendar.DATE, -1);
val.value=stack.calendar.getTime();
stack.push(val);
}else {
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
break;
case NOT:
if (val.type==TLValueType.BOOLEAN) {
stack.push(val.getBoolean() ? Stack.FALSE_VAL
: Stack.TRUE_VAL);
} else {
throw new TransformLangExecutorRuntimeException(node, new Object[] { val },
"logical condition does not evaluate to BOOLEAN value");
}
case MINUS:
if (val.type.isNumeric()) {
val=val.duplicate();
val.getNumeric().neg();
stack.push(val);
}else {
throw new TransformLangExecutorRuntimeException(node,new Object[] { val }, "variable is not of numeric type");
}
break;
case PLUS:
if (val.type.isNumeric()) {
val=val.duplicate();
val.getNumeric().abs();
stack.push(val);
}else {
throw new TransformLangExecutorRuntimeException(node,new Object[] { val }, "variable is not of numeric type");
}
break;
default:
throw new TransformLangExecutorRuntimeException(node, "unsupported operation");
}
return data;
}
}
|
package com.hsalf.smilerating;
import android.animation.Animator;
import android.animation.ArgbEvaluator;
import android.animation.FloatEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.annotation.ColorInt;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import java.util.HashMap;
import java.util.Map;
public class SmileRating extends BaseRating {
private static final String TAG = "RatingView";
private int mPlaceHolderSmileColor = Color.WHITE;
private int mAngryColor = Color.parseColor("#f29a68");
private int mNormalColor = Color.parseColor("#f2dd68");
private int mDrawingColor = Color.parseColor("#353431");
private int mTextSelectedColor = Color.BLACK;
private int mTextNonSelectedColor = Color.parseColor("#AEB3B5");
private int mPlaceholderBackgroundColor = Color.parseColor("#e6e8ed");
private String[] mNames = new String[]{
"Terrible", "Bad", "Okay", "Good", "Great"
};
private Face[] mFaces = new Face[SMILES_LIST.length];
private Map<Integer, Point> mTouchPoints = new HashMap<>();
private float mSmileGap;
private boolean mShowLine = true;
private float mSmileyAlpha = 1;
private Paint mPathPaint = new Paint();
private Paint mBackgroundPaint = new Paint();
private Paint mPointPaint1 = new Paint();
private Paint mPointPaint2 = new Paint();
// private Path mEyePathLeft = new Path();
// private Path mEyePathRight = new Path();
private Point mFaceCenter = new Point();
private Path mSmilePath = new Path();
private Paint mPlaceHolderFacePaint = new Paint();
private Paint mPlaceholderLinePaint = new Paint();
private Paint mPlaceHolderCirclePaint = new Paint();
private float divisions;
private ValueAnimator mValueAnimator = new ValueAnimator();
private FloatEvaluator mFloatEvaluator = new FloatEvaluator();
private ArgbEvaluator mColorEvaluator = new ArgbEvaluator();
private OvershootInterpolator mInterpolator = new OvershootInterpolator();
private ClickAnalyser mClickAnalyser;
private Matrix mScaleMatrix = new Matrix();
private RectF mScaleRect = new RectF();
private RectF mTouchBounds = new RectF();
private Path mDummyDrawPah = new Path();
private Paint mTextPaint = new Paint();
@Smiley
private int mSelectedSmile = OKAY;
@Smiley
private int mPreviousSmile = -1;
@Smiley
private int mNearestSmile = OKAY;
@Smiley
private int mPendingActionSmile = OKAY;
private Smileys mSmileys;
// private float mTranslation = 0;
private float mWidth;
private float mHeight;
private float mCenterY;
private float mFromRange;
private float mToRange;
private float mPrevX;
private boolean mFaceClickEngaged = false;
private OnRatingSelectedListener mOnRatingSelectedListener = null;
private OnSmileySelectionListener mOnSmileySelectionListener = null;
private float mPlaceHolderScale = 1f;
private boolean mSmileyNotSelectedPreviously = true;
public SmileRating(Context context) {
super(context);
init();
}
public SmileRating(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttrs(attrs);
init();
}
public SmileRating(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
parseAttrs(attrs);
init();
}
private void parseAttrs(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SmileRating);
mAngryColor = a.getColor(R.styleable.SmileRating_angryColor, mAngryColor);
mNormalColor = a.getColor(R.styleable.SmileRating_normalColor, mNormalColor);
mDrawingColor = a.getColor(R.styleable.SmileRating_drawingColor, mDrawingColor);
mPlaceHolderSmileColor = a.getColor(R.styleable.SmileRating_placeHolderSmileColor,
mPlaceHolderSmileColor);
mPlaceholderBackgroundColor = a.getColor(R.styleable.SmileRating_placeHolderBackgroundColor,
mPlaceholderBackgroundColor);
mTextSelectedColor = a.getColor(R.styleable.SmileRating_textSelectionColor,
mTextSelectedColor);
mTextNonSelectedColor = a.getColor(R.styleable.SmileRating_textNonSelectionColor,
mTextNonSelectedColor);
mShowLine = a.getBoolean(R.styleable.SmileRating_showLine, true);
a.recycle();
}
}
private void init() {
mClickAnalyser = ClickAnalyser.newInstance(getResources().getDisplayMetrics().density);
mTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
mPathPaint.setAntiAlias(true);
mPathPaint.setStrokeWidth(3);
mPathPaint.setColor(mDrawingColor);
mPathPaint.setStyle(Paint.Style.FILL);
mPointPaint1.setAntiAlias(true);
mPointPaint1.setColor(Color.RED);
mPointPaint1.setStyle(Paint.Style.FILL);
mPointPaint2.setAntiAlias(true);
mPointPaint2.setColor(Color.BLUE);
mPointPaint2.setStyle(Paint.Style.STROKE);
mBackgroundPaint.setAntiAlias(true);
mBackgroundPaint.setStyle(Paint.Style.FILL);
mPlaceHolderFacePaint.setAntiAlias(true);
mPlaceHolderFacePaint.setColor(mPlaceHolderSmileColor);
mPlaceHolderFacePaint.setStyle(Paint.Style.FILL);
mPlaceHolderCirclePaint.setAntiAlias(true);
mPlaceHolderCirclePaint.setColor(mPlaceholderBackgroundColor);
mPlaceHolderCirclePaint.setStyle(Paint.Style.FILL);
mPlaceholderLinePaint.setAntiAlias(true);
mPlaceholderLinePaint.setColor(mPlaceholderBackgroundColor);
mPlaceholderLinePaint.setStyle(Paint.Style.STROKE);
mValueAnimator.setDuration(250);
mValueAnimator.addListener(mAnimatorListener);
mValueAnimator.addUpdateListener(mAnimatorUpdateListener);
mValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
}
private ValueAnimator.AnimatorUpdateListener mAnimatorUpdateListener
= new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (mSmileyNotSelectedPreviously) {
mSmileyAlpha = animation.getAnimatedFraction();
invalidate();
} else {
float anim = (float) animation.getAnimatedValue();
moveSmile(anim);
}
}
};
private Animator.AnimatorListener mAnimatorListener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
moveSmile(mTouchPoints.get(mSelectedSmile).x);
}
@Override
public void onAnimationEnd(Animator animation) {
notifyListener();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
};
private void notifyListener() {
boolean reselected = mPreviousSmile == getSelectedSmile();
mPreviousSmile = mSelectedSmile;
mPendingActionSmile = mSelectedSmile;
if (mOnSmileySelectionListener != null) {
mOnSmileySelectionListener.onSmileySelected(mSelectedSmile, reselected);
}
if (mOnRatingSelectedListener != null) {
mOnRatingSelectedListener.onRatingSelected(getRating(), reselected);
}
}
public void setOnSmileySelectionListener(OnSmileySelectionListener l) {
mOnSmileySelectionListener = l;
}
public void setOnRatingSelectedListener(OnRatingSelectedListener l) {
mOnRatingSelectedListener = l;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
// mHeight = mWidth / 5.3f;
mHeight = mWidth / (5.3f * 1.3f);
mCenterY = mHeight / 2f;
mFaceCenter.y = mCenterY;
divisions = (mHeight / 32f);
mTextPaint.setTextSize(mHeight / 4.5f);
mSmileys = Smileys.newInstance(Math.round(mWidth), Math.round(mHeight));
setMeasuredDimension(Math.round(mWidth), (int) Math.round(mHeight + (mHeight * 0.48)));
createTouchPoints();
mPlaceholderLinePaint.setStrokeWidth(mHeight * 0.05f);
/*getSmiley(mSmileys, 0.5f, divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);*/
setSelectedSmile(mPendingActionSmile, mTouchPoints.get(mPendingActionSmile), false, false);
Log.i(TAG, "Selected smile:" + getSmileName(mPendingActionSmile));
}
private void createTouchPoints() {
mTouchPoints.clear();
float divisions = mWidth / 5f;
float divCenter = divisions / 2f;
mSmileGap = (divisions - mHeight) / 2f;
mFromRange = mSmileGap + (mHeight / 2);
mToRange = mWidth - (mHeight / 2) - mSmileGap;
int count = SMILES_LIST.length;
for (int i = 0; i < count; i++) {
mFaces[i] = createFace(i, mCenterY);
mTouchPoints.put(SMILES_LIST[i], new Point((divisions * i) + divCenter, mCenterY));
}
}
private Face createFace(int index, float centerY) {
Face face = new Face();
face.smileType = index;
getSmiley(mSmileys, index * 0.25f, divisions, mFromRange, mToRange, face.place,
face.smile, centerY);
face.place.y = centerY;
return face;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Point start = mFaces[0].place;
Point end = mFaces[mFaces.length - 1].place;
if (mShowLine) {
canvas.drawLine(start.x, start.y, end.x, end.y, mPlaceholderLinePaint);
}
Log.i(TAG, "******************");
for (Face face : mFaces) {
float scale = getScale(face.smileType);
canvas.drawCircle(face.place.x, face.place.y,
scale * (mHeight / 2), mPlaceHolderCirclePaint);
mScaleMatrix.reset();
face.smile.computeBounds(mScaleRect, true);
if (mSmileyNotSelectedPreviously) {
float nonSelectedScale = getScale(NONE);
mScaleMatrix.setScale(nonSelectedScale, nonSelectedScale,
mScaleRect.centerX(), mScaleRect.centerY());
if (mSelectedSmile == face.smileType) {
scale = mFloatEvaluator.evaluate(1 - mSmileyAlpha, 0, nonSelectedScale);
}
} else {
mScaleMatrix.setScale(scale, scale,
mScaleRect.centerX(), mScaleRect.centerY());
}
mDummyDrawPah.reset();
mDummyDrawPah.addPath(face.smile, mScaleMatrix);
canvas.drawPath(mDummyDrawPah, mPlaceHolderFacePaint);
float transY = 0.15f - (scale * 0.15f);
mTextPaint.setColor((int) mColorEvaluator.evaluate(((transY / 0.15f) - 0.2f) / 0.8f,
mTextNonSelectedColor, mTextSelectedColor));
drawTextCentered(getSmileName(face.smileType), face.place.x,
face.place.y + (mHeight * (0.70f + transY)), mTextPaint, canvas);
}
if (!mSmilePath.isEmpty()) {
if (mSmileyNotSelectedPreviously) {
/*mPathPaint.setAlpha(Math.round(255 * mSmileyAlpha));
mBackgroundPaint.setAlpha(Math.round(255 * mSmileyAlpha));*/
mPathPaint.setColor((Integer) mColorEvaluator
.evaluate(mSmileyAlpha, mPlaceHolderFacePaint.getColor(), mDrawingColor));
mBackgroundPaint.setColor((Integer) mColorEvaluator
.evaluate(mSmileyAlpha, mPlaceHolderCirclePaint.getColor(), mNormalColor));
mScaleMatrix.reset();
mSmilePath.computeBounds(mScaleRect, true);
float nonSelectedScale = mFloatEvaluator.evaluate(
mInterpolator.getInterpolation(mSmileyAlpha), getScale(NONE), 1f);
mScaleMatrix.setScale(nonSelectedScale, nonSelectedScale,
mScaleRect.centerX(), mScaleRect.centerY());
mDummyDrawPah.reset();
mDummyDrawPah.addPath(mSmilePath, mScaleMatrix);
canvas.drawCircle(mFaceCenter.x, mFaceCenter.y,
nonSelectedScale * (mHeight / 2f), mBackgroundPaint);
canvas.drawPath(mDummyDrawPah, mPathPaint);
} else {
canvas.drawCircle(mFaceCenter.x, mFaceCenter.y, mHeight / 2f, mBackgroundPaint);
canvas.drawPath(mSmilePath, mPathPaint);
}
}
}
private void drawTextCentered(String text, float x, float y, Paint paint, Canvas canvas) {
float xPos = x - (paint.measureText(text) / 2);
float yPos = (y - ((paint.descent() + paint.ascent()) / 2));
canvas.drawText(text, xPos, yPos, paint);
}
private float getScale(@Smiley int smile) {
if (mSelectedSmile == NONE) {
return 0.80f;
}
if (smile == mNearestSmile) {
return mPlaceHolderScale;
}
return 0.80f;
}
public String getSmileName(int smile) {
if (smile >= mNames.length || smile < 0) {
return null;
}
return mNames[smile];
}
public void setNameForSmile(@Smiley int smile, String title) {
mNames[smile] = title != null ? title : "";
invalidate();
}
public void setAngryColor(@ColorInt int color) {
this.mAngryColor = color;
getSmiley(mSmileys, getFractionBySmiley(mSelectedSmile), divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);
}
public void setNormalColor(@ColorInt int color) {
this.mNormalColor = color;
getSmiley(mSmileys, getFractionBySmiley(mSelectedSmile), divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);
}
public void setDrawingColor(@ColorInt int color) {
this.mDrawingColor = color;
mPathPaint.setColor(mDrawingColor);
invalidate();
}
public void setTextSelectedColor(@ColorInt int color) {
this.mTextSelectedColor = color;
invalidate();
}
public void setTextNonSelectedColor(@ColorInt int color) {
this.mTextNonSelectedColor = color;
invalidate();
}
public void setPlaceHolderSmileColor(@ColorInt int color) {
this.mPlaceHolderSmileColor = color;
mPlaceHolderFacePaint.setColor(mPlaceHolderSmileColor);
invalidate();
}
public void setPlaceholderBackgroundColor(@ColorInt int color) {
this.mPlaceholderBackgroundColor = color;
mPlaceholderLinePaint.setColor(mPlaceholderBackgroundColor);
mPlaceHolderCirclePaint.setColor(mPlaceholderBackgroundColor);
invalidate();
}
public void setShowLine(boolean showLine) {
mShowLine = showLine;
invalidate();
}
public void setTypeface(Typeface typeface) {
if (typeface == null) {
typeface = Typeface.DEFAULT;
}
mTextPaint.setTypeface(typeface);
}
public boolean isShowingLine() {
return mShowLine;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
float x = event.getX();
float y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
mClickAnalyser.start(x, y);
mFaceClickEngaged = isSmileyBounds(mFaceCenter.x, mFaceCenter.y,
x, y, mCenterY);
mPrevX = x;
break;
case MotionEvent.ACTION_MOVE:
mClickAnalyser.move(x, y);
if (mClickAnalyser.isMoved() && mFaceClickEngaged) {
moveSmile(mFaceCenter.x - (mPrevX - x));
}
mPrevX = x;
break;
case MotionEvent.ACTION_UP:
mFaceClickEngaged = false;
mClickAnalyser.stop(x, y);
if (!mClickAnalyser.isMoved()) {
onClickView(x, y);
} else {
positionSmile();
}
break;
}
return true;
}
private void positionSmile() {
if (NONE == mSelectedSmile) {
return;
}
float currentPosition = mFaceCenter.x;
float distance = Integer.MAX_VALUE;
Point point = null;
@Smiley
int smile = NONE;
for (Integer s : mTouchPoints.keySet()) {
Point p = mTouchPoints.get(s);
float d = Math.abs(p.x - currentPosition);
if (distance > d) {
point = p;
smile = s;
distance = d;
}
}
setSelectedSmile(smile, point, false, true);
}
private void moveSmile(float position) {
float fraction = (position - mFromRange) / (mToRange - mFromRange);
moveSmileByFraction(fraction);
}
private void moveSmileByFraction(float fraction) {
if (fraction >= 0f && fraction <= 1f) {
getSmiley(mSmileys, fraction, divisions, mFromRange, mToRange,
mFaceCenter, mSmilePath, mCenterY);
invalidate();
}
}
private void onClickView(float x, float y) {
for (Integer smile : mTouchPoints.keySet()) {
Point point = mTouchPoints.get(smile);
boolean touched = isSmileyBounds(point.x, point.y, x, y, mCenterY);
if (touched) {
if (smile == getSelectedSmile()) {
notifyListener();
} else {
setSelectedSmile(smile, point, true, true);
}
}
}
}
private boolean isSmileyBounds(float cx, float cy, float tx, float ty, float width) {
mTouchBounds.set(cx - width, 0, cx + width, getMeasuredHeight());
return mTouchBounds.contains(tx, ty);
}
/**
* Set the selected smiley
*
* @param smile is the smiley type you want this rating bar to show as selected smile
*/
public void setSelectedSmile(@Smiley int smile) {
setSelectedSmile(smile, false);
}
/**
* Set the selected smiley
*
* @param smile is the smiley type you want this rating bar to show as selected smile
* @param animate true if you want to set the selected smiley and animate it,
* false for no animation
*/
public void setSelectedSmile(@Smiley int smile, boolean animate) {
mPendingActionSmile = smile;
setSelectedSmile(smile, mTouchPoints.get(smile), true, animate);
}
private void setSelectedSmile(@Smiley int smile, Point point, boolean check, boolean animate) {
if (mSelectedSmile == smile && check) {
return;
}
if (mSelectedSmile == NONE) {
mSmileyNotSelectedPreviously = true;
} else if (smile == NONE) {
mSmileyNotSelectedPreviously = true;
} else {
mSmileyNotSelectedPreviously = false;
}
mSelectedSmile = smile;
if (mFaceCenter == null || point == null) {
return;
}
mValueAnimator.setFloatValues(mFaceCenter.x, point.x);
if (animate) {
mValueAnimator.start();
} else {
moveSmile(point.x);
// notifyListener();
}
}
/**
* @return the current selected smiley {@link #TERRIBLE} ,{@link #BAD},
* {@link #OKAY},{@link #GOOD},{@link #GREAT}
*/
@Smiley
public int getSelectedSmile() {
return mSelectedSmile;
}
/**
* @return the selected rating level from range of 1 to 5
*/
public int getRating() {
return getSelectedSmile() + 1;
}
/**
* Evaluates click actions using touch events
*/
protected static class ClickAnalyser {
private static final int MAX_CLICK_DISTANCE = 20;
private static final int MAX_CLICK_DURATION = 200;
private float mPressX;
private float mPressY;
private final float mDensity;
private long mPressStartTime;
private boolean mMoved = false;
private boolean mClickEventOccured = true;
public ClickAnalyser(float density) {
mDensity = density;
}
public static ClickAnalyser newInstance(float density) {
return new ClickAnalyser(density);
}
public void start(float x, float y) {
mPressX = x;
mPressY = y;
mMoved = false;
mClickEventOccured = true;
mPressStartTime = System.currentTimeMillis();
}
/**
* returns long press
*
* @param x
* @param y
* @return
*/
public void move(float x, float y) {
float dist = distance(mPressX, mPressY, x, y);
long time = System.currentTimeMillis() - mPressStartTime;
if (!mMoved && dist > MAX_CLICK_DISTANCE) {
mMoved = true;
}
if ((time) > MAX_CLICK_DURATION || mMoved) {
mClickEventOccured = false;
}
}
public boolean stop(float x, float y) {
move(x, y);
return mClickEventOccured;
}
private float distance(float x1, float y1, float x2, float y2) {
float dx = x1 - x2;
float dy = y1 - y2;
float distanceInPx = (float) Math.sqrt(dx * dx + dy * dy);
return pxToDp(distanceInPx);
}
public boolean isMoved() {
return mMoved;
}
private float pxToDp(float px) {
return px / mDensity;
}
}
private float getFractionBySmiley(@Smiley int smiley) {
switch (smiley) {
case BaseRating.BAD:
return 1f;
case BaseRating.GOOD:
return 0.75f;
case BaseRating.GREAT:
return 0.5f;
case BaseRating.OKAY:
return 0.25f;
case BaseRating.TERRIBLE:
return 0f;
}
return 0;
}
private void getSmiley(Smileys smileys, float fraction, float divisions, float fromRange,
float toRange, Point point, Path smilePath,
float centerY) {
if (smileys == null) {
return;
}
float actualTranslation = mFloatEvaluator.evaluate(fraction, fromRange, toRange);
point.x = actualTranslation;
float trans = actualTranslation - centerY;
if (fraction > 0.75f) {
fraction -= 0.75f;
fraction *= 4;
findNearestSmile(fraction, GOOD, GREAT);
mBackgroundPaint.setColor(mNormalColor);
transformSmile(trans, fraction, smilePath,
smileys.getSmile(GOOD), smileys.getSmile(GREAT), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, GREAT, smilePath, smilePath, centerY);
} else if (fraction > 0.50f) {
fraction -= 0.50f;
fraction *= 4;
findNearestSmile(fraction, OKAY, GOOD);
mBackgroundPaint.setColor(mNormalColor);
transformSmile(trans, fraction, smilePath,
smileys.getSmile(OKAY), smileys.getSmile(GOOD), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, GOOD, smilePath, smilePath, centerY);
} else if (fraction > 0.25f) {
fraction -= 0.25f;
fraction *= 4;
findNearestSmile(fraction, BAD, OKAY);
mBackgroundPaint.setColor(mNormalColor);
transformSmile(trans, fraction, smilePath,
smileys.getSmile(BAD), smileys.getSmile(OKAY), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, BAD, smilePath, smilePath, centerY);
} else if (fraction >= 0) {
fraction *= 4;
findNearestSmile(fraction, TERRIBLE, BAD);
mBackgroundPaint.setColor((Integer) mColorEvaluator.evaluate(fraction, mAngryColor, mNormalColor));
transformSmile(trans, fraction, smilePath,
smileys.getSmile(TERRIBLE), smileys.getSmile(BAD), mFloatEvaluator);
createEyeLocation(smileys, divisions, fraction, actualTranslation, TERRIBLE, smilePath, smilePath, centerY);
} else {
if (!mSmilePath.isEmpty()) {
mSmilePath.reset();
}
}
}
private void findNearestSmile(float fraction, @Smiley int leftSmile, @Smiley int rightSmile) {
if (fraction < 0.5f) {
mPlaceHolderScale = limitNumberInRange(fraction * 2);
mNearestSmile = leftSmile;
} else {
mPlaceHolderScale = limitNumberInRange(1f - (fraction - 0.5f) * 2);
mNearestSmile = rightSmile;
}
}
private float limitNumberInRange(float num) {
// The range is going to be in between 0 to 0.80
num *= 0.80f;
return num;
}
private void createEyeLocation(Smileys smileys, float divisions, float fraction, float actualTranslation, @Smiley int smile, Path leftEye, Path rightEye, float centerY) {
Eye eyeLeft = EyeEmotion.prepareEye(smileys.getEye(Eye.LEFT), mFloatEvaluator, fraction, smile);
Eye eyeRight = EyeEmotion.prepareEye(smileys.getEye(Eye.RIGHT), mFloatEvaluator, fraction, smile);
eyeLeft.radius = divisions * 2.5f;
eyeRight.radius = divisions * 2.5f;
eyeLeft.center.x = (divisions * 11f) + actualTranslation - centerY;
eyeLeft.center.y = centerY * 0.70f;
eyeRight.center.x = (divisions * 21f) + actualTranslation - centerY;
eyeRight.center.y = centerY * 0.70f;
eyeLeft.fillPath(leftEye);
eyeRight.fillPath(rightEye);
}
private static class Face {
Point place = new Point();
Path smile = new Path();
@Smiley
int smileType;
/*Path leftEye = new Path();
Path rightEye = new Path();*/
}
public interface OnSmileySelectionListener {
/**
* Called when a smiley is selected
*
* @param smiley is the type of smiley the user selected ({@link #GREAT}, {@link #BAD},
* {@link #OKAY},{@link #GOOD},{@link #GREAT})
* @param reselected is false when user selects different smiley that previously selected
* one true when the same smiley is selected. Except if it first time,
* then the value will be false.
*/
void onSmileySelected(@Smiley int smiley, boolean reselected);
}
public interface OnRatingSelectedListener {
/**
* Called when a smiley is selected
*
* @param level is the level of the rating (0 to 4)
* @param reselected is false when user selects different smiley that previously selected
* one true when the same smiley is selected. Except if it first time,
* then the value will be false.
*/
void onRatingSelected(int level, boolean reselected);
}
}
|
package edu.rpi.phil.legup.puzzles.lightup;
import java.util.LinkedHashSet;
import java.util.Set;
import edu.rpi.phil.legup.BoardState;
import edu.rpi.phil.legup.PuzzleRule;
import edu.rpi.phil.legup.newgui.LEGUP_Gui;
import edu.rpi.phil.legup.Contradiction;
public class RuleBulbsOutsideDiagonal extends PuzzleRule {
static final long serialVersionUID = 9501L;
public String getImageName() {
return "images/lightup/rules/EmptyCornersLegacy.png";
}
RuleBulbsOutsideDiagonal() {
setName("Bulbs Outside Diagonal");
description = "Cells on the external edges of a 3 diagonal to a numerical block must be bulbs.";
}
protected String checkRuleRaw(BoardState destBoardState) {
// Check for only one branch
if (destBoardState.getParents().size() != 1) {
return "This rule only involves having a single branch!";
}
// Add contradictions to check to set contras
Set<Contradiction> contras = new LinkedHashSet<Contradiction>();
contras.add(new ContradictionTooManyBulbs());
// Copy the parent state to compare with current state to find changes
BoardState origBoardState = destBoardState.getSingleParentState();
int width = origBoardState.getWidth();
int height = origBoardState.getHeight();
// Check each tile for any changes,
// make sure changes are allowed
// check that doing the opposite case would lead to a contradiction (thus proving the rule)
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// Check for changes
BoardState modified;
if (destBoardState.getCellContents(x, y) != origBoardState.getCellContents(x, y)) {
//Make sure cells placed are empty cells
if (destBoardState.getCellContents(x, y) == LightUp.CELL_EMPTY) {
return "Only bulbs are allowed for this rule!";
}
// Create alternative board state to apply other case/contradiction
modified = origBoardState.copy();
modified.getBoardCells()[y][x] = LightUp.CELL_LIGHT;
for (Contradiction c : contras) {
if (c.checkContradictionRaw(modified) == null)
return "Too many bulbs placed.";
}
int cellvalue = origBoardState.getCellContents(x, y);
String err = "Only valid when cell requires 3 bulbs and is on outer edges of cell.";
if (origBoardState.getCellContents(x-1, y) >= 10 && origBoardState.getCellContents(x-1, y) < 15 && origBoardState.getCellContents(x-1, y) != 13) {
return err;
}
if (origBoardState.getCellContents(x+1, y) >= 10 && origBoardState.getCellContents(x+1, y) < 15 && origBoardState.getCellContents(x+1, y) != 13) {
return err;
}
if (origBoardState.getCellContents(x, y-1) >= 10 && origBoardState.getCellContents(x, y-1) < 15 && origBoardState.getCellContents(x, y-1) != 13) {
return err;
}
if (origBoardState.getCellContents(x, y+1) >= 10 && origBoardState.getCellContents(x, y+1) < 15 && origBoardState.getCellContents(x, y+1) != 13) {
return err;
}
}
}
}
return null;
}
}
|
package dk.netarkivet.wayback.indexer;
import java.io.File;
import dk.netarkivet.common.CommonSettings;
import dk.netarkivet.common.distribute.arcrepository.ArcRepositoryClientFactory;
import dk.netarkivet.common.distribute.arcrepository.LocalArcRepositoryClient;
import dk.netarkivet.common.utils.FileUtils;
import dk.netarkivet.common.utils.Settings;
import dk.netarkivet.testutils.TestFileUtils;
import dk.netarkivet.testutils.preconfigured.ReloadSettings;
import dk.netarkivet.wayback.TestInfo;
import dk.netarkivet.wayback.WaybackSettings;
import junit.framework.TestCase;
public class IndexerTestCase extends TestCase {
private String oldClient = System.getProperty(CommonSettings.ARC_REPOSITORY_CLIENT);
private String oldFileDir = System.getProperty("settings.common.arcrepositoryClient.fileDir");
protected static File tempdir = new File(Settings.get(WaybackSettings.WAYBACK_INDEX_TEMPDIR));
ReloadSettings rs = new ReloadSettings();
public void setUp() {
rs.setUp();
System.setProperty(WaybackSettings.HIBERNATE_HBM2DDL_AUTO, "create-drop");
HibernateUtil.getSession().getSessionFactory().close();
FileUtils.removeRecursively(TestInfo.WORKING_DIR);
TestFileUtils.copyDirectoryNonCVS(TestInfo.ORIGINALS_DIR, TestInfo.WORKING_DIR);
System.setProperty(CommonSettings.ARC_REPOSITORY_CLIENT, "dk.netarkivet.common.distribute.arcrepository.LocalArcRepositoryClient");
System.setProperty("settings.common.arcrepositoryClient.fileDir", TestInfo.FILE_DIR.getAbsolutePath());
System.setProperty(CommonSettings.REMOTE_FILE_CLASS, "dk.netarkivet.common.distribute.TestRemoteFile");
assertTrue(ArcRepositoryClientFactory.getPreservationInstance() instanceof LocalArcRepositoryClient);
}
public void tearDown() {
HibernateUtil.getSession().getSessionFactory().close();
FileUtils.removeRecursively(TestInfo.WORKING_DIR);
FileUtils.remove(TestInfo.LOG_FILE);
if (oldClient != null) {
System.setProperty(CommonSettings.ARC_REPOSITORY_CLIENT, oldClient);
} else {
System.setProperty(CommonSettings.ARC_REPOSITORY_CLIENT, "");
}
if (oldFileDir != null ) {
System.setProperty("settings.common.arcrepositoryClient.fileDir", oldFileDir);
} else {
System.setProperty("settings.common.arcrepositoryClient.fileDir", "");
}
rs.tearDown();
}
public void testNothing() {
assertTrue("This is here to stop junit complaining that there are no "
+ "tests in this class", true);
}
}
|
package edu.duke.cabig.c3pr.domain;
import edu.duke.cabig.c3pr.utils.ProjectedList;
import edu.duke.cabig.c3pr.utils.StringUtils;
import gov.nih.nci.cabig.ctms.collections.LazyListHelper;
import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.collections15.functors.InstantiateFactory;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Where;
/**
* A systematic evaluation of an observation or an intervention (for example,
* treatment, drug, device, procedure or system) in one or more subjects.
* Frequently this is a test of a particular hypothesis about the treatment,
* drug, device, procedure or system. [CDAM] A study can be either primary or
* correlative. A study is considered a primary study if it has one or more
* correlative studies. A correlative study extends the objectives or
* observations of a primary study, enrolling the same, or a subset of the same,
* subjects as the primary study. A Clinical Trial is a Study with type=
* "intervention" with subjects of type="human".
*
* @author Priyatam
*/
@Entity
@Table(name = "STUDIES")
@GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "STUDIES_ID_SEQ") })
public class Study extends AbstractMutableDomainObject implements
Comparable<Study> {
private String blindedIndicator;
private String multiInstitutionIndicator;
private String randomizedIndicator;
private String shortTitleText;
private String longTitleText;
private String descriptionText;
private String precisText;
private String phaseCode;
private String status;
private String type;
private String primaryIdentifier;
private Integer targetAccrualNumber;
private List<Epoch> epochs;
private RandomizationType randomizationType;
private List<StudyDisease> studyDiseases = new ArrayList<StudyDisease>();
private List<StudyOrganization> studyOrganizations;
private List<Identifier> identifiers;
// TODO move into Command Object
private String[] diseaseTermIds;
private String diseaseCategoryAsText;
private LazyListHelper lazyListHelper;
// private ParameterizedInstantiateFactory<Identifier> identifierFactory;
public Study() {
lazyListHelper = new LazyListHelper();
lazyListHelper.add(StudySite.class,
new ParameterizedBiDirectionalInstantiateFactory<StudySite>(
StudySite.class, this));
lazyListHelper
.add(
StudyFundingSponsor.class,
new ParameterizedBiDirectionalInstantiateFactory<StudyFundingSponsor>(
StudyFundingSponsor.class, this));
lazyListHelper
.add(
StudyCoordinatingCenter.class,
new ParameterizedBiDirectionalInstantiateFactory<StudyCoordinatingCenter>(
StudyCoordinatingCenter.class, this));
// lazyListHelper.add(Epoch.class, epochFactory);
lazyListHelper
.add(
TreatmentEpoch.class,
new ParameterizedBiDirectionalInstantiateFactory<TreatmentEpoch>(
TreatmentEpoch.class, this));
lazyListHelper
.add(
NonTreatmentEpoch.class,
new ParameterizedBiDirectionalInstantiateFactory<NonTreatmentEpoch>(
NonTreatmentEpoch.class, this));
lazyListHelper.add(SystemAssignedIdentifier.class,
new ParameterizedInstantiateFactory<SystemAssignedIdentifier>(
SystemAssignedIdentifier.class));
lazyListHelper
.add(
OrganizationAssignedIdentifier.class,
new ParameterizedInstantiateFactory<OrganizationAssignedIdentifier>(
OrganizationAssignedIdentifier.class));
lazyListHelper.add(StudyAmendment.class, new InstantiateFactory<StudyAmendment>(StudyAmendment.class));
// mandatory, so that the lazy-projected list is managed properly.
setStudyOrganizations(new ArrayList<StudyOrganization>());
setEpochs(new ArrayList<Epoch>());
setIdentifiers(new ArrayList<Identifier>());
}
@Transient
public List<Identifier> getLocalIdentifiers() {
List<Identifier> localIdentifiers = new ArrayList<Identifier>();
for (Identifier identifier : getIdentifiers()) {
if ("Protocol Authority Identifier".equals(identifier.getType())
|| "Coordinating Center Identifier".equals(identifier
.getType())) {
// nothing
} else {
localIdentifiers.add(identifier);
}
}
return localIdentifiers;
}
@Transient
public List<StudySite> getStudySites() {
return lazyListHelper.getLazyList(StudySite.class);
}
public void setStudySites(List<StudySite> studySites) {
// do nothing
}
@Transient
public List<StudyFundingSponsor> getStudyFundingSponsors() {
return lazyListHelper.getLazyList(StudyFundingSponsor.class);
}
public void setStudyFundingSponsors(
List<StudyFundingSponsor> studyFundingSponsors) {
// do nothing
}
@Transient
public List<StudyCoordinatingCenter> getStudyCoordinatingCenters() {
return lazyListHelper.getLazyList(StudyCoordinatingCenter.class);
}
public void setStudyCoordinatingCenters(
List<StudyCoordinatingCenter> studyCoordinatingCenters) {
// do nothing
}
@OneToMany(mappedBy = "study", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyOrganization> getStudyOrganizations() {
return studyOrganizations;
}
public void setStudyOrganizations(List<StudyOrganization> studyOrganizations) {
this.studyOrganizations = studyOrganizations;
// initialize projected list for StudySite, StudyFundingSponsor and
// StudyCoordinatingCenter
lazyListHelper.setInternalList(StudySite.class,
new ProjectedList<StudySite>(this.studyOrganizations,
StudySite.class));
lazyListHelper.setInternalList(StudyFundingSponsor.class,
new ProjectedList<StudyFundingSponsor>(this.studyOrganizations,
StudyFundingSponsor.class));
lazyListHelper
.setInternalList(StudyCoordinatingCenter.class,
new ProjectedList<StudyCoordinatingCenter>(
this.studyOrganizations,
StudyCoordinatingCenter.class));
}
public void addStudyOrganization(StudyOrganization so) {
this.getStudyOrganizations().add(so);
so.setStudy(this);
}
public void removeStudyOrganization(StudyOrganization so) {
this.getStudyOrganizations().remove(so);
}
public void addEpoch(Epoch epoch) throws RuntimeException {
for (Epoch epochPresent : getEpochs()) {
if (epochPresent.equals(epoch)) {
throw new RuntimeException("epoch with same name already exists in study");
}
}
epoch.setStudy(this);
getEpochs().add(epoch);
}
public void removeEpoch(Epoch epoch) {
lazyListHelper.getLazyList(Epoch.class).remove(epoch);
}
public void addStudySite(StudySite studySite) {
studySite.setStudy(this);
lazyListHelper.getLazyList(StudySite.class).add(studySite);
}
public void removeStudySite(StudySite studySite) {
lazyListHelper.getLazyList(StudySite.class).remove(studySite);
}
public void addStudyDisease(StudyDisease studyDisease) {
studyDisease.setStudy(this);
studyDiseases.add(studyDisease);
}
public void addIdentifier(Identifier identifier) {
getIdentifiers().add(identifier);
}
public void removeIdentifier(Identifier identifier) {
getIdentifiers().remove(identifier);
}
@Transient
public OrganizationAssignedIdentifier getFundingSponsorAssignedIdentifier()
{
for (OrganizationAssignedIdentifier orgIdentifier:this.getOrganizationAssignedIdentifiers()){
if (orgIdentifier.getType().equals("Protocol Authority Identifier")) return orgIdentifier;
}
return null;
}
// / BEAN PROPERTIES
// TODO: this stuff should really, really not be in here. It's
// web-view/entry specific.
@Transient
public String[] getDiseaseTermIds() {
return diseaseTermIds;
}
@Transient
public String getDiseaseCategoryAsText() {
return diseaseCategoryAsText;
}
@OneToMany
@Cascade( { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
@JoinColumn(name = "STU_ID")
public List<Identifier> getIdentifiers() {
return identifiers;
}
public void setIdentifiers(List<Identifier> identifiers) {
this.identifiers = identifiers;
lazyListHelper.setInternalList(SystemAssignedIdentifier.class,
new ProjectedList<SystemAssignedIdentifier>(this.identifiers,
SystemAssignedIdentifier.class));
lazyListHelper
.setInternalList(OrganizationAssignedIdentifier.class,
new ProjectedList<OrganizationAssignedIdentifier>(
this.identifiers,
OrganizationAssignedIdentifier.class));
}
@Transient
public List<SystemAssignedIdentifier> getSystemAssignedIdentifiers() {
return lazyListHelper.getLazyList(SystemAssignedIdentifier.class);
}
public void setSystemAssignedIdentifiers(
List<SystemAssignedIdentifier> systemAssignedIdentifiers) {
// do nothing
}
@Transient
public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers() {
return lazyListHelper.getLazyList(OrganizationAssignedIdentifier.class);
}
public void setOrganizationAssignedIdentifiers(
List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) {
// do nothing
}
@OneToMany(mappedBy = "study", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<Epoch> getEpochs() {
return epochs;
}
public void addAmendment(final StudyAmendment amendment) {
getStudyAmendments().add(amendment);
}
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "stu_id", nullable = false)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyAmendment> getStudyAmendmentsInternal() {
return lazyListHelper.getInternalList(StudyAmendment.class);
}
public void setStudyAmendmentsInternal(final List<StudyAmendment> amendments) {
lazyListHelper.setInternalList(StudyAmendment.class, amendments);
}
@Transient
public List<StudyAmendment> getStudyAmendments() {
return lazyListHelper.getLazyList(StudyAmendment.class);
}
public void setStudyAmendments(final List<StudyAmendment> amendments) {
setStudyAmendmentsInternal(amendments);
}
public void setEpochs(List<Epoch> epochs) {
this.epochs = epochs;
lazyListHelper.setInternalList(TreatmentEpoch.class,
new ProjectedList<TreatmentEpoch>(this.epochs,
TreatmentEpoch.class));
lazyListHelper.setInternalList(NonTreatmentEpoch.class,
new ProjectedList<NonTreatmentEpoch>(this.epochs,
NonTreatmentEpoch.class));
}
@Transient
public List<TreatmentEpoch> getTreatmentEpochs() {
return lazyListHelper.getLazyList(TreatmentEpoch.class);
}
public void setTreatmentEpochs(List<TreatmentEpoch> treatmentEpochs) {
// do nothing
}
@Transient
public List<NonTreatmentEpoch> getNonTreatmentEpochs() {
return lazyListHelper.getLazyList(NonTreatmentEpoch.class);
}
public void setNonTreatmentEpochs(List<NonTreatmentEpoch> nonTreatmentEpochs) {
// do nothing
}
@OneToMany(mappedBy = "study", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyDisease> getStudyDiseases() {
return studyDiseases;
}
public void setStudyDiseases(List<StudyDisease> studyDiseases) {
this.studyDiseases = studyDiseases;
}
public void setDiseaseTermIds(String[] diseaseTermIds) {
this.diseaseTermIds = diseaseTermIds;
}
public void setDiseaseCategoryAsText(String diseaseCategoryAsText) {
this.diseaseCategoryAsText = diseaseCategoryAsText;
}
public String getDescriptionText() {
return descriptionText;
}
public void setDescriptionText(String descriptionText) {
this.descriptionText = descriptionText;
}
public String getLongTitleText() {
return longTitleText;
}
public void setLongTitleText(String longTitleText) {
this.longTitleText = longTitleText;
}
public String getPhaseCode() {
return phaseCode;
}
public void setPhaseCode(String phaseCode) {
this.phaseCode = phaseCode;
}
public String getPrecisText() {
return precisText;
}
public void setPrecisText(String precisText) {
this.precisText = precisText;
}
public String getShortTitleText() {
return shortTitleText;
}
public void setShortTitleText(String shortTitleText) {
this.shortTitleText = shortTitleText;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getTargetAccrualNumber() {
return targetAccrualNumber;
}
public void setTargetAccrualNumber(Integer targetAccrualNumber) {
this.targetAccrualNumber = targetAccrualNumber;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int compareTo(Study o) {
if (this.equals(o))
return 0;
return 1;
}
@Override public int hashCode() { final int PRIME = 31; int result=super.hashCode(); result = PRIME * result + ((getFundingSponsorAssignedIdentifier() == null) ? 0 :
getFundingSponsorAssignedIdentifier().hashCode()); return result; }
@Override public boolean equals(Object obj) { if (this == obj) return
true; if (getClass() !=
obj.getClass()) return false; final Study other = (Study) obj;
if ((this.getFundingSponsorAssignedIdentifier() == null)|| (other.getFundingSponsorAssignedIdentifier()==null)) {
return false;}
else if (!((this.getFundingSponsorAssignedIdentifier().getValue()).equals(other.getFundingSponsorAssignedIdentifier().getValue()))) {return false;}
else if (!((this.getFundingSponsorAssignedIdentifier().getHealthcareSite()).equals(other.getFundingSponsorAssignedIdentifier().getHealthcareSite()))) {return false;}
return true; }
@Transient
public String getTrimmedShortTitleText() {
return StringUtils.getTrimmedText(shortTitleText, 40);
}
@Transient
public String getPrimaryIdentifier() {
for (Identifier identifier : getIdentifiers()) {
if (identifier.getPrimaryIndicator().booleanValue() == true) {
return identifier.getValue();
}
}
return primaryIdentifier;
}
public String getBlindedIndicator() {
return blindedIndicator;
}
public void setBlindedIndicator(String blindedIndicator) {
this.blindedIndicator = blindedIndicator;
}
public String getMultiInstitutionIndicator() {
return multiInstitutionIndicator;
}
public void setMultiInstitutionIndicator(String multiInstitutionIndicator) {
this.multiInstitutionIndicator = multiInstitutionIndicator;
}
public String getRandomizedIndicator() {
return randomizedIndicator;
}
public void setRandomizedIndicator(String randomizedIndicator) {
this.randomizedIndicator = randomizedIndicator;
}
public RandomizationType getRandomizationType() {
return randomizationType;
}
public void setRandomizationType(RandomizationType randomizationType) {
this.randomizationType = randomizationType;
}
}
|
package com.datatorrent.stram.client;
import com.datatorrent.stram.client.StramAppLauncher.AppFactory;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>AppBundle class.</p>
*
* @author David Yan <david@datatorrent.com>
* @since 1.0.3
*/
public class AppBundle extends JarFile implements Closeable
{
public static final String ATTRIBUTE_DT_ENGINE_VERSION = "DT-Engine-Version";
public static final String ATTRIBUTE_DT_APP_BUNDLE_NAME = "DT-App-Bundle-Name";
public static final String ATTRIBUTE_DT_APP_BUNDLE_VERSION = "DT-App-Bundle-Version";
public static final String ATTRIBUTE_CLASS_PATH = "Class-Path";
private final String appBundleName;
private final String appBundleVersion;
private final String dtEngineVersion;
private final ArrayList<String> classPath = new ArrayList<String>();
private final String directory;
private final List<AppInfo> applications = new ArrayList<AppInfo>();
private final List<String> appJars = new ArrayList<String>();
private final List<String> appPropertiesFiles = new ArrayList<String>();
private final Set<String> requiredProperties = new TreeSet<String>();
private final Map<String, String> defaultProperties = new TreeMap<String, String>();
private final Set<String> configs = new TreeSet<String>();
public static class AppInfo
{
public final String name;
public final String jarName;
public final LogicalPlan dag;
public AppInfo(String name, String jarName, LogicalPlan dag)
{
this.name = name;
this.jarName = jarName;
this.dag = dag;
}
}
public AppBundle(File file) throws IOException, ZipException
{
this(file, false);
}
/**
* Creates an App Bundle object.
*
* If app directory is to be processed, there may be resource leak in the class loader. Only pass true for short-lived applications
*
* @param file
* @param processAppDirectory
* @throws java.io.IOException
* @throws net.lingala.zip4j.exception.ZipException
*/
public AppBundle(File file, boolean processAppDirectory) throws IOException, ZipException
{
super(file);
Manifest manifest = getManifest();
if (manifest == null) {
throw new IOException("Not a valid app bundle. MANIFEST.MF is not present.");
}
Attributes attr = manifest.getMainAttributes();
appBundleName = attr.getValue(ATTRIBUTE_DT_APP_BUNDLE_NAME);
appBundleVersion = attr.getValue(ATTRIBUTE_DT_APP_BUNDLE_VERSION);
dtEngineVersion = attr.getValue(ATTRIBUTE_DT_ENGINE_VERSION);
String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
if (classPathString == null) {
throw new IOException("Not a valid app bundle. Class-Path is missing from MANIFEST.MF");
}
classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
ZipFile zipFile = new ZipFile(file);
if (zipFile.isEncrypted()) {
throw new ZipException("Encrypted app bundle not supported yet");
}
File newDirectory = new File("/tmp/dt-appBundle-" + System.currentTimeMillis());
newDirectory.mkdirs();
directory = newDirectory.getAbsolutePath();
zipFile.extractAll(directory);
if (processAppDirectory) {
processAppDirectory(new File(newDirectory, "app"));
}
File confDirectory = new File(newDirectory, "conf");
if (confDirectory.exists()) {
processConfDirectory(confDirectory);
}
File propertiesXml = new File(newDirectory, "META-INF/properties.xml");
if (propertiesXml.exists()) {
processPropertiesXml(propertiesXml);
}
}
public String tempDirectory()
{
return directory;
}
@Override
public void close() throws IOException
{
super.close();
FileUtils.deleteDirectory(new File(directory));
}
public String getAppBundleName()
{
return appBundleName;
}
public String getAppBundleVersion()
{
return appBundleVersion;
}
public String getDtEngineVersion()
{
return dtEngineVersion;
}
public List<String> getClassPath()
{
return Collections.unmodifiableList(classPath);
}
public Collection<String> getConfigs()
{
return Collections.unmodifiableCollection(configs);
}
public List<AppInfo> getApplications()
{
return Collections.unmodifiableList(applications);
}
public List<String> getAppJars()
{
return Collections.unmodifiableList(appJars);
}
public List<String> getAppPropertiesFiles()
{
return Collections.unmodifiableList(appPropertiesFiles);
}
public Set<String> getRequiredProperties()
{
return Collections.unmodifiableSet(requiredProperties);
}
public Map<String, String> getDefaultProperties()
{
return Collections.unmodifiableMap(defaultProperties);
}
private void processAppDirectory(File dir)
{
Iterator<File> it = FileUtils.iterateFiles(dir, null, false);
Configuration config = new Configuration();
List<String> absClassPath = new ArrayList<String>(classPath);
for (int i = 0; i < absClassPath.size(); i++) {
String path = absClassPath.get(i);
if (!path.startsWith("/")) {
absClassPath.set(i, directory + "/" + path);
}
}
config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, StringUtils.join(absClassPath, ','));
while (it.hasNext()) {
File entry = it.next();
if (entry.getName().endsWith(".jar")) {
appJars.add(entry.getName());
try {
StramAppLauncher stramAppLauncher = new StramAppLauncher(entry, config);
stramAppLauncher.loadDependencies();
List<AppFactory> appFactories = stramAppLauncher.getBundledTopologies();
for (AppFactory appFactory : appFactories) {
String appName = stramAppLauncher.getLogicalPlanConfiguration().getAppAlias(appFactory.getName());
if (appName == null) {
appName = appFactory.getName();
}
applications.add(new AppInfo(appName, entry.getName(), stramAppLauncher.prepareDAG(appFactory)));
}
}
catch (Exception ex) {
LOG.error("Caught exception trying to process {}", entry.getName(), ex);
}
}
else if (entry.getName().endsWith(".properties")) {
// TBD
appPropertiesFiles.add(entry.getName());
}
else {
LOG.warn("Ignoring file {} with unknown extension in app directory", entry.getName());
}
}
}
private void processConfDirectory(File dir)
{
Iterator<File> it = FileUtils.iterateFiles(dir, null, false);
while (it.hasNext()) {
File entry = it.next();
if (entry.getName().endsWith(".xml")) {
configs.add(entry.getName());
}
}
}
private void processPropertiesXml(File file)
{
DTConfiguration config = new DTConfiguration();
try {
config.loadFile(file);
for (Map.Entry<String, String> entry : config) {
String key = entry.getKey();
String value = entry.getValue();
if (value == null) {
requiredProperties.add(key);
}
else {
defaultProperties.put(key, value);
}
}
}
catch (Exception ex) {
LOG.warn("Ignoring META_INF/properties.xml because of error", ex);
}
}
private static final Logger LOG = LoggerFactory.getLogger(AppBundle.class);
}
|
package model.objects.pen.normal;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Random;
import model.objects.pen.Pen;
import model.settings.Constants;
import model.settings.Status;
import model.settings.ViewSettings;
import model.util.DPoint;
/**
* Pencil fetched from paper.
* @author Julius Huelsmann
* @version %I%, %U%
*/
public class Pencil extends Pen {
/**
* serial version of pen.
*/
private static final long serialVersionUID = 0L;
/**
* The variance and the expectancies for inside and outside.
*/
private final int variance = 50, expectancyInside = 140,
expectancyOutside = 65;
/**
* Constructor: calls super -constructor.
* @param _index the index of the pen painting method (like line,
* point, mathematics)
* @param _thickness the thickness of painting
* @param _background the background.
*/
public Pencil(final int _index, final int _thickness,
final Color _background) {
//call super constructor
super(_index, _thickness, _background, getPath(_index));
}
/**
* {@inheritDoc}
*/
@Override
public final String getName() {
return "Pencil";
}
/**
* Return the path of the icon depending on kind of pen.
* @param _kind the kind of pen
* @return the path
*/
private static String getPath(final int _kind) {
switch (_kind) {
case Constants.PEN_ID_LINES:
return Constants.PATH_PEN_BLEI_LINE;
case Constants.PEN_ID_MATHS:
return Constants.PATH_PEN_BLEI_MATHS;
case Constants.PEN_ID_POINT:
return Constants.PATH_PEN_BLEI_POINT;
default:
Status.getLogger().severe("unknown paint index");
return null;
}
}
/**
* {@inheritDoc}
*/
@Override protected final void paintPoint(final DPoint _p,
final BufferedImage _bi, final boolean _final,
final DPoint _pnt_shift, final BufferedImage _g,
final Rectangle _r_visibleScope) {
for (int i = -getThickness() / 2; i <= getThickness() / 2; i++) {
for (int j = -getThickness() / 2; j <= getThickness() / 2; j++) {
//x and y location because is used twice for line
//drawing.
int x, y;
x = (int) _p.getX();
y = (int) _p.getY();
//if is in range
if (_final && x + i >= 0 && x + i < _bi.getWidth()
&& y + i < _bi.getHeight() && y + i >= 0) {
//set the given pixel in buffered image
if (_final && x >= 0 && x < _bi.getWidth()
&& y >= 0 && y < _bi.getHeight()) {
final int rbg = printPixel(x, y, i, j, x, y, _bi);
if (x + i >= 0 && x + i < _bi.getWidth()
&& y + j >= 0 && y + j < _bi.getHeight()) {
_bi.setRGB(x + i, y + j, rbg);
}
}
}
if (_g != null) {
//adjust the location at the zoom.
int rx = ((x + i) * Status.getImageShowSize().width)
/ Status.getImageSize().width;
int ry = ((y + j) * Status.getImageShowSize().height)
/ Status.getImageSize().height;
//add the shift coordinates for painting.
rx += _pnt_shift.getX();
ry += _pnt_shift.getY();
//the image pixel size in pixel for painting.
//for example if zoomed in once, an image pixel has
//got the size of two painted pixel in each dimension.
//thus it is necessary to paint 4 pixel. These pixel
//are painted under the previous pixel. Example:
// [x] [a] [ ] (x is the pixel which is
// [a] [a] [ ] already printed, a are those
// [ ] [ ] [ ] which are added to avoid gaps.
int imagePixelSizeX = Status.getImageShowSize().width
/ Status.getImageSize().width,
imagePixelSizeY = Status.getImageShowSize().height
/ Status.getImageSize().height;
//error prevention (divide by zero if zoomed out a little
//bit too much)
if (imagePixelSizeX == 0) {
imagePixelSizeX = 1;
}
if (imagePixelSizeY == 0) {
imagePixelSizeY = 1;
}
//if the data is displayed paint lines to graphics.
//otherwise nothing to do.
if (rx / imagePixelSizeX >= 0 && ry / imagePixelSizeY >= 0
//if the x coordinates are in range (displayed
//at the right edge of the screen)
&& (int) rx / imagePixelSizeX + 1
<= (int) ViewSettings.getView_bounds_page().width
// <= (int) Page.getInstance().getJlbl_painting()
// .getWidth()
/ imagePixelSizeX
//if the x coordinates are in range (displayed
//at the bottom edge of the screen)
&& (int) ry / imagePixelSizeY + 1
<= (int) ViewSettings.getView_bounds_page().height
// <= (int) Page.getInstance().getJlbl_painting()
// .getHeight()
/ imagePixelSizeY) {
int rbg = 0;
if (rx >= 0 && rx < _g.getWidth()
&& ry >= 0 && ry < _g.getHeight()) {
rbg = printPixel(x, y, i, j, (int)
(rx),
(int) (ry), _g);
}
Status.setCounter_paintedPoints(Status
.getCounter_paintedPoints() + 1);
if (rx >= 0 && rx < _g.getWidth()
&& ry >= 0 && ry < _g.getHeight()) {
_g.setRGB(rx, ry, rbg);
}
//for loop because i want to paint the gaps between the
//pixel if zoomed in.
for (int kx = 0; kx < imagePixelSizeX; kx++) {
for (int ky = 0; ky < imagePixelSizeY; ky++) {
if (rx + kx >= 0 && rx + kx < _g.getWidth()
&& ry + ky >= 0
&& ry + ky < _g.getHeight()) {
_g.setRGB(rx + kx, ry + ky, rbg);
}
}
}
}
}
}
}
}
/**
* Merge inverted colors. Usually called once for each
* color (red, green, blue).
*
* @param _clrA the INVERTED! value part of the first color
* @param _clrB the INVERTED!value part of the second color
* @return the merged color value part (not inverted anymore)
*/
private int mergeColors(final int _clrA, final int _clrB) {
final int maxRBG = 255;
double ma = 1.0 * _clrA / (_clrA + _clrB);
double mb = 1.0 * _clrB / (_clrA + _clrB);
double value = maxRBG - 1.0 * (_clrA * (1 + ma) + _clrB * (1 + mb))
/ (2 * 2);
return (int) value;
}
private int printPixel(final int _x,
final int _y, final int _i, final int _j, final int _rX,
final int _rY, final BufferedImage _bi) {
boolean oldVersion = false;
if (oldVersion ) {
return printPixelArea(_x, _y, _i, _j, _rX, _rY, _bi);
} else {
return printPixelArea2(_x, _y, _i, _j, _rX, _rY, _bi);
}
}
/**
* Return a part of the pixel area around point (x,y) at point (x+i, y+j).
* @param _x the x point
* @param _y the y point
* @param _i the x distance to center
* @param _j the y distance to center
* @param _rX the real x coordinate in image for fetching point
* @param _rY the real y coordinate in image for fetching point.
* @param _bi the BufferedImage for fetching old point.
* @return the RGB value of the pixel which will be printed.
*/
private int printPixelArea(final int _x,
final int _y, final int _i, final int _j, final int _rX,
final int _rY, final BufferedImage _bi) {
//the (inverted) colors
Color rgbInversOld, rgbInversNew;
final int maxRBG = 255;
//use different functions depending on whether the
//point is outside (or in the else branch inside)
if (
(_i == -1 && _j == -1)
|| (_i == 2)
|| (_j == 2)) {
int v = (int) normalDistribution(
expectancyOutside, variance);
if (v >= maxRBG - 1) {
v = maxRBG - 2;
}
rgbInversNew = new Color(v, v, v);
} else {
int v = (int) normalDistribution(
expectancyInside, variance);
if (v >= maxRBG - 1) {
v = maxRBG - 2;
}
rgbInversNew = new Color(v, v + 1, v + 2);
}
final Color clr_old = new Color(_bi.getRGB(_rX, _rY), true);
//fetch old color if the color is not completely white
//or transparent
if (clr_old.getAlpha() == 0
|| (clr_old.getRed() == maxRBG
&& clr_old.getGreen() == maxRBG
&& clr_old.getBlue() == maxRBG)) {
rgbInversOld = rgbInversNew;
} else {
rgbInversOld = new Color(maxRBG - clr_old.getRed(),
maxRBG - clr_old.getGreen(),
maxRBG - clr_old.getBlue());
}
Color merged = new Color(mergeColors(
rgbInversNew.getRed(), rgbInversOld.getRed()),
mergeColors(rgbInversNew.getGreen(),
rgbInversOld.getGreen()), mergeColors(
rgbInversNew.getBlue(),
rgbInversOld.getBlue()));
double fgSum = getClr_foreground().getRed()
+ getClr_foreground().getGreen()
+ getClr_foreground().getBlue();
final double hellerD = 2.5;
double anteilR = 1.0 * getClr_foreground().getRed() / fgSum;
double anteilG = 1.0 * getClr_foreground().getGreen() / fgSum;
double anteilB = 1.0 * getClr_foreground().getBlue() / fgSum;
double mw = (anteilR + anteilG + anteilB) / (2 + 1);
double anteilR2 = Math.abs(anteilR - (anteilR - mw) / 2);
double anteilG2 = Math.abs(anteilG - (anteilG - mw) / 2);
double anteilB2 = Math.abs(anteilB - (anteilB - mw) / 2);
int red = (int) (hellerD * anteilR2 * merged.getRed());
int green = (int) (hellerD * anteilG2 * merged.getGreen());
int blue = (int) (hellerD * anteilB2 * merged.getBlue());
if (red > maxRBG) {
red = maxRBG;
}
if (green > maxRBG) {
green = maxRBG;
}
if (blue > maxRBG) {
blue = maxRBG;
}
int abstand = Math.max(Math.abs(_i)* 2 + Math.abs(_j), 1);
red = 255 - (255 - red) / abstand;
green = 255 - (255 - green) / abstand;
blue = 255 - (255 - blue) / abstand;
final int alpha = 175;
return new Color(red, green, blue, alpha).getRGB();
}
/**
* Return a part of the pixel area around point (x,y) at point (x+i, y+j).
* @param _x the x point
* @param _y the y point
* @param _i the x distance to center
* @param _j the y distance to center
* @param _rX the real x coordinate in image for fetching point
* @param _rY the real y coordinate in image for fetching point.
* @param _bi the BufferedImage for fetching old point.
* @return the RGB value of the pixel which will be printed.
*/
private int printPixelArea2(
final int _x,
final int _y,
final int _i, final int _j,
final int _rX, final int _rY,
final BufferedImage _bi) {
//the (inverted) colors
Color clr_new0;
final int maxRBG = 255;
final int divisor = 1;
//use different functions depending on whether the
//point is outside (or in the else branch inside)
if (
(_i == -1 && _j == -1)
|| (_i == 2)
|| (_j == 2)) {
final int alphaOutside = 5;
int v = (int) normalDistribution(
expectancyOutside, variance);
if (v >= maxRBG - 1) {
v = maxRBG - 2;
}
final int sum = getClr_foreground().getRed()
+ getClr_foreground().getGreen()
+ getClr_foreground().getBlue();
if (sum != 0) {
clr_new0 = new Color(
v * getClr_foreground().getRed() / sum / divisor,
v * getClr_foreground().getGreen() / sum / divisor,
v * getClr_foreground().getBlue() / sum / divisor,
alphaOutside);
} else {
clr_new0 = new Color(
v,
(v + 1),
(v + 2),
alphaOutside);
}
} else {
int v = (int) normalDistribution(
expectancyInside, variance);
if (v >= maxRBG - 1) {
v = maxRBG - 2;
}
final int alphaInside = 140;
final int sum = getClr_foreground().getRed()
+ getClr_foreground().getGreen()
+ getClr_foreground().getBlue();
if (sum != 0) {
clr_new0 = new Color(
v * getClr_foreground().getRed() / sum / divisor,
(v + 1) * getClr_foreground().getGreen() / sum / divisor,
(v + 2) * getClr_foreground().getBlue() / sum / divisor,
alphaInside);
} else {
clr_new0 = new Color(
v,
(v + 1),
(v + 2),
alphaInside);
}
}
final Color clr_old = new Color(_bi.getRGB(_rX, _rY), true);
final int valueOld = (clr_old.getRed() + clr_old.getGreen() + clr_old.getBlue()) / 3;
final int valueNew = (getClr_foreground().getRed() + getClr_foreground().getGreen() + getClr_foreground().getBlue()) / 3;
final int value = (valueOld * 1 + valueNew * 2) / 3;
//TODO generate the alpha value (new)
final int alphaTotal = clr_old.getAlpha() + clr_new0.getAlpha();
Color clr_new = new Color(
clr_old.getRed() * clr_old.getAlpha() / alphaTotal
+ clr_new0.getRed() * clr_new0.getAlpha() / alphaTotal,
clr_old.getGreen() * clr_old.getAlpha() / alphaTotal
+ clr_new0.getGreen() * clr_new0.getAlpha() / alphaTotal,
clr_old.getBlue() * clr_old.getAlpha() / alphaTotal
+ clr_new0.getBlue() * clr_new0.getAlpha() / alphaTotal,
Math.min(255,
(2 * Math.max(clr_new0.getAlpha(),clr_old.getAlpha())
+ 1 * Math.min(clr_new0.getAlpha(),clr_old.getAlpha())) / 3
));
final int valueCalced = (clr_new.getRed() + clr_new.getGreen() + clr_new.getBlue() ) / 3;
Color clr_new_intensityAdapted = new Color(
Math.min(clr_new.getRed() * value / valueCalced, 254),
Math.min(clr_new.getGreen() * value / valueCalced, 254),
Math.min(clr_new.getBlue() * value / valueCalced, 254),
clr_new.getAlpha());
return clr_new_intensityAdapted.getRGB();
}
/**
* Calculate random integer inside random distribution.
* @param _expectancy the expectancy value
* @param _variance the variance
* @return random double value
*/
private static double normalDistribution(final int _expectancy,
final int _variance) {
double q = 0;
double u1 = 0, u2;
while (q == 0 || q > 1) {
u1 = new Random().nextDouble();
u2 = new Random().nextDouble();
q = u1 * u1 + u2 * u2;
}
double p = Math.sqrt((-1 * 2 * Math.log(q)) / q);
return u1 * p * _variance + _expectancy;
}
}
|
package br.com.redesocial.modelo.dao;
import br.com.redesocial.modelo.dto.Comentario;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
public class ComentarioDAO extends DAOCRUDBase<Comentario> {
@Override
public void excluir(int id) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("delete from comentarios where id = ?");
pstmt.setInt(1, id);
pstmt.executeUpdate();
}
@Override
public void alterar(Comentario p) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt = conexao.prepareStatement("update comentarios set descricao = ?, curtidas = ?, data = ?, postagem = ? ,resposta = ?, usuario = ? where id = ?");
pstmt.setString(1, p.getDescricao());
pstmt.setInt(2, p.getCurtidas());
pstmt.setDate(3, new java.sql.Date(p.getData().getTime()));
pstmt.setInt(4, p.getPostagem().getId());
pstmt.setInt(5, p.getResposta().getId());
pstmt.setInt(6, p.getUsuario().getId());
pstmt.setInt(7, p.getId());
pstmt.executeUpdate();
}
@Override
public Comentario selecionar(int id) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("Select * from comentarios where id = ?");
pstmt.setInt(1, id);
ResultSet rs;
rs = pstmt.executeQuery();
PostagemDAO postagemDAO = new PostagemDAO();
if (rs.next()){
Comentario c = new Comentario();
UsuarioDAO usuarioDAO = new UsuarioDAO();
c.setId(id);
c.setDescricao(rs.getString("descricao"));
c.setCurtidas(rs.getInt("curtidas"));
c.setData(rs.getDate("data"));
c.setPostagem(postagemDAO.selecionar(rs.getInt("postagem")));
c.setUsuario(usuarioDAO.selecionar(rs.getInt("usuario")));
int idResposta = rs.getInt("resposta");
if (!rs.wasNull()){
c.setResposta(this.selecionar(idResposta));
}
return c;
} else {
return null;
}
}
@Override
public List listar() throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("select * from comentarios order by data desc");
ResultSet rs;
rs = pstmt.executeQuery();
List lista;
lista = new ArrayList();
PostagemDAO postagemDAO = new PostagemDAO();
while (rs.next()){
Comentario c = new Comentario();
UsuarioDAO usuarioDAO = new UsuarioDAO();
c.setId(rs.getInt("id"));
c.setDescricao(rs.getString("descricao"));
c.setCurtidas(rs.getInt("curtidas"));
c.setData(rs.getDate("data"));
c.setPostagem(postagemDAO.selecionar(rs.getInt("postagem")));
c.setUsuario(usuarioDAO.selecionar(rs.getInt("usuario")));
int idResposta = rs.getInt("resposta");
if (!rs.wasNull()){
c.setResposta(this.selecionar(idResposta));
}
lista.add(c);
}
return lista;
}
@Override
public void inserir(Comentario c) throws Exception {
Connection conexao = getConexao();
if (c.getDescricao().equals("")){
throw new Exception("O comentário não pode estar vazio!");
}
PreparedStatement pstmt = conexao.prepareStatement("insert into comentarios(descricao, curtidas, data, postagem, resposta, usuario) values(?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, c.getDescricao());
pstmt.setInt(2, c.getCurtidas());
pstmt.setDate(3, new java.sql.Date(c.getData().getTime()));
pstmt.setInt(4, c.getPostagem().getId());
pstmt.setInt(6, c.getUsuario().getId());
if(c.getResposta() != null){
pstmt.setInt(5, c.getResposta().getId());
} else {
pstmt.setNull(5, Types.INTEGER);
}
pstmt.executeUpdate();
c.setId(getId(pstmt));
}
}
|
package br.com.redesocial.modelo.bo;
import br.com.redesocial.modelo.dto.Cidade;
import br.com.redesocial.modelo.dto.Estado;
import br.com.redesocial.modelo.dto.Pais;
import br.com.redesocial.modelo.dto.Usuario;
import br.com.redesocial.modelo.dto.enumeracoes.Sexo;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
/**
* Unidade de testes para o UsuarioBO
* @author Igor Justino Rodrigues
* @since 19/08/2017
*/
public class UsuarioBOTest {
@Test
public void testMetodoInserir() {
}
@Test
public void testMetodoListar() {
UsuarioBO usuariobo = new UsuarioBO();
try {
List existentes = usuariobo.listar();
int qtdeExistentes = existentes.size();
final int qtde = 2;
for (int i = 0; i < 2; i++){
Pais pais = new Pais();
pais.setNome("EUA");
PaisBO paisBO = new PaisBO();
paisBO.inserir(pais);
Estado estado = new Estado();
estado.setNome("California");
estado.setPais(pais);
EstadoBO estadoBO = new EstadoBO();
estadoBO.inserir(estado);
Cidade cidade = new Cidade();
cidade.setNome("Los Angeles");
cidade.setEstado(estado);
CidadeBO cidadeBO = new CidadeBO();
cidadeBO.inserir(cidade);
Usuario usuario = new Usuario();
usuario.setNome("Igor");
usuario.setDataCadastro(new Date());
usuario.setEmail("Igor@gmail.com");
Calendar calendario = Calendar.getInstance();
calendario.set(1998, 0, 8, 0, 0, 0);
usuario.setDataNascimento(calendario.getTime());
usuario.setSenha("123");
usuario.setSexo(Sexo.MASCULINO);
usuario.setStatus(true);
usuario.setTelefone("(62) 99654-0873");
usuario.setCidade(cidade);
try {
usuariobo.inserir(usuario);
} catch (Exception ex) {
fail("Falha ao inserir um álbum: " + ex.getMessage());
}
}
List existentesFinal = usuariobo.listar();
int qtdeExistentesFinal = existentesFinal.size();
int diferenca = qtdeExistentesFinal - qtdeExistentes;
assertEquals(qtde, diferenca);
} catch (Exception ex){
fail("Erro ao listar: " + ex.getMessage());
}
}
@Test
public void testMetodoSelecionar() {
}
@Test
public void testMetodoExcluir() throws Exception{
}
}
|
package commons.lang.quickbean;
import java.io.Serializable;
/**
* @author Wayne.Wang<5waynewang@gmail.com>
* @since 1:27:44 PM Nov 16, 2014
*/
public class ResponseObject<T> implements Serializable {
private static final long serialVersionUID = -906477148460366748L;
private int code;
private String msg;
private T result;
public ResponseObject() {
this(200, null, null);
}
public ResponseObject(T result) {
this(200, null, result);
}
public ResponseObject(int code, String msg) {
this(code, msg, null);
}
public ResponseObject(int code, String msg, T result) {
this.code = code;
this.msg = msg;
this.result = result;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
/**
* {@link #isSuccess()}
*/
@Deprecated
public boolean success() {
return this.isSuccess();
}
public boolean isSuccess() {
return this.code == 200;
}
}
|
package org.neo4j.shell;
import static java.lang.Runtime.getRuntime;
import static java.lang.System.getProperty;
import static org.junit.Assert.assertEquals;
import static org.neo4j.test.TargetDirectory.forTest;
import org.junit.Test;
import org.neo4j.test.ProcessStreamHandler;
public class TestRmiPublication
{
@Test
public void jvmShouldDieEvenIfWeLeaveSamveJvmClientIsLeftHanging() throws Exception
{
assertEquals( 0, spawnJvm( DontShutdownClient.class, "client" ) );
}
@Test
public void jvmShouldDieEvenIfLocalServerIsLeftHanging() throws Exception
{
assertEquals( 0, spawnJvm( DontShutdownLocalServer.class, "server" ) );
}
private int spawnJvm( Class<?> mainClass, String name ) throws Exception
{
String dir = forTest( getClass() ).directory( "client", true ).getAbsolutePath();
return waitForExit( getRuntime().exec( new String[] { "java", "-cp", getProperty( "java.class.path" ),
mainClass.getName(), dir } ), 20 );
}
private int waitForExit( Process process, int maxSeconds ) throws InterruptedException
{
try
{
long endTime = System.currentTimeMillis() + maxSeconds*1000;
ProcessStreamHandler streamHandler = new ProcessStreamHandler( process, false );
streamHandler.launch();
try
{
while ( System.currentTimeMillis() < endTime )
{
try
{
return process.exitValue();
}
catch ( IllegalThreadStateException e )
{ // OK, not exited yet
Thread.sleep( 100 );
}
}
throw new RuntimeException( "Process didn't exit on its own" );
}
finally
{
streamHandler.cancel();
}
}
finally
{
process.destroy();
}
}
}
|
package org.spine3.test;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Type;
import java.security.acl.AclNotFoundException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@SuppressWarnings({"ClassWithTooManyMethods", "OverlyComplexClass"})
public class VerifyShould {
private static final String EMPTY_STRING = "";
private static final String NON_EMPTY_STRING = "Non-empty string";
private static final String MAP_NAME = "map";
@Test
public void extend_Assert_class() {
final Type expectedSuperclass = Assert.class;
final Type actualSuperclass = Verify.class.getGenericSuperclass();
assertEquals(expectedSuperclass, actualSuperclass);
}
@Test
public void has_private_ctor() {
assertTrue(Tests.hasPrivateParameterlessCtor(Verify.class));
}
@SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"})
@Test
public void mangle_assertion_error() {
final AssertionError sourceError = new AssertionError();
final int framesBefore = sourceError.getStackTrace().length;
try {
throw Verify.mangledException(sourceError);
} catch (AssertionError e) {
final int framesAfter = e.getStackTrace().length;
assertEquals(framesBefore - 1, framesAfter);
}
}
@SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"})
@Test
public void mangle_assertion_error_for_specified_frame_count() {
final AssertionError sourceError = new AssertionError();
final int framesBefore = sourceError.getStackTrace().length;
final int framesToPop = 3;
try {
throw Verify.mangledException(sourceError, framesToPop);
} catch (AssertionError e) {
final int framesAfter = e.getStackTrace().length;
assertEquals(framesBefore - framesToPop + 1, framesAfter);
}
}
@SuppressWarnings("ErrorNotRethrown")
@Test
public void fail_with_specified_message_and_cause() {
final String message = "Test failed";
final Throwable cause = new Error();
try {
Verify.fail(message, cause);
fail("Error was not thrown");
} catch (AssertionError e) {
assertEquals(message, e.getMessage());
assertEquals(cause, e.getCause());
}
}
@Test(expected = AssertionError.class)
public void fail_if_float_values_are_positive_infinity() {
final float anyDeltaAcceptable = 0.0f;
Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable);
}
@Test(expected = AssertionError.class)
public void fail_if_float_values_are_negative_infinity() {
final float anyDeltaAcceptable = 0.0f;
Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable);
}
@Test(expected = AssertionError.class)
public void fail_if_float_values_are_NaN() {
final float anyDeltaAcceptable = 0.0f;
Verify.assertNotEquals(Float.NaN, Float.NaN, anyDeltaAcceptable);
}
@Test(expected = AssertionError.class)
public void fail_if_float_values_are_equal() {
final float positiveValue = 5.0f;
final float negativeValue = -positiveValue;
final float equalToValuesDifference = positiveValue - negativeValue;
Verify.assertNotEquals(positiveValue, negativeValue, equalToValuesDifference);
}
@Test
public void pass_if_float_values_are_different_types_of_infinity() {
final float anyDeltaAcceptable = 0.0f;
Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable);
Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable);
}
@Test
public void pass_if_float_values_are_not_equal() {
final float expected = 0.0f;
final float actual = 1.0f;
final float lessThanValuesDifference = Math.abs(expected - actual) - 0.1f;
Verify.assertNotEquals(expected, actual, lessThanValuesDifference);
}
@Test(expected = AssertionError.class)
public void fail_if_bool_values_are_equal() {
Verify.assertNotEquals(true, true);
}
@Test
public void pass_if_bool_values_are_not_equal() {
Verify.assertNotEquals(true, false);
}
@Test(expected = AssertionError.class)
public void fail_if_byte_values_are_equal() {
Verify.assertNotEquals((byte) 0, (byte) 0);
}
@Test
public void pass_if_byte_values_are_not_equal() {
Verify.assertNotEquals((byte) 0, (byte) 1);
}
@Test(expected = AssertionError.class)
public void fail_if_char_values_are_equal() {
Verify.assertNotEquals('a', 'a');
}
@Test
public void pass_if_char_values_are_not_equal() {
Verify.assertNotEquals('a', 'b');
}
@Test(expected = AssertionError.class)
public void fail_if_short_values_are_equal() {
Verify.assertNotEquals((short) 0, (short) 0);
}
@Test
public void pass_if_short_values_are_not_equal() {
Verify.assertNotEquals((short) 0, (short) 1);
}
@Test(expected = AssertionError.class)
public void fail_if_object_is_not_instance_of_specified_type() {
Verify.assertInstanceOf(Integer.class, "");
}
@Test
public void pass_if_object_is_instance_of_specified_type() {
final String instance = "";
Verify.assertInstanceOf(instance.getClass(), instance);
}
@Test(expected = AssertionError.class)
public void fail_if_object_is_instance_of_specified_type() {
final String instance = "";
Verify.assertNotInstanceOf(instance.getClass(), instance);
}
@Test
public void pass_if_object_is_not_instance_of_specified_type() {
Verify.assertNotInstanceOf(Integer.class, "");
}
@Test(expected = AssertionError.class)
public void fail_if_iterable_is_not_empty() {
Verify.assertIterableEmpty(FluentIterable.of(1));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_iterable_is_null_in_iterable_empty() {
Verify.assertIterableEmpty(null);
}
@Test
public void pass_if_iterable_is_empty() {
Verify.assertIterableEmpty(FluentIterable.of());
}
@Test(expected = AssertionError.class)
public void fail_if_map_is_not_empty() {
Verify.assertEmpty(Collections.singletonMap(1, 1));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_map_is_null_in_assert_empty() {
Verify.assertEmpty((Map) null);
}
@Test
public void pass_if_map_is_empty() {
Verify.assertEmpty(Collections.emptyMap());
}
@Test(expected = AssertionError.class)
public void fail_if_multimap_is_not_empty() {
final Multimap<Integer, Integer> multimap = ArrayListMultimap.create();
multimap.put(1, 1);
Verify.assertEmpty(multimap);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_multimap_is_null_in_assert_empty() {
Verify.assertEmpty((Multimap) null);
}
@Test
public void pass_if_multimap_is_empty() {
Verify.assertEmpty(ArrayListMultimap.create());
}
@Test(expected = AssertionError.class)
public void fail_if_iterable_is_empty() {
Verify.assertNotEmpty(FluentIterable.of());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_iterable_is_null_in_iterable_not_empty() {
Verify.assertIterableNotEmpty(null);
}
@Test
public void pass_if_iterable_is_not_empty() {
Verify.assertNotEmpty(FluentIterable.of(1));
}
@Test(expected = AssertionError.class)
public void fail_if_map_is_empty() {
Verify.assertNotEmpty(Collections.emptyMap());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_map_is_null_in_not_empty() {
Verify.assertNotEmpty((Map) null);
}
@Test
public void pass_if_map_is_not_empty() {
Verify.assertNotEmpty(Collections.singletonMap(1, 1));
}
@Test(expected = AssertionError.class)
public void fail_if_multimap_is_empty() {
Verify.assertNotEmpty(ArrayListMultimap.create());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_multimap_is_null_in_assert_not_empty() {
Verify.assertNotEmpty((Multimap) null);
}
@Test
public void pass_if_multimap_is_not_empty() {
final Multimap<Integer, Integer> multimap = ArrayListMultimap.create();
multimap.put(1, 1);
Verify.assertNotEmpty(multimap);
}
@SuppressWarnings("ZeroLengthArrayAllocation")
@Test(expected = AssertionError.class)
public void fail_if_array_is_empty() {
Verify.assertNotEmpty(new Integer[0]);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_array_is_null_in_assert_not_empty() {
Verify.assertNotEmpty((Integer[]) null);
}
@Test
public void pass_if_array_is_not_empty() {
final Integer[] array = {1, 2, 3};
Verify.assertNotEmpty(array);
}
@Test(expected = AssertionError.class)
public void fail_if_object_array_size_is_not_equal() {
Verify.assertSize(-1, new Object[1]);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_array_is_null_in_assert_size() {
Verify.assertSize(0, (Integer[]) null);
}
@Test
public void pass_if_object_array_size_is_equal() {
final int size = 0;
Verify.assertSize(size, new Object[size]);
}
@Test(expected = AssertionError.class)
public void fail_if_iterable_size_is_not_equal() {
Verify.assertSize(-1, FluentIterable.of(1));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_iterable_is_null_in_assert_size() {
Verify.assertSize(0, (Iterable) null);
}
@Test
public void pass_if_iterable_size_is_equal() {
Verify.assertSize(0, FluentIterable.of());
}
@Test(expected = AssertionError.class)
public void fail_if_map_size_is_not_equal() {
Verify.assertSize(-1, Collections.emptyMap());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_map_is_null_in_assert_size() {
Verify.assertSize(0, (Map) null);
}
@Test
public void pass_if_map_size_is_equal() {
Verify.assertSize(0, Collections.emptyMap());
}
@Test(expected = AssertionError.class)
public void fail_if_multimap_size_is_not_equal() {
Verify.assertSize(-1, ArrayListMultimap.create());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_multimap_is_null_in_assert_size() {
Verify.assertSize(0, (Multimap) null);
}
@Test
public void pass_if_multimap_size_is_equal() {
Verify.assertSize(0, ArrayListMultimap.create());
}
@Test(expected = AssertionError.class)
public void fail_if_collection_size_is_not_equal() {
Verify.assertSize(-1, Collections.emptyList());
}
@Test
public void pass_if_collection_size_is_equal() {
Verify.assertSize(0, Collections.emptyList());
}
@Test(expected = AssertionError.class)
public void fail_if_string_not_contains_char_sequence() {
Verify.assertContains(NON_EMPTY_STRING, EMPTY_STRING);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_char_sequence_is_null_in_contains() {
Verify.assertContains(null, EMPTY_STRING);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_string_is_null_in_contains() {
Verify.assertContains(EMPTY_STRING, (String) null);
}
@SuppressWarnings({"ConstantConditions", "ErrorNotRethrown"})
@Test(expected = AssertionError.class)
public void fail_if_contains_char_sequence_or_string_is_null() {
final String nullString = null;
try {
Verify.assertContains(null, EMPTY_STRING);
} catch (AssertionError e) {
Verify.assertContains(EMPTY_STRING, nullString);
}
}
@Test
public void pass_if_string_contains_char_sequence() {
Verify.assertContains(EMPTY_STRING, NON_EMPTY_STRING);
}
@Test(expected = AssertionError.class)
public void fail_is_string_contains_char_sequence() {
Verify.assertNotContains(EMPTY_STRING, NON_EMPTY_STRING);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_char_sequence_is_null_in_not_contains() {
Verify.assertNotContains(null, EMPTY_STRING);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_string_is_null_in_not_contains() {
Verify.assertNotContains(EMPTY_STRING, (String) null);
}
@Test
public void pass_if_string_not_contains_char_sequence() {
Verify.assertNotContains(NON_EMPTY_STRING, EMPTY_STRING);
}
@Test(expected = AssertionError.class)
public void fail_if_collection_not_contains_item() {
Verify.assertContains(1, Collections.emptyList());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_collections_is_null_in_contains() {
Verify.assertContains(1, (Collection) null);
}
@Test
public void pass_if_collection_contains_item() {
final Integer item = 1;
Verify.assertContains(item, Collections.singletonList(item));
}
@Test(expected = AssertionError.class)
public void fail_if_immutable_collection_not_contains_item() {
Verify.assertContains(1, ImmutableList.of());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_immutable_collections_is_null_in_contains() {
Verify.assertContains(1, null);
}
@Test
public void pass_if_immutable_collection_contains_item() {
final Integer item = 1;
Verify.assertContains(item, ImmutableList.of(item));
}
@Test(expected = AssertionError.class)
public void fail_if_iterable_not_contains_all() {
Verify.assertContainsAll(Collections.emptyList(), 1);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_iterable_is_null_in_contains_all() {
Verify.assertContainsAll(null);
}
@Test
public void pass_if_iterable_contains_all() {
final Integer item = 1;
Verify.assertContainsAll(Collections.singletonList(item), item);
}
@Test(expected = AssertionError.class)
public void fail_if_map_are_not_equal() {
final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1));
final Map<Integer, Map<Integer, Integer>> secondOne = Collections.singletonMap(1, Collections.singletonMap(1, 2));
Verify.assertMapsEqual(firstOne, secondOne, MAP_NAME);
}
@SuppressWarnings("ConstantConditions")
@Test
public void pass_if_maps_are_null() {
Verify.assertMapsEqual(null, null, MAP_NAME);
}
@Test
public void pass_if_maps_are_equal() {
final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1));
final Map<Integer, Map<Integer, Integer>> secondOne = new HashMap<>(firstOne);
Verify.assertMapsEqual(firstOne, secondOne, MAP_NAME);
}
@Test(expected = AssertionError.class)
public void fail_if_sets_are_not_equal_by_size() {
final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3, 4);
final Set<Integer> secondOne = Sets.newHashSet(1, 2, 4);
Verify.assertSetsEqual(firstOne, secondOne);
}
@Test(expected = AssertionError.class)
public void fail_if_sets_are_not_equal_by_content() {
final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3);
final Set<Integer> secondOne = Sets.newHashSet(1, 2, 777);
Verify.assertSetsEqual(firstOne, secondOne);
}
@Test(expected = AssertionError.class)
public void fail_if_sets_are_equal_by_size_but_have_over_than_5_differences() {
final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3, 4, 5, 6);
final Set<Integer> secondOne = Sets.newHashSet(11, 12, 13, 14, 15, 16);
Verify.assertSetsEqual(firstOne, secondOne);
}
@SuppressWarnings("ConstantConditions")
@Test
public void pass_if_sets_are_null() {
Verify.assertSetsEqual(null, null);
}
@Test
public void pass_if_sets_are_equal() {
final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3);
final Set<Integer> secondOne = Sets.newHashSet(firstOne);
Verify.assertSetsEqual(firstOne, secondOne);
}
@Test(expected = AssertionError.class)
public void fail_if_multimap_not_contains_entry() {
Verify.assertContainsEntry(1, 1, ArrayListMultimap.<Integer, Integer>create());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_multimap_is_null_in_contains_entry() {
Verify.assertContainsEntry(1, 1, null);
}
@Test
public void pass_if_multimap_contains_entry() {
final Integer entryKey = 1;
final Integer entryValue = 1;
final Multimap<Integer, Integer> multimap = ArrayListMultimap.create();
multimap.put(entryKey, entryValue);
Verify.assertContainsEntry(entryKey, entryValue, multimap);
}
@Test(expected = AssertionError.class)
public void fail_if_map_not_contains_key() {
Verify.assertContainsKey(1, Collections.emptyMap());
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_map_is_null_in_contains_key() {
Verify.assertContainsKey(1, null);
}
@Test
public void pass_if_map_contains_key() {
final Integer key = 1;
Verify.assertContainsKey(key, Collections.singletonMap(key, 1));
}
@Test(expected = AssertionError.class)
public void fail_if_map_contains_denied_key() {
final Integer key = 1;
Verify.denyContainsKey(key, Collections.singletonMap(key, 1));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_map_is_null_in_deny_contains_key() {
Verify.denyContainsKey(1, null);
}
@Test
public void pass_if_map_not_contains_denied_key() {
Verify.denyContainsKey(1, Collections.emptyMap());
}
@Test(expected = AssertionError.class)
public void fail_if_map_not_contains_entry() {
final Integer key = 0;
Verify.assertContainsKeyValue(key, 0, Collections.singletonMap(key, 1));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_map_is_null_in_contains_key_value() {
Verify.assertContainsKeyValue(1, 1, null);
}
@Test
public void pass_if_map_contains_entry() {
final Integer key = 1;
final Integer value = 1;
Verify.assertContainsKeyValue(key, value, Collections.singletonMap(key, value));
}
@Test(expected = AssertionError.class)
public void fail_if_collection_contains_item() {
final Integer item = 1;
Verify.assertNotContains(item, Collections.singletonList(item));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_collection_is_null_in_not_contains() {
Verify.assertNotContains(1, null);
}
@Test
public void pass_if_collection_not_contains_item() {
Verify.assertNotContains(1, Collections.emptyList());
}
@Test(expected = AssertionError.class)
public void fail_if_iterable_contains_item() {
final Integer item = 1;
Verify.assertNotContains(item, FluentIterable.of(item));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_iterable_is_null_in_contains_item() {
Verify.assertNotContains(1, (Iterable) null);
}
@Test
public void pass_if_iterable_not_contains_item() {
Verify.assertNotContains(1, FluentIterable.of());
}
@Test(expected = AssertionError.class)
public void fail_if_map_contains_key() {
final Integer key = 1;
Verify.assertNotContainsKey(key, Collections.singletonMap(key, 1));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_map_is_null_in_not_contains_key() {
Verify.assertNotContainsKey(1, null);
}
@Test
public void pass_if_map_not_contains_key() {
Verify.assertNotContainsKey(1, Collections.emptyMap());
}
@Test(expected = AssertionError.class)
public void fail_if_former_later_latter() {
final Integer firstItem = 1;
final Integer secondItem = 2;
final List<Integer> list = Arrays.asList(firstItem, secondItem);
Verify.assertBefore(secondItem, firstItem, list);
}
@Test(expected = AssertionError.class)
public void fail_if_former_and_latter_are_equal() {
final Integer sameItem = 1;
Verify.assertBefore(sameItem, sameItem, Collections.singletonList(sameItem));
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_list_is_null_in_assert_befor() {
Verify.assertBefore(1, 2, null);
}
@Test
public void pass_if_former_before_latter() {
final Integer firstItem = 1;
final Integer secondItem = 2;
final List<Integer> list = Arrays.asList(firstItem, secondItem);
Verify.assertBefore(firstItem, secondItem, list);
}
@Test(expected = AssertionError.class)
public void fail_if_list_item_not_at_index() {
final Integer firstItem = 1;
final Integer secondItem = 2;
final List<Integer> list = Arrays.asList(firstItem, secondItem);
Verify.assertItemAtIndex(firstItem, list.indexOf(secondItem), list);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_list_is_null_in_assert_item_at_index() {
Verify.assertItemAtIndex(1, 1, (List) null);
}
@Test
public void pass_if_list_item_at_index() {
final Integer value = 1;
final List<Integer> list = Collections.singletonList(value);
Verify.assertItemAtIndex(value, list.indexOf(value), list);
}
@Test(expected = AssertionError.class)
public void fail_if_array_item_not_at_index() {
final Integer firstItem = 1;
final Integer secondItem = 2;
final Object[] array = {firstItem, secondItem};
Verify.assertItemAtIndex(firstItem, 1, array);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_array_is_null_in_assert_item_at_index() {
Verify.assertItemAtIndex(1, 1, (Object[]) null);
}
@Test
public void pass_if_array_item_at_index() {
final Integer value = 1;
final Object[] array = {value};
Verify.assertItemAtIndex(value, 0, array);
}
@Test(expected = AssertionError.class)
public void fail_if_array_not_starts_with_items() {
final Integer[] array = {1, 2, 3};
final Integer notStartsWith = 777;
Verify.assertStartsWith(array, notStartsWith);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_array_is_null_in_starts_with() {
Verify.assertStartsWith((Integer[]) null, 1, 2, 3);
}
@Test(expected = AssertionError.class)
public void fail_if_items_is_empty_in_array_starts_with() {
Verify.assertStartsWith(new Integer[1]);
}
@Test
public void pass_if_array_starts_with_items() {
final Integer[] array = {1, 2};
final Integer firstItem = array[0];
Verify.assertStartsWith(array, firstItem);
}
@Test(expected = AssertionError.class)
public void fail_if_list_not_starts_with_items() {
final List<Integer> list = Arrays.asList(1, 2, 3);
final Integer notStartsWith = 777;
Verify.assertStartsWith(list, notStartsWith);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_list_is_null_in_starts_with() {
Verify.assertStartsWith((List) null, 1, 2, 3);
}
@Test(expected = AssertionError.class)
public void fail_if_items_is_empty_in_list_starts_with() {
Verify.assertStartsWith(Collections.emptyList());
}
@Test
public void pass_if_list_starts_with_items() {
final List<Integer> list = Arrays.asList(1, 2, 3);
final Integer firstItem = list.get(0);
Verify.assertStartsWith(list, firstItem);
}
@Test(expected = AssertionError.class)
public void fail_if_list_not_ends_with_items() {
final List<Integer> list = Arrays.asList(1, 2, 3);
final Integer notEndsWith = 777;
Verify.assertEndsWith(list, notEndsWith);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_list_is_null_in_ends_with() {
Verify.assertEndsWith((List) null, 1, 2, 3);
}
@Test(expected = AssertionError.class)
public void fail_if_items_is_empty_in_list_ends_with() {
Verify.assertEndsWith(Collections.emptyList());
}
@Test
public void pass_if_list_ends_with_items() {
final List<Integer> list = Arrays.asList(1, 2, 3);
final Integer lastItem = list.get(list.size() - 1);
Verify.assertEndsWith(list, lastItem);
}
@Test(expected = AssertionError.class)
public void fail_if_array_not_ends_with_items() {
final Integer[] array = {1, 2, 3};
final Integer notEndsWith = 777;
Verify.assertEndsWith(array, notEndsWith);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_array_is_null_in_ends_with() {
Verify.assertEndsWith((Integer[]) null, 1, 2, 3);
}
@Test(expected = AssertionError.class)
public void fail_if_items_is_empty_in_array_ends_with() {
Verify.assertEndsWith(new Integer[1]);
}
@Test
public void pass_if_array_ends_with() {
final Integer[] array = {1, 2, 3};
final Integer lastItem = array[array.length - 1];
Verify.assertEndsWith(array, lastItem);
}
@Test(expected = AssertionError.class)
public void fail_if_objects_are_not_equal() {
Verify.assertEqualsAndHashCode(1, 2);
}
@Test(expected = AssertionError.class)
public void fail_if_objects_are_equal_but_hash_codes_are_not_equal() {
final ClassThatViolateHashCodeAndCloneableContract objectA = new ClassThatViolateHashCodeAndCloneableContract(1);
final ClassThatViolateHashCodeAndCloneableContract objectB = new ClassThatViolateHashCodeAndCloneableContract(1);
Verify.assertEqualsAndHashCode(objectA, objectB);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_objects_are_null() {
Verify.assertEqualsAndHashCode(null, null);
}
@Test
public void pass_if_objects_and_their_hash_codes_are_equal() {
Verify.assertEqualsAndHashCode(1, 1);
}
@Test(expected = AssertionError.class)
public void fail_if_value_is_not_negative() {
Verify.assertNegative(1);
}
@Test(expected = AssertionError.class)
public void fail_if_value_is_zero_in_assert_negative() {
Verify.assertNegative(0);
}
@Test
public void pass_if_value_is_negative() {
Verify.assertNegative(-1);
}
@Test(expected = AssertionError.class)
public void fail_if_value_is_not_positive() {
Verify.assertPositive(-1);
}
@Test(expected = AssertionError.class)
public void fail_if_value_is_zero_in_assert_positive() {
Verify.assertPositive(0);
}
@Test
public void pass_if_value_is_positive() {
Verify.assertPositive(1);
}
@Test(expected = AssertionError.class)
public void fail_if_value_is_positive() {
Verify.assertZero(1);
}
@Test(expected = AssertionError.class)
public void fail_if_value_is_negative() {
Verify.assertZero(-1);
}
@Test
public void pass_if_value_is_zero() {
Verify.assertZero(0);
}
@Test(expected = AssertionError.class)
public void fail_if_clone_returns_same_object() {
Verify.assertShallowClone(new ClassThatViolateHashCodeAndCloneableContract(1));
}
@Test(expected = AssertionError.class)
public void fail_if_clone_does_not_work_correctly() {
Verify.assertShallowClone(new ClassThatImplementCloneableIncorrectly(1));
}
@Test
public void pass_if_cloneable_equals_and_hash_code_overridden_correctly() {
Verify.assertShallowClone(new ClassThatImplementCloneableCorrectly(1));
}
@Test(expected = AssertionError.class)
public void fail_if_class_instantiable() {
Verify.assertClassNonInstantiable(Object.class);
}
@Test(expected = AssertionError.class)
public void fail_if_class_instantiable_through_reflection() {
Verify.assertClassNonInstantiable(ClassWithPrivateCtor.class);
}
@Test
public void pass_if_new_instance_throw_instantiable_exception() {
Verify.assertClassNonInstantiable(void.class);
}
@Test
public void pass_if_class_non_instantiable_through_reflection() {
Verify.assertClassNonInstantiable(ClassThatThrowExceptionInConstructor.class);
}
@Test(expected = AssertionError.class)
public void fail_if_runnable_not_throws_error() {
final Runnable notThrowsException = new Runnable() {
@Override
public void run() {
}
};
Verify.assertError(AssertionError.class, notThrowsException);
}
@Test(expected = AssertionError.class)
public void fail_if_runnable_not_throws_specified_error() {
final Runnable throwsAssertionError = new Runnable() {
@Override
public void run() {
throw new AssertionError();
}
};
Verify.assertError(Error.class, throwsAssertionError);
}
@Test
public void pass_if_runnable_throws_specified_error() {
final Runnable throwsAssertionError = new Runnable() {
@Override
public void run() {
throw new AssertionError();
}
};
Verify.assertError(AssertionError.class, throwsAssertionError);
}
@Test(expected = AssertionError.class)
public void fail_if_callable_not_throws_exception() {
final Callable notThrowsException = new Callable() {
@Override
public Object call() throws Exception {
return null;
}
};
Verify.assertThrows(Exception.class, notThrowsException);
}
@Test(expected = AssertionError.class)
public void fail_if_callable_not_throws_specified_exception() {
final Callable throwsEmptyStackException = new Callable() {
@Override
public Object call() throws Exception {
throw new EmptyStackException();
}
};
Verify.assertThrows(Exception.class, throwsEmptyStackException);
}
@Test
public void pass_if_callable_throws_specified_exception() {
final Callable throwsEmptyStackException = new Callable() {
@Override
public Object call() throws Exception {
throw new EmptyStackException();
}
};
Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException);
}
@Test(expected = AssertionError.class)
public void fail_if_runnable_not_throws_exception() {
final Runnable notThrowsException = new Runnable() {
@Override
public void run() {
}
};
Verify.assertThrows(Exception.class, notThrowsException);
}
@Test(expected = AssertionError.class)
public void fail_if_runnable_not_throws_specified_exception() {
final Runnable throwsEmptyStackException = new Runnable() {
@Override
public void run() {
throw new EmptyStackException();
}
};
Verify.assertThrows(Exception.class, throwsEmptyStackException);
}
@Test
public void pass_if_runnable_throws_specified_exception() {
final Runnable throwsEmptyStackException = new Runnable() {
@Override
public void run() {
throw new EmptyStackException();
}
};
Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException);
}
@Test(expected = AssertionError.class)
public void fail_if_callable_not_throws_exception_with_cause() {
final Callable notThrowsException = new Callable() {
@Override
public Object call() throws Exception {
return null;
}
};
Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException);
}
@Test(expected = AssertionError.class)
public void fail_if_callable_throws_exception_with_different_causes() {
final Throwable expectedCause = new EmptyStackException();
final Throwable actualCause = new AclNotFoundException();
final RuntimeException runtimeException = new RuntimeException(actualCause);
final Callable throwsRuntimeException = new Callable() {
@Override
public Object call() {
throw runtimeException;
}
};
Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_callable_expected_cause_is_null() {
final Callable throwsRuntimeException = new Callable() {
@Override
public Object call() {
throw new RuntimeException(new EmptyStackException());
}
};
Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException);
}
@Test
public void pass_if_callable_throws_specified_exception_with_specified_cause() {
final Throwable cause = new EmptyStackException();
final RuntimeException runtimeException = new RuntimeException(cause);
final Callable throwsRuntimeException = new Callable() {
@Override
public Object call() {
throw runtimeException;
}
};
Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException);
}
@Test(expected = AssertionError.class)
public void fail_if_runnable_not_throws_exception_with_cause() {
final Runnable notThrowsException = new Runnable() {
@Override
public void run() {
}
};
Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException);
}
@Test(expected = AssertionError.class)
public void fail_if_runnable_throws_exception_with_different_causes() {
final Throwable expectedCause = new EmptyStackException();
final Throwable actualCause = new AclNotFoundException();
final RuntimeException runtimeException = new RuntimeException(actualCause);
final Runnable throwsRuntimeException = new Runnable() {
@Override
public void run() {
throw runtimeException;
}
};
Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = AssertionError.class)
public void fail_if_runnable_expected_cause_is_null() {
final Runnable throwsRuntimeException = new Runnable() {
@Override
public void run() {
throw new RuntimeException(new EmptyStackException());
}
};
Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException);
}
@Test
public void pass_if_runnable_throws_specified_exception_with_specified_cause() {
final Throwable cause = new EmptyStackException();
final RuntimeException runtimeException = new RuntimeException(cause);
final Runnable throwsRuntimeException = new Runnable() {
@Override
public void run() {
throw runtimeException;
}
};
Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException);
}
@SuppressWarnings("EqualsAndHashcode")
private static class ClassThatViolateHashCodeAndCloneableContract implements Cloneable {
private final int value;
private ClassThatViolateHashCodeAndCloneableContract(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClassThatViolateHashCodeAndCloneableContract that = (ClassThatViolateHashCodeAndCloneableContract) o;
return value == that.value;
}
@SuppressWarnings("MethodDoesntCallSuperMethod")
@Override
protected Object clone() throws CloneNotSupportedException {
return this;
}
}
private static class ClassThatImplementCloneableCorrectly implements Cloneable {
private final int value;
private ClassThatImplementCloneableCorrectly(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClassThatImplementCloneableCorrectly that = (ClassThatImplementCloneableCorrectly) o;
return value == that.value;
}
@Override
public int hashCode() {
return value;
}
}
private static final class ClassThatImplementCloneableIncorrectly implements Cloneable {
private final int value;
private ClassThatImplementCloneableIncorrectly(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClassThatImplementCloneableIncorrectly that = (ClassThatImplementCloneableIncorrectly) o;
return value == that.value;
}
@Override
public int hashCode() {
return value;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return new ClassThatImplementCloneableIncorrectly(value + 1);
}
}
private static class ClassWithPrivateCtor {
@SuppressWarnings("RedundantNoArgConstructor")
private ClassWithPrivateCtor() {
}
}
private static class ClassThatThrowExceptionInConstructor {
private ClassThatThrowExceptionInConstructor() {
throw new AssertionError("This is non-instantiable class");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.